Merge main into gatekeeper/fix-4911-1

Align the vendored cosine repair and SDK dependency with the upstream Lance beta.17 pin.
This commit is contained in:
Gatefixer
2026-11-11 16:14:50 +00:00
105 changed files with 7798 additions and 539 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "0.42.0-beta.10"
current_version = "0.42.0-beta.11"
parse = """(?x)
(?P<major>0|[1-9]\\d*)\\.
(?P<minor>0|[1-9]\\d*)\\.
+2
View File
@@ -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.
+2 -1
View File
@@ -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
+6 -4
View File
@@ -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:
+2 -1
View File
@@ -179,7 +179,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:
Generated
+52 -51
View File
@@ -3814,8 +3814,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "fsst"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"rand 0.9.5",
@@ -5292,8 +5292,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a"
[[package]]
name = "lance"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arc-swap",
"arrow",
@@ -5368,8 +5368,8 @@ dependencies = [
[[package]]
name = "lance-arrow"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5391,7 +5391,7 @@ dependencies = [
[[package]]
name = "lance-arrow-scalar"
version = "59.0.0"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5405,7 +5405,7 @@ dependencies = [
[[package]]
name = "lance-arrow-stats"
version = "59.0.0"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5414,8 +5414,8 @@ dependencies = [
[[package]]
name = "lance-bitpacking"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrayref",
"crunchy",
@@ -5425,8 +5425,8 @@ dependencies = [
[[package]]
name = "lance-core"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5464,8 +5464,8 @@ dependencies = [
[[package]]
name = "lance-datafusion"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow",
"arrow-array",
@@ -5496,8 +5496,8 @@ dependencies = [
[[package]]
name = "lance-datafusion-exec"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow",
"arrow-array",
@@ -5522,8 +5522,8 @@ dependencies = [
[[package]]
name = "lance-datagen"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow",
"arrow-array",
@@ -5540,8 +5540,8 @@ dependencies = [
[[package]]
name = "lance-derive"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"proc-macro2",
"quote",
@@ -5550,8 +5550,8 @@ dependencies = [
[[package]]
name = "lance-encoding"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-arith",
"arrow-array",
@@ -5584,8 +5584,8 @@ dependencies = [
[[package]]
name = "lance-file"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-arith",
"arrow-array",
@@ -5616,8 +5616,8 @@ dependencies = [
[[package]]
name = "lance-geo"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5648,8 +5648,8 @@ dependencies = [
[[package]]
name = "lance-index"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arc-swap",
"arrow",
@@ -5716,12 +5716,13 @@ dependencies = [
"tokio",
"tracing",
"twox-hash",
"uuid",
]
[[package]]
name = "lance-index-core"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5744,8 +5745,8 @@ dependencies = [
[[package]]
name = "lance-io"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow",
"arrow-array",
@@ -5790,8 +5791,8 @@ dependencies = [
[[package]]
name = "lance-jsonb"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"byteorder",
"ethnum",
@@ -5808,7 +5809,7 @@ dependencies = [
[[package]]
name = "lance-linalg"
version = "15.0.0-beta.16"
version = "15.0.0-beta.17"
dependencies = [
"approx",
"argminmax 0.7.1",
@@ -5830,8 +5831,8 @@ dependencies = [
[[package]]
name = "lance-namespace"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow",
"async-trait",
@@ -5845,8 +5846,8 @@ dependencies = [
[[package]]
name = "lance-namespace-impls"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arc-swap",
"arrow",
@@ -5900,8 +5901,8 @@ dependencies = [
[[package]]
name = "lance-select"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5915,8 +5916,8 @@ dependencies = [
[[package]]
name = "lance-table"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow",
"arrow-array",
@@ -5957,8 +5958,8 @@ dependencies = [
[[package]]
name = "lance-testing"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5971,8 +5972,8 @@ dependencies = [
[[package]]
name = "lance-tokenizer"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
version = "15.0.0-beta.17"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127"
dependencies = [
"frostem",
"icu_segmenter",
@@ -5985,7 +5986,7 @@ dependencies = [
[[package]]
name = "lancedb"
version = "0.42.0-beta.10"
version = "0.42.0-beta.11"
dependencies = [
"ahash",
"anyhow",
@@ -6096,7 +6097,7 @@ dependencies = [
[[package]]
name = "lancedb-cli"
version = "0.42.0-beta.10"
version = "0.42.0-beta.11"
dependencies = [
"anyhow",
"arrow-array",
@@ -6139,7 +6140,7 @@ dependencies = [
[[package]]
name = "lancedb-nodejs"
version = "0.42.0-beta.10"
version = "0.42.0-beta.11"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -6164,7 +6165,7 @@ dependencies = [
[[package]]
name = "lancedb-python"
version = "0.42.0-beta.10"
version = "0.42.0-beta.11"
dependencies = [
"arc-swap",
"arrow",
+14 -14
View File
@@ -20,20 +20,20 @@ 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-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.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lancedb = { path = "rust/lancedb", default-features = false }
ahash = "0.8"
anyhow = "1"
+1 -1
View File
@@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`:
<dependency>
<groupId>com.lancedb</groupId>
<artifactId>lancedb-core</artifactId>
<version>0.42.0-beta.10</version>
<version>0.42.0-beta.11</version>
</dependency>
```
+90 -5
View File
@@ -704,6 +704,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`&lt;[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)&gt;
***
### 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`&lt;[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)[]&gt;
***
### functionErrors()
```ts
@@ -1141,11 +1182,26 @@ LanceDB Enterprise it is the server's backfill job.
Refresh options, mirroring the SQL
`REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
`errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
and `initTimeoutSeconds` govern failing rows, and `batchSize`,
`gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker`
size the workers. All are LanceDB Enterprise only; a LanceDB Embedded
refresh rejects every option other than `batchSize`, `gpuClass` and
`gpuCount`.
and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
`maxConcurrency`, `resourceBudget` and
`maxExecutorProcessesPerWorker` size registered Function refreshes.
`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.
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
deployment defaults for CPU and memory, and cannot be combined with
`resourceBudget`. `numWorkers` applies only to expression columns; use
`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
@@ -1156,6 +1212,12 @@ LanceDB Enterprise it is the server's backfill job.
```ts
const job = await table.refreshColumnAsync("embedding", {
where: "published_at > '2026-01-01'",
resourceBudget: {
cpuMillis: 8000,
memoryBytes: 16 * 1024 ** 3,
},
maxConcurrency: 4,
publicationIntervalRows: 10000,
errorPolicy: "skip",
maxFailedFraction: 0.01,
rowTimeoutSeconds: 30,
@@ -1583,3 +1645,26 @@ Waits for asynchronous indexing to complete on the table.
#### Returns
`Promise`&lt;`void`&gt;
***
### 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`&lt;[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)&gt;
+5
View File
@@ -95,10 +95,15 @@
- [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)
- [FunctionWorkerResourceBudget](interfaces/FunctionWorkerResourceBudget.md)
- [HnswPqOptions](interfaces/HnswPqOptions.md)
- [HnswSqOptions](interfaces/HnswSqOptions.md)
- [IndexConfig](interfaces/IndexConfig.md)
@@ -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,39 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / FunctionWorkerResourceBudget
# Interface: FunctionWorkerResourceBudget
Aggregate worker resources for one Enterprise Function refresh.
## Properties
### cpuMillis
```ts
cpuMillis: number;
```
Aggregate CPU budget in millicores; 1000 is one CPU.
***
### gpuCount?
```ts
optional gpuCount: number;
```
Aggregate GPU budget. Omitted means zero, a CPU-only refresh.
***
### memoryBytes
```ts
memoryBytes: number;
```
Aggregate memory budget in bytes.
+10
View File
@@ -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
+37 -1
View File
@@ -8,7 +8,8 @@
Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every
option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores
`batchSize`, `gpuClass` and `gpuCount` and rejects the rest.
`batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including
`resourceBudget`.
## Properties
@@ -63,6 +64,17 @@ Deadline for Function initialization, in seconds.
***
### maxConcurrency?
```ts
optional maxConcurrency: number;
```
Override the registered Function's maximum concurrent user-code calls
for this logical execution.
***
### maxExecutorProcessesPerWorker?
```ts
@@ -105,6 +117,30 @@ Worker count for an expression column; Function columns reject it.
***
### 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
optional resourceBudget: FunctionWorkerResourceBudget;
```
Complete aggregate CPU and memory budget for a registered Function
refresh. `gpuCount` inside the budget defaults to zero.
***
### rowTimeoutSeconds?
```ts
+8
View File
@@ -523,6 +523,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
+18
View File
@@ -78,6 +78,24 @@ Not every agent supports project scope; `npx plugins targets` lists what it
found and what each target supports.
</Accordion>
## Automated prompt catalog {#automated-prompts}
Explore the prompts covered by automated agent evaluations. Each prompt uses
example data and may require existing tables,
indexes, metadata, branches, version history, or running jobs. Replace the test
fixtures and connection details with your own before using a prompt.
The evaluations run against a LanceDB Enterprise test database, with and
without the agent plugin. Evaluation coverage does not guarantee success for
every agent or model.
Prompts are reproduced verbatim, including the answer formats used by automated
grading. Table names, local files, and placeholders in these prompts refer to
test fixtures. Supply your own data, database connection, and timestamps when
adapting them.
{/* agent-eval-catalog */}
## Example prompts {#example-prompts}
These prompts show the kind of work the plugin helps an agent get right on
+4 -3
View File
@@ -49,9 +49,10 @@ tbl = db.open_table("frames") # opens /data/frames.lance; version=N pins a vers
Use `lancedb` for search, retrieval, data curation, multimodal blob access and
application code. Install `pylance` (`import lance`) only when building query
engines or connectors, calling format-level fragment APIs directly, or
converting plain-scan lazy or legacy blob columns with `to_pandas()` (see
[Multimodal data and blobs](/management/table#multimodal) for `pylance`-free
conversions).
converting plain-scan lazy blob handles with `to_pandas()`. Legacy plain-scan
byte conversions use LanceDB's native path without `pylance` (see
[Multimodal data and blobs](/management/table#multimodal) for conversion
boundaries).
| `pylance` (`import lance`) | `lancedb` (`import lancedb`) |
| --- | --- |
+10 -6
View File
@@ -60,6 +60,7 @@ from lancedb import function
@function(
pip=["numpy==2.2.0"],
batch_size=32,
max_concurrency=4,
row_timeout_seconds=90,
)
def score_batch(value: pa.Array) -> pa.Array:
@@ -72,12 +73,15 @@ once a function also does something with real fixed cost per call -- loading
a model, opening a connection, making a network round trip.
`batch_size` caps the number of input rows in each execution batch; actual
batches may be smaller. `row_timeout_seconds` bounds each Python call: one
row for scalar Functions or the entire batch for vectorized Functions. It
does not include the instance's `__init__`. Both settings are fixed into the
registered version and apply to direct calls, computed columns, and
materialized-view refreshes alike. Omit them to use adaptive batching and the
service's default per-call deadline.
batches may be smaller. `max_concurrency` limits user-code calls in flight for
one Function within one logical execution; it does not limit calls across
different jobs and is not an account-wide quota. `row_timeout_seconds` bounds
each Python call: one row for scalar Functions or the entire batch for
vectorized Functions. It does not include the instance's `__init__`. These
settings are fixed into the registered version and apply to direct calls,
computed columns, and materialized-view refreshes alike. A refresh can
override `max_concurrency` for that execution. Omit it to preserve the
existing behavior.
## Stateful Functions: load once, call many times {#stateful}
@@ -60,9 +60,49 @@ columns through `col(...)`, keyed by the output column name. It commits a
new, empty table version the same way a SQL expression does, so the usual
[versioning](/management/table#versioning) applies.
Both a Function application and a SQL expression accept the same
`auto_refresh_enabled` and `auto_refresh_interval_seconds` options, and both
refresh and toggle the same way; see [Auto Refresh](/enterprise/auto-refresh).
Both a Function application and a SQL expression accept
`auto_refresh_enabled` and `auto_refresh_interval_seconds`, and both refresh
and toggle the same way; see [Auto Refresh](/enterprise/auto-refresh).
Python and Rust Function declarations can also set
`auto_refresh_resource_budget` to give their automatic refreshes an aggregate
CPU, memory, and optional GPU budget. CPU and memory are required. The nested
`gpu_count` defaults to zero, so omitting it requests CPU-only workers:
<CodeGroup>
```python Python icon="python"
table.add_columns(
{"caption": version(jpeg=col("jpeg"))},
auto_refresh_resource_budget={
"cpu_millis": 8000,
"memory_bytes": 16 * 1024**3,
},
)
```
```rust Rust icon="rust"
table
.add_columns()
.function(function_application)
.computed_options(ComputedColumnOptions {
auto_refresh_enabled: true,
auto_refresh_interval_seconds: None,
auto_refresh_resource_budget: Some(
FunctionWorkerResourceBudget::new(8000, 17_179_869_184),
),
})
.execute()
.await?;
```
</CodeGroup>
This setting applies to every output in the Function binding. SQL-expression
columns do not use Function workers, so they reject
`auto_refresh_resource_budget` instead of accepting an option that has no
effect. The separate `resource_budget` refresh option configures one explicit
refresh and does not change this automatic-refresh declaration. The Node.js
SDK does not currently expose a Function declaration through `addColumns`, so
this option is not added to an unsupported surface.
## Fill a column with a SQL expression {#expressions}
+169 -7
View File
@@ -150,6 +150,68 @@ 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.
*/}
### Configure workers and resources {#resources}
SQL exposes the worker budget directly, which is the lever when a backfill is
@@ -166,8 +228,97 @@ The resource values cap the Function workers together: this example allows
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.
When setting CPU or memory, supply all three budget fields, using
`gpu_count = 0` for a CPU-only Function.
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:
<CodeGroup>
```python Python icon="python"
job = table.refresh_column_async(
"embedding",
resource_budget={
"cpu_millis": 8000,
"memory_bytes": 16 * 1024**3,
},
)
job.wait()
```
```rust Rust icon="rust"
use lancedb::table::{
FunctionWorkerResourceBudget,
RefreshColumnOptions,
};
let _job = table
.refresh_column_async_with_options(
"embedding",
RefreshColumnOptions::default().resource_budget(
FunctionWorkerResourceBudget::new(8000, 17_179_869_184),
),
)
.await?;
```
```typescript TypeScript icon="typescript"
const job = await table.refreshColumnAsync("embedding", {
resourceBudget: {
cpuMillis: 8000,
memoryBytes: 16 * 1024 ** 3,
},
});
await job.wait();
```
</CodeGroup>
On current SQL servers, the equivalent `REFRESH COLUMN ... WITH (...)` form
still takes all three fields when CPU or memory is set; use `gpu_count = 0`
for a CPU-only Function. The SDK normalizes an omitted nested GPU count to a
numeric zero before sending the request.
The existing top-level `gpu_count` / `gpuCount` option remains the shorthand
for changing only the aggregate GPU budget. It cannot be combined with the
complete resource budget. Omitting both preserves the server's existing
defaults.
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
refreshes. SQL-expression columns reject the automatic resource-budget option
because they do not use Function workers.
To override the registered Function's call concurrency for this logical
execution only:
<CodeGroup>
```python Python icon="python"
job = table.refresh_column_async("embedding", max_concurrency=4)
job.wait()
```
```rust Rust icon="rust"
use lancedb::table::RefreshColumnOptions;
let _job = table
.refresh_column_async_with_options(
"embedding",
RefreshColumnOptions::default().max_concurrency(4),
)
.await?;
```
```typescript TypeScript icon="typescript"
const job = await table.refreshColumnAsync("embedding", {
maxConcurrency: 4,
});
await job.wait();
```
</CodeGroup>
`max_concurrency` caps user-code calls in flight for one Function within one
logical execution. It is not an account-wide quota and does not resize or
rewrite `resource_budget`. Omitting it uses the registration default; a
refresh value overrides that default for this execution only.
`batch_size` caps rows in one Function call; LanceDB adapts actual call and
work sizes. For Function columns, the refresh defaults to
@@ -248,7 +399,8 @@ async fn refresh(
</CodeGroup>
`gpu_count` is the aggregate GPU budget for the refresh's Function workers,
not a request for that many GPUs per worker. It must be positive.
not a request for that many GPUs per worker. It must be positive and preserves
the deployment's CPU and memory defaults.
`gpu_class` must name a class returned by `list_gpu_classes()`; class names
are lowercase DNS labels. Omit either option to use the Function's registered
class or the server's configured budget. `list_gpu_classes()` requires System
@@ -262,8 +414,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"
@@ -274,6 +426,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;
@@ -291,7 +450,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
@@ -341,7 +502,8 @@ The SDK rejects a blank `where`, a `max_failed_fraction` outside 0 to 1, a
timeout that is not a positive number and a zero worker or process count
before sending the request; the server validates everything else. A LanceDB
Embedded refresh rejects every option other than `batch_size`, `gpu_class`
and `gpu_count`.
and `gpu_count`; in particular, it rejects `resource_budget` rather than
silently ignoring it.
## When a refresh fails {#failures}
+10 -4
View File
@@ -107,7 +107,9 @@ single `id` is the SQL query UUID. Repeated waits reuse the completed result.
</CodeBlock>
`create_function` is the blocking equivalent. A registered version is fetched
with `db.get_function(name, version=...)`.
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.
<Note>
The SQL command submits an internal `create_function` image-build job and
@@ -118,9 +120,10 @@ have no registry history and cannot be reopened with `open_job()`.
## List and describe {#list-describe}
`list_functions` pages through every published version in a namespace,
ordered by name then version; `get_function` opens one exact version by
name and `version`. Both take `namespace_path`, defaulting to the root
namespace, the same as `create_function`.
ordered by name then version. `get_function` accepts an integer or string
version, or resolves the latest visible revision when `version` is omitted.
Both take `namespace_path`, defaulting to the root namespace, the same as
`create_function`.
<CodeGroup>
```python Python icon="python"
@@ -128,6 +131,7 @@ for version in db.list_functions():
print(version.name, version.version, version.created_at_millis)
version = db.get_function("double", version="1")
latest = db.get_function("double")
```
```rust
@@ -140,6 +144,7 @@ while let Some(version) = versions.try_next().await? {
}
let version = connection.get_function("double", "1", &[]).await?;
let latest = connection.get_function_latest("double", &[]).await?;
# Ok(())
# }
```
@@ -151,6 +156,7 @@ SHOW FUNCTIONS
SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100)
DESCRIBE FUNCTION double WITH (version = '1')
DESCRIBE FUNCTION double
```
</CodeGroup>
+65 -16
View File
@@ -465,9 +465,11 @@ methods `to_pandas()`, `to_arrow()`, `to_list()`, and `to_batches()` accept a
For supported local v2 blob projections, `to_pandas(blob_mode="bytes")` and
`to_pandas(blob_mode="descriptions")` use native Arrow conversion without
pylance. Pandas conversions that need the Lance scanner, including plain-scan
`"lazy"` handles and legacy blobs, still require pylance. `to_arrow()`,
`to_list()`, `to_batches()`, and the fetch methods do not require pylance.
pylance. Eligible local plain scans also convert row-addressable legacy blob
bytes without pylance. Pandas conversions that need the Lance scanner,
including plain-scan `"lazy"` handles and scanner-only options, still require
pylance. `to_arrow()`, `to_list()`, `to_batches()`, and the fetch methods do
not require pylance for supported local queries.
`blob_mode="bytes"` requires a LanceDB Embedded table snapshot, so Enterprise
and in-memory tables raise `NotImplementedError`. On an Enterprise table,
@@ -477,6 +479,51 @@ 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`.
###### 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:
| Read path | Value |
| --- | --- |
| SQL or an 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. |
For an Enterprise source table, select the rows and fetch their bytes explicitly.
The following example copies up to 100 rows from an existing `images` table with
an integer `id` and a blob `image` column. Keep the source unchanged during this
operation: selection and fetching are separate requests.
```python
import lancedb
import pyarrow as pa
source = db.open_table("images")
hits = (
source.search()
.where("id < 100")
.select(["id"])
.with_row_id(True)
.limit(100)
.to_arrow()
)
payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist()
subset = db.create_table(
"image_subset",
schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]),
)
if hits.num_rows:
subset.add([
{"id": image_id, "image": payload}
for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True)
])
```
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.
`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
@@ -486,10 +533,11 @@ PyArrow.
###### Stream blob results {#multimodal-blob-batches}
`to_batches(blob_mode="bytes")` fetches blob v2 payloads one batch at a time
and returns them as Arrow `large_binary` values. Iterate over the reader and
call `batch.to_pandas()` to convert each batch to a DataFrame without collecting
all payloads at once.
`to_batches(blob_mode="bytes")` fetches row-addressable blob v2 payloads and
eligible local plain-scan legacy v1 payloads one batch at a time and returns
them as Arrow `large_binary` values. Iterate over the reader and call
`batch.to_pandas()` to convert each batch to a DataFrame without collecting all
payloads at once.
For sync queries, call `query.to_batches(batch_size=64, blob_mode="bytes")`
and iterate with `for`. For async queries, call
@@ -497,17 +545,18 @@ and iterate with `for`. For async queries, call
with `async for`. Sync full-text and hybrid queries do not support
`to_batches()`.
The default `"lazy"` mode returns descriptors and keeps automatic `_rowid`
columns visible for manual fetches. `"descriptions"` returns the five-field
descriptors. Both `"bytes"` and `"descriptions"` hide automatic row IDs;
explicitly requested row IDs remain visible.
The default `"lazy"` mode returns blob v2 descriptors and keeps their automatic
`_rowid` columns visible for manual fetches. `"descriptions"` returns the
five-field descriptors. Both `"bytes"` and `"descriptions"` hide automatic row
IDs; explicitly requested row IDs remain visible.
Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`,
including no legacy blobs, blobs inside lists, Enterprise tables, or namespace
`QueryTable` pushdown. If concurrent writers can overwrite the table, use a
separate reader checked out to a fixed version before querying. Otherwise,
an overwrite can invalidate the row IDs used to fetch bytes and raise
`ValueError`.
including no blobs inside lists, Enterprise tables, namespace `QueryTable`
pushdown, or query shapes that cannot preserve their row results. Legacy v1
bytes are limited to eligible local plain scans. 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}
+3 -2
View File
@@ -59,8 +59,9 @@ uv add --prerelease allow --index https://pypi.fury.io/lancedb/ lancedb
Most applications only need `lancedb`. Install the optional `pylance` extra and
include the Lance preview index only when building query engines or connectors,
calling format-level `lance` APIs directly, or converting plain-scan lazy or
legacy blob columns with `to_pandas()`:
calling format-level `lance` APIs directly, or converting plain-scan lazy blob
handles with `to_pandas()`. Legacy plain-scan byte conversions use LanceDB's
native path and do not require `pylance`:
<CodeGroup>
```bash Python (pip) icon="terminal"
+4 -1
View File
@@ -94,9 +94,12 @@ registration handle has type `query` and uses the SQL query UUID as its single
```sql
DESCRIBE FUNCTION embed WITH (version = '1', include_source = true)
DESCRIBE FUNCTION embed
```
DESCRIBE returns one `definition` JSON column for the exact version.
DESCRIBE returns one `definition` JSON column for the exact version. When
`version` is omitted, it resolves and returns the latest currently visible
immutable revision.
`include_source` defaults to false; source-inclusive reads report an omission
when the stored artifact exceeds the inline source limit.
+1 -1
View File
@@ -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.11</version>
<relativePath>../pom.xml</relativePath>
</parent>
+2 -2
View File
@@ -6,7 +6,7 @@
<groupId>com.lancedb</groupId>
<artifactId>lancedb-parent</artifactId>
<version>0.42.0-beta.10</version>
<version>0.42.0-beta.11</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.17</lance-core.version>
<jackson.version>2.18.12</jackson.version>
<spotless.skip>false</spotless.skip>
<spotless.version>2.30.0</spotless.version>
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "lancedb-nodejs"
edition.workspace = true
version = "0.42.0-beta.10"
version = "0.42.0-beta.11"
publish = false
license.workspace = true
description.workspace = true
+237 -1
View File
@@ -647,6 +647,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 +776,8 @@ describe("remote connection", () => {
const job = await table.refreshColumnAsync("embedding", {
where: "id % 2 = 0",
batchSize: 16,
publicationIntervalRows: 60,
maxConcurrency: 3,
gpuClass: "a10g",
gpuCount: 2,
errorPolicy: "skip",
@@ -693,6 +789,37 @@ 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,
memoryBytes: 16 * 1024 ** 3,
},
});
await expect(
table.refreshColumnAsync("embedding", {
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"],
@@ -700,8 +827,99 @@ 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"],
[{ maxConcurrency: 2 ** 32 }, "maxConcurrency"],
[{ maxConcurrency: Number.NaN }, "maxConcurrency"],
[{ maxConcurrency: Number.POSITIVE_INFINITY }, "maxConcurrency"],
[{ numWorkers: 0 }, "num_workers"],
[{ gpuCount: 0 }, "gpu_count"],
[
{
resourceBudget: {
cpuMillis: 1_000,
memoryBytes: 1_024,
},
gpuCount: 1,
},
"gpu_count cannot be combined with resource_budget",
],
[
{
resourceBudget: {
cpuMillis: 0,
memoryBytes: 1_024,
},
},
"resourceBudget.cpuMillis",
],
[
{
resourceBudget: {
cpuMillis: 1_000,
memoryBytes: 1_024,
gpuCount: 1.5,
},
},
"resourceBudget.gpuCount",
],
[
{
resourceBudget: {
cpuMillis: 1_000,
memoryBytes: 1_024,
gpuCount: -1,
},
},
"resourceBudget.gpuCount",
],
[
{
resourceBudget: {
cpuMillis: 1_000,
memoryBytes: 1_024,
gpuCount: 2 ** 32,
},
},
"resourceBudget.gpuCount",
],
[
{
resourceBudget: {
cpuMillis: 1_000,
memoryBytes: 1_024,
gpuCount: Number.NaN,
},
},
"resourceBudget.gpuCount",
],
[
{
resourceBudget: {
cpuMillis: 1_000,
memoryBytes: 1_024,
gpuCount: Number.POSITIVE_INFINITY,
},
},
"resourceBudget.gpuCount",
],
] as const) {
await expect(
table.refreshColumnAsync("embedding", options),
@@ -712,12 +930,30 @@ describe("remote connection", () => {
expect(bodies).toEqual([
JSON.parse(
`{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16,
"gpu_class": "a10g", "gpu_count": 2, "error_policy": "skip",
"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,
"row_timeout_seconds": 30, "init_timeout_seconds": 120,
"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": {
"cpu_millis": 8000,
"memory_bytes": 17179869184,
"gpu_count": 0
}}`,
),
]);
});
+16
View File
@@ -5686,6 +5686,22 @@ 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");
await expect(
table.refreshColumnAsync("x", {
resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 },
}),
).rejects.toThrow("resource_budget requires a LanceDB Enterprise refresh");
});
it("records Function errors only on remote tables", async () => {
+5
View File
@@ -57,6 +57,7 @@ export {
AddResult,
AddColumnsResult,
RefreshColumnOptions,
FunctionWorkerResourceBudget,
RefreshColumnResult,
FunctionErrors,
FunctionErrorsOptions,
@@ -153,6 +154,10 @@ export {
export {
Table,
FunctionColumnAutoRefreshStatus,
FunctionColumnLastRefreshJob,
FunctionColumnStatus,
FunctionColumnVersionStatus,
Branches,
BranchColumnSummary,
BranchColumnChange,
+148 -5
View File
@@ -35,6 +35,7 @@ import {
FunctionErrorsOptions,
IndexConfig,
IndexStatistics,
JobFailureInfo,
Branches as NativeBranches,
OptimizeStats,
RTEStats,
@@ -258,6 +259,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.
*
@@ -722,15 +793,36 @@ export abstract class Table {
* @param {RefreshColumnOptions} options Refresh options, mirroring the SQL
* `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
* `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
* and `initTimeoutSeconds` govern failing rows, and `batchSize`,
* `gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker`
* size the workers. All are LanceDB Enterprise only; a LanceDB Embedded
* refresh rejects every option other than `batchSize`, `gpuClass` and
* `gpuCount`.
* and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
* `maxConcurrency`, `resourceBudget` and
* `maxExecutorProcessesPerWorker` size registered Function refreshes.
* `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.
* 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
* deployment defaults for CPU and memory, and cannot be combined with
* `resourceBudget`. `numWorkers` applies only to expression columns; use
* `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", {
* where: "published_at > '2026-01-01'",
* resourceBudget: {
* cpuMillis: 8000,
* memoryBytes: 16 * 1024 ** 3,
* },
* maxConcurrency: 4,
* publicationIntervalRows: 10000,
* errorPolicy: "skip",
* maxFailedFraction: 0.01,
* rowTimeoutSeconds: 30,
@@ -765,6 +857,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.
*
@@ -1542,6 +1660,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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-darwin-arm64",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.11",
"os": ["darwin"],
"cpu": ["arm64"],
"main": "lancedb.darwin-arm64.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-gnu",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.11",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-musl",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.11",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-gnu",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.11",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-musl",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.11",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-arm64-msvc",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.11",
"os": [
"win32"
],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-x64-msvc",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.11",
"os": ["win32"],
"cpu": ["x64"],
"main": "lancedb.win32-x64-msvc.node",
+1 -1
View File
@@ -11,7 +11,7 @@
"ann"
],
"private": false,
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.11",
"main": "dist/index.js",
"exports": {
".": "./dist/index.js",
+16 -6
View File
@@ -138,12 +138,7 @@ impl Job {
/// Why the job failed, when it failed and the server reports a reason.
#[napi(getter)]
pub fn failure(&self) -> Option<JobFailureInfo> {
self.inner.failure().map(|failure| JobFailureInfo {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
})
self.inner.failure().map(Into::into)
}
/// This job's recorded lifecycle events, as an Arrow IPC stream buffer.
@@ -216,10 +211,25 @@ impl From<lancedb::database::JobInfo> for JobInfo {
/// The server's account of why a job failed.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct JobFailureInfo {
pub phase: Option<String>,
pub message: Option<String>,
/// User-code traceback, possibly truncated by the server.
pub traceback: Option<String>,
pub retryable: Option<bool>,
/// Isolated SQL job that raised this failure, when supplied by the server.
pub sql_job_id: Option<String>,
}
impl From<lancedb::error::JobFailure> for JobFailureInfo {
fn from(failure: lancedb::error::JobFailure) -> Self {
Self {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
sql_job_id: failure.sql_job_id,
}
}
}
+242 -2
View File
@@ -9,7 +9,8 @@ use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema};
use lancedb::table::{
AddDataMode, ColumnAlteration as LanceColumnAlteration,
FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken,
NewColumnTransform, Ref, Table as LanceDbTable,
FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref,
Table as LanceDbTable,
};
use napi::Env;
use napi::bindgen_prelude::*;
@@ -19,6 +20,7 @@ use napi_derive::napi;
use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable};
use crate::error::NapiErrorExt;
use crate::index::Index;
use crate::job::JobFailureInfo;
use crate::merge::NativeMergeInsertBuilder;
use crate::query::{Query, TakeQuery, VectorQuery};
use crate::util::schema_to_buffer;
@@ -533,6 +535,55 @@ impl Table {
Ok(errors.into())
}
#[napi(catch_unwind)]
pub async fn function_column_statuses(
&self,
column: Option<String>,
) -> napi::Result<Vec<FunctionColumnStatus>> {
let statuses = self
.inner_ref()?
.function_column_statuses(column.as_deref())
.await
.default_error()?;
Ok(statuses.into_iter().map(Into::into).collect())
}
#[napi(catch_unwind)]
pub async fn function_column_status(
&self,
column: String,
) -> napi::Result<FunctionColumnStatus> {
let status = self
.inner_ref()?
.function_column_status(&column)
.await
.default_error()?;
Ok(status.into())
}
#[napi(catch_unwind)]
pub async fn wait_for_function_column(
&self,
column: String,
timeout_seconds: Option<i64>,
) -> napi::Result<FunctionColumnStatus> {
let timeout = timeout_seconds
.map(|seconds| {
u64::try_from(seconds)
.map(std::time::Duration::from_secs)
.map_err(|_| {
napi::Error::from_reason("timeoutSeconds must be a non-negative integer")
})
})
.transpose()?;
let status = self
.inner_ref()?
.wait_for_function_column(&column, timeout)
.await
.default_error()?;
Ok(status.into())
}
#[napi(catch_unwind)]
pub async fn refresh_materialized_view(
&self,
@@ -1586,9 +1637,60 @@ pub struct FunctionErrorsOptions {
pub limit: Option<i64>,
}
/// Aggregate worker resources for one Enterprise Function refresh.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionWorkerResourceBudget {
/// Aggregate CPU budget in millicores; 1000 is one CPU.
pub cpu_millis: f64,
/// Aggregate memory budget in bytes.
pub memory_bytes: f64,
/// Aggregate GPU budget. Omitted means zero, a CPU-only refresh.
pub gpu_count: Option<f64>,
}
fn positive_safe_integer(value: f64, name: &str) -> napi::Result<u64> {
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
if !value.is_finite() || value.fract() != 0.0 || !(1.0..=MAX_SAFE_INTEGER).contains(&value) {
return Err(napi::Error::from_reason(format!(
"{name} must be a positive safe integer"
)));
}
Ok(value as u64)
}
fn resource_budget_gpu_count(value: Option<f64>) -> napi::Result<u32> {
let Some(value) = value else {
return Ok(0);
};
if !value.is_finite() || value.fract() != 0.0 || !(0.0..=u32::MAX as f64).contains(&value) {
return Err(napi::Error::from_reason(
"resourceBudget.gpuCount must be an integer between 0 and 4294967295",
));
}
Ok(value as u32)
}
fn positive_u32(value: Option<f64>, name: &str) -> napi::Result<Option<u32>> {
value
.map(|value| {
if !value.is_finite()
|| value.fract() != 0.0
|| !(1.0..=u32::MAX as f64).contains(&value)
{
return Err(napi::Error::from_reason(format!(
"{name} must be an integer between 1 and 4294967295"
)));
}
Ok(value as u32)
})
.transpose()
}
/// Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every
/// option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores
/// `batchSize`, `gpuClass` and `gpuCount` and rejects the rest.
/// `batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including
/// `resourceBudget`.
#[napi(object)]
#[derive(Clone, Debug, Default)]
pub struct RefreshColumnOptions {
@@ -1597,8 +1699,19 @@ pub struct RefreshColumnOptions {
pub where_clause: Option<String>,
/// Maximum rows per Function call; must be greater than zero.
pub batch_size: Option<u32>,
/// 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.
pub publication_interval_rows: Option<f64>,
/// Override the registered Function's maximum concurrent user-code calls
/// for this logical execution.
pub max_concurrency: Option<f64>,
/// GPU class for Function workers.
pub gpu_class: Option<String>,
/// Complete aggregate CPU and memory budget for a registered Function
/// refresh. `gpuCount` inside the budget defaults to zero.
pub resource_budget: Option<FunctionWorkerResourceBudget>,
/// Positive aggregate GPU budget for Function workers.
pub gpu_count: Option<u32>,
/// `"fail"` (default) stops on a row error; `"skip"` writes null and
@@ -1627,7 +1740,24 @@ impl TryFrom<RefreshColumnOptions> for lancedb::table::RefreshColumnOptions {
let mut options = Self::default();
options.where_clause = value.where_clause;
options.batch_size = value.batch_size.map(|size| size as usize);
options.publication_interval_rows = value
.publication_interval_rows
.map(|rows| positive_safe_integer(rows, "publicationIntervalRows"))
.transpose()?;
options.max_concurrency = positive_u32(value.max_concurrency, "maxConcurrency")?;
options.gpu_class = value.gpu_class;
options.resource_budget = value
.resource_budget
.map(|budget| {
Ok::<_, napi::Error>(
LanceFunctionWorkerResourceBudget::new(
positive_safe_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?,
positive_safe_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?,
)
.with_gpu_count(resource_budget_gpu_count(budget.gpu_count)?),
)
})
.transpose()?;
options.gpu_count = value.gpu_count;
options.error_policy = match value.error_policy.as_deref() {
None => None,
@@ -1728,6 +1858,116 @@ pub struct FunctionErrors {
pub truncated: bool,
}
/// One exact immutable Function revision attached to a table output.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnVersionStatus {
pub name: String,
pub namespace_path: Vec<String>,
pub object_id: String,
pub location: String,
pub version: String,
pub manifest_digest: String,
}
/// Latest matching refresh Job projected for a Function output.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnLastRefreshJob {
pub job_id: String,
pub state: String,
pub automatic: Option<bool>,
pub completed_at_millis: Option<BigInt>,
pub failure: Option<JobFailureInfo>,
}
impl From<lancedb::table::FunctionColumnLastRefreshJob> for FunctionColumnLastRefreshJob {
fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self {
Self {
job_id: job.job_id,
state: job.state,
automatic: job.automatic,
completed_at_millis: job.completed_at_millis.map(BigInt::from),
failure: job.failure.map(Into::into),
}
}
}
/// Automatic-refresh projection for a Function output.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnAutoRefreshStatus {
pub enabled: bool,
pub interval_seconds: Option<BigInt>,
pub active_job_id: Option<String>,
pub state: String,
pub failure_streak: u32,
pub effective_cooldown_millis: Option<BigInt>,
pub blocked_reason: Option<String>,
pub next_run_at_millis: Option<BigInt>,
pub next_run_at_reason: Option<String>,
}
/// Exact four-way status of one Function output at one table version.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnStatus {
pub column: String,
pub binding_id: String,
pub function: FunctionColumnVersionStatus,
pub table_version: BigInt,
pub rows: BigInt,
pub fresh: BigInt,
pub stale: BigInt,
pub never_computed: BigInt,
pub failed: BigInt,
pub last_refresh_job: Option<FunctionColumnLastRefreshJob>,
pub last_failure_job: Option<FunctionColumnLastRefreshJob>,
pub auto_refresh: FunctionColumnAutoRefreshStatus,
}
impl From<lancedb::table::FunctionColumnStatus> for FunctionColumnStatus {
fn from(status: lancedb::table::FunctionColumnStatus) -> Self {
Self {
column: status.column,
binding_id: status.binding_id,
function: FunctionColumnVersionStatus {
name: status.function.name,
namespace_path: status.function.namespace_path,
object_id: status.function.object_id,
location: status.function.location,
version: status.function.version,
manifest_digest: status.function.manifest_digest,
},
table_version: BigInt::from(status.table_version),
rows: BigInt::from(status.rows),
fresh: BigInt::from(status.fresh),
stale: BigInt::from(status.stale),
never_computed: BigInt::from(status.never_computed),
failed: BigInt::from(status.failed),
last_refresh_job: status.last_refresh_job.map(Into::into),
last_failure_job: status.last_failure_job.map(Into::into),
auto_refresh: FunctionColumnAutoRefreshStatus {
enabled: status.auto_refresh.enabled,
interval_seconds: status.auto_refresh.interval_seconds.map(BigInt::from),
active_job_id: status.auto_refresh.active_job_id,
state: status.auto_refresh.state.as_str().to_string(),
failure_streak: status.auto_refresh.failure_streak,
effective_cooldown_millis: status
.auto_refresh
.effective_cooldown_millis
.map(BigInt::from),
blocked_reason: status
.auto_refresh
.blocked_reason
.map(|reason| reason.as_str().to_string()),
next_run_at_millis: status.auto_refresh.next_run_at_millis.map(BigInt::from),
next_run_at_reason: status.auto_refresh.next_run_at_reason,
},
}
}
}
impl From<lancedb::function::FunctionErrors> for FunctionErrors {
fn from(errors: lancedb::function::FunctionErrors) -> Self {
Self {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.42.0-beta.10"
version = "0.42.0-beta.11"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
+1 -1
View File
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.0.0b16",
"pylance==15.0.0b17",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+14
View File
@@ -17,6 +17,16 @@ __version__ = str(_Version(_native_version))
from ._lancedb import connect as lancedb_connect
from ._lancedb import FtsToken
from ._lancedb import (
FunctionColumnAutoRefreshStatus as FunctionColumnAutoRefreshStatus,
)
from ._lancedb import (
FunctionColumnLastRefreshJob as FunctionColumnLastRefreshJob,
)
from ._lancedb import FunctionColumnStatus as FunctionColumnStatus
from ._lancedb import (
FunctionColumnVersionStatus as FunctionColumnVersionStatus,
)
from ._lancedb import FunctionErrorFragment as FunctionErrorFragment
from ._lancedb import FunctionErrorRecord as FunctionErrorRecord
from ._lancedb import FunctionErrors as FunctionErrors
@@ -660,6 +670,10 @@ __all__ = [
"AsyncTable",
"CompactionOptions",
"FtsToken",
"FunctionColumnAutoRefreshStatus",
"FunctionColumnLastRefreshJob",
"FunctionColumnStatus",
"FunctionColumnVersionStatus",
"col",
"Expr",
"func",
+30 -6
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Blob fetch API and v2 projection helpers."""
"""Blob fetch API and projection helpers."""
from __future__ import annotations
@@ -13,7 +13,11 @@ from typing import TYPE_CHECKING, Optional, Union
import pyarrow as pa
from .expr import Expr
from .schema import blob_column_paths, row_addressable_blob_v2_paths
from .schema import (
blob_column_paths,
row_addressable_blob_paths,
row_addressable_blob_v2_paths,
)
from .types import BlobMode, QueryProjection, QueryProjectionSpec
if TYPE_CHECKING:
@@ -165,6 +169,25 @@ def blob_v2_projection_sources(
return _project_blob_paths(row_addressable_blob_v2_paths(schema), projection)
def blob_projection_sources(
schema: pa.Schema,
projection: QueryProjection,
*,
include_legacy: bool = False,
) -> dict[str, str]:
"""Map projected blob outputs to row-addressable source columns.
Legacy v1 columns are included only when the caller can safely fetch them
through the same row-id path as v2.
"""
paths = (
row_addressable_blob_paths(schema)
if include_legacy
else row_addressable_blob_v2_paths(schema)
)
return _project_blob_paths(paths, projection)
def reject_unfetchable_blob_columns(
schema: pa.Schema, projection: QueryProjection, blob_sources: dict[str, str]
) -> None:
@@ -177,8 +200,9 @@ def reject_unfetchable_blob_columns(
if unfetchable:
raise ValueError(
f"blob_mode='bytes' cannot fetch blob columns {unfetchable}. Bytes are "
"fetched by row id, which covers blob v2 columns with one blob per "
"row but not legacy blob columns or blobs inside lists. Use "
"fetched by row id for legacy and v2 columns in local plain scans, "
"but not for blobs inside lists or query shapes whose result columns "
"cannot be matched back to the source. Use "
"blob_mode='descriptions' or remove these columns from the projection."
)
@@ -269,7 +293,7 @@ def finalize_blob_query_table(
return stash_auto_row_ids(tbl, blob_paths)
async def replace_v2_blob_columns_with_bytes(
async def replace_blob_columns_with_bytes(
tbl: pa.Table,
blob_sources: dict[str, str],
fetch_blobs: FetchBlobsAsync,
@@ -289,7 +313,7 @@ async def replace_v2_blob_columns_with_bytes(
return tbl
def replace_v2_blob_columns_with_bytes_sync(
def replace_blob_columns_with_bytes_sync(
tbl: pa.Table,
blob_sources: dict[str, str],
fetch_blobs: FetchBlobsSync,
+65 -1
View File
@@ -25,6 +25,7 @@ from .index import (
LabelList,
Fm,
NGram,
ZoneMap,
HnswPq,
HnswSq,
HnswFlat,
@@ -189,7 +190,10 @@ class Connection(object):
self, request_json: str, namespace_path: Optional[List[str]] = None
) -> Job: ...
async def get_function(
self, name: str, version: str, namespace_path: Optional[List[str]] = None
self,
name: str,
version: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
) -> str: ...
def list_functions(
self,
@@ -408,6 +412,7 @@ class Job:
) -> Optional[str]: ...
async def cancel(self) -> None: ...
async def refresh(self) -> None: ...
async def timeline(self) -> str: ...
async def events(
self,
*,
@@ -501,6 +506,8 @@ class JobDescription:
class SqlQuery:
@property
def id(self) -> UUID: ...
@property
def job_id(self) -> Optional[str]: ...
async def describe(self) -> QueryDescription: ...
async def reader(self) -> RecordBatchStream: ...
async def cancel(self) -> None: ...
@@ -509,6 +516,8 @@ class QueryDescription:
@property
def id(self) -> UUID: ...
@property
def job_id(self) -> Optional[str]: ...
@property
def status(self) -> str: ...
@property
def progress(self) -> Optional[float]: ...
@@ -549,6 +558,7 @@ class Table:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
],
replace: Optional[bool],
@@ -572,6 +582,7 @@ class Table:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
],
replace: Optional[bool],
@@ -605,6 +616,7 @@ class Table:
columns: list[tuple[str, str]],
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[int] = None,
auto_refresh_resource_budget: Optional[dict[str, int]] = None,
) -> AddColumnsResult: ...
async def add_function_columns(
self,
@@ -612,6 +624,7 @@ class Table:
output_name: Optional[str],
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[int] = None,
auto_refresh_resource_budget: Optional[dict[str, int]] = None,
) -> AddColumnsResult: ...
async def refresh_column(
self,
@@ -619,7 +632,9 @@ class Table:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
@@ -637,7 +652,9 @@ class Table:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
@@ -655,6 +672,13 @@ class Table:
column: Optional[str] = None,
limit: Optional[int] = None,
) -> FunctionErrors: ...
async def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]: ...
async def column_status(self, column: str) -> FunctionColumnStatus: ...
async def wait_column_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus: ...
async def refresh_materialized_view(
self,
source_version: Optional[int] = None,
@@ -1072,6 +1096,46 @@ class FunctionErrors:
fragments: list[FunctionErrorFragment]
truncated: bool
class FunctionColumnVersionStatus:
name: str
namespace_path: list[str]
object_id: str
location: str
version: str
manifest_digest: str
class FunctionColumnLastRefreshJob:
job_id: str
state: str
automatic: Optional[bool]
completed_at_millis: Optional[int]
failure: Optional[JobFailureInfo]
class FunctionColumnAutoRefreshStatus:
enabled: bool
interval_seconds: Optional[int]
active_job_id: Optional[str]
state: str
failure_streak: int
effective_cooldown_millis: Optional[int]
blocked_reason: Optional[str]
next_run_at_millis: Optional[int]
next_run_at_reason: Optional[str]
class FunctionColumnStatus:
column: str
binding_id: str
function: FunctionColumnVersionStatus
table_version: int
rows: int
fresh: int
stale: int
never_computed: int
failed: int
last_refresh_job: Optional[FunctionColumnLastRefreshJob]
last_failure_job: Optional[FunctionColumnLastRefreshJob]
auto_refresh: FunctionColumnAutoRefreshStatus
class RefreshMaterializedViewResult:
@staticmethod
def from_json(value: str) -> RefreshMaterializedViewResult: ...
+40 -7
View File
@@ -140,6 +140,18 @@ def _view_description(
)
def _normalize_function_version(version: Optional[Union[int, str]]) -> Optional[str]:
if version is None:
return None
if isinstance(version, bool):
raise TypeError("version must be an int, str, or None")
if isinstance(version, int):
return str(version)
if isinstance(version, str):
return version
raise TypeError("version must be an int, str, or None")
class DBConnection(EnforceOverrides):
"""An active LanceDB connection interface.
@@ -1027,10 +1039,15 @@ class DBConnection(EnforceOverrides):
self,
name: str,
*,
version: str,
version: Optional[Union[int, str]] = None,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
"""Open one exact immutable Function version from the remote catalog."""
"""Open an immutable Function version from the remote catalog.
``version`` may be an integer or string. When omitted, the server
resolves the latest currently visible revision and returns that exact
immutable version.
"""
raise NotImplementedError(
_append_doc_url(
"Function catalog operations are not supported "
@@ -1515,7 +1532,10 @@ class DBConnection(EnforceOverrides):
This submits through :meth:`execute_query_async` and waits until the
initial result stream is readable. It does not wait for the full query
to finish.
to finish. A statement that ran as a server-side SQL job exposes the
durable Job Registry id in the reader schema metadata under
``x-lancedb-sql-job-id``. Use :meth:`execute_query_async` when the
query handle itself is needed.
"""
return self.execute_query_async(
query,
@@ -1554,6 +1574,9 @@ class DBConnection(EnforceOverrides):
stops a directly streamed query; deferred execution requires explicit
cancellation. Open ``reader()`` directly: a streamed query needs its
reader to make progress and reports ``running`` until the stream ends.
Once a server-side SQL job exists, ``describe().job_id`` exposes its
durable Job Registry id while the query is still running. This is
separate from the connection-scoped query ``id``.
LanceDB Embedded connections do not support SQL.
"""
@@ -2304,9 +2327,10 @@ class LanceDBConnection(DBConnection):
self,
name: str,
*,
version: str,
version: Optional[Union[int, str]] = None,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
version = _normalize_function_version(version)
return LOOP.run(
self._conn.get_function(
name, version=version, namespace_path=namespace_path
@@ -3604,10 +3628,16 @@ class AsyncConnection(object):
self,
name: str,
*,
version: str,
version: Optional[Union[int, str]] = None,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
"""Open one exact immutable Function version from the remote catalog."""
"""Open an immutable Function version from the remote catalog.
``version`` may be an integer or string. When omitted, the server
resolves the latest currently visible revision and returns that exact
immutable version.
"""
version = _normalize_function_version(version)
return FunctionVersion.from_json(
await self._inner.get_function(name, version, namespace_path)
)
@@ -4128,7 +4158,10 @@ class AsyncConnection(object):
This submits through :meth:`execute_query_async` and waits until the
initial result stream is readable. It does not wait for the full query
to finish.
to finish. A statement that ran as a server-side SQL job exposes the
durable Job Registry id in the reader schema metadata under
``x-lancedb-sql-job-id``. Use :meth:`execute_query_async` when the
query handle itself is needed.
"""
submitted = await self.execute_query_async(
query,
+47 -9
View File
@@ -97,6 +97,16 @@ def _validate_batch_size(value: Any) -> Optional[int]:
return value
def _validate_max_concurrency(value: Any) -> Optional[int]:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError("max_concurrency must be an integer")
if not 1 <= value <= 2**32 - 1:
raise ValueError("max_concurrency must be between 1 and 4294967295")
return value
def _validate_row_timeout(value: Any) -> Optional[float]:
if value is None:
return None
@@ -529,9 +539,10 @@ class FunctionVersion(_RemoteValue):
``gpu_class`` is the operator-defined GPU pool fixed into this Function
version, or ``None`` when registration used the deployment default.
``batch_size``, ``row_timeout_seconds``, and ``result_stability`` retain
the execution controls reported by the catalog. They are ``None`` for
versions registered before the corresponding declaration.
``batch_size``, ``max_concurrency``, ``row_timeout_seconds``, and
``result_stability`` retain the execution controls reported by the
catalog. They are ``None`` for versions registered before the
corresponding declaration.
"""
name: str
@@ -548,6 +559,7 @@ class FunctionVersion(_RemoteValue):
disabled: bool
gpu_class: Optional[str] = None
batch_size: Optional[int] = None
max_concurrency: Optional[int] = None
row_timeout_seconds: Optional[float] = None
result_stability: Optional[str] = None
@@ -556,6 +568,11 @@ class FunctionVersion(_RemoteValue):
def _validate_batch_size(cls, value):
return _validate_batch_size(value)
@field_validator("max_concurrency", mode="before")
@classmethod
def _validate_max_concurrency(cls, value):
return _validate_max_concurrency(value)
@field_validator("row_timeout_seconds", mode="before")
@classmethod
def _validate_row_timeout(cls, value):
@@ -691,6 +708,7 @@ class FunctionRegistrationRequest(_RemoteValue):
signature: FunctionSignature
runtime: PythonRuntimeSpec
batch_size: Optional[int] = None
max_concurrency: Optional[int] = None
row_timeout_seconds: Optional[float] = None
retry_policy: Optional[FunctionRetryPolicy] = None
secret_bindings: tuple[SecretBinding, ...] = ()
@@ -701,6 +719,11 @@ class FunctionRegistrationRequest(_RemoteValue):
def _validate_batch_size(cls, value):
return _validate_batch_size(value)
@field_validator("max_concurrency", mode="before")
@classmethod
def _validate_max_concurrency(cls, value):
return _validate_max_concurrency(value)
@field_validator("row_timeout_seconds", mode="before")
@classmethod
def _validate_row_timeout(cls, value):
@@ -1428,19 +1451,21 @@ def _is_function_decorator(node: ast.expr) -> bool:
)
def _literal_source(value: Any) -> str:
def _literal_source(value: Any, name: str) -> str:
if value is None or type(value) in (bool, int, str, bytes):
return repr(value)
if type(value) is float and math.isfinite(value):
return repr(value)
if type(value) is tuple:
children = ", ".join(_literal_source(child) for child in value)
children = ", ".join(_literal_source(child, name) for child in value)
if len(value) == 1:
children += ","
return f"({children})"
raise TypeError(
"Function source references an unsupported global value of type "
f"{type(value).__name__}"
f"{type(value).__name__} in {name!r}. Only None, bool, int, str, bytes, "
"finite float, and tuples of these literals can be captured. "
"Define this value inside the function or class body instead."
)
@@ -1875,7 +1900,7 @@ class _SourcePackager:
if imported is value:
self._require_importable(module_name)
return f"from {module_name} import {qualname} as {name}"
return f"{name} = {_literal_source(value)}"
return f"{name} = {_literal_source(value, name)}"
def _require_importable(self, module_name: str) -> None:
"""Warn about an import the Function's environment may not be able to
@@ -2161,6 +2186,7 @@ class FunctionDefinition:
env: Mapping[str, str],
python_version: Optional[str],
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
row_timeout_seconds: Optional[float] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
gpu: bool = False,
@@ -2308,6 +2334,7 @@ class FunctionDefinition:
signature=signature,
runtime=runtime,
batch_size=batch_size,
max_concurrency=max_concurrency,
row_timeout_seconds=row_timeout_seconds,
retry_policy=retry_policy,
models=models,
@@ -2406,6 +2433,7 @@ def function(
env: Optional[Mapping[str, str]] = None,
python_version: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
row_timeout_seconds: Optional[float] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
gpu: bool = False,
@@ -2429,6 +2457,7 @@ def function(
env: Optional[Mapping[str, str]] = None,
python_version: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
row_timeout_seconds: Optional[float] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
gpu: bool = False,
@@ -2486,8 +2515,8 @@ def function(
- modules, and classes and functions importable from an installed
package, become imports; the package must be declared in ``pip`` or
``conda``;
- literals (``None``, booleans, numbers, strings, bytes, tuples of them)
are inlined;
- literals (``None``, ``bool``, ``int``, ``str``, ``bytes``, finite
``float``, and tuples containing only these literals) are inlined;
- functions and classes defined in ``__main__``, such as notebook cells,
are packaged by source, together with what they reference;
- modules and packages listed in ``code`` are shipped as Python source and
@@ -2505,6 +2534,9 @@ def function(
image. Warnings follow normal Python warning filters and may be promoted
to errors. Declare every third-party import in ``pip`` or ``conda`` even
when it happens to be installed on the registration host.
Other global values, including Arrow types and schemas, lists, dictionaries,
sets, and NumPy arrays, cannot be captured as literals. Define them inside
the function or class body instead.
Closures, lambdas, nested definitions, mutable module-level
objects, code that reaches the module namespace another way
(``globals()``/``eval``, ``sys.modules``, ``builtins``), and a
@@ -2559,6 +2591,11 @@ def function(
Maximum number of input rows supplied in one execution batch. Must be
between 1 and 4294967295. Remote execution may use smaller batches.
When omitted, the service chooses the batch size adaptively.
max_concurrency : int, optional
Maximum user-code calls in flight for one Function within one logical
execution. Must be between 1 and 4294967295. A refresh can override
this default for that execution only. Omitting it preserves the
existing behavior. This is not an account-wide quota.
row_timeout_seconds : float, optional
Positive, finite deadline in seconds for each Python call: one row for
scalar Functions and one batch for vectorized Functions. This does not
@@ -2695,6 +2732,7 @@ def function(
env={} if env is None else env,
python_version=python_version,
batch_size=batch_size,
max_concurrency=max_concurrency,
row_timeout_seconds=row_timeout_seconds,
retry_policy=retry_policy,
gpu=gpu,
+17
View File
@@ -130,6 +130,23 @@ class NGram:
pass
@dataclass
class ZoneMap:
"""Describe a ZoneMap index configuration.
A `ZoneMap` index stores compact min and max summaries for contiguous
ranges (zones) of rows. During a scan it skips any zone whose summary
cannot satisfy the predicate, so it accelerates range and equality
filters such as `col > 10`, `col BETWEEN a AND b`, and `col = x`,
without changing the results.
It suits large numeric or temporal columns whose values are correlated
with row order (for example `timestamp`, `price`, `id`).
"""
pass
@dataclass
class FTS:
"""Describe a FTS index configuration.
+64 -15
View File
@@ -4,9 +4,11 @@
"""Handles to asynchronous registry jobs, SQL queries, and local operations."""
import asyncio
import json
import reprlib
import time
from datetime import timedelta
from os import PathLike
from pathlib import Path
from typing import Any, Callable, Generic, Optional, TypeVar, cast
import pyarrow as pa
@@ -422,6 +424,31 @@ class AsyncJob(Generic[T]):
description = self._inner._description if self._inner is not None else None
return getattr(description, name) if description is not None else None
async def export_timeline(self, path: str | PathLike[str]) -> None:
"""Write a fresh recorded Function job timeline as Chrome trace JSON.
Open the file in Perfetto or Chrome tracing. The recording contains
retained split spans grouped by worker and timestamped job phases.
Batch counts and latency statistics are included as details; individual
batch timestamps are not recorded. Running jobs export a partial snapshot
without waiting or cancelling. Download again to include later work.
Requires a server-side Function job and a server supporting timeline
export. Unsupported operations raise ``NotImplementedError`` or a server
error. The destination is overwritten only after the trace is fetched.
Filesystem errors propagate to the caller.
Examples
--------
>>> await job.export_timeline("refresh.trace.json") # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"job timeline export requires a server-side Function job"
)
trace = await self._inner.timeline()
await asyncio.to_thread(Path(path).write_text, trace, encoding="utf-8")
async def events(
self,
*,
@@ -461,43 +488,49 @@ class AsyncJob(Generic[T]):
_REPR_INDENT = " " * 4
_REPR_MAX_FIELD_LENGTH = 240
_PAYLOAD_REPR = reprlib.Repr()
_PAYLOAD_REPR.maxlevel = 2
_PAYLOAD_REPR.maxdict = 4
_PAYLOAD_REPR.maxlist = 4
_PAYLOAD_REPR.maxtuple = 4
_PAYLOAD_REPR.maxstring = 120
_PAYLOAD_REPR.maxother = 120
def _repr_payload(value: Any) -> str:
"""Render a job payload as indented JSON, aligned under its field."""
try:
rendered = json.dumps(value, indent=4)
except TypeError:
return repr(value)
return rendered.replace("\n", "\n" + _REPR_INDENT)
"""Bound nested payload previews without changing the stored values."""
rendered = _PAYLOAD_REPR.repr(value).replace("\n", "\\n")
if len(rendered) > _REPR_MAX_FIELD_LENGTH:
return rendered[: _REPR_MAX_FIELD_LENGTH - 3] + "..."
return rendered
def _job_repr(kind: str, job: Any) -> str:
"""Render every field the handle currently knows, omitting the rest.
"""Show cached job identity and bounded previews without backend calls.
One field per line, with the JSON payloads indented, because a refresh
job's spec and result are the point of printing it.
The complete payloads remain available through ``spec`` and ``result``.
"""
state = job.state
if state is None:
# Nothing has been fetched yet, so there is nothing to lay out.
known = f"id={job.id!r}, " if job.id is not None else ""
known = f"id={_repr_payload(job.id)}, " if job.id is not None else ""
return f"{kind}({known}not refreshed)"
fields = []
if job.id is not None:
fields.append(f"id={job.id!r}")
fields.append(f"state={state!r}")
fields.append(f"id={_repr_payload(job.id)}")
fields.append(f"state={_repr_payload(state)}")
for name in ("job_type", "creation_ms"):
value = getattr(job, name)
if value is not None:
fields.append(f"{name}={value!r}")
fields.append(f"{name}={_repr_payload(value)}")
for name in ("spec", "result"):
value = getattr(job, name)
if value is not None:
fields.append(f"{name}={_repr_payload(value)}")
if job.failure is not None:
fields.append(f"failure={job.failure!r}")
fields.append(f"failure={_repr_payload(job.failure)}")
body = "".join(f"\n{_REPR_INDENT}{field}," for field in fields)
return f"{kind}({body}\n)"
@@ -615,6 +648,22 @@ class Job(Generic[T]):
def _field(self, name: str) -> Optional[Any]:
return getattr(self._inner, name) if self._inner is not None else None
def export_timeline(self, path: str | PathLike[str]) -> None:
"""Write Chrome trace JSON for this Function job.
See :meth:`AsyncJob.export_timeline`. Open the file in Perfetto or
Chrome tracing.
Examples
--------
>>> job.export_timeline("refresh.trace.json") # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"job timeline export requires a server-side Function job"
)
return LOOP.run(self._inner.export_timeline(path))
def events(
self,
*,
+187 -77
View File
@@ -48,12 +48,13 @@ from ._blob import (
FetchBlobsAsync,
FetchBlobsSync,
blob_auto_row_id_for_scan,
blob_projection_sources,
blob_v2_projection_sources,
finalize_blob_query_table,
reject_unfetchable_blob_columns,
reject_unmatched_blob_outputs,
replace_v2_blob_columns_with_bytes,
replace_v2_blob_columns_with_bytes_sync,
replace_blob_columns_with_bytes,
replace_blob_columns_with_bytes_sync,
strip_auto_row_ids,
validate_blob_mode,
)
@@ -206,7 +207,10 @@ def _blob_bytes_without_snapshot_error() -> NotImplementedError:
"blob_mode='bytes' cannot safely materialize blob columns without a "
"stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown "
"run the query on a server, so the blob fetch could read another table "
"version. Use blob_mode='descriptions'."
"version. Use blob_mode='descriptions' to inspect descriptors. To read "
"payloads, select row IDs with with_row_id(True), then call "
"table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, "
"row_ids). Keep the source unchanged between selection and fetching."
)
@@ -242,6 +246,17 @@ def _query_is_plain_scan(query: Query) -> bool:
)
def _query_is_plain_blob_scan(query: Query) -> bool:
"""Whether native batch conversion can preserve this query's row result."""
return (
query.vector is None
and query.full_text_query is None
and query.take_offsets is None
and query.take_row_ids is None
and not query.postfilter
)
def _filter_to_sql(filter: Optional[Union[str, Expr]]) -> Optional[str]:
if filter is None:
return None
@@ -418,7 +433,7 @@ def _finish_plain_scan_pandas(
) -> pd.DataFrame:
if blob_sources:
tbl = _scanner_to_table(scanner)
tbl = replace_v2_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
tbl = replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
if strip_auto_row_id and "_rowid" in tbl.column_names:
tbl = tbl.drop_columns(["_rowid"])
if flatten is not None:
@@ -453,7 +468,10 @@ def _finish_remote_pandas(
raise NotImplementedError(
f"remote to_pandas(blob_mode={blob_mode!r}) cannot safely materialize "
"blob columns without a stable table snapshot; "
"use blob_mode='descriptions'"
"use blob_mode='descriptions' to inspect descriptors. To read payloads, "
"select row IDs with with_row_id(True), then call "
"table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, "
"row_ids). Keep the source unchanged between selection and fetching."
)
@@ -469,7 +487,7 @@ async def _finish_plain_scan_pandas_async(
) -> pd.DataFrame:
if blob_sources:
tbl = _scanner_to_table(scanner)
tbl = await replace_v2_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
tbl = await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
if strip_auto_row_id and "_rowid" in tbl.column_names:
tbl = tbl.drop_columns(["_rowid"])
if flatten is not None:
@@ -1275,10 +1293,10 @@ class LanceQueryBuilder(ABC):
blob_mode: str, default "lazy"
Controls how blob columns are returned. Local blob v2 queries support
``"bytes"`` and ``"descriptions"`` without pylance. Eligible local
plain scans use pylance's scanner for lazy blob handles in ``"lazy"``
mode and for legacy blob columns. Other local blob v2
queries return descriptors in ``"lazy"`` and ``"descriptions"``
modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
plain scans also support ``"bytes"`` for row-addressable legacy blob
columns without pylance. Other local blob v2 queries return
descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
in ``"bytes"`` mode, through :meth:`to_arrow`.
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
@@ -1346,8 +1364,8 @@ class LanceQueryBuilder(ABC):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
"""
raise NotImplementedError
@@ -1364,7 +1382,7 @@ class LanceQueryBuilder(ABC):
Execute the query and return the results as a pyarrow
[RecordBatchReader](https://arrow.apache.org/docs/python/generated/pyarrow.RecordBatchReader.html)
For v2 blob projections, the default ``blob_mode="lazy"`` keeps the
For blob v2 projections, the default ``blob_mode="lazy"`` keeps the
auto ``_rowid`` column visible so batch consumers can call
``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide
automatic row ids.
@@ -1384,10 +1402,11 @@ class LanceQueryBuilder(ABC):
The timeout also covers reading the batches, so consuming them
slowly can exceed it.
blob_mode: str, default "lazy"
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
payloads one batch at a time, without requiring pylance. Bytes mode
has the same restrictions as :meth:`to_arrow`.
``"lazy"`` keeps blob v2 descriptors and auto row ids for manual
fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches
supported row-addressable blob payloads one batch at a time, without
requiring pylance. Bytes mode has the same restrictions as
:meth:`to_arrow`.
Examples
--------
@@ -1593,20 +1612,41 @@ class LanceQueryBuilder(ABC):
def _scan_needs_row_id(self) -> bool:
return self._user_requested_row_id() or self._blob_auto_row_id_enabled()
def _query_for_scan(self) -> Query:
def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query:
query = self.to_query_object()
if self._scan_needs_row_id():
if self._scan_needs_row_id() or blob_sources:
query.with_row_id = True
return query
def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
if blob_mode != "bytes":
return False
try:
query = self.to_query_object()
except NotImplementedError:
return False
return (
_query_is_plain_blob_scan(query)
and getattr(self, "_reranker", None) is None
and not _query_needs_lance_scanner(self)
and _supports_local_blob_fetch(
self._table._table,
getattr(self._table, "_pushdown_operations", ()),
)
)
def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
"""Map projected blob v2 outputs to their source columns.
"""Map projected blob outputs to their source columns.
Bytes mode is checked here, before the query runs.
"""
validate_blob_mode(blob_mode)
schema = self._table.schema
blob_sources = blob_v2_projection_sources(schema, self._columns)
blob_sources = blob_projection_sources(
schema,
self._columns,
include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode),
)
if blob_mode != "bytes":
return blob_sources
reject_unfetchable_blob_columns(schema, self._columns, blob_sources)
@@ -1627,7 +1667,7 @@ class LanceQueryBuilder(ABC):
return tbl
if blob_mode == "descriptions":
return strip_auto_row_ids(tbl, blob_sources)
return replace_v2_blob_columns_with_bytes_sync(
return replace_blob_columns_with_bytes_sync(
tbl, blob_sources, self._table.fetch_blobs
)
@@ -1639,18 +1679,23 @@ class LanceQueryBuilder(ABC):
blob_sources: dict[str, str],
) -> pa.Table:
blob_auto_row_id = self._blob_auto_row_id_enabled()
finalized = finalize_blob_query_table(
tbl,
user_requested_row_id=self._user_requested_row_id(),
blob_auto_row_id=blob_auto_row_id,
blob_paths=blob_sources.keys() if blob_auto_row_id else (),
)
if blob_mode == "bytes" and blob_sources:
# Bytes conversion reads _rowid directly, including when the
# projection mixes legacy and v2 columns.
finalized = tbl
else:
finalized = finalize_blob_query_table(
tbl,
user_requested_row_id=self._user_requested_row_id(),
blob_auto_row_id=blob_auto_row_id,
blob_paths=blob_sources.keys() if blob_auto_row_id else (),
)
finalized = self._apply_arrow_blob_mode(finalized, blob_mode, blob_sources)
# with_row_id(False) does not reach the scan, which adds _rowid anyway.
# Lazy keeps it because fetch_blobs(hits) reads it there.
if (
blob_mode != "lazy"
and self._with_row_id is False
and not self._user_requested_row_id()
and "_rowid" in finalized.column_names
):
finalized = finalized.drop_columns(["_rowid"])
@@ -1890,18 +1935,29 @@ class LanceQueryBuilder(ABC):
query = self.to_query_object()
if not _query_is_plain_scan(query):
return None
blob_sources = (
blob_projection_sources(
self._table.schema,
query.columns,
include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode),
)
if blob_mode == "bytes"
else {}
)
# Remote and in-memory tables have no Lance dataset to scan.
if not self._table._table._inner._is_native() or (
get_uri_scheme(self._table._dataset_path) == "memory"
):
return None
# Blob v2 payloads and descriptions use LanceDB's native fetch path.
# Only lazy handles, legacy blobs, and scanner-only options need pylance.
if (
blob_mode != "lazy"
and not _query_needs_lance_scanner(self)
and blob_v2_projection_sources(self._table.schema, query.columns)
# Bytes conversions use LanceDB's fetch path for both blob versions.
# Descriptions for v2 do too; lazy handles still need the scanner.
if not _query_needs_lance_scanner(self) and (
(blob_mode == "bytes" and blob_sources)
or (
blob_mode == "descriptions"
and blob_v2_projection_sources(self._table.schema, query.columns)
)
):
return None
try:
@@ -1909,12 +1965,7 @@ class LanceQueryBuilder(ABC):
except ImportError as err:
raise _unsupported_blob_pandas_error(str(err)) from err
blob_auto_row_id = self._blob_auto_row_id_enabled()
blob_sources = (
blob_v2_projection_sources(self._table.schema, query.columns)
if blob_mode == "bytes"
else {}
)
if blob_sources:
if blob_mode == "bytes":
reject_unfetchable_blob_columns(
self._table.schema, query.columns, blob_sources
)
@@ -2248,8 +2299,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
"""
blob_sources = self._validated_blob_sources(blob_mode)
return self._finalize_blob_query_table(
@@ -2327,7 +2378,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
vector = self._query if isinstance(self._query, list) else self._query.tolist()
if isinstance(vector[0], np.ndarray):
vector = [v.tolist() for v in vector]
query = self._query_for_scan()
query = self._query_for_scan(blob_sources)
result_set = self._table._execute_query(
query, batch_size=batch_size, timeout=timeout
)
@@ -2545,7 +2596,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
blob_sources = self._validated_blob_sources(blob_mode)
self._table._ensure_no_legacy_fts_index()
query = self._query_for_scan()
query = self._query_for_scan(blob_sources)
results = self._table._execute_query(query, timeout=timeout).read_all()
if self._reranker is not None:
results = self._reranker.rerank_fts(self._query, results)
@@ -2591,6 +2642,8 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
blob_mode: BlobMode = "lazy",
) -> pa.Table:
blob_sources = self._validated_blob_sources(blob_mode)
if blob_mode == "bytes" and blob_sources:
return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all()
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
blob_mode=blob_mode,
@@ -2624,7 +2677,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
blob_mode: BlobMode = "lazy",
) -> pa.RecordBatchReader:
blob_sources = self._validated_blob_sources(blob_mode)
query = self._query_for_scan()
query = self._query_for_scan(blob_sources)
reader = self._table._execute_query(
query, batch_size=batch_size, timeout=timeout
)
@@ -3495,6 +3548,22 @@ class AsyncQueryBase(object):
self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
self._inner.with_row_id()
async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
if blob_mode != "bytes" or self._table is None:
return False
try:
query = self.to_query_object()
except NotImplementedError:
return False
return (
_query_is_plain_blob_scan(query)
and getattr(self, "_reranker", None) is None
and not _query_needs_lance_scanner(self)
and _supports_local_blob_fetch(
self._table, self._table._pushdown_operations
)
)
def select(self, columns: Union[List[str], dict[str, str]]) -> Self:
"""
Return only the specified columns.
@@ -3602,10 +3671,11 @@ class AsyncQueryBase(object):
The timeout also covers reading the batches, so consuming them
slowly can exceed it.
blob_mode: str, default "lazy"
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
payloads one batch at a time, without requiring pylance. Bytes mode
has the same restrictions as :meth:`to_arrow`.
``"lazy"`` keeps blob v2 descriptors and auto row ids for manual
fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches
supported row-addressable blob payloads one batch at a time, without
requiring pylance. Bytes mode has the same restrictions as
:meth:`to_arrow`.
Examples
--------
@@ -3614,13 +3684,16 @@ class AsyncQueryBase(object):
"""
blob_sources = await self._validated_blob_sources(blob_mode)
reader = await self._execute_batches(
max_batch_length=max_batch_length, timeout=timeout
max_batch_length=max_batch_length,
timeout=timeout,
blob_sources=blob_sources,
)
if blob_mode == "lazy":
return reader
async def convert(tbl: pa.Table) -> pa.Table:
tbl = self._finalize_blob_query_table(tbl)
if not (blob_mode == "bytes" and blob_sources):
tbl = self._finalize_blob_query_table(tbl)
tbl = await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources)
if not self._user_requested_row_id() and "_rowid" in tbl.column_names:
tbl = tbl.drop_columns(["_rowid"])
@@ -3641,7 +3714,24 @@ class AsyncQueryBase(object):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
if (
blob_sources
and not self._user_requested_row_id()
and await self._can_fetch_plain_legacy_blobs("bytes")
):
# Build a separate query so the hidden row id needed for byte
# conversion cannot leak into later executions of this builder.
query = self.to_query_object()
query.with_row_id = True
if self._table is None:
raise RuntimeError("blob query is not bound to a table")
row_id_query = self._table._sync_query_to_async(query)
return await row_id_query._execute_batches(
max_batch_length=max_batch_length,
timeout=timeout,
)
await self._maybe_add_blob_row_id()
return AsyncRecordBatchReader(
await self._inner.execute(
@@ -3658,7 +3748,7 @@ class AsyncQueryBase(object):
return await self._inner.output_schema()
async def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
"""Map projected blob v2 outputs to their source columns.
"""Map projected blob outputs to their source columns.
Bytes mode is checked here, before the query runs.
"""
@@ -3668,7 +3758,11 @@ class AsyncQueryBase(object):
return {}
schema = await self._table.schema()
projection = _query_request_projection(self._inner.to_query_request())
blob_sources = blob_v2_projection_sources(schema, projection)
blob_sources = blob_projection_sources(
schema,
projection,
include_legacy=await self._can_fetch_plain_legacy_blobs(blob_mode),
)
if blob_mode != "bytes":
return blob_sources
reject_unfetchable_blob_columns(schema, projection, blob_sources)
@@ -3689,7 +3783,7 @@ class AsyncQueryBase(object):
return tbl
if blob_mode == "descriptions":
return strip_auto_row_ids(tbl, blob_sources)
return await replace_v2_blob_columns_with_bytes(
return await replace_blob_columns_with_bytes(
tbl, blob_sources, self._table.fetch_blobs
)
@@ -3715,11 +3809,14 @@ class AsyncQueryBase(object):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``.
"""
blob_sources = await self._validated_blob_sources(blob_mode)
if blob_mode == "bytes" and blob_sources:
reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode)
return pa.Table.from_batches(await reader.read_all(), schema=reader.schema)
batch_iter = await self.to_batches(timeout=timeout)
tbl = self._finalize_blob_query_table(
pa.Table.from_batches(await batch_iter.read_all(), schema=batch_iter.schema)
@@ -3792,10 +3889,10 @@ class AsyncQueryBase(object):
blob_mode: str, default "lazy"
Controls how blob columns are returned. Local blob v2 queries support
``"bytes"`` and ``"descriptions"`` without pylance. Eligible local
plain scans use pylance's scanner for lazy blob handles in ``"lazy"``
mode and for legacy blob columns. Other local blob v2
queries return descriptors in ``"lazy"`` and ``"descriptions"``
modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
plain scans also support ``"bytes"`` for row-addressable legacy blob
columns without pylance. Other local blob v2 queries return
descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
in ``"bytes"`` mode, through :meth:`to_arrow`.
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
@@ -3873,21 +3970,27 @@ class AsyncQueryBase(object):
with_row_id=self._with_row_id,
)
blob_sources = (
blob_v2_projection_sources(schema, query.columns)
blob_projection_sources(
schema,
query.columns,
include_legacy=await self._can_fetch_plain_legacy_blobs(blob_mode),
)
if blob_mode == "bytes"
else {}
)
if blob_sources:
if blob_mode == "bytes":
reject_unfetchable_blob_columns(schema, query.columns, blob_sources)
# Remote and in-memory tables have no Lance dataset to scan.
if not self._table._inner._is_native() or (
get_uri_scheme(await self._table.uri()) == "memory"
):
return None
if (
blob_mode != "lazy"
and not _query_needs_lance_scanner(self)
and blob_v2_projection_sources(schema, query.columns)
if not _query_needs_lance_scanner(self) and (
(blob_mode == "bytes" and blob_sources)
or (
blob_mode == "descriptions"
and blob_v2_projection_sources(schema, query.columns)
)
):
return None
try:
@@ -4398,8 +4501,11 @@ class AsyncFTSQuery(AsyncStandardQuery):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
reader = await super()._execute_batches(timeout=timeout)
reader = await super()._execute_batches(
timeout=timeout, blob_sources=blob_sources
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
results = self._reranker.rerank_fts(self.get_query(), results)
@@ -4722,8 +4828,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
reader = await super()._execute_batches(timeout=timeout)
reader = await super()._execute_batches(
timeout=timeout, blob_sources=blob_sources
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
results = self._reranker.rerank_vector(self._query_string, results)
@@ -4851,11 +4960,14 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
# WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s.
return await _wal_hybrid.with_pk_fallback_async(
lambda: self._run_hybrid(
max_batch_length=max_batch_length, timeout=timeout
max_batch_length=max_batch_length,
timeout=timeout,
blob_sources=blob_sources,
),
self._table,
fused=lambda: self._pk_fusion is not None,
@@ -4867,19 +4979,18 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
fts_query, vec_query, limit, offset = await self._create_child_queries()
req = fts_query._inner.to_query_request()
blob_auto_row_id = False
blob_auto_row_id = bool(blob_sources)
blob_paths: tuple[str, ...] = ()
if self._table is not None:
schema = await self._table.schema()
projection = _query_request_projection(req)
blob_auto_row_id = blob_auto_row_id_for_scan(
schema,
projection,
with_row_id=self._with_row_id,
blob_auto_row_id = blob_auto_row_id or blob_auto_row_id_for_scan(
schema, projection, with_row_id=self._with_row_id
)
if blob_auto_row_id:
blob_paths = tuple(
@@ -5176,8 +5287,7 @@ class BaseQueryBuilder(object):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` is not supported for remote or pushdown blob queries.
"""
return LOOP.run(self._inner.to_arrow(timeout, blob_mode=blob_mode))
+3 -2
View File
@@ -37,7 +37,7 @@ import pyarrow as pa
from ..common import DATA
from lancedb.listing import Listing, NamespaceListing, TableListing
from ..db import DBConnection, LOOP
from ..db import DBConnection, LOOP, _normalize_function_version
from ..functions import FunctionVersion, FunctionDefinition
from ..graph import EdgeTable, NodeTable, PropertyGraph
from ..job import AsyncJob, Job
@@ -985,9 +985,10 @@ class RemoteDBConnection(DBConnection):
self,
name: str,
*,
version: str,
version: Optional[Union[int, str]] = None,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
version = _normalize_function_version(version)
return LOOP.run(
self._conn.get_function(
name, version=version, namespace_path=namespace_path
+24
View File
@@ -34,6 +34,7 @@ from lancedb._lancedb import (
DeleteResult,
DropColumnsResult,
FtsToken,
FunctionColumnStatus,
IndexConfig,
RTEWriteSpec,
MergeResult,
@@ -1127,6 +1128,7 @@ class RemoteTable(Table):
computed: Dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
) -> AddColumnsResult:
return LOOP.run(
self._table.add_columns(
@@ -1134,6 +1136,7 @@ class RemoteTable(Table):
computed=computed,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
auto_refresh_resource_budget=auto_refresh_resource_budget,
)
)
@@ -1143,7 +1146,9 @@ class RemoteTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1160,7 +1165,9 @@ class RemoteTable(Table):
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -1180,7 +1187,9 @@ class RemoteTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1198,7 +1207,9 @@ class RemoteTable(Table):
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -1223,6 +1234,19 @@ class RemoteTable(Table):
self._table.function_errors(job_id=job_id, column=column, limit=limit)
)
def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]:
return LOOP.run(self._table.column_statuses(column=column))
def column_status(self, column: str) -> FunctionColumnStatus:
return LOOP.run(self._table.column_status(column))
def wait_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus:
return LOOP.run(self._table.wait_fresh(column, timeout))
def alter_columns(
self, *alterations: Iterable[Dict[str, str]]
) -> AlterColumnsResult:
+9
View File
@@ -122,6 +122,15 @@ def blob_v2_column_paths(schema: pa.Schema) -> list[str]:
return [path for path, _ in _collect_blob_paths(schema, is_blob_v2_field)]
def row_addressable_blob_paths(schema: pa.Schema) -> list[str]:
"""Blob v1 and v2 paths with one blob addressable by table row id."""
return [
path
for path, has_list_ancestor in _collect_blob_paths(schema, is_blob_like_field)
if not has_list_ancestor
]
def row_addressable_blob_v2_paths(schema: pa.Schema) -> list[str]:
"""Blob v2 paths with one blob addressable by table row id.
+30 -2
View File
@@ -104,6 +104,15 @@ class AsyncQuery:
"""The stable identifier scoped to the connection that submitted it."""
return self._inner.id
@property
def job_id(self) -> Optional[str]:
"""The durable Job Registry id once the server reports this query as a job.
A running query reports it after :meth:`describe` observes the latest
server status. This is separate from the connection-scoped ``id``.
"""
return self._inner.job_id
async def describe(self) -> QueryDescription:
"""Get a point-in-time description of the query."""
return await self._inner.describe()
@@ -118,7 +127,12 @@ class AsyncQuery:
return AsyncRecordBatchReader(await self._inner.reader())
async def cancel(self) -> None:
"""Request cancellation of the query."""
"""Request cancellation of this query's Flight execution.
A durable server-side job may reject this operation because its Flight
waiter cannot cancel the registry job. Use ``connection.cancel_job()``
with ``job_id`` to cancel that job.
"""
await self._inner.cancel()
@@ -133,6 +147,15 @@ class Query:
"""The stable identifier scoped to the connection that submitted it."""
return self._inner.id
@property
def job_id(self) -> Optional[str]:
"""The durable Job Registry id once the server reports this query as a job.
A running query reports it after :meth:`describe` observes the latest
server status. This is separate from the connection-scoped ``id``.
"""
return self._inner.job_id
def describe(self) -> QueryDescription:
"""Get a point-in-time description of the query."""
return LOOP.run(self._inner.describe())
@@ -159,7 +182,12 @@ class Query:
return pa.RecordBatchReader.from_batches(reader.schema, batches())
def cancel(self) -> None:
"""Request cancellation of the query."""
"""Request cancellation of this query's Flight execution.
A durable server-side job may reject this operation because its Flight
waiter cannot cancel the registry job. Use ``connection.cancel_job()``
with ``job_id`` to cancel that job.
"""
LOOP.run(self._inner.cancel())
+212 -29
View File
@@ -35,7 +35,7 @@ from urllib.parse import urlparse
from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable
from . import __version__
from ._lancedb import _parse_field_path
from ._lancedb import FunctionColumnStatus, _parse_field_path
from ._blob import (
BlobFile,
_normalize_blob_descriptor,
@@ -75,6 +75,7 @@ from .index import (
LabelList,
Fm,
NGram,
ZoneMap,
HnswPq,
HnswSq,
HnswFlat,
@@ -300,6 +301,7 @@ IndexConfigType = Union[
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
]
@@ -1587,8 +1589,8 @@ class Table(ABC):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
Returns
-------
@@ -1907,7 +1909,7 @@ class Table(ABC):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
wait_timeout : timedelta, optional
@@ -2624,6 +2626,12 @@ class Table(ABC):
bytes. The client splits requests automatically and reads an individual
larger blob through the Range route. This method still materializes all
bytes in memory; for large values use :meth:`fetch_blob_files`.
The returned Arrow ``large_binary`` array contains payload bytes, not
SQL/query descriptor dictionaries. Use ``.to_pylist()`` to obtain
Python ``bytes`` or ``None`` values for copying into a blob column.
Select row IDs with ``search().with_row_id(True)`` first. Selection and
fetching are separate requests: keep the source unchanged between them.
"""
@abstractmethod
@@ -3077,6 +3085,7 @@ class Table(ABC):
computed: Dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
):
"""
Add new columns with defined values.
@@ -3145,6 +3154,12 @@ class Table(ABC):
When omitted, the server determines when to refresh. Applies to every
computed output in this call.
Scheduling options require computed or Function columns.
auto_refresh_resource_budget: dict[str, int], optional
Aggregate CPU, memory, and GPU budget for automatic refreshes of a
registered Function declaration. ``cpu_millis`` and
``memory_bytes`` are required; ``gpu_count`` defaults to zero.
This option cannot be used with SQL-expression columns. LanceDB
Enterprise only.
Returns
-------
@@ -3178,7 +3193,9 @@ class Table(ABC):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3217,21 +3234,35 @@ class Table(ABC):
Maximum rows per Function call on the remote server. Must be
greater than zero. None uses the server default. Has no effect on
local expression-backed columns.
max_concurrency: int, optional
Override the registered Function's maximum concurrent user-code
calls for this logical execution. Must be between 1 and
4294967295. None uses the registration default. This is not an
account-wide quota. LanceDB Enterprise only; local refreshes
reject this option.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
resource_budget: dict[str, int], optional
Aggregate resources for one registered Function refresh. The
``cpu_millis`` and ``memory_bytes`` keys are required;
``gpu_count`` is optional and defaults to zero, which requests a
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
None keeps the Function's registered class or the deployment
default. LanceDB Enterprise only.
gpu_count: int, optional
Positive aggregate GPU budget for Function workers. None leaves
the server's configured budget unchanged. LanceDB Enterprise
only.
Positive aggregate GPU budget for Function workers without changing
the deployment's CPU and memory defaults. None leaves the server's
configured budget unchanged. For a complete CPU and memory budget,
use ``resource_budget`` instead. LanceDB Enterprise only.
retry_policy: FunctionRetryPolicy, optional
Override retries of failed user-code calls. Only use when repeating
partial work is safe. Set max_attempts=1 to disable retries.
@@ -3251,7 +3282,8 @@ class Table(ABC):
Deadline for Function initialization. LanceDB Enterprise only.
num_workers: int, optional
Worker count for an expression column; registered Function
columns reject it. LanceDB Enterprise only.
columns reject it and use ``resource_budget`` instead. LanceDB
Enterprise only.
max_executor_processes_per_worker: int, optional
Cap on executor processes per Function worker. LanceDB
Enterprise only.
@@ -3270,7 +3302,9 @@ class Table(ABC):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3308,21 +3342,35 @@ class Table(ABC):
greater than zero. None uses the server default. Lower this for
slow Functions to stay within the executor's per-call deadline.
Has no effect on local expression-backed columns.
max_concurrency: int, optional
Override the registered Function's maximum concurrent user-code
calls for this logical execution. Must be between 1 and
4294967295. None uses the registration default. This is not an
account-wide quota. LanceDB Enterprise only; local refreshes
reject this option.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
resource_budget: dict[str, int], optional
Aggregate resources for one registered Function refresh. The
``cpu_millis`` and ``memory_bytes`` keys are required;
``gpu_count`` is optional and defaults to zero, which requests a
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
None keeps the Function's registered class or the deployment
default. LanceDB Enterprise only.
gpu_count: int, optional
Positive aggregate GPU budget for Function workers. None leaves
the server's configured budget unchanged. LanceDB Enterprise
only.
Positive aggregate GPU budget for Function workers without changing
the deployment's CPU and memory defaults. None leaves the server's
configured budget unchanged. For a complete CPU and memory budget,
use ``resource_budget`` instead. LanceDB Enterprise only.
retry_policy: FunctionRetryPolicy, optional
Override retries of failed user-code calls. Only use when repeating
partial work is safe. Set max_attempts=1 to disable retries.
@@ -3342,7 +3390,8 @@ class Table(ABC):
Deadline for Function initialization. LanceDB Enterprise only.
num_workers: int, optional
Worker count for an expression column; registered Function
columns reject it. LanceDB Enterprise only.
columns reject it and use ``resource_budget`` instead. LanceDB
Enterprise only.
max_executor_processes_per_worker: int, optional
Cap on executor processes per Function worker. LanceDB
Enterprise only.
@@ -3455,6 +3504,36 @@ class Table(ABC):
... print("listing stopped at the limit")
"""
@abstractmethod
def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]:
"""Return exact status for Function-backed output columns.
All statuses describe one server table version. ``column=None`` returns
every Function output. This operation is available on LanceDB
Enterprise tables. A table handle pinned to an exact version requests
that version; a latest handle retains the normal read-freshness
behavior.
"""
@abstractmethod
def column_status(self, column: str) -> FunctionColumnStatus:
"""Return exact status for one Function-backed output column."""
@abstractmethod
def wait_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus:
"""Poll until the column has no stale or never-computed rows.
Rows already failed remain visible in the returned status and do not
keep this method waiting. The method never submits or cancels work.
Transport errors and unrecoverable status-evidence errors propagate.
A typed finalization-pending response is retried; arbitrary failure
responses are not.
"""
@abstractmethod
def alter_columns(self, *alterations: Iterable[Dict[str, str]]):
"""
@@ -4132,7 +4211,7 @@ class LanceTable(Table):
):
return self.to_arrow().to_pandas(**kwargs)
if blob_mode == "bytes" and blob_v2_column_paths(self.schema):
if blob_mode == "bytes" and schema_has_blob_field(self.schema):
return self.search().to_pandas(blob_mode=blob_mode, **kwargs)
return self.to_lance().to_pandas(blob_mode=blob_mode, **kwargs)
@@ -4145,8 +4224,8 @@ class LanceTable(Table):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
Returns
-------
@@ -4285,7 +4364,7 @@ class LanceTable(Table):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
wait_timeout : timedelta, optional
@@ -5440,6 +5519,7 @@ class LanceTable(Table):
computed: Dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
) -> AddColumnsResult:
return LOOP.run(
self._table.add_columns(
@@ -5447,6 +5527,7 @@ class LanceTable(Table):
computed=computed,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
auto_refresh_resource_budget=auto_refresh_resource_budget,
)
)
@@ -5456,7 +5537,9 @@ class LanceTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5476,7 +5559,9 @@ class LanceTable(Table):
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -5496,7 +5581,9 @@ class LanceTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5518,7 +5605,9 @@ class LanceTable(Table):
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -5545,6 +5634,19 @@ class LanceTable(Table):
self._table.function_errors(job_id=job_id, column=column, limit=limit)
)
def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]:
return LOOP.run(self._table.column_statuses(column=column))
def column_status(self, column: str) -> FunctionColumnStatus:
return LOOP.run(self._table.column_status(column))
def wait_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus:
return LOOP.run(self._table.wait_fresh(column, timeout))
def alter_columns(
self, *alterations: Iterable[Dict[str, str]]
) -> AlterColumnsResult:
@@ -6608,7 +6710,7 @@ class AsyncTable:
if blob_mode == "lazy" and get_uri_scheme(await self.uri()) == "memory":
return (await self.to_arrow()).to_pandas(**kwargs)
if blob_mode == "bytes" and blob_v2_column_paths(schema):
if blob_mode == "bytes" and schema_has_blob_field(schema):
return await self.query().to_pandas(blob_mode=blob_mode, **kwargs)
return (await self.to_lance()).to_pandas(blob_mode=blob_mode, **kwargs)
@@ -6620,8 +6722,8 @@ class AsyncTable:
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
Returns
-------
@@ -6662,6 +6764,7 @@ class AsyncTable:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
]
] = None,
@@ -6738,12 +6841,13 @@ class AsyncTable:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
),
):
raise TypeError(
"config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
" BTree, Bitmap, LabelList, Fm, NGram, or FTS, but got "
" BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, or FTS, but got "
+ str(type(config))
)
try:
@@ -6782,6 +6886,7 @@ class AsyncTable:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
]
] = None,
@@ -7425,7 +7530,10 @@ class AsyncTable:
if query.offset is not None:
async_query = async_query.offset(query.offset)
if query.columns:
async_query = async_query.select(query.columns)
columns = query.columns
if isinstance(columns, list) and columns and isinstance(columns[0], tuple):
columns = dict(columns)
async_query = async_query.select(columns)
if query.filter is not None:
async_query = async_query.where(query.filter)
if query.fast_search:
@@ -7720,6 +7828,7 @@ class AsyncTable:
computed: dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
) -> AddColumnsResult:
"""
Add new columns with defined values.
@@ -7786,6 +7895,12 @@ class AsyncTable:
not force recomputation. Applies to every declared computed output.
These options cannot be used with one-time transforms or ordinary
all-null columns.
auto_refresh_resource_budget: dict[str, int], optional
Aggregate CPU, memory, and GPU budget for automatic refreshes of
registered Function outputs. ``cpu_millis`` and ``memory_bytes``
are required; ``gpu_count`` defaults to zero. SQL-expression
columns do not use Function workers and reject this option.
LanceDB Enterprise only.
Examples
--------
@@ -7814,6 +7929,7 @@ class AsyncTable:
options_supplied = (
auto_refresh_enabled is not None
or auto_refresh_interval_seconds is not None
or auto_refresh_resource_budget is not None
)
function_application = None
function_output_name = None
@@ -7842,6 +7958,7 @@ class AsyncTable:
function_output_name,
auto_refresh_enabled,
auto_refresh_interval_seconds,
auto_refresh_resource_budget,
)
if isinstance(transforms, pa.Field):
@@ -7862,6 +7979,7 @@ class AsyncTable:
list(computed.items()),
auto_refresh_enabled,
auto_refresh_interval_seconds,
auto_refresh_resource_budget,
)
if options_supplied:
raise ValueError(
@@ -7883,7 +8001,9 @@ class AsyncTable:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -7922,21 +8042,35 @@ class AsyncTable:
Maximum rows per Function call on the remote server. Must be
greater than zero. None uses the server default. Has no effect on
local expression-backed columns.
max_concurrency: int, optional
Override the registered Function's maximum concurrent user-code
calls for this logical execution. Must be between 1 and
4294967295. None uses the registration default. This is not an
account-wide quota. LanceDB Enterprise only; local refreshes
reject this option.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
resource_budget: dict[str, int], optional
Aggregate resources for one registered Function refresh. The
``cpu_millis`` and ``memory_bytes`` keys are required;
``gpu_count`` is optional and defaults to zero, which requests a
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
None keeps the Function's registered class or the deployment
default. LanceDB Enterprise only.
gpu_count: int, optional
Positive aggregate GPU budget for Function workers. None leaves
the server's configured budget unchanged. LanceDB Enterprise
only.
Positive aggregate GPU budget for Function workers without changing
the deployment's CPU and memory defaults. None leaves the server's
configured budget unchanged. For a complete CPU and memory budget,
use ``resource_budget`` instead. LanceDB Enterprise only.
retry_policy: FunctionRetryPolicy, optional
Override retries of failed user-code calls. Only use when repeating
partial work is safe. Set max_attempts=1 to disable retries.
@@ -7956,7 +8090,8 @@ class AsyncTable:
Deadline for Function initialization. LanceDB Enterprise only.
num_workers: int, optional
Worker count for an expression column; registered Function
columns reject it. LanceDB Enterprise only.
columns reject it and use ``resource_budget`` instead. LanceDB
Enterprise only.
max_executor_processes_per_worker: int, optional
Cap on executor processes per Function worker. LanceDB
Enterprise only.
@@ -7970,7 +8105,9 @@ class AsyncTable:
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8074,13 +8211,41 @@ class AsyncTable:
job_id=job_id, column=column, limit=limit
)
async def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]:
"""Return exact status for Function-backed output columns.
All results describe one server table version. ``column=None`` returns
every Function output. A handle pinned to an exact version requests
that version.
"""
return await self._inner.column_statuses(column=column)
async def column_status(self, column: str) -> FunctionColumnStatus:
"""Return exact status for one Function-backed output column."""
return await self._inner.column_status(column)
async def wait_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus:
"""Poll until no stale or never-computed rows remain.
Failed rows do not block completion. Server and transport errors are
not retried. Only the typed finalization-pending response is retried
with bounded backoff; arbitrary 500 responses surface immediately.
"""
return await self._inner.wait_column_fresh(column, timeout)
async def refresh_column_async(
self,
column: str,
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8118,21 +8283,35 @@ class AsyncTable:
greater than zero. None uses the server default. Lower this for
slow Functions to stay within the executor's per-call deadline.
Has no effect on local expression-backed columns.
max_concurrency: int, optional
Override the registered Function's maximum concurrent user-code
calls for this logical execution. Must be between 1 and
4294967295. None uses the registration default. This is not an
account-wide quota. LanceDB Enterprise only; local refreshes
reject this option.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
resource_budget: dict[str, int], optional
Aggregate resources for one registered Function refresh. The
``cpu_millis`` and ``memory_bytes`` keys are required;
``gpu_count`` is optional and defaults to zero, which requests a
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
None keeps the Function's registered class or the deployment
default. LanceDB Enterprise only.
gpu_count: int, optional
Positive aggregate GPU budget for Function workers. None leaves
the server's configured budget unchanged. LanceDB Enterprise
only.
Positive aggregate GPU budget for Function workers without changing
the deployment's CPU and memory defaults. None leaves the server's
configured budget unchanged. For a complete CPU and memory budget,
use ``resource_budget`` instead. LanceDB Enterprise only.
retry_policy: FunctionRetryPolicy, optional
Override retries of failed user-code calls. Only use when repeating
partial work is safe. Set max_attempts=1 to disable retries.
@@ -8152,7 +8331,8 @@ class AsyncTable:
Deadline for Function initialization. LanceDB Enterprise only.
num_workers: int, optional
Worker count for an expression column; registered Function
columns reject it. LanceDB Enterprise only.
columns reject it and use ``resource_budget`` instead. LanceDB
Enterprise only.
max_executor_processes_per_worker: int, optional
Cap on executor processes per Function worker. LanceDB
Enterprise only.
@@ -8183,7 +8363,9 @@ class AsyncTable:
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8741,6 +8923,7 @@ class IndexStatistics:
"BITMAP",
"LABEL_LIST",
"NGRAM",
"ZONEMAP",
]
distance_type: Optional[Literal["l2", "cosine", "dot"]] = None
num_indices: Optional[int] = None
+63 -4
View File
@@ -1070,8 +1070,10 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path):
)
table.add([{"id": 1, "image": b"one"}])
with pytest.raises(NotImplementedError, match="stable table snapshot"):
with pytest.raises(NotImplementedError, match="stable table snapshot") as exc:
table.to_arrow(blob_mode="bytes")
assert "fetch_blobs(column, row_ids)" in str(exc.value)
assert "with_row_id(True)" in str(exc.value)
with pytest.raises(NotImplementedError, match="stable table snapshot"):
table.search().to_list(blob_mode="bytes")
with pytest.raises(NotImplementedError, match="stable table snapshot"):
@@ -1103,6 +1105,36 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path)
await table.query().to_batches(blob_mode="bytes")
def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path):
db = lancedb.connect(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
rows = [
{"id": 1, "image": b"one"},
{"id": 2, "image": b""},
{"id": 3, "image": None},
{"id": 4, "image": b"excluded"},
]
source = db.create_table("source", data=rows, schema=schema)
hits = (
source.search()
.where("id < 4")
.select(["id"])
.with_row_id(True)
.limit(100)
.to_arrow()
)
payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist()
subset = db.create_table("subset", schema=schema)
subset.add(
[
{"id": image_id, "image": payload}
for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True)
]
)
copied = subset.search().to_list(blob_mode="bytes")
assert sorted(copied, key=lambda row: row["id"]) == rows[:3]
def test_fetch_blobs_round_trip():
table = _blob_table(
"round_trip",
@@ -1619,16 +1651,41 @@ def test_bytes_mode_rejects_blobs_inside_lists():
def test_row_addressable_paths_exclude_list_children():
from lancedb.schema import row_addressable_blob_v2_paths
from lancedb.schema import (
row_addressable_blob_paths,
row_addressable_blob_v2_paths,
)
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("info", pa.struct([lancedb.blob("blob")])),
pa.field(
"info",
pa.struct(
[
lancedb.blob("blob"),
pa.field(
"legacy",
pa.large_binary(),
metadata={"lance-encoding:blob": "true"},
),
]
),
),
pa.field(
"legacy",
pa.large_binary(),
metadata={"lance-encoding:blob": "true"},
),
pa.field("images", pa.list_(lancedb.blob("image"))),
]
)
assert blob_v2_column_paths(schema) == ["info.blob", "images.image"]
assert row_addressable_blob_paths(schema) == [
"info.blob",
"info.legacy",
"legacy",
]
assert row_addressable_blob_v2_paths(schema) == ["info.blob"]
@@ -2293,6 +2350,8 @@ async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch):
if blob_mode != "lazy":
assert "_rowid" not in reader.schema.names
assert "_lance_row_id" not in str(reader.schema)
else:
assert "_rowid" in reader.schema.names
class _KeepAllScoresReranker(Reranker):
@@ -2336,7 +2395,7 @@ def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
.rerank(_KeepAllScoresReranker())
)
with pytest.raises(ValueError, match=r"\['blob'\].*legacy blob columns"):
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
query.to_arrow(blob_mode="bytes")
@@ -8,12 +8,7 @@ import textwrap
import pytest
@pytest.mark.parametrize("api", ["sync", "async"])
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
def test_blob_query_without_pylance(tmp_path, api, result):
if result == "pandas":
pytest.importorskip("pandas")
script = """\
_WITHOUT_LANCE = """\
import importlib.abc
import sys
@@ -23,7 +18,15 @@ class MissingLance(importlib.abc.MetaPathFinder):
raise ModuleNotFoundError(fullname, name="lance")
sys.meta_path.insert(0, MissingLance())
""" + textwrap.dedent(
"""
@pytest.mark.parametrize("api", ["sync", "async"])
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
def test_blob_query_without_pylance(tmp_path, api, result):
if result == "pandas":
pytest.importorskip("pandas")
script = _WITHOUT_LANCE + textwrap.dedent(
"""\
import asyncio
import lancedb
@@ -94,3 +97,187 @@ sys.meta_path.insert(0, MissingLance())
text=True,
)
assert completed.returncode == 0, completed.stderr
@pytest.mark.parametrize("api", ["sync", "async"])
@pytest.mark.parametrize("result", ["pandas", "batches", "arrow"])
def test_plain_legacy_blob_query_without_pylance(tmp_path, api, result):
if result == "pandas":
pytest.importorskip("pandas")
script = _WITHOUT_LANCE + textwrap.dedent(
"""\
import asyncio
import lancedb
import pyarrow as pa
from lancedb.query import ColumnOrdering
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("filename", pa.string()),
pa.field(
"video_blob",
pa.large_binary(),
metadata={"lance-encoding:blob": "true"},
),
]
)
rows = [
{"id": 1, "filename": "file-1.mp4", "video_blob": b"outside"},
{"id": 2, "filename": "file-2.mp4", "video_blob": b""},
{"id": 3, "filename": "file-3.mp4", "video_blob": None},
{"id": 4, "filename": "file-4.mp4", "video_blob": b"four"},
]
expected = [
{"filename": "file-2.mp4", "payload": b""},
{"filename": "file-3.mp4", "payload": None},
{"filename": "file-4.mp4", "payload": b"four"},
]
def configure(query):
return (
query.select({"filename": "filename", "payload": "video_blob"})
.where("id >= 2")
.order_by(
[ColumnOrdering(column_name="id", ascending=True)]
)
.limit(3)
)
async def main():
storage_options = {"new_table_data_storage_version": "2.1"}
if sys.argv[2] == "async":
db = await lancedb.connect_async(
sys.argv[1], storage_options=storage_options
)
table = await db.create_table("legacy", schema=schema)
await table.add(rows)
table = await db.open_table("legacy")
def query():
return configure(table.query())
def original_query():
return table.query().select(
{"filename": "filename", "payload": "video_blob"}
).limit(1)
def empty_query():
return query().where("id < 0")
def batches():
return query().to_batches(
max_batch_length=1, blob_mode="bytes"
)
else:
db = lancedb.connect(
sys.argv[1], storage_options=storage_options
)
table = db.create_table("legacy", schema=schema)
table.add(rows)
table = db.open_table("legacy")
def query():
return configure(table.search())
def original_query():
return table.search().select(
{"filename": "filename", "payload": "video_blob"}
).limit(1)
def empty_query():
return query().where("id < 0")
def batches():
return query().to_batches(
batch_size=1, blob_mode="bytes"
)
if sys.argv[2] == "async":
reused = table.query().select(
{"filename": "filename", "payload": "video_blob"}
).limit(3)
byte_reader = await reused.to_batches(blob_mode="bytes")
await byte_reader.read_all()
lazy_reader = await reused.to_batches(blob_mode="lazy")
assert "_rowid" not in lazy_reader.schema.names
await lazy_reader.read_all()
reused.select(["filename"])
nonblob_reader = await reused.to_batches(blob_mode="lazy")
assert nonblob_reader.schema.names == ["filename"]
await nonblob_reader.read_all()
if sys.argv[3] == "pandas":
frame = query().to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
frame = await frame
assert frame.to_dict("records") == expected
original = original_query().to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
original = await original
assert original.to_dict("records") == [
{"filename": "file-1.mp4", "payload": b"outside"}
]
direct = table.to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
direct = await direct
assert direct.to_dict("records") == rows
empty = empty_query().to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
empty = await empty
assert empty.to_dict("records") == []
elif sys.argv[3] == "batches":
reader = batches()
if sys.argv[2] == "async":
reader = await reader
rows_out = [batch async for batch in reader]
else:
rows_out = list(reader)
assert reader.schema.field("payload").type == pa.large_binary()
assert "_rowid" not in reader.schema.names
assert all(batch.num_rows == 1 for batch in rows_out)
assert all(batch.schema == reader.schema for batch in rows_out)
actual = [row for batch in rows_out for row in batch.to_pylist()]
assert actual == expected
original_reader = original_query().to_batches(blob_mode="bytes")
if sys.argv[2] == "async":
original_reader = await original_reader
original_rows = [batch async for batch in original_reader]
else:
original_rows = list(original_reader)
assert [
row for batch in original_rows for row in batch.to_pylist()
] == [{"filename": "file-1.mp4", "payload": b"outside"}]
empty_reader = empty_query().to_batches(blob_mode="bytes")
if sys.argv[2] == "async":
empty_reader = await empty_reader
empty_batches = [batch async for batch in empty_reader]
else:
empty_batches = list(empty_reader)
assert empty_batches == []
assert empty_reader.schema.field("payload").type == pa.large_binary()
else:
table_out = query().to_arrow(blob_mode="bytes")
if sys.argv[2] == "async":
table_out = await table_out
assert table_out.schema.field("payload").type == pa.large_binary()
assert "_rowid" not in table_out.column_names
assert table_out.to_pylist() == expected
original = original_query().to_arrow(blob_mode="bytes")
if sys.argv[2] == "async":
original = await original
assert original.to_pylist() == [
{"filename": "file-1.mp4", "payload": b"outside"}
]
direct = table.to_arrow(blob_mode="bytes")
if sys.argv[2] == "async":
direct = await direct
assert direct.to_pylist() == rows
empty_table = empty_query().to_arrow(blob_mode="bytes")
if sys.argv[2] == "async":
empty_table = await empty_table
assert empty_table.num_rows == 0
assert empty_table.schema.field("payload").type == pa.large_binary()
assert "lance" not in sys.modules
asyncio.run(main())
"""
)
completed = subprocess.run(
[sys.executable, "-c", script, str(tmp_path), api, result],
capture_output=True,
text=True,
)
assert completed.returncode == 0, completed.stderr
@@ -184,6 +184,7 @@ def test_function_version_preserves_execution_controls():
value = job_result("remote_function_job.json")
value.update(
batch_size=12,
max_concurrency=4,
row_timeout_seconds=8.0,
result_stability="input_and_context",
)
@@ -192,9 +193,14 @@ def test_function_version_preserves_execution_controls():
assert encoded == value
assert type(encoded["batch_size"]) is int
assert type(encoded["max_concurrency"]) is int
assert type(encoded["row_timeout_seconds"]) is float
assert type(encoded["result_stability"]) is str
for invalid in [True, 1.5, 0, -1, 2**32]:
with pytest.raises(ValueError, match="max_concurrency"):
FunctionVersion(**{**value, "max_concurrency": invalid})
def test_function_version_binds_named_columns_as_one_immutable_application():
version = FunctionVersion.from_json(
@@ -459,6 +465,7 @@ class _FunctionDeclarationInner:
output_name,
auto_refresh_enabled,
auto_refresh_interval_seconds,
auto_refresh_resource_budget,
):
self.calls.append(
(
@@ -466,6 +473,7 @@ class _FunctionDeclarationInner:
output_name,
auto_refresh_enabled,
auto_refresh_interval_seconds,
auto_refresh_resource_budget,
)
)
return "declared"
@@ -491,7 +499,7 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
)
assert result == "declared"
assert inner.calls[-1][1] == "features"
assert inner.calls[-1][2:] == (None, None)
assert inner.calls[-1][2:] == (None, None, None)
bare = application._copy(update={"columns": {}}).rename(
columns={"normalized_text": "search_text"}
@@ -502,7 +510,7 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
assert result == "declared"
assert inner.calls[-1][1] is None
assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"}
assert inner.calls[-1][2:] == (False, 300)
assert inner.calls[-1][2:] == (False, 300, None)
@pytest.mark.asyncio
@@ -134,6 +134,7 @@ def test_function_execution_controls_match_shared_registration_golden():
env={"MODE": "test"},
python_version="3.12",
batch_size=2,
max_concurrency=4,
row_timeout_seconds=0.75,
)(normalize_score.__wrapped__)
assert (
@@ -193,6 +194,11 @@ def test_function_retry_policy_rejects_invalid_options(options):
({"batch_size": 0}, "batch_size"),
({"batch_size": 2**32}, "batch_size"),
({"batch_size": True}, "batch_size"),
({"max_concurrency": 0}, "max_concurrency"),
({"max_concurrency": -1}, "max_concurrency"),
({"max_concurrency": 2**32}, "max_concurrency"),
({"max_concurrency": True}, "max_concurrency"),
({"max_concurrency": 1.5}, "max_concurrency"),
({"row_timeout_seconds": 0}, "row_timeout_seconds"),
({"row_timeout_seconds": -0.25}, "row_timeout_seconds"),
({"row_timeout_seconds": float("inf")}, "row_timeout_seconds"),
@@ -1894,6 +1900,8 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path):
db.create_function_async(normalize_score)
with pytest.raises(NotImplementedError, match=message):
db.get_function("normalize_score", version=FUNCTION_VERSION)
with pytest.raises(NotImplementedError, match=message):
db.get_function("normalize_score")
with pytest.raises(NotImplementedError, match=message):
list(db.list_functions())
with pytest.raises(NotImplementedError, match=message):
@@ -1903,8 +1911,10 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path):
class _RawFunctionCatalog:
def __init__(self, definition, *, encode=False):
self.definition = json.dumps(definition) if encode else definition
self.requested_versions = []
async def get_function(self, _name, version, namespace_path):
async def get_function(self, _name, version=None, namespace_path=None):
self.requested_versions.append(version)
return self.definition
def list_functions(self, *, namespace_path=None, page_token=None, page_limit=None):
@@ -1944,13 +1954,22 @@ async def test_async_catalog_path_preserves_execution_controls():
row_timeout_seconds=8.0,
result_stability="input_and_context",
)
connection = AsyncConnection(_RawFunctionCatalog(definition, encode=True))
catalog = _RawFunctionCatalog(definition, encode=True)
connection = AsyncConnection(catalog)
latest = await connection.get_function("embed")
integer = await connection.get_function("embed", version=1)
exact = await connection.get_function("embed", version="1")
await connection.get_function("embed", version="001")
listed = [item async for item in connection.list_functions(page_limit=32)]
assert len(listed) == 1
for version in [exact, *listed]:
for version in [latest, integer, exact, *listed]:
assert _assert_execution_control_encoding(version) == definition
assert catalog.requested_versions == [None, "1", "1", "001"]
with pytest.raises(TypeError, match="int, str, or None"):
await connection.get_function("embed", version=True)
with pytest.raises(TypeError, match="int, str, or None"):
await connection.get_function("embed", version=1.5)
def test_sync_catalog_path_preserves_execution_controls():
@@ -1963,13 +1982,22 @@ def test_sync_catalog_path_preserves_execution_controls():
result_stability="input_and_context",
)
connection = object.__new__(RemoteDBConnection)
connection._conn = _RawFunctionCatalog(FunctionVersion(**definition))
catalog = _RawFunctionCatalog(FunctionVersion(**definition))
connection._conn = catalog
latest = connection.get_function("embed")
integer = connection.get_function("embed", version=1)
exact = connection.get_function("embed", version="1")
connection.get_function("embed", version="001")
listed = list(connection.list_functions(page_limit=32))
assert len(listed) == 1
for version in [exact, *listed]:
for version in [latest, integer, exact, *listed]:
assert _assert_execution_control_encoding(version) == definition
assert catalog.requested_versions == [None, "1", "1", "001"]
with pytest.raises(TypeError, match="int, str, or None"):
connection.get_function("embed", version=True)
with pytest.raises(TypeError, match="int, str, or None"):
connection.get_function("embed", version=1.5)
def test_sync_drop_function_emits_server_warnings_without_changing_bool_api():
@@ -127,6 +127,60 @@ def test_function_without_initialization_keeps_its_wire_form():
assert request["artifact"]["kind"] == "python_callable"
@pytest.mark.parametrize("kind", ["function", "class"])
@pytest.mark.parametrize(
("global_value", "value_type"),
[
("pa.struct([('label', pa.string())])", "StructType"),
("(1, (pa.int64(),))", "DataType"),
("{'label': 1}", "dict"),
("float('inf')", "float"),
],
)
def test_unsupported_global_names_value_and_remedy(
helper_package, kind, global_value, value_type
):
definition = (
"class uses_global:\n"
" def __call__(self, value: int) -> int:\n"
" return value if CAPTURED_VALUE else 0\n"
if kind == "class"
else "def uses_global(value: int) -> int:\n"
" return value if CAPTURED_VALUE else 0\n"
)
module = helper_package(
"fx_unsupported_global",
{
"__init__.py": f"import pyarrow as pa\nCAPTURED_VALUE = {global_value}\n"
+ definition
},
)
with pytest.raises(TypeError) as error:
function(module.uses_global)
message = str(error.value)
assert "CAPTURED_VALUE" in message
assert value_type in message
assert "finite float" in message
assert "inside the function or class body" in message
def test_supported_nested_literal_global_still_packages(helper_package):
module = helper_package(
"fx_literal_global",
{
"__init__.py": "CAPTURED_VALUE = (None, True, 1, 'label', "
"b'bytes', (1.5,))\n"
"def uses_global(value: int) -> int:\n"
" return value + CAPTURED_VALUE[2]\n"
},
)
definition = function(module.uses_global)
namespace = {}
exec(compile(artifact(definition), "user_function.py", "exec"), namespace)
assert namespace["uses_global"](3) == 4
assert namespace["CAPTURED_VALUE"] == module.CAPTURED_VALUE
@pytest.mark.parametrize("annotation", ["Array", "RecordBatch"])
@pytest.mark.parametrize("kind", ["function", "class"])
def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package):
+24
View File
@@ -22,6 +22,7 @@ from lancedb.index import (
LabelList,
Fm,
NGram,
ZoneMap,
HnswPq,
HnswSq,
HnswFlat,
@@ -279,6 +280,28 @@ async def test_create_ngram_index(db_async):
assert "ScalarIndexQuery" in plan
@pytest.mark.asyncio
async def test_create_zonemap_index(db_async):
# ZoneMap indexes accelerate range and equality filters on ordered columns.
data = pa.table(
{
"id": list(range(100)),
"value": list(range(100)),
}
)
table = await db_async.create_table("zonemap_table", data)
await table.create_index("value", config=ZoneMap())
indices = await table.list_indices()
assert len(indices) == 1
assert indices[0].index_type == "ZoneMap"
assert indices[0].columns == ["value"]
# The index narrows a range scan without changing its results.
result = await table.query().where("value >= 90").to_arrow()
assert sorted(result["id"].to_pylist()) == list(range(90, 100))
@pytest.mark.asyncio
async def test_create_bitmap_index(some_table: AsyncTable):
await some_table.create_index("id", config=Bitmap())
@@ -591,6 +614,7 @@ def test_index_statistics_index_type_lists_all_supported_values():
"BITMAP",
"LABEL_LIST",
"NGRAM",
"ZONEMAP",
}
assert (
+97
View File
@@ -2,8 +2,10 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import asyncio
import json
import time
from datetime import timedelta
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -13,6 +15,50 @@ from lancedb.job import AsyncJob, Job, _progress_eta
from lancedb.remote.errors import HttpError, RetryError
@pytest.mark.parametrize("sync", [False, True])
def test_job_repr_bounds_large_payloads_without_fetching(sync):
spec = {"initialization": list(range(100000)), "source": "x" * 100000}
result = {"rows_computed": 7, "details": [{"data": b"x" * 10000}] * 1000}
inner = SimpleNamespace(
id="job-repr",
_state="failed",
job_type="function_refresh",
_description=SimpleNamespace(
creation_ms=2000,
spec=spec,
result=result,
failure="worker failed " + "x" * 10000,
),
)
job = AsyncJob(inner)
if sync:
job = Job(job)
rendered = repr(job)
assert len(rendered) < 1600
assert len(rendered.splitlines()) <= 10
assert "id='job-repr'" in rendered
assert "state='failed'" in rendered
assert "job_type='function_refresh'" in rendered
assert "rows_computed" in rendered
assert "worker failed" in rendered
assert "..." in rendered
assert len(repr(job.status)) < 1700
assert job.spec is spec
assert job.result is result
assert len(job.spec["initialization"]) == 100000
@pytest.mark.parametrize("sync", [False, True])
def test_job_repr_handles_unobserved_and_local_jobs(sync):
unobserved = AsyncJob(SimpleNamespace(id="job-pending", _state=None))
local = AsyncJob(None)
if sync:
unobserved, local = Job(unobserved), Job(local)
assert "id='job-pending', not refreshed" in repr(unobserved)
assert "state='finished'" in repr(local)
assert "failure=" not in repr(local)
@pytest.fixture(params=["async", "sync"])
def wait_job(request):
async def wait(inner, timeout=None, result_decoder=None):
@@ -706,3 +752,54 @@ async def test_query_wait_timeout_requires_keeping_original_handle():
assert "continues on the server" in message
assert "keep this handle to continue waiting" in message
assert "db.open_job" not in message
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path):
trace = {
"traceEvents": [{"ph": "X", "ts": 0, "dur": 1000}],
"metadata": {"partial": True},
}
inner = SimpleNamespace(
timeline=AsyncMock(return_value=json.dumps(trace)),
wait=AsyncMock(),
cancel=AsyncMock(),
)
job = AsyncJob(inner)
path = tmp_path / "job.trace.json"
if sync:
await asyncio.to_thread(Job(job).export_timeline, str(path))
else:
await job.export_timeline(path)
assert json.loads(path.read_text()) == trace
inner.timeline.assert_awaited_once_with()
inner.wait.assert_not_awaited()
inner.cancel.assert_not_awaited()
@pytest.mark.asyncio
async def test_export_timeline_failure_preserves_existing_file(tmp_path):
path = tmp_path / "job.trace.json"
path.write_text("previous recording")
job = AsyncJob(
SimpleNamespace(
timeline=AsyncMock(side_effect=RuntimeError("unsupported server"))
)
)
with pytest.raises(RuntimeError, match="unsupported server"):
await job.export_timeline(path)
assert path.read_text() == "previous recording"
with pytest.raises(NotImplementedError, match="server-side Function job"):
await AsyncJob(None).export_timeline(path)
with pytest.raises(NotImplementedError, match="server-side Function job"):
Job(None).export_timeline(path)
@pytest.mark.asyncio
async def test_export_timeline_reports_filesystem_errors(tmp_path):
job = AsyncJob(
SimpleNamespace(timeline=AsyncMock(return_value='{"traceEvents":[]}'))
)
with pytest.raises(FileNotFoundError):
await job.export_timeline(tmp_path / "missing" / "trace.json")
+12 -8
View File
@@ -348,7 +348,7 @@ def test_plain_scan_query_to_pandas_blob_bytes_projection(tmp_db, blob_schema):
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
def test_plain_scan_query_to_pandas_blob_mode_uses_native_path(
tmp_db, monkeypatch, blob_mode
):
pytest.importorskip("lance")
@@ -362,7 +362,8 @@ def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
def fail_to_arrow(*args, **kwargs):
raise AssertionError("to_arrow should not be called before native pandas")
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
if blob_mode == "descriptions":
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
df = query.to_pandas(blob_mode=blob_mode)
@@ -488,7 +489,7 @@ async def test_async_plain_scan_query_to_pandas_blob_bytes_projection(
@pytest.mark.asyncio
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
async def test_async_plain_scan_query_to_pandas_blob_mode_uses_native_path(
tmp_db_async, monkeypatch, blob_mode
):
pytest.importorskip("lance")
@@ -502,7 +503,8 @@ async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow
async def fail_to_arrow(*args, **kwargs):
raise AssertionError("to_arrow should not be called before native pandas")
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
if blob_mode == "descriptions":
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
df = await query.to_pandas(blob_mode=blob_mode)
@@ -541,12 +543,14 @@ def test_vector_query_to_pandas_legacy_blob_descriptions_and_bytes(tmp_db):
df = query.to_pandas(blob_mode="descriptions")
assert df["blob"].tolist() == [{"position": 0, "size": 3}]
with pytest.raises(ValueError, match="legacy blob columns"):
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
query.to_pandas(blob_mode="bytes")
with pytest.raises(ValueError, match="legacy blob columns"):
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
query.to_arrow(blob_mode="bytes")
with pytest.raises(ValueError, match="legacy blob columns"):
table.to_arrow(blob_mode="bytes")
table_arrow = table.to_arrow(blob_mode="bytes")
assert table_arrow.schema.field("blob").type == pa.large_binary()
assert "_rowid" not in table_arrow.column_names
assert table_arrow["blob"].to_pylist() == [b"one", b"two", b"three", b"four"]
assert table.to_pandas(blob_mode="bytes")["blob"].tolist() == [
b"one",
b"two",
+346 -10
View File
@@ -10,6 +10,7 @@ import io
import inspect
import json
import multiprocessing as mp
from pathlib import Path
import pickle
import re
import socket
@@ -36,6 +37,7 @@ from lancedb.graph import (
PropertyGraph,
PropertyGraphDescription,
)
from lancedb.functions import FunctionApplication, function
from lancedb.query import (
AsyncQuery,
ColumnOrdering,
@@ -1863,7 +1865,16 @@ def test_remote_create_index_async_returns_job():
{"batch_size": None},
{"batch_size": 1},
{"batch_size": 8},
{"max_concurrency": 3},
{"publication_interval_rows": 60},
{"resource_budget": {"cpu_millis": 2000, "memory_bytes": 4 * 1024**3}},
{
"resource_budget": {
"cpu_millis": 8000,
"memory_bytes": 16 * 1024**3,
"gpu_count": 2,
}
},
{"gpu_class": "a10g", "gpu_count": 2},
{
"retry_policy": {"transient": True, "max_attempts": 3},
@@ -1904,6 +1915,12 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
expected["gpu_class"] = refresh_kwargs["gpu_class"]
if refresh_kwargs.get("gpu_count") is not None:
expected["gpu_count"] = refresh_kwargs["gpu_count"]
if refresh_kwargs.get("resource_budget") is not None:
budget = refresh_kwargs["resource_budget"]
expected["resource_budget"] = {
**budget,
"gpu_count": budget.get("gpu_count", 0),
}
if refresh_kwargs.get("retry_policy") is not None:
expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate(
refresh_kwargs["retry_policy"]
@@ -1912,6 +1929,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
expected["error_policy"] = refresh_kwargs["error_policy"]
for key in (
"where",
"max_concurrency",
"publication_interval_rows",
"max_failed_fraction",
"max_failed_rows",
@@ -2092,7 +2110,45 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle():
({"init_timeout_seconds": -5}, "init_timeout_seconds"),
({"publication_interval_rows": 0}, "publication_interval_rows"),
({"publication_interval_rows": -1}, "publication_interval_rows"),
({"max_concurrency": True}, "max_concurrency"),
({"max_concurrency": 1.5}, "max_concurrency"),
({"max_concurrency": 0}, "max_concurrency"),
({"max_concurrency": -1}, "max_concurrency"),
({"max_concurrency": 2**32}, "max_concurrency"),
({"num_workers": 0}, "num_workers"),
(
{"resource_budget": {"cpu_millis": 1000}},
"resource_budget.memory_bytes",
),
(
{
"resource_budget": {
"cpu_millis": 0,
"memory_bytes": 1,
}
},
"resource_budget.cpu_millis",
),
(
{
"resource_budget": {
"cpu_millis": 1000,
"memory_bytes": 1,
},
"gpu_count": 1,
},
"gpu_count cannot be combined with resource_budget",
),
(
{
"resource_budget": {
"cpu_millis": 1000,
"memory_bytes": 1,
"unknown": 1,
}
},
"unsupported key 'unknown'",
),
(
{"max_executor_processes_per_worker": -2},
"max_executor_processes_per_worker",
@@ -2232,6 +2288,164 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(attempts):
assert everything.truncated is True
def test_remote_function_column_status_passes_pinned_version():
queries = []
status = {
"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": None,
"next_run_at_reason": "job_queued_not_started",
},
}
def handler(request):
parsed = urlparse(request.path)
if parsed.path == "/v1/table/test/describe/":
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(
json.dumps({"version": 42, "schema": {"fields": []}}).encode()
)
elif parsed.path == "/v1/table/test/function_columns/status":
queries.append(parse_qs(parsed.query))
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps([status]).encode())
else:
request.send_response(404)
request.end_headers()
with mock_lancedb_connection(handler) as db:
table = db.open_table("test")
table.checkout(42)
result = table.column_status("embedding")
assert queries == [{"column": ["embedding"], "version": ["42"]}]
assert result.table_version == 42
assert (result.fresh, result.stale, result.never_computed, result.failed) == (
2,
2,
0,
0,
)
assert result.auto_refresh.state == "queued"
assert result.auto_refresh.active_job_id == "job-queued"
assert result.auto_refresh.failure_streak == 1
assert result.auto_refresh.next_run_at_reason == "job_queued_not_started"
assert result.last_refresh_job.state == "cancelled"
assert result.last_refresh_job.failure is None
assert result.last_failure_job.job_id == "job-failed"
failure = result.last_failure_job.failure
assert failure.phase == "finalize"
assert failure.message == "worker timed out"
assert failure.traceback == "Traceback: timeout"
assert failure.retryable is True
assert failure.sql_job_id == "sql-job-7"
def test_remote_wait_fresh_retries_only_typed_finalization_pending():
calls = 0
status = {
"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": 1,
"fresh": 1,
"stale": 0,
"never_computed": 0,
"failed": 0,
"auto_refresh": {
"enabled": False,
"state": "disabled",
"failure_streak": 0,
"next_run_at_millis": None,
},
}
def handler(request):
nonlocal calls
parsed = urlparse(request.path)
if parsed.path == "/v1/table/test/describe/":
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(
json.dumps({"version": 42, "schema": {"fields": []}}).encode()
)
elif parsed.path == "/v1/table/test/function_columns/status":
calls += 1
if calls == 1:
request.send_response(503)
request.send_header(
"x-lancedb-error-code",
"function_column_status_finalization_pending",
)
request.end_headers()
request.wfile.write(b"finalization pending")
else:
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps([status]).encode())
else:
request.send_response(404)
request.end_headers()
with mock_lancedb_connection(handler) as db:
table = db.open_table("test")
result = table.wait_fresh("embedding", timeout=timedelta(seconds=2))
assert calls == 2
assert result.fresh == result.rows == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
@pytest.mark.parametrize("failure", ["send", "read"])
@@ -4958,8 +5172,12 @@ def test_sync_remote_blob_pandas_avoids_storage_access(
assert "_rowid" not in df.columns
assert df["image"][0]["size"] == 5
else:
with pytest.raises(NotImplementedError, match="stable table snapshot"):
with pytest.raises(
NotImplementedError, match="stable table snapshot"
) as exc:
query.to_pandas(blob_mode=blob_mode)
assert "fetch_blobs(column, row_ids)" in str(exc.value)
assert "with_row_id(True)" in str(exc.value)
@pytest.mark.asyncio
@@ -5539,9 +5757,6 @@ def test_remote_job_handle_reports_its_own_detail():
assert json.loads(job._spec_json) == {"column": "vec"}
assert json.loads(job._result_json) == {"rows_assigned": 1000000}
# print() shows everything the handle knows and nothing it does not.
# print() lays every known field out on its own line, with the JSON
# payloads indented rather than crammed onto one line.
assert repr(job) == "\n".join(
[
"Job(",
@@ -5549,12 +5764,8 @@ def test_remote_job_handle_reports_its_own_detail():
" state='finished',",
" job_type='refresh_column',",
" creation_ms=2000,",
" spec={",
' "column": "vec"',
" },",
" result={",
' "rows_assigned": 1000000',
" },",
" spec={'column': 'vec'},",
" result={'rows_assigned': 1000000},",
")",
]
)
@@ -5787,6 +5998,92 @@ def test_remote_add_columns_reader_not_supported():
assert all("/add_columns/" not in path for path in requests)
@pytest.mark.asyncio
async def test_remote_add_function_columns_forwards_auto_refresh_resource_budget():
bodies = []
application = FunctionApplication.from_json(
json.dumps(
{
"function": {
"name": "embed",
"version": "1",
"object_id": "fixture",
"location": "memory:///fixture",
"manifest_digest": (
"sha256:7e22f815b6648e14f093a3979a8e5a2082"
"fa773ebe1ec84b135cae7e84d6f8e6"
),
},
"inputs": [
{
"parameter": "text",
"kind": "column",
"value": {"path": "text"},
}
],
"output": {
"kind": "scalar",
"arrow_type": "float32",
"nullable": False,
},
}
)
)
def handler(request):
if request.path == "/v1/table/test/describe/":
response = {
"version": 1,
"schema": {
"fields": [
{
"name": "text",
"type": {"type": "string"},
"nullable": True,
}
]
},
}
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(response).encode())
elif request.path == "/v1/table/test/add_columns/":
content_len = int(request.headers.get("Content-Length", 0))
bodies.append(json.loads(request.rfile.read(content_len)))
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(b'{"version": 2}')
else:
request.send_response(404)
request.end_headers()
budget = {"cpu_millis": 2_000, "memory_bytes": 4 * 1024**3}
with mock_lancedb_connection(handler) as db:
table = db.open_table("test")
table.add_columns(
{"embedding": application},
auto_refresh_resource_budget=budget,
)
async with mock_lancedb_connection_async(handler) as db:
table = await db.open_table("test")
await table.add_columns(
{"embedding": application},
auto_refresh_resource_budget=budget,
)
assert len(bodies) == 2
for body in bodies:
assert body["auto_refresh_enabled"] is True
assert body["auto_refresh_resource_budget"] == {
**budget,
"gpu_count": 0,
}
assert body["new_columns"] == [{"name": "embedding", "all_null": True}]
@pytest.mark.asyncio
async def test_async_property_graph_handles():
calls = []
@@ -5962,6 +6259,45 @@ def _mock_remote_table_with_sql(flight_server):
yield lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
def test_remote_function_registration_transports_max_concurrency():
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust"
/ "lancedb"
/ "tests"
/ "fixtures"
/ "first_class_functions"
/ "v1"
/ "remote_function_version.canonical.json"
)
definition = json.loads(fixture.read_text())
definition["max_concurrency"] = 4
@function(name="normalize_score", max_concurrency=4)
def registered(value: float) -> float:
return value
class RegistrationServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.tickets = []
def do_get(self, context, ticket):
self.tickets.append(ticket.ticket)
return flight.RecordBatchStream(
pa.table({"definition": [json.dumps(definition)]})
)
server = RegistrationServer()
with _mock_remote_sql_connection(server) as kwargs:
version = lancedb.connect(**kwargs).create_function(registered)
assert len(server.tickets) == 1
assert b'"max_concurrency":4' in server.tickets[0]
assert version.max_concurrency == 4
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
+10
View File
@@ -20,6 +20,7 @@ NIL_QUERY_ID = UUID(int=0)
class FakeNativeQuery:
id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef")
job_id = None
async def reader(self):
return pa.table({"value": [1, 2]})
@@ -68,6 +69,15 @@ def test_query_id_is_uuid():
assert Query(query).id == query.id
def test_query_job_id_is_optional_and_separate_from_query_id():
native = FakeNativeQuery()
native.job_id = "j1-durable"
query = AsyncQuery(native)
assert query.id != query.job_id
assert query.job_id == "j1-durable"
assert Query(query).job_id == "j1-durable"
def test_connection_serializes_sql_host_override():
endpoint = "grpc+tls://sql.example.com:10026"
restored = lancedb.deserialize_conn(
+30
View File
@@ -5995,7 +5995,12 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
({"max_failed_rows": 10}, "max_failed_rows"),
({"row_timeout_seconds": 30}, "row_timeout_seconds"),
({"init_timeout_seconds": 60}, "init_timeout_seconds"),
({"max_concurrency": 4}, "max_concurrency"),
({"publication_interval_rows": 60}, "publication_interval_rows"),
(
{"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}},
"resource_budget",
),
({"num_workers": 2}, "num_workers"),
({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
],
@@ -6031,6 +6036,16 @@ def test_function_errors_are_remote_only(tmp_path):
table.function_errors()
def test_function_column_status_is_remote_only(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("t", [{"x": 1}])
with pytest.raises(
NotImplementedError,
match="exact Function column status is supported only in LanceDB Enterprise",
):
table.wait_fresh("x")
@pytest.mark.experimental_functions
@pytest.mark.parametrize("batch_size", [None, 8])
def test_refresh_column_async_returns_job(tmp_path, batch_size):
@@ -6251,6 +6266,21 @@ def test_auto_refresh_options_require_computed_columns(tmp_path):
table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True)
def test_auto_refresh_resource_budget_requires_a_function(tmp_path):
table = lancedb.connect(tmp_path).create_table("invalid_budget", [{"x": 1}])
before = table.version
with pytest.raises(ValueError, match="registered Function"):
table.add_columns(
computed={"doubled": "x * 2"},
auto_refresh_resource_budget={
"cpu_millis": 1_000,
"memory_bytes": 1_024,
},
)
assert table.version == before
assert table.schema.names == ["x"]
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
+8 -8
View File
@@ -877,22 +877,22 @@ impl Connection {
})
}
#[pyo3(signature = (name, version, namespace_path=None))]
#[pyo3(signature = (name, version=None, namespace_path=None))]
pub fn get_function(
self_: PyRef<'_, Self>,
name: String,
version: String,
version: Option<String>,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
.get_function(name, version, &namespace_path)
.await
.infer_error()?
.to_canonical_json()
.infer_error()
let function = match version {
Some(version) => inner.get_function(name, version, &namespace_path).await,
None => inner.get_function_latest(name, &namespace_path).await,
}
.infer_error()?;
function.to_canonical_json().infer_error()
})
}
+3 -1
View File
@@ -10,6 +10,7 @@ use lancedb::index::{
Index as LanceDbIndex,
scalar::{
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
ZoneMapIndexBuilder,
},
};
use pyo3::IntoPyObject;
@@ -117,6 +118,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
"LabelList" => Ok(LanceDbIndex::LabelList(Default::default())),
"Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())),
"NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())),
"ZoneMap" => Ok(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default())),
"FTS" => {
let params = source.extract::<FtsParams>()?;
let code_options = CodeAnalyzerOptions {
@@ -291,7 +293,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
Ok(LanceDbIndex::IvfHnswFlat(hnsw_flat_builder))
}
not_supported => Err(PyValueError::new_err(format!(
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
not_supported
))),
}
+21 -8
View File
@@ -152,6 +152,13 @@ impl Job {
self.inner.description().map(JobDescription::from)
}
pub fn timeline(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
Ok(inner.timeline().await.infer_error()?.to_string())
})
}
#[pyo3(signature = (*, limit=None, filter=None))]
pub fn events(
self_: PyRef<'_, Self>,
@@ -228,7 +235,7 @@ impl From<lancedb::database::JobInfo> for JobInfo {
/// The server's account of why a job failed.
#[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)]
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct JobFailureInfo {
phase: Option<String>,
message: Option<String>,
@@ -238,6 +245,18 @@ pub struct JobFailureInfo {
sql_job_id: Option<String>,
}
impl From<lancedb::error::JobFailure> for JobFailureInfo {
fn from(failure: lancedb::error::JobFailure) -> Self {
Self {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
sql_job_id: failure.sql_job_id,
}
}
}
#[pymethods]
impl JobFailureInfo {
fn __repr__(&self) -> String {
@@ -341,13 +360,7 @@ impl From<lancedb::database::JobDescription> for JobDescription {
.filter(|result| !result.is_null())
.map(|result| result.to_string()),
_progress_json: Some(progress_json),
failure: description.failure.map(|failure| JobFailureInfo {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
sql_job_id: failure.sql_job_id,
}),
failure: description.failure.map(Into::into),
}
}
}
+8 -3
View File
@@ -16,9 +16,10 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery};
use session::Session;
use table::{
AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken,
FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, MergeResult, PyBlobFile,
RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, Table,
UpdateFieldMetadataResult, UpdateResult,
FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus,
FunctionColumnVersionStatus, FunctionErrorFragment, FunctionErrorRecord, FunctionErrors,
MergeResult, PyBlobFile, RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult,
Table, UpdateFieldMetadataResult, UpdateResult,
};
pub mod arrow;
@@ -117,6 +118,10 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<FunctionErrors>()?;
m.add_class::<FunctionErrorRecord>()?;
m.add_class::<FunctionErrorFragment>()?;
m.add_class::<FunctionColumnStatus>()?;
m.add_class::<FunctionColumnVersionStatus>()?;
m.add_class::<FunctionColumnLastRefreshJob>()?;
m.add_class::<FunctionColumnAutoRefreshStatus>()?;
m.add_class::<RefreshMaterializedViewResult>()?;
m.add_class::<AlterColumnsResult>()?;
m.add_class::<UpdateFieldMetadataResult>()?;
+9 -2
View File
@@ -31,6 +31,11 @@ impl Query {
self.inner.id()
}
#[getter]
pub fn job_id(&self) -> Option<String> {
self.inner.job_id()
}
pub fn describe(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
@@ -63,6 +68,7 @@ impl Query {
#[derive(Clone)]
pub struct QueryDescription {
id: Uuid,
job_id: Option<String>,
status: String,
progress: Option<f64>,
expires_at: Option<DateTime<Utc>>,
@@ -72,8 +78,8 @@ pub struct QueryDescription {
impl QueryDescription {
fn __repr__(&self) -> String {
format!(
"QueryDescription(id={:?}, status={:?}, progress={:?}, expires_at={:?})",
self.id, self.status, self.progress, self.expires_at
"QueryDescription(id={:?}, job_id={:?}, status={:?}, progress={:?}, expires_at={:?})",
self.id, self.job_id, self.status, self.progress, self.expires_at
)
}
}
@@ -82,6 +88,7 @@ impl From<lancedb::sql::QueryDescription> for QueryDescription {
fn from(description: lancedb::sql::QueryDescription) -> Self {
Self {
id: description.id,
job_id: description.job_id,
status: description.status.to_string(),
progress: description.progress,
expires_at: description.expires_at,
+307 -19
View File
@@ -15,6 +15,7 @@ use crate::{
error::PythonErrorExt,
expr::PyExpr,
index::{CodeAnalyzerOptions, IndexConfig, extract_index_params},
job::JobFailureInfo,
query::{Query, TakeQuery},
table::scannable::PyScannable,
};
@@ -29,15 +30,17 @@ use lancedb::connection::LanceFileVersion;
use lancedb::index::scalar::FtsIndexBuilder;
use lancedb::table::{
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, Ref,
RefreshColumnOptions, Table as LanceDbTable,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionWorkerResourceBudget, IndexRemapMode,
NewColumnTransform, Ref, RefreshColumnOptions, Table as LanceDbTable,
};
use lancedb::tokenize as lancedb_tokenize;
use pyo3::{
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
exceptions::{PyRuntimeError, PyValueError},
pyclass, pyfunction, pymethods,
types::{IntoPyDict, PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods},
types::{
IntoPyDict, PyAnyMethods, PyBool, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods,
},
};
mod scannable;
@@ -46,7 +49,9 @@ mod scannable;
struct RefreshColumnArgs {
where_clause: Option<String>,
batch_size: Option<i64>,
max_concurrency: Option<u32>,
publication_interval_rows: Option<i64>,
resource_budget: Option<FunctionWorkerResourceBudget>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -70,11 +75,97 @@ fn positive_count<T: TryFrom<i64>>(value: Option<i64>, name: &str) -> PyResult<O
.transpose()
}
fn positive_u32_integer(value: Option<&Bound<'_, PyAny>>, name: &str) -> PyResult<Option<u32>> {
let Some(value) = value else {
return Ok(None);
};
if value.is_none() || value.is_instance_of::<PyBool>() {
return Err(PyValueError::new_err(format!(
"{name} must be an integer between 1 and 4294967295"
)));
}
let parsed = value.extract::<i64>().map_err(|_| {
PyValueError::new_err(format!(
"{name} must be an integer between 1 and 4294967295"
))
})?;
u32::try_from(parsed)
.ok()
.filter(|parsed| *parsed > 0)
.map(Some)
.ok_or_else(|| {
PyValueError::new_err(format!(
"{name} must be an integer between 1 and 4294967295"
))
})
}
fn resource_budget_integer(
value: &Bound<'_, PyAny>,
name: &str,
allow_zero: bool,
) -> PyResult<u64> {
if value.is_none() || value.is_instance_of::<PyBool>() {
return Err(PyValueError::new_err(format!(
"resource_budget.{name} must be an integer"
)));
}
let parsed = value
.extract::<u64>()
.map_err(|_| PyValueError::new_err(format!("resource_budget.{name} must be an integer")))?;
if !allow_zero && parsed == 0 {
return Err(PyValueError::new_err(format!(
"resource_budget.{name} must be greater than zero"
)));
}
Ok(parsed)
}
fn parse_resource_budget(
budget: Option<&Bound<'_, PyDict>>,
) -> PyResult<Option<FunctionWorkerResourceBudget>> {
let Some(budget) = budget else {
return Ok(None);
};
for key in budget.keys() {
let key = key
.extract::<String>()
.map_err(|_| PyValueError::new_err("resource_budget keys must be strings"))?;
if !matches!(key.as_str(), "cpu_millis" | "memory_bytes" | "gpu_count") {
return Err(PyValueError::new_err(format!(
"resource_budget contains unsupported key '{key}'"
)));
}
}
let cpu_millis = budget
.get_item("cpu_millis")?
.ok_or_else(|| PyValueError::new_err("resource_budget.cpu_millis is required"))?;
let cpu_millis = resource_budget_integer(&cpu_millis, "cpu_millis", false)?;
let memory_bytes = budget
.get_item("memory_bytes")?
.ok_or_else(|| PyValueError::new_err("resource_budget.memory_bytes is required"))?;
let memory_bytes = resource_budget_integer(&memory_bytes, "memory_bytes", false)?;
let gpu_count = match budget.get_item("gpu_count")? {
None => 0,
Some(value) if value.is_none() => 0,
Some(value) => {
u32::try_from(resource_budget_integer(&value, "gpu_count", true)?).map_err(|_| {
PyValueError::new_err("resource_budget.gpu_count must be no greater than u32::MAX")
})?
}
};
Ok(Some(
FunctionWorkerResourceBudget::new(cpu_millis, memory_bytes).with_gpu_count(gpu_count),
))
}
fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOptions> {
let RefreshColumnArgs {
where_clause,
batch_size,
max_concurrency,
publication_interval_rows,
resource_budget,
gpu_class,
gpu_count,
retry_policy,
@@ -116,8 +207,10 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
.map(usize::try_from)
.transpose()
.map_err(|_| PyValueError::new_err("batch_size must be greater than zero"))?;
options.max_concurrency = max_concurrency;
options.publication_interval_rows =
positive_count(publication_interval_rows, "publication_interval_rows")?;
options.resource_budget = resource_budget;
options.gpu_class = gpu_class;
options.gpu_count = gpu_count
.map(|count| {
@@ -800,6 +893,140 @@ impl From<lancedb::function::FunctionErrors> for FunctionErrors {
}
}
/// Exact immutable Function revision attached to a table output.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnVersionStatus {
pub name: String,
pub namespace_path: Vec<String>,
pub object_id: String,
pub location: String,
pub version: String,
pub manifest_digest: String,
}
impl From<lancedb::function::FunctionVersionRef> for FunctionColumnVersionStatus {
fn from(function: lancedb::function::FunctionVersionRef) -> Self {
Self {
name: function.name,
namespace_path: function.namespace_path,
object_id: function.object_id,
location: function.location,
version: function.version,
manifest_digest: function.manifest_digest,
}
}
}
/// Latest matching refresh Job projected for a Function output.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnLastRefreshJob {
pub job_id: String,
pub state: String,
pub automatic: Option<bool>,
pub completed_at_millis: Option<i64>,
pub failure: Option<JobFailureInfo>,
}
impl From<lancedb::table::FunctionColumnLastRefreshJob> for FunctionColumnLastRefreshJob {
fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self {
Self {
job_id: job.job_id,
state: job.state,
automatic: job.automatic,
completed_at_millis: job.completed_at_millis,
failure: job.failure.map(Into::into),
}
}
}
/// Automatic-refresh projection for a Function output.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnAutoRefreshStatus {
pub enabled: bool,
pub interval_seconds: Option<u64>,
pub active_job_id: Option<String>,
pub state: String,
pub failure_streak: u32,
pub effective_cooldown_millis: Option<u64>,
pub blocked_reason: Option<String>,
pub next_run_at_millis: Option<i64>,
pub next_run_at_reason: Option<String>,
}
impl From<lancedb::table::FunctionColumnAutoRefreshStatus> for FunctionColumnAutoRefreshStatus {
fn from(status: lancedb::table::FunctionColumnAutoRefreshStatus) -> Self {
Self {
enabled: status.enabled,
interval_seconds: status.interval_seconds,
active_job_id: status.active_job_id,
state: status.state.as_str().to_string(),
failure_streak: status.failure_streak,
effective_cooldown_millis: status.effective_cooldown_millis,
blocked_reason: status
.blocked_reason
.map(|reason| reason.as_str().to_string()),
next_run_at_millis: status.next_run_at_millis,
next_run_at_reason: status.next_run_at_reason,
}
}
}
/// Exact four-way status of one Function output at one table version.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnStatus {
pub column: String,
pub binding_id: String,
pub function: FunctionColumnVersionStatus,
pub table_version: u64,
pub rows: u64,
pub fresh: u64,
pub stale: u64,
pub never_computed: u64,
pub failed: u64,
pub last_refresh_job: Option<FunctionColumnLastRefreshJob>,
pub last_failure_job: Option<FunctionColumnLastRefreshJob>,
pub auto_refresh: FunctionColumnAutoRefreshStatus,
}
#[pymethods]
impl FunctionColumnStatus {
pub fn __repr__(&self) -> String {
format!(
"FunctionColumnStatus(column={:?}, table_version={}, rows={}, fresh={}, stale={}, never_computed={}, failed={})",
self.column,
self.table_version,
self.rows,
self.fresh,
self.stale,
self.never_computed,
self.failed
)
}
}
impl From<lancedb::table::FunctionColumnStatus> for FunctionColumnStatus {
fn from(status: lancedb::table::FunctionColumnStatus) -> Self {
Self {
column: status.column,
binding_id: status.binding_id,
function: status.function.into(),
table_version: status.table_version,
rows: status.rows,
fresh: status.fresh,
stale: status.stale,
never_computed: status.never_computed,
failed: status.failed,
last_refresh_job: status.last_refresh_job.map(Into::into),
last_failure_job: status.last_failure_job.map(Into::into),
auto_refresh: status.auto_refresh.into(),
}
}
}
#[pyclass(get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct RefreshMaterializedViewResult {
@@ -2153,17 +2380,21 @@ impl Table {
})
}
#[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
pub fn add_computed_columns(
self_: PyRef<'_, Self>,
#[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))]
pub fn add_computed_columns<'py>(
self_: PyRef<'py, Self>,
columns: Vec<(String, String)>,
auto_refresh_enabled: Option<bool>,
auto_refresh_interval_seconds: Option<u64>,
) -> PyResult<Bound<'_, PyAny>> {
auto_refresh_resource_budget: Option<Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self_.inner_ref()?.clone();
let options = ComputedColumnOptions {
auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true),
auto_refresh_interval_seconds,
auto_refresh_resource_budget: parse_resource_budget(
auto_refresh_resource_budget.as_ref(),
)?,
};
options.validate().infer_error()?;
future_into_py(self_.py(), async move {
@@ -2180,20 +2411,24 @@ impl Table {
})
}
#[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
pub fn add_function_columns(
self_: PyRef<'_, Self>,
#[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))]
pub fn add_function_columns<'py>(
self_: PyRef<'py, Self>,
application_json: String,
output_name: Option<String>,
auto_refresh_enabled: Option<bool>,
auto_refresh_interval_seconds: Option<u64>,
) -> PyResult<Bound<'_, PyAny>> {
auto_refresh_resource_budget: Option<Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
let application =
lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?;
let inner = self_.inner_ref()?.clone();
let options = ComputedColumnOptions {
auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true),
auto_refresh_interval_seconds,
auto_refresh_resource_budget: parse_resource_budget(
auto_refresh_resource_budget.as_ref(),
)?,
};
options.validate().infer_error()?;
future_into_py(self_.py(), async move {
@@ -2210,14 +2445,16 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column(
self_: PyRef<'_, Self>,
pub fn refresh_column<'py>(
self_: PyRef<'py, Self>,
column: String,
r#where: Option<String>,
batch_size: Option<i64>,
max_concurrency: Option<Bound<'py, PyAny>>,
publication_interval_rows: Option<i64>,
resource_budget: Option<Bound<'py, PyDict>>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2228,11 +2465,13 @@ impl Table {
init_timeout_seconds: Option<f64>,
num_workers: Option<i64>,
max_executor_processes_per_worker: Option<i64>,
) -> PyResult<Bound<'_, PyAny>> {
) -> PyResult<Bound<'py, PyAny>> {
let options = refresh_column_options(RefreshColumnArgs {
where_clause: r#where,
batch_size,
max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?,
publication_interval_rows,
resource_budget: parse_resource_budget(resource_budget.as_ref())?,
gpu_class,
gpu_count,
retry_policy,
@@ -2254,14 +2493,16 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column_async(
self_: PyRef<'_, Self>,
pub fn refresh_column_async<'py>(
self_: PyRef<'py, Self>,
column: String,
r#where: Option<String>,
batch_size: Option<i64>,
max_concurrency: Option<Bound<'py, PyAny>>,
publication_interval_rows: Option<i64>,
resource_budget: Option<Bound<'py, PyDict>>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2272,11 +2513,13 @@ impl Table {
init_timeout_seconds: Option<f64>,
num_workers: Option<i64>,
max_executor_processes_per_worker: Option<i64>,
) -> PyResult<Bound<'_, PyAny>> {
) -> PyResult<Bound<'py, PyAny>> {
let options = refresh_column_options(RefreshColumnArgs {
where_clause: r#where,
batch_size,
max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?,
publication_interval_rows,
resource_budget: parse_resource_budget(resource_budget.as_ref())?,
gpu_class,
gpu_count,
retry_policy,
@@ -2317,6 +2560,51 @@ impl Table {
})
}
#[pyo3(signature = (column=None))]
pub fn column_statuses(
self_: PyRef<'_, Self>,
column: Option<String>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let statuses = inner
.function_column_statuses(column.as_deref())
.await
.infer_error()?;
Ok(statuses
.into_iter()
.map(FunctionColumnStatus::from)
.collect::<Vec<_>>())
})
}
pub fn column_status(self_: PyRef<'_, Self>, column: String) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let status = inner.function_column_status(&column).await.infer_error()?;
Ok(FunctionColumnStatus::from(status))
})
}
#[pyo3(signature = (column, timeout=None))]
pub fn wait_column_fresh<'py>(
self_: PyRef<'py, Self>,
column: String,
timeout: Option<Bound<'py, PyAny>>,
) -> PyResult<Bound<'py, PyAny>> {
let timeout = timeout
.map(|timeout| timeout.extract::<std::time::Duration>())
.transpose()?;
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let status = inner
.wait_for_function_column(&column, timeout)
.await
.infer_error()?;
Ok(FunctionColumnStatus::from(status))
})
}
#[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_materialized_view(
+8 -7
View File
@@ -2147,7 +2147,7 @@ requires-dist = [
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
{ name = "pydantic", specifier = ">=2.7.4,<3" },
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b16" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b17" },
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
@@ -4301,7 +4301,7 @@ crypto = [
[[package]]
name = "pylance"
version = "15.0.0b16"
version = "15.0.0b17"
source = { registry = "https://pypi.fury.io/lance-format/" }
dependencies = [
{ name = "lance-namespace" },
@@ -4312,11 +4312,12 @@ dependencies = [
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
]
wheels = [
{ url = "https://pypi.fury.io/lance-format/-/ver_uZ4Az/pylance-15.0.0b16-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c4ed0ab9213082d9d8cc93aa09351e84574c76ddefc422a2ad073115bd9a1b43" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1nenYa/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f28f7b757ade1e4b556e788bc77d4ffcc351a9c8c570b35f769c457e9cc13bf" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1cb3ns/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49f358f3ddf33d76567f56d0e4a66c218dc1a2d2f06d37d779e13c87b1c3d9a6" },
{ url = "https://pypi.fury.io/lance-format/-/ver_g7LAk/pylance-15.0.0b16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:288c1b41f5068990672c8c182b4b79d6389c1a907c59ef6047cbee494d1e34ec" },
{ url = "https://pypi.fury.io/lance-format/-/ver_12YRtQ/pylance-15.0.0b16-cp310-abi3-win_amd64.whl", hash = "sha256:fa69acdd0960280f6fe8a83ea992fc92e2ed5a0eeb5159b90493dfc76831f752" },
{ url = "https://pypi.fury.io/lance-format/-/ver_il4JF/pylance-15.0.0b17-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:ee3c3d2baf1f0d788d706638873317740178a81988b71ffda47a2e71d1e15ff3" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2hFd0a/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a5b576e35054d4866d823ebadc9d3c531165628feb29ca1528db15b9082675a" },
{ url = "https://pypi.fury.io/lance-format/-/ver_29zVw5/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47c534032d2f251f396657e47efbc224ee2d1964495d7982a449e5e1cdcf3169" },
{ url = "https://pypi.fury.io/lance-format/-/ver_548nr/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:509db7d8be3eebb111b7d28aa486437424cb3663cfb7f502b71532fa37ba7155" },
{ url = "https://pypi.fury.io/lance-format/-/ver_gmpNu/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd2cc05c2d553d44c54570612e793136e3433fcba28e4d51a503cca8f45435ea" },
{ url = "https://pypi.fury.io/lance-format/-/ver_Otspk/pylance-15.0.0b17-cp310-abi3-win_amd64.whl", hash = "sha256:510c419e21a4daa4c18db4cc5048bd7dfc706924b23e13136306935f2e3e0c25" },
]
[[package]]
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb"
version = "0.42.0-beta.10"
version = "0.42.0-beta.11"
edition.workspace = true
description = "LanceDB: A serverless, low-latency vector database for AI applications"
license.workspace = true
@@ -46,7 +46,7 @@ lance-io = { workspace = true }
lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lindera"] }
lance-table = { workspace = true }
# Keep the upstream source for downstream SDKs, where workspace patches do not apply.
lance-linalg = { "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.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { workspace = true }
lance-arrow = { workspace = true }
lance-namespace = { workspace = true }
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-cli"
version = "0.42.0-beta.10"
version = "0.42.0-beta.11"
edition = "2021"
license.workspace = true
repository.workspace = true
+20 -3
View File
@@ -668,9 +668,10 @@ impl Connection {
/// Look up one exact immutable Function version in the remote catalog.
///
/// Both the logical name and server-assigned version id are required;
/// mutable aliases and latest-version lookup are intentionally absent.
/// LanceDB Embedded databases return [`Error::NotSupported`].
/// Both the logical name and server-assigned version id are required.
/// Use [`Self::get_function_latest`] when the caller wants the latest
/// currently visible revision. LanceDB Embedded databases return
/// [`Error::NotSupported`].
pub async fn get_function(
&self,
name: impl AsRef<str>,
@@ -682,6 +683,22 @@ impl Connection {
.await
}
/// Look up the latest currently visible immutable Function version.
///
/// The server resolves and returns one exact version document. This is a
/// resolution point, not a mutable alias: later registrations do not
/// change the returned object. LanceDB Embedded databases return
/// [`Error::NotSupported`].
pub async fn get_function_latest(
&self,
name: impl AsRef<str>,
namespace_path: &[String],
) -> Result<crate::function::FunctionVersion> {
self.internal
.get_function_latest(name.as_ref(), namespace_path)
.await
}
/// List every published immutable Function version in `namespace_path` of
/// the remote catalog. Functions in child namespaces are not included.
///
+8
View File
@@ -552,6 +552,14 @@ pub trait Database:
) -> Result<crate::function::FunctionVersion> {
function_catalog_not_supported()
}
/// Look up the latest currently visible immutable Function version.
async fn get_function_latest(
&self,
_name: &str,
_namespace_path: &[String],
) -> Result<crate::function::FunctionVersion> {
function_catalog_not_supported()
}
/// Fetch one page of published immutable Function versions in one namespace.
async fn list_functions(
&self,
+44 -1
View File
@@ -253,24 +253,48 @@ impl snafu::AsErrorSource for InterruptionSource {
/// A job run remotely carries whatever the server reported, which older servers
/// do not report at all. Every field is absent rather than invented when the
/// backend does not supply it.
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub struct JobFailure {
/// The stage the job was in, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub phase: Option<String>,
/// A human-readable reason, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
/// User-code traceback, possibly truncated by the server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub traceback: Option<String>,
/// Whether a retry could clear the failure, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retryable: Option<bool>,
/// Isolated SQL job that raised this failure, when the server supplies
/// one across the Flight SQL boundary.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sql_job_id: Option<String>,
/// The underlying error from a job run in this process or a structured
/// remote Flight SQL failure.
#[serde(skip)]
pub source: Option<Arc<Error>>,
}
impl PartialEq for JobFailure {
fn eq(&self, other: &Self) -> bool {
let source_matches = match (&self.source, &other.source) {
(None, None) => true,
(Some(left), Some(right)) => Arc::ptr_eq(left, right),
_ => false,
};
self.phase == other.phase
&& self.message == other.message
&& self.traceback == other.traceback
&& self.retryable == other.retryable
&& self.sql_job_id == other.sql_job_id
&& source_matches
}
}
impl Eq for JobFailure {}
impl JobFailure {
/// A failure whose only known detail is the error that caused it.
pub(crate) fn from_source(source: Arc<Error>) -> Self {
@@ -543,6 +567,25 @@ fn has_unsupported_local_filesystem_source(error: &(dyn std::error::Error + 'sta
}
impl Error {
/// HTTP status associated with a remote request error.
///
/// Retry wrappers preserve the underlying status. Other error variants do
/// not represent an HTTP response and return `None`.
#[cfg(feature = "remote")]
pub fn status_code(&self) -> Option<reqwest::StatusCode> {
match self {
Self::Http { status_code, .. } => *status_code,
Self::Retry { status_code, .. } => *status_code,
Self::TableNotFound { source, .. } => {
source.downcast_ref::<Self>().and_then(Self::status_code)
}
Self::JobFailed { failure, .. } => {
failure.source.as_deref().and_then(Self::status_code)
}
_ => None,
}
}
/// Structured resource details reported by a remote HTTP error.
///
/// Older servers do not include these fields, in which case this returns
+50
View File
@@ -611,6 +611,13 @@ pub struct FunctionVersion {
deserialize_with = "deserialize_batch_size"
)]
batch_size: Option<u32>,
/// Default maximum concurrent user-code calls per logical execution.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_max_concurrency"
)]
max_concurrency: Option<u32>,
/// Per-call deadline in seconds.
#[serde(default, skip_serializing_if = "Option::is_none")]
row_timeout_seconds: Option<RowTimeoutSeconds>,
@@ -681,6 +688,11 @@ impl FunctionVersion {
self.batch_size
}
/// Default maximum concurrent user-code calls, when declared.
pub fn max_concurrency(&self) -> Option<u32> {
self.max_concurrency
}
/// Per-call deadline in seconds, when declared.
pub fn row_timeout_seconds(&self) -> Option<f64> {
self.row_timeout_seconds.map(RowTimeoutSeconds::get)
@@ -769,6 +781,18 @@ where
Ok(value)
}
fn deserialize_max_concurrency<'de, D>(
deserializer: D,
) -> std::result::Result<Option<u32>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<u32>::deserialize(deserializer)
.map_err(|error| de::Error::custom(format!("max_concurrency: {error}")))?;
validate_max_concurrency_value(value).map_err(de::Error::custom)?;
Ok(value)
}
fn validate_batch_size_value(value: Option<u32>) -> std::result::Result<(), &'static str> {
if value == Some(0) {
return Err("batch_size must be between 1 and u32::MAX");
@@ -776,6 +800,13 @@ fn validate_batch_size_value(value: Option<u32>) -> std::result::Result<(), &'st
Ok(())
}
fn validate_max_concurrency_value(value: Option<u32>) -> std::result::Result<(), &'static str> {
if value == Some(0) {
return Err("max_concurrency must be between 1 and u32::MAX");
}
Ok(())
}
fn validate_row_timeout_value(value: Option<f64>) -> std::result::Result<(), &'static str> {
if value.is_some_and(|seconds| !seconds.is_finite() || seconds <= 0.0) {
return Err("row_timeout_seconds must be positive and finite");
@@ -804,6 +835,15 @@ pub struct FunctionRegistrationRequest {
deserialize_with = "deserialize_batch_size"
)]
pub batch_size: Option<u32>,
/// Default maximum concurrent user-code calls for each logical execution
/// of this Function version. Omission leaves the current behavior
/// unchanged.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_max_concurrency"
)]
pub max_concurrency: Option<u32>,
/// Deadline for each Python call, in seconds: one row for scalar Functions
/// and one batch for vectorized Functions. It does not govern Function
/// initialization.
@@ -841,6 +881,7 @@ impl FunctionRegistrationRequest {
message: message.to_string(),
};
validate_batch_size_value(self.batch_size).map_err(invalid_input)?;
validate_max_concurrency_value(self.max_concurrency).map_err(invalid_input)?;
validate_row_timeout_value(self.row_timeout_seconds).map_err(invalid_input)?;
if let Some(policy) = &self.retry_policy {
policy.validate()?;
@@ -1318,6 +1359,15 @@ mod tests {
assert_eq!(version.gpu_class(), Some("a10g"));
let encoded: Value = serde_json::from_str(&version.to_canonical_json().unwrap()).unwrap();
assert_eq!(encoded["gpu_class"], "a10g");
document["max_concurrency"] = serde_json::json!(4);
let version = FunctionVersion::from_json(&document.to_string()).unwrap();
assert_eq!(version.max_concurrency(), Some(4));
let encoded: Value = serde_json::from_str(&version.to_canonical_json().unwrap()).unwrap();
assert_eq!(encoded["max_concurrency"], 4);
document["max_concurrency"] = serde_json::json!(0);
assert!(FunctionVersion::from_json(&document.to_string()).is_err());
}
#[test]
+27
View File
@@ -85,6 +85,11 @@ pub(crate) trait JobHandle: Send + Sync {
async fn describe(&self) -> Result<JobDescription> {
job_detail_not_supported("describing a job")
}
/// Chrome Trace Event JSON for a server-side Function job.
async fn timeline(&self) -> Result<Value> {
job_detail_not_supported("job timeline export")
}
/// The job's recorded lifecycle events.
async fn events(&self, _request: JobEventsRequest) -> Result<Vec<RecordBatch>> {
job_detail_not_supported("job event history")
@@ -468,6 +473,28 @@ where
}
}
/// Fetch a recorded Function job timeline as Chrome Trace Event JSON.
///
/// The snapshot opens in Perfetto or Chrome tracing. It contains retained
/// split and positioned phase spans; batch statistics remain arguments,
/// because individual batch timestamps are not recorded. Running jobs return
/// a partial recording without waiting for completion. Requires server support;
/// in-process operations and SQL query handles do not support this operation.
///
/// ```no_run
/// # async fn export(job: &lancedb::job::Job) -> Result<(), Box<dyn std::error::Error>> {
/// let trace = job.timeline().await?;
/// std::fs::write("job.trace.json", trace.to_string())?;
/// # Ok(())
/// # }
/// ```
pub async fn timeline(&self) -> Result<Value> {
match &self.inner {
JobInner::Handle { handle, .. } => handle.timeline().await,
JobInner::Completed(_) => job_detail_not_supported("job timeline export"),
}
}
/// Waits until the operation reaches a terminal state.
///
/// Returns the endpoint's typed result. Unit-result jobs return `()`.
+57 -1
View File
@@ -887,7 +887,20 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
validate_function_name(name)?;
validate_namespace(namespace_path)?;
self.sql_client()?
.describe_function(name, version, namespace_path)
.describe_function(name, Some(version), namespace_path)
.await
.map_err(direct_catalog_resource_error)
}
async fn get_function_latest(
&self,
name: &str,
namespace_path: &[String],
) -> Result<FunctionVersion> {
validate_function_name(name)?;
validate_namespace(namespace_path)?;
self.sql_client()?
.describe_function(name, None, namespace_path)
.await
.map_err(direct_catalog_resource_error)
}
@@ -4248,6 +4261,49 @@ mod tests {
);
}
#[tokio::test]
async fn test_job_timeline_fetches_recorded_trace_without_waiting() {
let conn = Connection::new_with_handler(|request| {
let body: serde_json::Value =
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
assert_eq!(body["job_id"], "job-1");
let body = match request.url().path() {
"/v1/jobs/describe" => {
r#"{"job_id":"job-1","job_type":"function_refresh","job_state":"IN_PROGRESS","creation_ms":1}"#
}
"/v1/jobs/timeline" => {
r#"{"traceEvents":[{"ph":"X","pid":1,"tid":1,"ts":0,"dur":1000,"name":"Split 1"}],"metadata":{"partial":true}}"#
}
path => panic!("Unexpected request: {path}"),
};
http::Response::builder().status(200).body(body).unwrap()
});
let job = conn.open_job("job-1").await.unwrap();
let trace = job.timeline().await.unwrap();
assert_eq!(trace["traceEvents"][0]["dur"], 1000);
assert_eq!(trace["metadata"]["partial"], true);
}
#[tokio::test]
async fn test_job_timeline_rejects_an_unrelated_json_response() {
let conn = Connection::new_with_handler(|request| {
let body = if request.url().path() == "/v1/jobs/describe" {
r#"{"job_id":"job-1","job_type":"function_refresh","job_state":"SUCCEEDED","creation_ms":1}"#
} else {
r#"{"message":"not a trace"}"#
};
http::Response::builder().status(200).body(body).unwrap()
});
let job = conn.open_job("job-1").await.unwrap();
assert!(
job.timeline()
.await
.unwrap_err()
.to_string()
.contains("not Chrome Trace Event JSON")
);
}
#[tokio::test]
async fn test_job_events_scope_to_that_job() {
let schema = Arc::new(Schema::new(vec![Field::new(
+26
View File
@@ -235,6 +235,32 @@ impl<S: HttpSend> JobHandle for RemoteJob<S> {
Ok(self.fetch_description().await?.1.into_description())
}
async fn timeline(&self) -> Result<serde_json::Value> {
let request = self
.client
.post("/v1/jobs/timeline")
.json(&serde_json::json!({"job_id": self.job_id}));
let (request_id, response) = self.client.send(request).await?;
let response = self.client.check_response(&request_id, response).await?;
let body = response.text().await.err_to_http(request_id.clone())?;
let trace: serde_json::Value =
serde_json::from_str(&body).map_err(|error| Error::Http {
source: format!("failed to parse job timeline: {error}").into(),
request_id: request_id.clone(),
status_code: None,
})?;
if !trace
.get("traceEvents")
.is_some_and(serde_json::Value::is_array)
{
return Err(Error::Http {
source: "server response is not Chrome Trace Event JSON; job timeline export requires server support".into(),
request_id, status_code: None,
});
}
Ok(trace)
}
async fn events(&self, request: JobEventsRequest) -> Result<Vec<RecordBatch>> {
let mut body = serde_json::json!({ "job_id": self.job_id });
if let Some(limit) = request.limit {
+205 -61
View File
@@ -19,11 +19,12 @@ use arrow_flight::{
FlightDescriptor, FlightEndpoint, FlightInfo, PollInfo,
};
use arrow_schema::{Schema, SchemaRef};
use futures::TryStreamExt;
use futures::{StreamExt, TryStreamExt};
use http::header::{HeaderMap, HeaderName, HeaderValue};
use prost::Message;
use serde::{Serialize, de::DeserializeOwned};
use tokio::sync::{Mutex, Notify, OnceCell, mpsc};
use tonic::Request;
use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity};
use uuid::Uuid;
@@ -87,6 +88,12 @@ struct ResultEndpointStream {
stream: FlightRecordBatchStream,
request_id: String,
read_timeout: Duration,
job_id: Option<String>,
}
struct PollResult {
info: PollInfo,
job_id: Option<String>,
}
struct PreparedSqlResult {
@@ -233,10 +240,19 @@ impl SqlClient {
materialized_view_job_handle,
)
.await?;
let query = match opened.submission {
let stream::OpenedSubmission {
submission,
materialized_view_job_handle_supported,
job_id,
} = opened;
let query = match submission {
Submission::Stream(response) => {
let query =
Arc::new(StreamingQuery::new(query_id, self.inner.clone(), response));
let query = Arc::new(StreamingQuery::new(
query_id,
self.inner.clone(),
response,
job_id.clone(),
));
self.queries
.insert(query_id, RegisteredQuery::Streamed(query.clone()));
Query::new(Arc::new(StreamingQueryHandle::new(query)))
@@ -247,6 +263,7 @@ impl SqlClient {
self.inner.clone(),
request.default_namespace_path,
poll_info,
job_id,
)?);
self.queries
.insert(query_id, RegisteredQuery::Polled(query.clone()));
@@ -255,8 +272,7 @@ impl SqlClient {
};
Ok(SubmittedQuery {
query,
materialized_view_job_handle_supported: opened
.materialized_view_job_handle_supported,
materialized_view_job_handle_supported,
})
})
.await
@@ -283,6 +299,7 @@ impl SqlClient {
self.inner.clone(),
default_namespace_path.to_vec(),
poll_info,
None,
)?);
self.queries
.insert(query_id, RegisteredQuery::Polled(query.clone()));
@@ -383,16 +400,29 @@ impl SqlClientInner {
&self,
descriptor: FlightDescriptor,
default_namespace_path: &[String],
) -> Result<Option<PollInfo>> {
) -> Result<Option<PollResult>> {
let request_id = uuid::Uuid::new_v4().to_string();
let mut client = self
.client_with_headers(default_namespace_path, &request_id)
.await
.map_err(|err| sql_error(&request_id, err))?;
match tokio::time::timeout(STATUS_POLL_TIMEOUT, client.poll_flight_info(descriptor)).await {
Ok(result) => result
.map(Some)
.map_err(|err| sql_flight_error(&request_id, &err)),
let connection = self.connection(&request_id).await?;
let headers = self.headers(default_namespace_path, &request_id).await?;
let metadata = client_with_headers(connection.client.clone(), &headers)?
.metadata()
.clone();
let mut request = Request::new(descriptor);
*request.metadata_mut() = metadata;
match tokio::time::timeout(
STATUS_POLL_TIMEOUT,
connection.client.clone().poll_flight_info(request),
)
.await
{
Ok(Ok(response)) => {
let job_id = sql_job_id_from_metadata(response.metadata());
Ok(Some(PollResult {
info: response.into_inner(),
job_id,
}))
}
Ok(Err(status)) => Err(sql_status_error(&request_id, &status)),
Err(_) => Ok(None),
}
}
@@ -401,7 +431,7 @@ impl SqlClientInner {
&self,
descriptor: FlightDescriptor,
default_namespace_path: &[String],
) -> Result<PollInfo> {
) -> Result<PollResult> {
let read_timeout = resolve_timeout(
self.client_config.timeout_config.read_timeout,
"LANCE_CLIENT_READ_TIMEOUT",
@@ -413,12 +443,18 @@ impl SqlClientInner {
loop {
let started = Instant::now();
let request_id = uuid::Uuid::new_v4().to_string();
let mut client = self
.client_with_headers(default_namespace_path, &request_id)
.await?;
let result =
tokio::time::timeout(read_timeout, client.poll_flight_info(descriptor.clone()))
.await;
let connection = self.connection(&request_id).await?;
let headers = self.headers(default_namespace_path, &request_id).await?;
let metadata = client_with_headers(connection.client.clone(), &headers)?
.metadata()
.clone();
let mut request = Request::new(descriptor.clone());
*request.metadata_mut() = metadata;
let result = tokio::time::timeout(
read_timeout,
connection.client.clone().poll_flight_info(request),
)
.await;
let poll_info = match result {
Err(_) if retry_count < retry_config.read_retries => {
retry_count += 1;
@@ -426,7 +462,7 @@ impl SqlClientInner {
continue;
}
Err(_) => return Err(sql_error(&request_id, "SQL query poll timed out")),
Ok(Err(FlightError::Tonic(status)))
Ok(Err(status))
if matches!(
status.code(),
tonic::Code::DeadlineExceeded | tonic::Code::Unavailable
@@ -436,8 +472,14 @@ impl SqlClientInner {
tokio::time::sleep(poll_retry_delay(&retry_config, retry_count)).await;
continue;
}
Ok(Err(error)) => return Err(sql_flight_error(&request_id, &error)),
Ok(Ok(poll_info)) => poll_info,
Ok(Err(status)) => return Err(sql_status_error(&request_id, &status)),
Ok(Ok(response)) => {
let job_id = sql_job_id_from_metadata(response.metadata());
PollResult {
info: response.into_inner(),
job_id,
}
}
};
if let Some(delay) = MIN_POLL_INTERVAL.checked_sub(started.elapsed()) {
tokio::time::sleep(delay).await;
@@ -461,17 +503,27 @@ impl SqlClientInner {
let ticket = endpoint.ticket.ok_or_else(|| {
sql_error(&request_id, "SQL result endpoint did not include a ticket")
})?;
let mut endpoint_client = self
.client_with_headers(default_namespace_path, &request_id)
.await?;
let stream = tokio::time::timeout(read_timeout, endpoint_client.do_get(ticket))
.await
.map_err(|_| sql_error(&request_id, "SQL result fetch timed out"))?
.map_err(|err| sql_flight_error(&request_id, &err))?;
let connection = self.connection(&request_id).await?;
let headers = self.headers(default_namespace_path, &request_id).await?;
let metadata = client_with_headers(connection.client.clone(), &headers)?
.metadata()
.clone();
let mut request = Request::new(ticket);
*request.metadata_mut() = metadata;
let response =
tokio::time::timeout(read_timeout, connection.client.clone().do_get(request))
.await
.map_err(|_| sql_error(&request_id, "SQL result fetch timed out"))?
.map_err(|status| sql_status_error(&request_id, &status))?;
let job_id = sql_job_id_from_metadata(response.metadata());
let stream = response
.into_inner()
.map_err(|status| FlightError::Tonic(Box::new(status)));
Ok(ResultEndpointStream {
stream,
stream: FlightRecordBatchStream::new_from_flight_data(stream),
request_id,
read_timeout,
job_id,
})
}
@@ -547,6 +599,7 @@ impl SqlClientInner {
Ok(CancelOutcome::Status(status))
}
#[cfg(test)]
async fn client_with_headers(
&self,
default_namespace_path: &[String],
@@ -684,6 +737,7 @@ impl QueryRegistry {
struct RemoteQuery {
id: Uuid,
job_id: StdMutex<Option<String>>,
client: Arc<SqlClientInner>,
default_namespace_path: Vec<String>,
state: Mutex<PollInfo>,
@@ -713,6 +767,7 @@ impl RemoteQuery {
client: Arc<SqlClientInner>,
default_namespace_path: Vec<String>,
poll_info: PollInfo,
job_id: Option<String>,
) -> Result<Self> {
let expires_at = query_expiration(&poll_info)?;
let terminal_at = OnceLock::new();
@@ -724,6 +779,7 @@ impl RemoteQuery {
};
Ok(Self {
id,
job_id: StdMutex::new(job_id.filter(|job_id| !job_id.is_empty())),
client,
default_namespace_path,
state: Mutex::new(poll_info),
@@ -850,6 +906,44 @@ impl RemoteQuery {
*self.last_accessed.lock().unwrap() = Instant::now();
}
fn job_id(&self) -> Option<String> {
self.job_id.lock().unwrap().clone()
}
fn observe_job_id(&self, job_id: Option<&str>) -> Result<()> {
let Some(job_id) = job_id.filter(|job_id| !job_id.is_empty()) else {
return Ok(());
};
let mut current = self.job_id.lock().unwrap();
match current.as_deref() {
None => *current = Some(job_id.to_string()),
Some(existing) if existing == job_id => {}
Some(existing) => {
return Err(Error::Runtime {
message: format!(
"SQL query changed durable job identity from {existing} to {job_id}"
),
});
}
}
Ok(())
}
fn observe_error_job_id(&self, error: &Error) -> Result<()> {
self.observe_job_id(
error
.remote_error_metadata()
.and_then(|metadata| metadata.job_id.as_deref()),
)
}
fn record_error_job_id<T>(&self, result: Result<T>) -> Result<T> {
if let Err(error) = &result {
self.observe_error_job_id(error)?;
}
result
}
async fn poll_next_state(&self, descriptor: FlightDescriptor) -> Result<PollInfo> {
self.touch();
if self.is_cancellation_requested() {
@@ -874,10 +968,11 @@ impl RemoteQuery {
Err(_) if self.is_cancellation_requested() => {
return Err(self.cancelled_error());
}
result => result?,
result => self.record_error_job_id(result)?,
},
};
self.update_state(&descriptor, updated).await
self.observe_job_id(updated.job_id.as_deref())?;
self.update_state(&descriptor, updated.info).await
}
async fn prepare_result(self: &Arc<Self>) -> Result<PreparedSqlResult> {
@@ -894,8 +989,9 @@ impl RemoteQuery {
result = self.client.open_result_endpoint(
endpoint,
&self.default_namespace_path,
) => result?,
) => self.record_error_job_id(result)?,
};
self.observe_job_id(endpoint_stream.job_id.as_deref())?;
let buffered_batch = tokio::select! {
biased;
_ = self.wait_for_cancellation() => return Err(self.cancelled_error()),
@@ -908,6 +1004,7 @@ impl RemoteQuery {
.ok_or_else(|| Error::Runtime {
message: "SQL result endpoint did not include a schema".to_string(),
})?;
self.observe_job_id(sql_job_id_from_schema(&schema).as_deref())?;
return Ok(PreparedSqlResult {
schema,
next_endpoint: 1,
@@ -925,6 +1022,7 @@ impl RemoteQuery {
.map_err(|err| sql_error(&request_id, err))?,
)
};
self.observe_job_id(sql_job_id_from_schema(&schema).as_deref())?;
return Ok(PreparedSqlResult {
schema,
next_endpoint: 0,
@@ -1001,7 +1099,7 @@ impl RemoteQuery {
result = self.client.open_result_endpoint(
endpoint,
&self.default_namespace_path,
) => result?,
) => self.record_error_job_id(result)?,
});
continue;
}
@@ -1067,24 +1165,22 @@ impl RemoteQuery {
self.touch();
if self.is_cancellation_requested() {
let state = self.state.lock().await.clone();
return query_description(self.id, &state, self.lifecycle());
return query_description(self.id, self.job_id(), &state, self.lifecycle());
}
let state = self.state.lock().await.clone();
let state = if let Some(descriptor) = state.flight_descriptor.clone() {
let poll_guard = tokio::select! {
biased;
_ = self.wait_for_cancellation() => return query_description(
self.id,
&state,
self.lifecycle(),
),
_ = self.wait_for_cancellation() => {
return query_description(self.id, self.job_id(), &state, self.lifecycle())
}
poll_guard = tokio::time::timeout(
STATUS_POLL_TIMEOUT,
self.poll_gate.lock(),
) => poll_guard,
};
let Ok(_poll_guard) = poll_guard else {
return query_description(self.id, &state, self.lifecycle());
return query_description(self.id, self.job_id(), &state, self.lifecycle());
};
let latest = self.state.lock().await.clone();
if latest.flight_descriptor.as_ref() != Some(&descriptor) {
@@ -1092,25 +1188,28 @@ impl RemoteQuery {
} else {
let updated = tokio::select! {
biased;
_ = self.wait_for_cancellation() => return query_description(
self.id,
&latest,
self.lifecycle(),
),
_ = self.wait_for_cancellation() => {
return query_description(self.id, self.job_id(), &latest, self.lifecycle())
}
result = self.client.poll_status(
descriptor.clone(),
&self.default_namespace_path,
) => match result {
Err(_) if self.is_cancellation_requested() => return query_description(
self.id,
&latest,
self.lifecycle(),
),
result => result?,
Err(error) if self.is_cancellation_requested() => {
self.observe_error_job_id(&error)?;
return query_description(
self.id,
self.job_id(),
&latest,
self.lifecycle(),
);
}
result => self.record_error_job_id(result)?,
},
};
if let Some(updated) = updated {
self.update_state(&descriptor, updated).await?
self.observe_job_id(updated.job_id.as_deref())?;
self.update_state(&descriptor, updated.info).await?
} else {
latest
}
@@ -1118,7 +1217,7 @@ impl RemoteQuery {
} else {
state
};
query_description(self.id, &state, self.lifecycle())
query_description(self.id, self.job_id(), &state, self.lifecycle())
}
async fn cancel(&self) -> Result<()> {
@@ -1214,11 +1313,15 @@ impl RemoteQuery {
if self.state.lock().await.flight_descriptor.as_ref() != Some(&descriptor) {
continue;
}
let updated = self.client.poll_continuation(
let updated = self.record_error_job_id(
self.client.poll_continuation(
descriptor.clone(),
&self.default_namespace_path,
).await?;
self.update_state(&descriptor, updated).await?;
)
.await,
)?;
self.observe_job_id(updated.job_id.as_deref())?;
self.update_state(&descriptor, updated.info).await?;
}
_ = notified => {}
}
@@ -1247,6 +1350,10 @@ impl QueryHandle for RemoteQueryHandle {
self.query.id
}
fn job_id(&self) -> Option<String> {
self.query.job_id()
}
async fn describe(&self) -> Result<QueryDescription> {
self.query.describe().await
}
@@ -1286,7 +1393,12 @@ impl QueryHandle for RemoteQueryHandle {
receiver.recv().await.map(|item| (item, receiver))
});
result_start.commit();
Ok(Box::pin(SimpleRecordBatchStream::new(stream, schema)))
let stream: SendableRecordBatchStream =
Box::pin(SimpleRecordBatchStream::new(stream, schema));
Ok(match self.job_id() {
Some(job_id) => attach_sql_job_id(stream, &job_id),
None => stream,
})
}
async fn cancel(&self) -> Result<()> {
@@ -1296,12 +1408,14 @@ impl QueryHandle for RemoteQueryHandle {
fn query_description(
id: Uuid,
job_id: Option<String>,
poll_info: &PollInfo,
lifecycle: QueryLifecycle,
) -> Result<QueryDescription> {
let expires_at = query_expiration(poll_info)?;
Ok(QueryDescription {
id,
job_id,
status: match lifecycle {
QueryLifecycle::Cancelling => QueryStatus::Cancelling,
QueryLifecycle::Cancelled => QueryStatus::Cancelled,
@@ -1317,6 +1431,36 @@ fn query_description(
})
}
fn sql_job_id_from_metadata(metadata: &tonic::metadata::MetadataMap) -> Option<String> {
metadata
.get(SQL_JOB_ID_METADATA_KEY)
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
fn sql_job_id_from_schema(schema: &Schema) -> Option<String> {
schema
.metadata()
.get(SQL_JOB_ID_METADATA_KEY)
.filter(|value| !value.is_empty())
.cloned()
}
pub(super) fn attach_sql_job_id(
stream: SendableRecordBatchStream,
job_id: &str,
) -> SendableRecordBatchStream {
let mut metadata = stream.schema().metadata().clone();
metadata.insert(SQL_JOB_ID_METADATA_KEY.to_string(), job_id.to_string());
let schema = Arc::new(stream.schema().as_ref().clone().with_metadata(metadata));
let batch_schema = schema.clone();
let stream = stream.map(move |batch| {
batch.and_then(|batch| batch.with_schema(batch_schema.clone()).map_err(Error::from))
});
Box::pin(SimpleRecordBatchStream::new(stream, schema))
}
fn query_expiration(poll_info: &PollInfo) -> Result<Option<chrono::DateTime<chrono::Utc>>> {
poll_info
.expiration_time
+7 -4
View File
@@ -51,17 +51,20 @@ impl SqlClient {
pub(in crate::remote) async fn describe_function(
&self,
name: &str,
version: &str,
version: Option<&str>,
namespace: &[String],
) -> Result<FunctionVersion> {
validate_function_name(name)?;
validate_namespace(namespace)?;
let version_clause = match version {
Some(version) => format!(" WITH (version = {})", literal(version)),
None => String::new(),
};
self.object_job(
ExecuteQueryRequest {
query: format!(
"DESCRIBE FUNCTION {} WITH (version = {})",
quote_identifier(name),
literal(version)
"DESCRIBE FUNCTION {}{version_clause}",
quote_identifier(name)
),
default_namespace_path: namespace.to_vec(),
parameters: None,
+43 -1
View File
@@ -55,6 +55,7 @@ pub(super) struct StreamingQuery {
cancelled: Notify,
terminal_at: OnceLock<Instant>,
last_accessed: StdMutex<Instant>,
job_id: StdMutex<Option<String>>,
}
struct PreparedStream {
@@ -125,6 +126,7 @@ pub(super) enum Submission {
pub(super) struct OpenedSubmission {
pub(super) submission: Submission,
pub(super) materialized_view_job_handle_supported: bool,
pub(super) job_id: Option<String>,
}
impl StreamingQuery {
@@ -190,6 +192,7 @@ impl StreamingQuery {
}
.map_err(|_| sql_error(&request_id, "SQL query submission timed out"))?
.map_err(|error| sql_status_error(&request_id, &error))?;
let response_job_id = super::sql_job_id_from_metadata(response.metadata());
let negotiated = response
.metadata()
.get(PROTOCOL_HEADER)
@@ -233,6 +236,7 @@ impl StreamingQuery {
return Ok(OpenedSubmission {
submission: Submission::Deferred(info),
materialized_view_job_handle_supported,
job_id: response_job_id,
});
}
}
@@ -245,8 +249,10 @@ impl StreamingQuery {
stream,
request_id,
read_timeout,
job_id: None,
}),
materialized_view_job_handle_supported: false,
job_id: response_job_id,
})
}
@@ -254,6 +260,7 @@ impl StreamingQuery {
id: Uuid,
client: Arc<SqlClientInner>,
response: ResultEndpointStream,
job_id: Option<String>,
) -> Self {
Self {
id,
@@ -263,6 +270,7 @@ impl StreamingQuery {
cancelled: Notify::new(),
terminal_at: OnceLock::new(),
last_accessed: StdMutex::new(Instant::now()),
job_id: StdMutex::new(job_id.filter(|job_id| !job_id.is_empty())),
}
}
@@ -291,6 +299,7 @@ impl StreamingQuery {
};
Ok(QueryDescription {
id: self.id,
job_id: self.job_id(),
status,
progress: (status == QueryStatus::Finished).then_some(1.0),
expires_at: None,
@@ -326,6 +335,29 @@ impl StreamingQuery {
*self.lifecycle.lock().unwrap() == Lifecycle::Cancelled
}
fn job_id(&self) -> Option<String> {
self.job_id.lock().unwrap().clone()
}
fn observe_job_id(&self, job_id: Option<&str>) -> Result<()> {
let Some(job_id) = job_id.filter(|job_id| !job_id.is_empty()) else {
return Ok(());
};
let mut current = self.job_id.lock().unwrap();
match current.as_deref() {
None => *current = Some(job_id.to_string()),
Some(existing) if existing == job_id => {}
Some(existing) => {
return Err(Error::Runtime {
message: format!(
"SQL query changed durable job identity from {existing} to {job_id}"
),
});
}
}
Ok(())
}
fn cancelled_error(&self) -> Error {
Error::JobCancelled {
job_id: Some(self.id.to_string()),
@@ -373,6 +405,7 @@ impl StreamingQuery {
.ok_or_else(|| Error::Runtime {
message: "SQL result stream did not include a schema".to_string(),
})?;
self.observe_job_id(super::sql_job_id_from_schema(&schema).as_deref())?;
if first.is_none() {
self.settle(Lifecycle::Finished);
}
@@ -476,6 +509,10 @@ impl QueryHandle for StreamingQueryHandle {
self.query.id
}
fn job_id(&self) -> Option<String> {
self.query.job_id()
}
async fn describe(&self) -> Result<QueryDescription> {
self.query.describe()
}
@@ -526,7 +563,12 @@ impl QueryHandle for StreamingQueryHandle {
receiver.recv().await.map(|item| (item, receiver))
});
result_start.commit();
Ok(Box::pin(SimpleRecordBatchStream::new(stream, schema)))
let stream: SendableRecordBatchStream =
Box::pin(SimpleRecordBatchStream::new(stream, schema));
Ok(match self.job_id() {
Some(job_id) => super::attach_sql_job_id(stream, &job_id),
None => stream,
})
}
async fn cancel(&self) -> Result<()> {
+200 -10
View File
@@ -160,8 +160,17 @@ impl TestSqlService {
return Response::new(rows);
}
let poll_info = self.defer.then(|| {
let mut info = FlightInfo::new()
.with_endpoint(FlightEndpoint::new().with_ticket(Ticket::new(query.to_string())));
let mut info = FlightInfo::new();
if !query.starts_with("SELECT durable job") {
info = info.with_endpoint(
FlightEndpoint::new().with_ticket(Ticket::new(query.to_string())),
);
}
if query.starts_with("SELECT durable job") {
info = info
.try_with_schema(&self.result_for_query(query).schema())
.unwrap();
}
if self.materialized_view_job_handle_supported {
info.app_metadata = b"early-v1".to_vec().into();
}
@@ -198,6 +207,13 @@ impl TestSqlService {
response
.metadata_mut()
.insert(PROTOCOL_HEADER, PROTOCOL_VERSION.parse().unwrap());
if query.starts_with("SELECT direct durable job") {
let job_id = query.rsplit(' ').next().unwrap();
response.metadata_mut().insert(
SQL_JOB_ID_METADATA_KEY,
format!("job-{job_id}").parse().unwrap(),
);
}
response
}
}
@@ -351,7 +367,14 @@ impl FlightService for TestSqlService {
.insert("x-lancedb-sql-job-id", "job-1".parse().unwrap());
return Err(status);
}
let complete = if query == "SELECT no info" {
if query == "SELECT durable job failure" && stage == 1 {
let mut status = Status::internal("durable SQL job failed");
status
.metadata_mut()
.insert("x-lancedb-sql-job-id", "job-1".parse().unwrap());
return Err(status);
}
let complete = if query == "SELECT no info" || query.starts_with("SELECT durable job") {
stage >= 2
} else {
stage >= 1
@@ -362,11 +385,14 @@ impl FlightService for TestSqlService {
} else {
query.clone()
};
let mut info = FlightInfo::new().with_endpoint(
FlightEndpoint::new()
.with_ticket(Ticket::new(first_ticket))
.with_location("grpc://127.0.0.1:1"),
);
let mut info = FlightInfo::new();
if !(query.starts_with("SELECT durable job") && !complete) {
info = info.with_endpoint(
FlightEndpoint::new()
.with_ticket(Ticket::new(first_ticket))
.with_location("grpc://127.0.0.1:1"),
);
}
if query == "SELECT incremental" && stage > 0 {
info = info.with_endpoint(
FlightEndpoint::new()
@@ -378,13 +404,21 @@ impl FlightService for TestSqlService {
let schema = self.result_for_query(&query).schema();
info = info.try_with_schema(&schema).unwrap();
}
Ok(Response::new(PollInfo {
let mut response = Response::new(PollInfo {
info: (query != "SELECT no info" || stage > 0).then_some(info),
flight_descriptor: (!complete)
.then(|| FlightDescriptor::new_cmd(format!("poll:{}:{query}", stage + 1))),
progress: Some(if complete { 1.0 } else { 0.25 }),
expiration_time: None,
}))
});
if query.starts_with("SELECT durable job") && stage > 0 {
let job_id = query.rsplit(' ').next().unwrap();
response.metadata_mut().insert(
SQL_JOB_ID_METADATA_KEY,
format!("job-{job_id}").parse().unwrap(),
);
}
Ok(response)
}
async fn get_schema(
@@ -730,6 +764,106 @@ async fn parameters_travel_on_one_exchange() {
assert_eq!(headers[0].api_key, "test-key");
}
#[tokio::test]
async fn running_job_backed_queries_expose_their_own_durable_job_id() {
let service = TestSqlService {
adaptive: true,
defer: true,
..Default::default()
};
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let first = client
.execute(ExecuteQueryRequest::new("SELECT durable job first"))
.await
.unwrap();
let second = client
.execute(ExecuteQueryRequest::new("SELECT durable job second"))
.await
.unwrap();
assert_eq!(first.job_id(), None);
assert_eq!(second.job_id(), None);
let first_description = first.describe().await.unwrap();
let second_description = second.describe().await.unwrap();
assert_eq!(first_description.status, QueryStatus::Running);
assert_eq!(first_description.job_id.as_deref(), Some("job-first"));
assert_eq!(second_description.status, QueryStatus::Running);
assert_eq!(second_description.job_id.as_deref(), Some("job-second"));
assert_ne!(first.id(), second.id());
assert_ne!(first_description.job_id, second_description.job_id);
let reader = first.reader().await.unwrap();
assert_eq!(
reader
.schema()
.metadata()
.get(SQL_JOB_ID_METADATA_KEY)
.map(String::as_str),
Some("job-first")
);
assert_eq!(first.job_id().as_deref(), Some("job-first"));
assert_eq!(second.job_id().as_deref(), Some("job-second"));
let reader_only = client
.execute(ExecuteQueryRequest::new("SELECT durable job reader-only"))
.await
.unwrap();
let reader_only_result = reader_only.reader().await.unwrap();
assert_eq!(
reader_only_result
.schema()
.metadata()
.get(SQL_JOB_ID_METADATA_KEY)
.map(String::as_str),
Some("job-reader-only")
);
let ordinary = client
.execute(ExecuteQueryRequest::new("SELECT ordinary"))
.await
.unwrap();
assert_eq!(ordinary.describe().await.unwrap().job_id, None);
}
#[tokio::test]
async fn direct_job_backed_queries_expose_the_initial_response_job_id() {
let service = TestSqlService {
adaptive: true,
..Default::default()
};
let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await;
let query = client
.execute(ExecuteQueryRequest::new("SELECT direct durable job direct"))
.await
.unwrap();
assert_eq!(query.job_id().as_deref(), Some("job-direct"));
assert_eq!(
query.describe().await.unwrap().job_id.as_deref(),
Some("job-direct")
);
let reader = query.reader().await.unwrap();
assert_eq!(
reader
.schema()
.metadata()
.get(SQL_JOB_ID_METADATA_KEY)
.map(String::as_str),
Some("job-direct")
);
let batches = reader.try_collect::<Vec<_>>().await.unwrap();
assert_eq!(batches.len(), 1);
assert_eq!(
batches[0]
.schema()
.metadata()
.get(SQL_JOB_ID_METADATA_KEY)
.map(String::as_str),
Some("job-direct")
);
}
/// The server plans before it answers, so a refusal is the submission's.
#[tokio::test]
async fn a_refused_statement_fails_its_submission() {
@@ -1213,6 +1347,35 @@ async fn function_failure_preserves_the_isolated_sql_job_id() {
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn fast_durable_job_failure_exposes_the_same_job_id_on_the_query_handle() {
let (client, shutdown) = start_sql_service(
TestSqlService {
adaptive: true,
defer: true,
..Default::default()
},
ClientConfig::default(),
)
.await;
let query = client
.execute(ExecuteQueryRequest {
query: "SELECT durable job failure".into(),
default_namespace_path: vec![],
parameters: None,
})
.await
.unwrap();
assert_eq!(query.job_id(), None);
let Err(Error::JobFailed { job_id, .. }) = collect_result(&query).await else {
panic!("a failed durable query must remain a structured JobFailed error");
};
assert_eq!(job_id.as_deref(), Some("job-1"));
assert_eq!(query.job_id().as_deref(), Some("job-1"));
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn rejected_job_cancellation_does_not_abort_sql_completion() {
let service = TestSqlService {
@@ -1843,6 +2006,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() {
flight_descriptor: Some(FlightDescriptor::new_cmd("restored")),
..Default::default()
},
None,
)
.unwrap(),
);
@@ -1975,6 +2139,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() {
flight_descriptor: Some(FlightDescriptor::new_cmd(descriptor)),
..Default::default()
},
None,
)
.unwrap(),
);
@@ -1996,6 +2161,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() {
expiration_time: Some(Default::default()),
..Default::default()
},
None,
)
.unwrap(),
);
@@ -2012,6 +2178,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() {
flight_descriptor: Some(FlightDescriptor::new_cmd("stale")),
..Default::default()
},
None,
)
.unwrap(),
);
@@ -2792,6 +2959,7 @@ async fn function_creation_and_description_use_sql_query_handles() {
for (defer, with_models) in [(false, false), (false, true), (true, false), (true, true)] {
let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap();
request_json["batch_size"] = serde_json::json!(2);
request_json["max_concurrency"] = serde_json::json!(4);
request_json["row_timeout_seconds"] = serde_json::json!(0.75);
request_json["secret_bindings"] = serde_json::json!([{
"kind": "env",
@@ -2800,6 +2968,7 @@ async fn function_creation_and_description_use_sql_query_handles() {
}]);
let mut version_json: serde_json::Value = serde_json::from_str(VERSION).unwrap();
version_json["batch_size"] = serde_json::json!(12);
version_json["max_concurrency"] = serde_json::json!(4);
version_json["row_timeout_seconds"] = serde_json::json!(8.0);
version_json["result_stability"] = serde_json::json!("input_and_context");
if with_models {
@@ -2843,6 +3012,7 @@ async fn function_creation_and_description_use_sql_query_handles() {
assert_eq!(created.name(), "embed");
assert_eq!(created.version(), "1");
assert_eq!(created.batch_size(), Some(12));
assert_eq!(created.max_concurrency(), Some(4));
assert_eq!(created.row_timeout_seconds(), Some(8.0));
assert_eq!(created.result_stability(), Some("input_and_context"));
// Assert the actual SQL body, after the same native JSON decode used
@@ -2862,6 +3032,7 @@ async fn function_creation_and_description_use_sql_query_handles() {
serde_json::from_str(&created.to_canonical_json().unwrap()).unwrap();
assert_eq!(created_json["image"].get("models"), expected_models);
assert_eq!(created_json["batch_size"], 12);
assert_eq!(created_json["max_concurrency"], 4);
assert_eq!(created_json["row_timeout_seconds"], 8.0);
assert_eq!(created_json["result_stability"], "input_and_context");
assert_eq!(
@@ -2874,20 +3045,30 @@ async fn function_creation_and_description_use_sql_query_handles() {
.unwrap();
assert_eq!(described.name(), "embed");
assert_eq!(described.batch_size(), Some(12));
assert_eq!(described.max_concurrency(), Some(4));
assert_eq!(described.row_timeout_seconds(), Some(8.0));
assert_eq!(described.result_stability(), Some("input_and_context"));
let described_json: serde_json::Value =
serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap();
assert_eq!(described_json["image"].get("models"), expected_models);
assert_eq!(described_json["batch_size"], 12);
assert_eq!(described_json["max_concurrency"], 4);
assert_eq!(described_json["row_timeout_seconds"], 8.0);
assert_eq!(described_json["result_stability"], "input_and_context");
let latest = db
.get_function_latest("embed", &["team".into()])
.await
.unwrap();
assert_eq!(latest.name(), "embed");
assert_eq!(latest.version(), "1");
assert_eq!(latest.batch_size(), Some(12));
let listed = db
.list_functions(&["team".into()], Default::default())
.await
.unwrap();
assert_eq!(listed.items.len(), 1);
assert_eq!(listed.items[0].batch_size(), Some(12));
assert_eq!(listed.items[0].max_concurrency(), Some(4));
assert_eq!(listed.items[0].row_timeout_seconds(), Some(8.0));
assert_eq!(
listed.items[0].result_stability(),
@@ -2897,10 +3078,12 @@ async fn function_creation_and_description_use_sql_query_handles() {
serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap();
assert_eq!(listed_json["image"].get("models"), expected_models);
assert_eq!(listed_json["batch_size"], 12);
assert_eq!(listed_json["max_concurrency"], 4);
assert_eq!(listed_json["row_timeout_seconds"], 8.0);
assert_eq!(listed_json["result_stability"], "input_and_context");
let seen = statements.lock().unwrap();
assert_eq!(seen[1], "DESCRIBE FUNCTION \"embed\" WITH (version = '1')");
assert_eq!(seen[2], "DESCRIBE FUNCTION \"embed\"");
shutdown.send(()).unwrap();
}
}
@@ -2931,6 +3114,13 @@ async fn function_creation_rejects_invalid_execution_controls_before_sql() {
request.batch_size = Some(0);
let error = db.create_function_async(request, &[]).await.unwrap_err();
assert!(matches!(error, Error::InvalidInput { message } if message.contains("batch_size")));
let mut request = crate::function::FunctionRegistrationRequest::from_json(REQUEST).unwrap();
request.max_concurrency = Some(0);
let error = db.create_function_async(request, &[]).await.unwrap_err();
assert!(
matches!(error, Error::InvalidInput { message } if message.contains("max_concurrency"))
);
assert!(statements.lock().unwrap().is_empty());
shutdown.send(()).unwrap();
}
+720 -2
View File
@@ -42,7 +42,8 @@ use crate::table::query::create_multi_vector_plan;
use crate::table::rte_stats::GetRTEStatsResponse;
use crate::table::write_progress::FinishOnDrop;
use crate::table::{
AlterColumnsResult, FieldMetadataUpdate, RefreshColumnResult, UpdateFieldMetadataResult,
AlterColumnsResult, FieldMetadataUpdate, FunctionColumnStatus, RefreshColumnResult,
UpdateFieldMetadataResult,
};
use crate::table::{AnyQuery, Filter, Predicate, PreprocessingOutput, TableStatistics};
use crate::utils::background_cache::BackgroundCache;
@@ -288,6 +289,10 @@ impl<S: HttpSend> crate::job::JobHandle for FreshnessJob<S> {
crate::job::JobHandle::describe(&self.inner).await
}
async fn timeline(&self) -> Result<serde_json::Value> {
crate::job::JobHandle::timeline(&self.inner).await
}
async fn events(
&self,
request: crate::job::JobEventsRequest,
@@ -369,6 +374,10 @@ impl<S: HttpSend> crate::job::JobHandle for MaterializedViewRefreshJob<S> {
crate::job::JobHandle::describe(&self.inner).await
}
async fn timeline(&self) -> Result<serde_json::Value> {
crate::job::JobHandle::timeline(&self.inner).await
}
async fn events(
&self,
request: crate::job::JobEventsRequest,
@@ -3951,6 +3960,9 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
if let Some(interval) = options.auto_refresh_interval_seconds {
body["auto_refresh_interval_seconds"] = serde_json::json!(interval);
}
if let Some(budget) = options.auto_refresh_resource_budget {
body["auto_refresh_resource_budget"] = serde_json::json!(budget);
}
self.apply_branch_body(&mut body);
let request = self
.client
@@ -4074,6 +4086,54 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
})
}
async fn function_column_statuses(
&self,
column: Option<&str>,
) -> Result<Vec<FunctionColumnStatus>> {
let mut request = self.apply_branch_query(self.client.get(&format!(
"/v1/table/{}/function_columns/status",
self.identifier
)));
if let Some(column) = column {
request = request.query(&[("column", column)]);
}
let read_snapshot = self.snapshot_read_state().await;
if let Some(version) = read_snapshot.version {
request = request.query(&[("version", version)]);
}
let request = read_snapshot.freshness.apply(request);
// A typed finalization-pending 503 is a domain result. Let the caller's
// bounded wait policy handle it instead of a generic 5xx retry loop.
let (request_id, response) = self.client.send_with_retry(request, None, false).await?;
if response.status().is_success() {
read_snapshot
.freshness
.observe_headers(&self.freshness, response.headers());
}
let response = self.check_table_response(&request_id, response).await?;
let body = response.text().await.err_to_http(request_id.clone())?;
let statuses: Vec<FunctionColumnStatus> =
serde_json::from_str(&body).map_err(|error| Error::Http {
source: format!("failed to parse Function column status response: {error}").into(),
request_id,
status_code: None,
})?;
crate::table::function_column_status::validate_statuses(&statuses)?;
if let Some(requested_version) = read_snapshot.version
&& let Some(returned_version) = statuses
.iter()
.map(|status| status.table_version)
.find(|version| *version != requested_version)
{
return Err(Error::Runtime {
message: format!(
"Function column status response returned table version {returned_version}, but the table handle is pinned to version {requested_version}"
),
});
}
Ok(statuses)
}
async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result<AlterColumnsResult> {
self.check_mutable().await?;
let body = alterations
@@ -10361,6 +10421,7 @@ mod tests {
.computed_options(crate::table::computed_columns::ComputedColumnOptions {
auto_refresh_enabled: false,
auto_refresh_interval_seconds: interval,
auto_refresh_resource_budget: None,
})
.execute()
.await
@@ -10797,6 +10858,11 @@ mod tests {
))
.unwrap();
expected["auto_refresh_enabled"] = serde_json::json!(true);
expected["auto_refresh_resource_budget"] = serde_json::json!({
"cpu_millis": 8_000,
"memory_bytes": 17_179_869_184_u64,
"gpu_count": 2,
});
assert_eq!(actual, expected);
http::Response::builder()
.status(200)
@@ -10824,6 +10890,14 @@ mod tests {
let result = table
.add_columns()
.function(application)
.computed_options(crate::table::computed_columns::ComputedColumnOptions {
auto_refresh_enabled: true,
auto_refresh_interval_seconds: None,
auto_refresh_resource_budget: Some(
crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184)
.with_gpu_count(2),
),
})
.execute()
.await
.unwrap();
@@ -11028,6 +11102,48 @@ mod tests {
assert_eq!(job.id(), Some("j-gpu"));
}
#[rstest]
#[case(None, 0)]
#[case(Some(2), 2)]
#[tokio::test]
async fn test_refresh_column_async_resource_budget(
#[case] gpu_count: Option<u32>,
#[case] expected_gpu_count: u32,
) {
use crate::table::{FunctionWorkerResourceBudget, RefreshColumnOptions};
let table = Table::new_with_handler("my_table", move |request| {
assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column");
assert_eq!(
request_body_json(&request),
serde_json::json!({
"column": "quality",
"resource_budget": {
"cpu_millis": 8_000,
"memory_bytes": 17_179_869_184_u64,
"gpu_count": expected_gpu_count,
},
})
);
http::Response::builder()
.status(202)
.body(r#"{"job_id":"j-budget"}"#)
.unwrap()
});
let mut budget = FunctionWorkerResourceBudget::new(8_000, 17_179_869_184);
if let Some(gpu_count) = gpu_count {
budget = budget.with_gpu_count(gpu_count);
}
let job = table
.refresh_column_async_with_options(
"quality",
RefreshColumnOptions::default().resource_budget(budget),
)
.await
.unwrap();
assert_eq!(job.id(), Some("j-budget"));
}
#[tokio::test]
async fn test_refresh_column_async_retry_policy() {
use crate::function::{FunctionErrorPolicy, FunctionRetryPolicy};
@@ -11072,6 +11188,7 @@ mod tests {
serde_json::json!({
"column": "quality",
"where": "id % 2 = 0",
"max_concurrency": 3,
"publication_interval_rows": 60,
"error_policy": "skip",
"max_failed_fraction": 0.01,
@@ -11089,6 +11206,7 @@ mod tests {
});
let options = RefreshColumnOptions::default()
.where_clause("id % 2 = 0")
.max_concurrency(3)
.publication_interval_rows(60)
.error_policy(FunctionErrorPolicy::Skip)
.max_failed_fraction(0.01)
@@ -11133,6 +11251,10 @@ mod tests {
RefreshColumnOptions::default().num_workers(0),
"num_workers",
),
(
RefreshColumnOptions::default().max_concurrency(0),
"max_concurrency",
),
(
RefreshColumnOptions::default().max_executor_processes_per_worker(0),
"max_executor_processes_per_worker",
@@ -11155,7 +11277,7 @@ mod tests {
#[tokio::test]
async fn test_refresh_column_rejects_invalid_gpu_options_before_request() {
use crate::table::RefreshColumnOptions;
use crate::table::{FunctionWorkerResourceBudget, RefreshColumnOptions};
let table = Table::new_with_handler("my_table", |_| -> http::Response<String> {
panic!("invalid GPU options must not send a request")
@@ -11170,6 +11292,22 @@ mod tests {
"gpu_class",
),
(RefreshColumnOptions::default().gpu_count(0), "gpu_count"),
(
RefreshColumnOptions::default()
.resource_budget(FunctionWorkerResourceBudget::new(0, 1)),
"resource_budget.cpu_millis",
),
(
RefreshColumnOptions::default()
.resource_budget(FunctionWorkerResourceBudget::new(1, 0)),
"resource_budget.memory_bytes",
),
(
RefreshColumnOptions::default()
.resource_budget(FunctionWorkerResourceBudget::new(1, 1))
.gpu_count(1),
"gpu_count cannot be combined with resource_budget",
),
] {
let error = table
.refresh_column_async_with_options("quality", options)
@@ -11269,6 +11407,583 @@ mod tests {
assert_eq!(schema_requests.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn test_function_column_status_decodes_one_exact_snapshot() {
let table = Table::new_with_handler("my_table", |request| {
assert_eq!(request.method(), "GET");
assert_eq!(
request.url().path(),
"/v1/table/my_table/function_columns/status"
);
assert_eq!(request.url().query(), None);
http::Response::builder()
.status(200)
.body(
r#"[{
"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":10,
"fresh":6,
"stale":2,
"never_computed":1,
"failed":1,
"last_refresh_job":{
"job_id":"job-7",
"state":"finished",
"automatic":true,
"completed_at_millis":1790000000000
},
"auto_refresh":{
"enabled":true,
"interval_seconds":60,
"active_job_id":null,
"state":"unobservable",
"failure_streak":0,
"next_run_at_millis":null,
"next_run_at_reason":"authoritative_scheduler_projection_unavailable"
}
}]"#,
)
.unwrap()
});
let statuses = table.function_column_statuses(None).await.unwrap();
assert_eq!(statuses.len(), 1);
assert_eq!(statuses[0].table_version, 42);
assert_eq!(statuses[0].failed, 1);
assert_eq!(
statuses[0]
.last_refresh_job
.as_ref()
.map(|job| job.job_id.as_str()),
Some("job-7")
);
assert_eq!(
statuses[0].auto_refresh.state,
crate::table::FunctionColumnAutoRefreshState::Unobservable
);
}
#[tokio::test]
async fn test_function_column_status_filters_with_a_get_query() {
let table = Table::new_with_handler("my_table", |request| {
assert_eq!(request.method(), "GET");
assert_eq!(request.url().query(), Some("column=embedding"));
http::Response::builder()
.status(200)
.body(
r#"[{
"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":0,
"fresh":0,
"stale":0,
"never_computed":0,
"failed":0,
"auto_refresh":{
"enabled":false,
"state":"disabled",
"failure_streak":0,
"next_run_at_millis":null
}
}]"#,
)
.unwrap()
});
let status = table.function_column_status("embedding").await.unwrap();
assert_eq!(status.column, "embedding");
assert!(status.last_refresh_job.is_none());
assert_eq!(
status.auto_refresh.state,
crate::table::FunctionColumnAutoRefreshState::Disabled
);
}
#[tokio::test]
async fn test_wait_for_function_column_retries_only_typed_finalization_pending() {
let calls = Arc::new(AtomicUsize::new(0));
let table = Table::new_with_handler("my_table", {
let calls = calls.clone();
move |_request| {
if calls.fetch_add(1, Ordering::SeqCst) == 0 {
http::Response::builder()
.status(StatusCode::SERVICE_UNAVAILABLE)
.header(
"x-lancedb-error-code",
crate::table::function_column_status::FINALIZATION_PENDING_ERROR_CODE,
)
.body(b"finalization pending".to_vec())
.unwrap()
} else {
http::Response::builder()
.status(200)
.body(
br#"[{
"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":0,
"fresh":0,
"stale":0,
"never_computed":0,
"failed":0,
"auto_refresh":{
"enabled":false,
"state":"disabled",
"failure_streak":0,
"next_run_at_millis":null
}
}]"#
.to_vec(),
)
.unwrap()
}
}
});
let status = table
.wait_for_function_column("embedding", Some(Duration::from_secs(2)))
.await
.unwrap();
assert_eq!(status.table_version, 42);
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn test_finalization_code_on_other_status_is_not_retried() {
let calls = Arc::new(AtomicUsize::new(0));
let table = Table::new_with_handler("my_table", {
let calls = calls.clone();
move |_request| {
calls.fetch_add(1, Ordering::SeqCst);
http::Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(
"x-lancedb-error-code",
crate::table::function_column_status::FINALIZATION_PENDING_ERROR_CODE,
)
.body(b"misclassified pending".to_vec())
.unwrap()
}
});
let error = table
.wait_for_function_column("embedding", Some(Duration::from_secs(2)))
.await
.unwrap_err();
assert!(error.to_string().contains("misclassified pending"));
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn test_wait_for_function_column_does_not_retry_generic_500() {
let calls = Arc::new(AtomicUsize::new(0));
let table = Table::new_with_handler("my_table", {
let calls = calls.clone();
move |_request| {
calls.fetch_add(1, Ordering::SeqCst);
http::Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(b"corrupt freshness evidence".to_vec())
.unwrap()
}
});
let error = table
.wait_for_function_column("embedding", Some(Duration::from_secs(2)))
.await
.unwrap_err();
assert!(error.to_string().contains("corrupt freshness evidence"));
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn test_function_column_status_decodes_agent_up_to_date() {
let table = Table::new_with_handler("my_table", |_request| {
http::Response::builder()
.status(200)
.body(
r#"[{
"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":4,
"stale":0,
"never_computed":0,
"failed":0,
"auto_refresh":{
"enabled":true,
"interval_seconds":60,
"state":"up_to_date",
"failure_streak":0,
"next_run_at_millis":null
}
}]"#,
)
.unwrap()
});
let status = table.function_column_status("embedding").await.unwrap();
assert_eq!(
status.auto_refresh.state,
crate::table::FunctionColumnAutoRefreshState::UpToDate
);
}
#[tokio::test]
async fn test_function_column_status_decodes_scheduler_lifecycle_and_failures() {
let table = Table::new_with_handler("my_table", |_request| {
http::Response::builder()
.status(200)
.body(
r#"[
{
"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"
}
},
{
"column":"rerank",
"binding_id":"fb_02",
"function":{
"name":"rerank",
"object_id":"rerank",
"location":"objects/rerank",
"version":"3",
"manifest_digest":"sha256:def"
},
"table_version":42,
"rows":0,
"fresh":0,
"stale":0,
"never_computed":0,
"failed":0,
"auto_refresh":{
"enabled":true,
"interval_seconds":60,
"state":"blocked",
"failure_streak":5,
"blocked_reason":"failure_threshold_reached",
"next_run_at_millis":null
}
},
{
"column":"classify",
"binding_id":"fb_03",
"function":{
"name":"classify",
"object_id":"classify",
"location":"objects/classify",
"version":"2",
"manifest_digest":"sha256:ghi"
},
"table_version":42,
"rows":0,
"fresh":0,
"stale":0,
"never_computed":0,
"failed":0,
"auto_refresh":{
"enabled":true,
"interval_seconds":60,
"state":"blocked",
"failure_streak":0,
"blocked_reason":"binding_revision_missing",
"next_run_at_millis":null
}
},
{
"column":"summarize",
"binding_id":"fb_04",
"function":{
"name":"summarize",
"object_id":"summarize",
"location":"objects/summarize",
"version":"4",
"manifest_digest":"sha256:jkl"
},
"table_version":42,
"rows":0,
"fresh":0,
"stale":0,
"never_computed":0,
"failed":0,
"auto_refresh":{
"enabled":true,
"interval_seconds":60,
"state":"blocked",
"failure_streak":3,
"effective_cooldown_millis":8000,
"blocked_reason":"preparation_backoff",
"next_run_at_millis":null
}
}]"#,
)
.unwrap()
});
let statuses = table.function_column_statuses(None).await.unwrap();
assert_eq!(statuses.len(), 4);
let status = &statuses[0];
assert_eq!(
status.auto_refresh.state,
crate::table::FunctionColumnAutoRefreshState::Queued
);
assert_eq!(
status.auto_refresh.active_job_id.as_deref(),
Some("job-queued")
);
assert_eq!(
status.auto_refresh.next_run_at_reason.as_deref(),
Some("job_queued_not_started")
);
assert_eq!(
status
.last_refresh_job
.as_ref()
.map(|job| job.state.as_str()),
Some("cancelled")
);
let failure_job = status.last_failure_job.as_ref().unwrap();
assert_eq!(failure_job.job_id, "job-failed");
let failure = failure_job.failure.as_ref().unwrap();
assert_eq!(failure.phase.as_deref(), Some("finalize"));
assert_eq!(failure.message.as_deref(), Some("worker timed out"));
assert_eq!(failure.retryable, Some(true));
assert_eq!(failure.sql_job_id.as_deref(), Some("sql-job-7"));
assert_eq!(statuses[1].auto_refresh.failure_streak, 5);
assert_eq!(
statuses[1].auto_refresh.blocked_reason,
Some(crate::table::FunctionColumnAutoRefreshBlockedReason::FailureThresholdReached)
);
assert_eq!(
statuses[2].auto_refresh.blocked_reason,
Some(crate::table::FunctionColumnAutoRefreshBlockedReason::BindingRevisionMissing)
);
assert_eq!(statuses[3].auto_refresh.failure_streak, 3);
assert_eq!(
statuses[3].auto_refresh.effective_cooldown_millis,
Some(8000)
);
assert_eq!(
statuses[3].auto_refresh.blocked_reason,
Some(crate::table::FunctionColumnAutoRefreshBlockedReason::PreparationBackoff)
);
}
#[tokio::test]
async fn test_function_column_status_passes_a_pinned_version() {
let calls = Arc::new(AtomicUsize::new(0));
let status_calls = Arc::new(AtomicUsize::new(0));
let table = Table::new_with_handler("my_table", {
let calls = calls.clone();
let status_calls = status_calls.clone();
move |request| {
calls.fetch_add(1, Ordering::SeqCst);
match request.url().path() {
"/v1/table/my_table/describe/" => {
assert_eq!(request_body_json(&request)["version"], 42);
http::Response::builder()
.status(200)
.body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string())
.unwrap()
}
"/v1/table/my_table/function_columns/status" => {
assert_eq!(request.method(), "GET");
let query: std::collections::BTreeMap<_, _> =
request.url().query_pairs().collect();
assert_eq!(
query.get("column").map(|value| value.as_ref()),
Some("embedding")
);
assert_eq!(query.get("version").map(|value| value.as_ref()), Some("42"));
let returned_version = if status_calls.fetch_add(1, Ordering::SeqCst) == 0 {
42
} else {
43
};
http::Response::builder()
.status(200)
.body(format!(
r#"[{{
"column":"embedding",
"binding_id":"fb_01",
"function":{{
"name":"embed",
"object_id":"embed",
"location":"objects/embed",
"version":"7",
"manifest_digest":"sha256:abc"
}},
"table_version":{returned_version},
"rows":0,
"fresh":0,
"stale":0,
"never_computed":0,
"failed":0,
"auto_refresh":{{
"enabled":false,
"state":"disabled",
"failure_streak":0,
"next_run_at_millis":null
}}
}}]"#,
))
.unwrap()
}
path => panic!("unexpected request path: {path}"),
}
}
});
table.checkout(42).await.unwrap();
let status = table.function_column_status("embedding").await.unwrap();
assert_eq!(status.table_version, 42);
assert_eq!(calls.load(Ordering::SeqCst), 2);
let error = table.function_column_status("embedding").await.unwrap_err();
assert!(
error.to_string().contains(
"returned table version 43, but the table handle is pinned to version 42"
)
);
assert_eq!(status_calls.load(Ordering::SeqCst), 2);
assert_eq!(calls.load(Ordering::SeqCst), 3);
}
#[tokio::test]
async fn test_function_column_status_keeps_latest_freshness_headers() {
let table = RemoteTable::new_mock(
"my_table".to_string(),
|request| {
assert_eq!(request.method(), "GET");
assert_eq!(
request.url().query_pairs().collect::<Vec<_>>(),
vec![(
std::borrow::Cow::Borrowed("column"),
std::borrow::Cow::Borrowed("embedding")
)]
);
assert_eq!(
request
.headers()
.get("x-lancedb-min-version")
.and_then(|value| value.to_str().ok()),
Some("7")
);
http::Response::builder()
.status(200)
.body(
r#"[{
"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":0,
"fresh":0,
"stale":0,
"never_computed":0,
"failed":0,
"auto_refresh":{
"enabled":false,
"state":"disabled",
"failure_streak":0,
"next_run_at_millis":null
}
}]"#,
)
.unwrap()
},
None,
);
table.freshness.lock().unwrap().min_version = Some(7);
let statuses = table
.function_column_statuses(Some("embedding"))
.await
.unwrap();
assert_eq!(statuses.len(), 1);
}
/// The error listing is table-addressed with optional job and column
/// filters, mirroring the server's SQL surface, and the two non-record
/// signals come back as their own fields rather than as rows.
@@ -11426,6 +12141,8 @@ mod tests {
.body(events.clone())
.unwrap()
}
"/v1/jobs/timeline" => http::Response::builder().status(200)
.body(br#"{"traceEvents":[],"metadata":{"partial":true}}"#.to_vec()).unwrap(),
other => panic!("unexpected path {other}"),
}
});
@@ -11442,6 +12159,7 @@ mod tests {
.await
.unwrap();
assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 1);
assert_eq!(job.timeline().await.unwrap()["metadata"]["partial"], true);
}
/// A newly submitted refresh returns a freshness-wrapped handle. Waiting
+27 -3
View File
@@ -44,6 +44,10 @@ impl fmt::Display for QueryStatus {
pub struct QueryDescription {
/// The stable, connection-scoped identifier assigned when the query was submitted.
pub id: Uuid,
/// The durable Job Registry identifier for a server-side SQL job, when the
/// submitted statement ran as one. This identifier can be passed to
/// `open_job`; `id` remains connection-scoped.
pub job_id: Option<String>,
/// The server-visible lifecycle state.
pub status: QueryStatus,
/// Server-reported completion progress, when known. Values are in `[0.0, 1.0]`,
@@ -56,6 +60,9 @@ pub struct QueryDescription {
#[async_trait]
pub(crate) trait QueryHandle: Send + Sync {
fn id(&self) -> Uuid;
fn job_id(&self) -> Option<String> {
None
}
async fn describe(&self) -> Result<QueryDescription>;
async fn reader(&self) -> Result<SendableRecordBatchStream>;
async fn cancel(&self) -> Result<()>;
@@ -68,8 +75,9 @@ pub(crate) trait QueryHandle: Send + Sync {
/// return result tickets. Dropping an unread handle or its reader stops a
/// directly streamed query; deferred execution continues until explicitly
/// cancelled. This applies equally with and without parameters.
/// Identifier lookup is scoped to the connection that submitted the query and
/// is not a durable resume mechanism.
/// [`Self::id`] is scoped to the connection that submitted the query. When the
/// server runs the statement as a SQL job, [`Self::job_id`] exposes the durable
/// Job Registry identifier accepted by `open_job`.
pub struct Query {
handle: Arc<dyn QueryHandle>,
}
@@ -79,6 +87,7 @@ impl std::fmt::Debug for Query {
formatter
.debug_struct("Query")
.field("id", &self.id())
.field("job_id", &self.job_id())
.finish()
}
}
@@ -94,6 +103,16 @@ impl Query {
self.handle.id()
}
/// Return the durable Job Registry identifier when the server has reported
/// one for this query.
///
/// A running query may report it after [`Self::describe`] observes the
/// server's latest status. The connection-scoped [`Self::id`] remains a
/// separate identifier.
pub fn job_id(&self) -> Option<String> {
self.handle.job_id()
}
/// Get a point-in-time description of the query.
///
/// Directly streamed queries stay [`QueryStatus::Running`] until the result
@@ -115,7 +134,12 @@ impl Query {
self.handle.reader().await
}
/// Request cancellation of the query.
/// Request cancellation of this query's Flight execution.
///
/// For a durable server-side SQL job, the operation may return
/// [`Error::NotSupported`] because the Flight waiter cannot cancel the
/// registry job. Use [`Connection::cancel_job`](crate::Connection::cancel_job)
/// with [`Self::job_id`] to cancel that job.
pub async fn cancel(&self) -> Result<()> {
self.handle.cancel().await
}
+101 -10
View File
@@ -83,6 +83,7 @@ pub mod datafusion;
pub(crate) mod dataset;
pub mod delete;
pub mod freshness;
pub mod function_column_status;
pub mod merge;
pub mod optimize;
pub(crate) mod primary_key;
@@ -106,6 +107,11 @@ pub use computed_columns::{
ComputedColumn, ComputedColumnKind, computed_column_from_field, computed_columns,
};
pub use delete::DeleteResult;
pub use function_column_status::{
FunctionColumnAutoRefreshBlockedReason, FunctionColumnAutoRefreshState,
FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus,
FunctionColumnVersionStatus,
};
use futures::future::join_all;
pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags};
pub use lance::dataset::scanner::DatasetRecordBatchStream;
@@ -114,7 +120,7 @@ pub use optimize::{
CompactionMode, CompactionOptions, CompactionOverrides, IndexRemapMode, OptimizeAction,
OptimizeStats,
};
pub use refresh::{RefreshColumnOptions, RefreshColumnResult};
pub use refresh::{FunctionWorkerResourceBudget, RefreshColumnOptions, RefreshColumnResult};
pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats};
pub use schema_evolution::{
AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate,
@@ -961,6 +967,19 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
.append_to("per-row Function errors are recorded only in LanceDB Enterprise"),
})
}
/// Exact four-way freshness status for Function-backed output columns.
///
/// `column` filters to one user-visible output; `None` returns every
/// Function output. The default returns `NotSupported`.
async fn function_column_statuses(
&self,
_column: Option<&str>,
) -> Result<Vec<FunctionColumnStatus>> {
Err(Error::NotSupported {
message: DocLink::Functions
.append_to("exact Function column status is supported only in LanceDB Enterprise"),
})
}
/// Alter columns in the table.
async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result<AlterColumnsResult>;
/// Drop columns from the table.
@@ -2144,10 +2163,14 @@ impl Table {
/// [`RefreshColumnOptions::publication_interval_rows()`] sets an opt-in
/// row-count publication threshold for completed Function outputs; unset
/// keeps whole-fragment publication.
/// [`RefreshColumnOptions::resource_budget()`] sets the aggregate CPU,
/// memory, and GPU budget for a Function refresh.
/// [`RefreshColumnOptions::gpu_class()`] selects a GPU pool and
/// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget.
/// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget
/// without changing the deployment's CPU and memory defaults.
/// Batch-size and GPU options have no effect on expression-backed columns
/// in LanceDB Embedded; a publication threshold is rejected there.
/// in LanceDB Embedded; a resource budget and publication threshold are
/// rejected there.
/// Remote refreshes require
/// [`Table::refresh_column_async_with_options`].
///
@@ -2208,13 +2231,15 @@ impl Table {
/// [`RefreshColumnOptions::publication_interval_rows()`] to publish
/// completed Function outputs at a row-count threshold; unset keeps
/// whole-fragment publication. Set
/// [`RefreshColumnOptions::gpu_class()`] and
/// [`RefreshColumnOptions::gpu_count()`] to override the registered GPU
/// class or set an aggregate GPU budget for Function workers. Unset values
/// use the Function and server defaults; zero counts and malformed class
/// names are rejected before submitting a job. Embedded expression
/// refreshes ignore the batch-size and GPU options, and reject publication
/// thresholds and other Enterprise-only options.
/// [`RefreshColumnOptions::resource_budget()`] to pass a complete aggregate
/// CPU, memory, and GPU budget for a Function refresh. The standalone
/// [`RefreshColumnOptions::gpu_count()`] shorthand and
/// [`RefreshColumnOptions::gpu_class()`] placement remain available; a
/// resource budget cannot be combined with the gpu-count shorthand. Unset
/// values use the Function and server defaults; invalid counts and malformed
/// class names are rejected before submitting a job. Embedded expression
/// refreshes ignore the batch-size and GPU options, and reject resource
/// budgets, publication thresholds, and other Enterprise-only options.
///
/// ```
/// # use lancedb::{Table, table::RefreshColumnOptions};
@@ -2240,6 +2265,72 @@ impl Table {
.await
}
/// Return exact freshness status for all Function-backed output columns.
///
/// The server evaluates all counts at one table version. Clients never
/// derive counts by joining schema, Job, and error listings. A handle
/// pinned with `checkout` sends that exact version, while a latest handle
/// keeps the existing read-freshness headers.
pub async fn function_column_statuses(
&self,
column: Option<&str>,
) -> Result<Vec<FunctionColumnStatus>> {
let statuses = self.inner.function_column_statuses(column).await?;
function_column_status::validate_statuses(&statuses)?;
Ok(statuses)
}
/// Return exact freshness status for one Function-backed output column.
pub async fn function_column_status(&self, column: &str) -> Result<FunctionColumnStatus> {
let mut statuses = self.function_column_statuses(Some(column)).await?;
if statuses.len() != 1 || statuses[0].column != column {
return Err(Error::ColumnNotFound {
name: column.to_string(),
});
}
Ok(statuses.remove(0))
}
/// Poll until a Function output has no stale or never-computed rows.
///
/// Failed rows do not keep the call pending. A typed
/// `function_column_status_finalization_pending` response is retried with
/// bounded exponential backoff; every other error is returned immediately.
pub async fn wait_for_function_column(
&self,
column: &str,
timeout: Option<std::time::Duration>,
) -> Result<FunctionColumnStatus> {
let started = std::time::Instant::now();
let mut delay = std::time::Duration::from_millis(250);
loop {
let result = self.function_column_status(column).await;
match result {
Ok(status) if status.stale == 0 && status.never_computed == 0 => return Ok(status),
Ok(_) => {}
Err(error) if function_column_status::is_finalization_pending(&error) => {}
Err(error) => return Err(error),
}
let sleep_for = match timeout {
Some(timeout) => {
let remaining = timeout.saturating_sub(started.elapsed());
if remaining.is_zero() {
return Err(Error::Timeout {
message: format!(
"Function column '{column}' did not become fresh before timeout"
),
});
}
delay.min(remaining)
}
None => delay,
};
tokio::time::sleep(sleep_for).await;
delay = std::cmp::min(delay * 2, std::time::Duration::from_secs(1));
}
}
/// The per-row errors Function refreshes recorded on this table: the
/// rows a refresh skipped under its skip policy, with the failing input
/// and the error, plus a summary for any fragment whose detail was
+42 -1
View File
@@ -171,7 +171,9 @@ impl AddColumnsBuilder {
/// Configure automatic refresh for every output declared in this call.
/// Settings are stored with the declaration. They require computed or
/// Function columns; LanceDB Embedded persists them without starting a scheduler.
/// Function columns. LanceDB Embedded persists enabled and interval settings
/// without starting a scheduler; an automatic resource budget requires an
/// Enterprise registered Function and rejects SQL-expression columns.
///
/// ```
/// # use lancedb::{Table, table::computed_columns::ComputedColumnOptions};
@@ -180,6 +182,7 @@ impl AddColumnsBuilder {
/// .computed_options(ComputedColumnOptions {
/// auto_refresh_enabled: true,
/// auto_refresh_interval_seconds: Some(300),
/// auto_refresh_resource_budget: None,
/// }).execute().await?;
/// # Ok(())
/// # }
@@ -207,6 +210,13 @@ impl AddColumnsBuilder {
.into(),
});
}
if options.auto_refresh_resource_budget.is_some() && function.is_none() {
return Err(Error::InvalidInput {
message:
"auto_refresh_resource_budget requires a registered Function declaration"
.into(),
});
}
}
let options = options.unwrap_or_default();
@@ -289,6 +299,7 @@ mod tests {
let options = ComputedColumnOptions {
auto_refresh_enabled: false,
auto_refresh_interval_seconds: Some(300),
auto_refresh_resource_budget: None,
};
let result = table
.add_columns()
@@ -373,6 +384,36 @@ mod tests {
);
}
#[tokio::test]
async fn auto_refresh_resource_budget_requires_a_function() {
let table = table_with_two_columns("budget_expression").await;
let err = table
.add_columns()
.computed("doubled", "x * 2")
.computed_options(ComputedColumnOptions {
auto_refresh_enabled: true,
auto_refresh_interval_seconds: None,
auto_refresh_resource_budget: Some(
crate::table::FunctionWorkerResourceBudget::new(1_000, 1_024),
),
})
.execute()
.await
.unwrap_err();
assert!(
matches!(&err, Error::InvalidInput { message } if message.contains("registered Function")),
"{err:?}"
);
assert!(
table
.schema()
.await
.unwrap()
.field_with_name("doubled")
.is_err()
);
}
#[tokio::test]
async fn test_requires_a_transform() {
let table = table_with_two_columns("no_transform").await;
+161 -3
View File
@@ -42,6 +42,7 @@ use serde_json::Value;
use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding};
use crate::materialized_view::without_declarations;
use crate::table::FunctionWorkerResourceBudget;
use crate::utils::resolve_arrow_field_path;
use crate::{Error, Result};
@@ -61,6 +62,9 @@ pub const INPUTS_META_KEY: &str = "computed_column.inputs";
pub const AUTO_REFRESH_ENABLED_META_KEY: &str = "computed_column.auto_refresh_enabled";
/// Minimum interval between successful automatic refreshes, in seconds.
pub const AUTO_REFRESH_INTERVAL_META_KEY: &str = "computed_column.auto_refresh_interval_seconds";
/// Aggregate worker-resource budget for automatic Function refreshes.
pub const AUTO_REFRESH_RESOURCE_BUDGET_META_KEY: &str =
"computed_column.auto_refresh_resource_budget";
/// Scheduling settings persisted on each computed output. LanceDB Embedded
/// stores these settings; automatic scheduling requires LanceDB Enterprise.
@@ -73,6 +77,10 @@ pub struct ComputedColumnOptions {
/// When omitted, the server determines when to refresh.
#[serde(skip_serializing_if = "Option::is_none")]
pub auto_refresh_interval_seconds: Option<u64>,
/// Aggregate worker-resource budget for automatic Function refreshes.
/// This option requires a registered Function output.
#[serde(skip_serializing_if = "Option::is_none")]
pub auto_refresh_resource_budget: Option<FunctionWorkerResourceBudget>,
}
impl Default for ComputedColumnOptions {
@@ -80,6 +88,7 @@ impl Default for ComputedColumnOptions {
Self {
auto_refresh_enabled: true,
auto_refresh_interval_seconds: None,
auto_refresh_resource_budget: None,
}
}
}
@@ -95,6 +104,9 @@ impl ComputedColumnOptions {
message: "auto_refresh_interval_seconds must be a positive integer no greater than u64::MAX / 1000".into(),
});
}
if let Some(budget) = &self.auto_refresh_resource_budget {
budget.validate()?;
}
Ok(())
}
@@ -112,6 +124,15 @@ impl ComputedColumnOptions {
message: "auto_refresh_interval_seconds must be a positive integer".into(),
})?);
}
if let Some(value) = metadata.get(AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) {
options.auto_refresh_resource_budget = Some(serde_json::from_str(value).map_err(
|error| Error::InvalidInput {
message: format!(
"auto_refresh_resource_budget must be a valid resource budget: {error}"
),
},
)?);
}
options.validate()?;
Ok(options)
}
@@ -119,6 +140,7 @@ impl ComputedColumnOptions {
/// Attach validated settings to newly declared computed output fields.
pub fn apply_to_schema(&self, schema: &ArrowSchema) -> Result<ArrowSchema> {
self.validate()?;
let option_metadata = self.metadata()?;
let fields = schema
.fields()
.iter()
@@ -134,7 +156,7 @@ impl ComputedColumnOptions {
return field.clone();
}
let mut metadata = field.metadata().clone();
metadata.extend(self.metadata());
metadata.extend(option_metadata.clone());
Arc::new(field.as_ref().clone().with_metadata(metadata))
})
.collect::<Vec<_>>();
@@ -145,7 +167,7 @@ impl ComputedColumnOptions {
}
/// Field metadata values shared by native and server declaration paths.
pub fn metadata(&self) -> HashMap<String, String> {
pub fn metadata(&self) -> Result<HashMap<String, String>> {
let mut metadata = HashMap::from([(
AUTO_REFRESH_ENABLED_META_KEY.into(),
self.auto_refresh_enabled.to_string(),
@@ -153,7 +175,15 @@ impl ComputedColumnOptions {
if let Some(interval) = self.auto_refresh_interval_seconds {
metadata.insert(AUTO_REFRESH_INTERVAL_META_KEY.into(), interval.to_string());
}
metadata
if let Some(budget) = &self.auto_refresh_resource_budget {
metadata.insert(
AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(),
serde_json::to_string(budget).map_err(|error| Error::InvalidInput {
message: format!("failed to encode auto_refresh_resource_budget: {error}"),
})?,
);
}
Ok(metadata)
}
}
@@ -181,6 +211,11 @@ pub const FUNCTION_BINDINGS_VERSION: u32 = 1;
/// declared before signatures existed.
pub const SOURCE_SIGNATURE_META_KEY: &str = "computed_refresh.source_signature";
/// Signatures of input-preserving rewrites whose retained Function outputs
/// are current but whose inserted rows still need their first computation.
/// A sidecar reference keeps this separate from completed freshness stamps.
pub const PENDING_FILL_SIGNATURE_META_KEY: &str = "computed_refresh.pending_fill_signature";
/// Field metadata key holding the definition digest a column was last
/// computed under. A change to it makes every row stale.
pub const DEFINITION_VERSION_META_KEY: &str = "computed_refresh.definition_version";
@@ -2533,6 +2568,129 @@ pub(crate) mod test_support {
#[cfg(test)]
mod tests {
#[test]
fn computed_auto_refresh_resource_budget_metadata_round_trips() {
let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184)
.with_gpu_count(2);
let options = super::ComputedColumnOptions {
auto_refresh_enabled: true,
auto_refresh_interval_seconds: Some(300),
auto_refresh_resource_budget: Some(budget),
};
assert_eq!(
super::ComputedColumnOptions::from_metadata(&HashMap::new()).unwrap(),
super::ComputedColumnOptions::default()
);
let metadata = options.metadata().unwrap();
assert_eq!(
metadata
.get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY)
.map(String::as_str),
Some(r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":2}"#)
);
assert_eq!(
super::ComputedColumnOptions::from_metadata(&metadata).unwrap(),
options
);
let mut omitted_gpu = metadata.clone();
omitted_gpu.insert(
super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(),
r#"{"cpu_millis":8000,"memory_bytes":17179869184}"#.into(),
);
let decoded = super::ComputedColumnOptions::from_metadata(&omitted_gpu).unwrap();
assert_eq!(decoded.auto_refresh_resource_budget.unwrap().gpu_count, 0);
assert_eq!(
decoded
.metadata()
.unwrap()
.get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY)
.map(String::as_str),
Some(r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":0}"#)
);
for invalid in [
r#"{"memory_bytes":17179869184,"gpu_count":2}"#,
r#"{"cpu_millis":8000,"gpu_count":2}"#,
r#"{"cpu_millis":"8000","memory_bytes":17179869184,"gpu_count":2}"#,
r#"{"cpu_millis":-1,"memory_bytes":17179869184,"gpu_count":2}"#,
r#"{"cpu_millis":18446744073709551616,"memory_bytes":17179869184,"gpu_count":2}"#,
r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":-1}"#,
r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":4294967296}"#,
r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":2,"unknown":1}"#,
r#"{"cpu_millis":0,"memory_bytes":17179869184,"gpu_count":2}"#,
r#"{"cpu_millis":8000,"memory_bytes":0,"gpu_count":2}"#,
] {
let mut malformed = metadata.clone();
malformed.insert(
super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(),
invalid.into(),
);
assert!(
super::ComputedColumnOptions::from_metadata(&malformed).is_err(),
"accepted invalid budget: {invalid}"
);
}
}
#[test]
fn computed_auto_refresh_resource_budget_applies_to_function_outputs() {
let function_field = |name: &str, ordinal: u32| {
ArrowField::new(name, DataType::Int32, true).with_metadata(HashMap::from([
(
super::COMPUTED_COLUMN_META_KEY.to_string(),
"true".to_string(),
),
(
super::KIND_META_KEY.to_string(),
super::FUNCTION_KIND.to_string(),
),
(
super::FUNCTION_BINDING_ID_META_KEY.to_string(),
"binding-1".to_string(),
),
(
super::FUNCTION_OUTPUT_ORDINAL_META_KEY.to_string(),
ordinal.to_string(),
),
("custom".to_string(), "preserved".to_string()),
]))
};
let schema = ArrowSchema::new(vec![
ArrowField::new("input", DataType::Int32, true),
function_field("first", 0),
function_field("second", 1),
function_field("assignment", super::FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL),
]);
let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184)
.with_gpu_count(2);
let updated = super::ComputedColumnOptions {
auto_refresh_resource_budget: Some(budget),
..Default::default()
}
.apply_to_schema(&schema)
.unwrap();
for name in ["first", "second"] {
let metadata = updated.field_with_name(name).unwrap().metadata();
assert_eq!(
metadata.get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY),
Some(&serde_json::to_string(&budget).unwrap())
);
assert_eq!(
metadata.get("custom").map(String::as_str),
Some("preserved")
);
}
assert!(
!updated
.field_with_name("assignment")
.unwrap()
.metadata()
.contains_key(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY)
);
}
/// The gate's reproducer: the validator applies the same schema-level
/// guard declaring does, so a staging caller is refused before it commits
/// anything else.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,339 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! Read-only status for Function-backed table columns.
use serde::{Deserialize, Serialize};
use crate::error::JobFailure;
use crate::function::FunctionVersionRef;
use crate::{Error, Result};
/// Stable HTTP error code for a status read waiting on its matching finalize.
pub const FINALIZATION_PENDING_ERROR_CODE: &str = "function_column_status_finalization_pending";
/// One exact immutable Function revision attached to a table output.
pub type FunctionColumnVersionStatus = FunctionVersionRef;
/// Latest matching refresh Job projected for a Function output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionColumnLastRefreshJob {
pub job_id: String,
pub state: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub automatic: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub completed_at_millis: Option<i64>,
/// Why this Job failed, when the server retained a structured failure.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure: Option<JobFailure>,
}
/// Automatic-refresh scheduling state that the server can prove.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FunctionColumnAutoRefreshState {
Disabled,
Running,
Queued,
UpToDate,
Ready,
WaitingInterval,
WaitingBackoff,
Blocked,
Unobservable,
}
impl FunctionColumnAutoRefreshState {
pub const fn as_str(self) -> &'static str {
match self {
Self::Disabled => "disabled",
Self::Running => "running",
Self::Queued => "queued",
Self::UpToDate => "up_to_date",
Self::Ready => "ready",
Self::WaitingInterval => "waiting_interval",
Self::WaitingBackoff => "waiting_backoff",
Self::Blocked => "blocked",
Self::Unobservable => "unobservable",
}
}
}
/// Why an enabled automatic refresh is not currently schedulable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FunctionColumnAutoRefreshBlockedReason {
TableHasMemWal,
InputsNotSettled,
DependencyInFlight,
TableCapacity,
Cancelled,
PreparationBackoff,
FailureThresholdReached,
BindingRevisionMissing,
}
impl FunctionColumnAutoRefreshBlockedReason {
pub const fn as_str(self) -> &'static str {
match self {
Self::TableHasMemWal => "table_has_mem_wal",
Self::InputsNotSettled => "inputs_not_settled",
Self::DependencyInFlight => "dependency_in_flight",
Self::TableCapacity => "table_capacity",
Self::Cancelled => "cancelled",
Self::PreparationBackoff => "preparation_backoff",
Self::FailureThresholdReached => "failure_threshold_reached",
Self::BindingRevisionMissing => "binding_revision_missing",
}
}
}
/// Automatic-refresh projection for a Function output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionColumnAutoRefreshStatus {
pub enabled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval_seconds: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active_job_id: Option<String>,
pub state: FunctionColumnAutoRefreshState,
pub failure_streak: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub effective_cooldown_millis: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blocked_reason: Option<FunctionColumnAutoRefreshBlockedReason>,
/// Null is intentional until the Lance Agent exposes its scheduler decision.
pub next_run_at_millis: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_run_at_reason: Option<String>,
}
/// Exact status of one Function output at one table version.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionColumnStatus {
pub column: String,
pub binding_id: String,
pub function: FunctionColumnVersionStatus,
pub table_version: u64,
pub rows: u64,
pub fresh: u64,
pub stale: u64,
pub never_computed: u64,
pub failed: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_refresh_job: Option<FunctionColumnLastRefreshJob>,
/// Newest failed refresh Job. Unlike `last_refresh_job`, this remains
/// visible when the latest attempt was cancelled.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_failure_job: Option<FunctionColumnLastRefreshJob>,
pub auto_refresh: FunctionColumnAutoRefreshStatus,
}
impl FunctionColumnStatus {
/// Whether this status is safe to expose as an exact four-way count.
pub fn validate(&self) -> Result<()> {
let classified = self
.fresh
.checked_add(self.stale)
.and_then(|count| count.checked_add(self.never_computed))
.and_then(|count| count.checked_add(self.failed));
if classified != Some(self.rows) {
return Err(Error::Runtime {
message: format!(
"Function column '{}' status counts do not partition {} rows",
self.column, self.rows
),
});
}
if self.auto_refresh.state == FunctionColumnAutoRefreshState::Blocked
&& self.auto_refresh.blocked_reason.is_none()
{
return Err(Error::Runtime {
message: format!(
"Function column '{}' reported a blocked scheduler state without a reason",
self.column
),
});
}
if self.auto_refresh.state == FunctionColumnAutoRefreshState::Unobservable
&& self.auto_refresh.next_run_at_millis.is_none()
&& self
.auto_refresh
.next_run_at_reason
.as_deref()
.is_none_or(str::is_empty)
{
return Err(Error::Runtime {
message: format!(
"Function column '{}' omitted a reason for an unavailable next run",
self.column
),
});
}
Ok(())
}
}
/// Validate one GET response, whose objects must all describe one snapshot.
pub fn validate_statuses(statuses: &[FunctionColumnStatus]) -> Result<()> {
let mut table_versions = statuses.iter().map(|status| status.table_version);
let Some(first) = table_versions.next() else {
return Ok(());
};
if table_versions.any(|version| version != first) {
return Err(Error::Runtime {
message: "Function column statuses came from different table versions".to_string(),
});
}
statuses.iter().try_for_each(FunctionColumnStatus::validate)
}
/// Whether an error is the typed transient response used while the data
/// version's matching freshness finalization is still in progress.
pub fn is_finalization_pending(error: &Error) -> bool {
#[cfg(feature = "remote")]
{
error.status_code() == Some(reqwest::StatusCode::SERVICE_UNAVAILABLE)
&& error
.remote_error_metadata()
.and_then(|metadata| metadata.error_code.as_deref())
== Some(FINALIZATION_PENDING_ERROR_CODE)
}
#[cfg(not(feature = "remote"))]
{
let _ = error;
false
}
}
#[cfg(test)]
mod tests {
use super::*;
fn status(column: &str, table_version: u64) -> FunctionColumnStatus {
FunctionColumnStatus {
column: column.to_string(),
binding_id: "fb_01".to_string(),
function: FunctionVersionRef {
name: "embed".to_string(),
namespace_path: Vec::new(),
object_id: "embed".to_string(),
location: "objects/embed".to_string(),
version: "7".to_string(),
manifest_digest: "sha256:abc".to_string(),
},
table_version,
rows: 10,
fresh: 6,
stale: 2,
never_computed: 1,
failed: 1,
last_refresh_job: None,
last_failure_job: None,
auto_refresh: FunctionColumnAutoRefreshStatus {
enabled: true,
interval_seconds: Some(60),
active_job_id: None,
state: FunctionColumnAutoRefreshState::Unobservable,
failure_streak: 0,
effective_cooldown_millis: None,
blocked_reason: None,
next_run_at_millis: None,
next_run_at_reason: Some(
"authoritative_scheduler_projection_unavailable".to_string(),
),
},
}
}
#[test]
fn validates_a_single_version_and_four_way_partition() {
validate_statuses(&[status("a", 42), status("b", 42)]).unwrap();
let error = validate_statuses(&[status("a", 42), status("b", 43)]).unwrap_err();
assert!(error.to_string().contains("different table versions"));
let mut invalid = status("a", 42);
invalid.fresh += 1;
let error = validate_statuses(&[invalid]).unwrap_err();
assert!(error.to_string().contains("do not partition 10 rows"));
}
#[test]
fn wire_keeps_job_and_auto_refresh_metadata() {
let mut value = status("a", 42);
value.last_refresh_job = Some(FunctionColumnLastRefreshJob {
job_id: "job-7".to_string(),
state: "finished".to_string(),
automatic: Some(true),
completed_at_millis: Some(1_790_000_000_000),
failure: None,
});
let encoded = serde_json::to_value(value).unwrap();
assert_eq!(encoded["last_refresh_job"]["job_id"], "job-7");
assert_eq!(encoded["auto_refresh"]["enabled"], true);
assert_eq!(
encoded["auto_refresh"]["next_run_at_reason"],
"authoritative_scheduler_projection_unavailable"
);
}
#[test]
fn scheduler_wire_names_are_stable() {
for (state, expected) in [
(FunctionColumnAutoRefreshState::Queued, "queued"),
(FunctionColumnAutoRefreshState::UpToDate, "up_to_date"),
] {
assert_eq!(
serde_json::to_string(&state).unwrap(),
format!("\"{expected}\"")
);
}
for (reason, expected) in [
(
FunctionColumnAutoRefreshBlockedReason::FailureThresholdReached,
"failure_threshold_reached",
),
(
FunctionColumnAutoRefreshBlockedReason::BindingRevisionMissing,
"binding_revision_missing",
),
] {
assert_eq!(
serde_json::to_string(&reason).unwrap(),
format!("\"{expected}\"")
);
}
}
#[test]
fn blocked_auto_refresh_wire_keeps_its_reason() {
let mut value = status("a", 42);
value.auto_refresh.state = FunctionColumnAutoRefreshState::Blocked;
value.auto_refresh.failure_streak = 3;
value.auto_refresh.effective_cooldown_millis = Some(8000);
value.auto_refresh.blocked_reason =
Some(FunctionColumnAutoRefreshBlockedReason::PreparationBackoff);
value.auto_refresh.next_run_at_reason = None;
let encoded = serde_json::to_value(&value).unwrap();
assert_eq!(encoded["auto_refresh"]["state"], "blocked");
assert_eq!(
encoded["auto_refresh"]["blocked_reason"],
"preparation_backoff"
);
assert_eq!(encoded["auto_refresh"]["failure_streak"], 3);
assert_eq!(encoded["auto_refresh"]["effective_cooldown_millis"], 8000);
value.validate().unwrap();
value.auto_refresh.blocked_reason = None;
assert!(
value
.validate()
.unwrap_err()
.to_string()
.contains("blocked scheduler state without a reason")
);
}
}
+16 -1
View File
@@ -385,6 +385,8 @@ pub(crate) async fn execute_merge_insert(
}
let dataset = table.dataset.get().await?;
let source_schema = source.schema();
let on = params.on.clone();
let mut builder = LanceMergeInsertBuilder::try_new(dataset.clone(), params.on)?;
match (
params.when_matched_update_all,
@@ -432,8 +434,21 @@ pub(crate) async fn execute_merge_insert(
Either::Right(job.execute(source).map_err(|e| e.into()))
};
let (new_dataset, stats) = future.await?;
let mut new_dataset = new_dataset.as_ref().clone();
if let Err(error) = super::freshness::preserve_function_freshness(
&mut new_dataset,
super::freshness::FunctionWrite::Merge {
source_schema: &source_schema,
on: &on,
num_inserted_rows: stats.num_inserted_rows,
},
)
.await
{
log::warn!("merge committed but Function freshness could not be preserved: {error}");
}
let version = new_dataset.manifest().version;
table.dataset.update(new_dataset.as_ref().clone());
table.dataset.update(new_dataset);
Ok(MergeResult {
version,
num_updated_rows: stats.num_updated_rows,
+90
View File
@@ -55,6 +55,55 @@ use crate::function::validate_gpu_class_name;
use crate::job::Job;
use crate::{Error, Result};
/// Aggregate worker resources for one Enterprise Function refresh.
///
/// CPU is in millicores (1000 = one core) and memory is in bytes. These
/// values cap the Function workers together; they are not per-worker
/// allocations. The default GPU budget is zero, which describes a CPU-only
/// Function. This option is rejected by LanceDB Embedded refreshes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct FunctionWorkerResourceBudget {
pub cpu_millis: u64,
pub memory_bytes: u64,
/// Aggregate GPU budget across the refresh. Zero is CPU-only.
#[serde(default)]
pub gpu_count: u32,
}
impl FunctionWorkerResourceBudget {
/// Create a CPU-only aggregate budget.
pub fn new(cpu_millis: u64, memory_bytes: u64) -> Self {
Self {
cpu_millis,
memory_bytes,
gpu_count: 0,
}
}
/// Set the aggregate GPU budget.
pub fn with_gpu_count(mut self, gpu_count: u32) -> Self {
self.gpu_count = gpu_count;
self
}
/// Require every per-tier resource limit to request at least one unit.
pub fn validate(&self) -> Result<()> {
if self.cpu_millis == 0 {
return Err(Error::InvalidInput {
message: "resource_budget.cpu_millis must be greater than zero".into(),
});
}
if self.memory_bytes == 0 {
return Err(Error::InvalidInput {
message: "resource_budget.memory_bytes must be greater than zero".into(),
});
}
Ok(())
}
}
/// Options for refreshing a computed column.
///
/// Serializes to the Enterprise backfill request body, one key per set
@@ -100,6 +149,12 @@ pub struct RefreshColumnOptions {
/// effect on expression-backed columns in LanceDB Embedded.
#[serde(skip_serializing_if = "Option::is_none")]
pub batch_size: Option<usize>,
/// Override the registered Function's maximum concurrent user-code calls
/// for this logical execution. Must be greater than zero. `None` uses the
/// registration default, or disabled when the Function declares none.
/// This is not an account quota and does not change `resource_budget`.
#[serde(skip_serializing_if = "Option::is_none")]
pub max_concurrency: Option<u32>,
/// Opt-in row-count threshold for publishing completed Function outputs.
///
/// Must be greater than zero. `None` keeps whole-fragment publication.
@@ -108,6 +163,10 @@ pub struct RefreshColumnOptions {
/// rejects this option.
#[serde(skip_serializing_if = "Option::is_none")]
pub publication_interval_rows: Option<u64>,
/// Complete aggregate CPU, memory, and GPU budget for a registered
/// Function refresh. Cannot be combined with `gpu_count`.
#[serde(skip_serializing_if = "Option::is_none")]
pub resource_budget: Option<FunctionWorkerResourceBudget>,
/// GPU class for Function workers in LanceDB Enterprise.
///
/// `None` keeps the Function's registered class, or the deployment default
@@ -182,6 +241,13 @@ impl RefreshColumnOptions {
self
}
/// Override the registered Function's maximum concurrent user-code calls
/// for this logical execution.
pub fn max_concurrency(mut self, max_concurrency: u32) -> Self {
self.max_concurrency = Some(max_concurrency);
self
}
/// Use `rows` as the opt-in publication threshold for completed Function
/// outputs. The actual publication boundary can be larger than this value.
pub fn publication_interval_rows(mut self, rows: u64) -> Self {
@@ -189,6 +255,15 @@ impl RefreshColumnOptions {
self
}
/// Set the aggregate worker resource budget for a Function refresh.
///
/// Use [`FunctionWorkerResourceBudget::new`] for a CPU-only budget, or
/// [`FunctionWorkerResourceBudget::with_gpu_count`] to include GPUs.
pub fn resource_budget(mut self, budget: FunctionWorkerResourceBudget) -> Self {
self.resource_budget = Some(budget);
self
}
/// Request Function workers from `gpu_class`.
pub fn gpu_class(mut self, gpu_class: impl Into<String>) -> Self {
self.gpu_class = Some(gpu_class.into());
@@ -216,10 +291,12 @@ impl RefreshColumnOptions {
"max_executor_processes_per_worker",
self.max_executor_processes_per_worker.is_some(),
),
("max_concurrency", self.max_concurrency.is_some()),
(
"publication_interval_rows",
self.publication_interval_rows.is_some(),
),
("resource_budget", self.resource_budget.is_some()),
]
.into_iter()
.find_map(|(name, set)| set.then_some(name))
@@ -272,11 +349,24 @@ impl RefreshColumnOptions {
message: "batch_size must be greater than zero".into(),
});
}
if self.max_concurrency == Some(0) {
return Err(Error::InvalidInput {
message: "max_concurrency must be greater than zero".into(),
});
}
if self.publication_interval_rows == Some(0) {
return Err(Error::InvalidInput {
message: "publication_interval_rows must be greater than zero".into(),
});
}
if self.resource_budget.is_some() && self.gpu_count.is_some() {
return Err(Error::InvalidInput {
message: "gpu_count cannot be combined with resource_budget".into(),
});
}
if let Some(budget) = &self.resource_budget {
budget.validate()?;
}
if let Some(gpu_class) = &self.gpu_class {
validate_gpu_class_name(gpu_class)?;
}
+19 -2
View File
@@ -113,6 +113,11 @@ pub(crate) async fn execute_update(
}
// 4. Apply the columns (SET clause)
let written_columns = update
.columns
.iter()
.map(|(column, _)| column.clone())
.collect::<Vec<_>>();
for (column, value) in update.columns {
builder = builder.set(column, &value)?;
}
@@ -120,13 +125,25 @@ pub(crate) async fn execute_update(
// 5. Execute the operation (Write new files)
let operation = builder.build()?;
let res = operation.execute().await?;
let mut new_dataset = res.new_dataset.as_ref().clone();
if let Err(error) = super::freshness::preserve_function_freshness(
&mut new_dataset,
super::freshness::FunctionWrite::Update {
columns: &written_columns,
},
)
.await
{
log::warn!("update committed but Function freshness could not be preserved: {error}");
}
// 6. Update the table's view of the latest version
table.dataset.update(res.new_dataset.as_ref().clone());
let version = new_dataset.version().version;
table.dataset.update(new_dataset);
Ok(UpdateResult {
rows_updated: res.rows_updated,
version: res.new_dataset.version().version,
version,
})
}

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