diff --git a/.bumpversion.toml b/.bumpversion.toml index 992d126d0..076443831 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.10" +current_version = "0.42.0-beta.11" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml index 8d8763e1d..e96d5b095 100644 --- a/.github/workflows/cli.yml +++ b/.github/workflows/cli.yml @@ -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. diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index a8dd3993e..1b7d3dcbc 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -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 diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 5aea2ca30..8730e220d 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -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: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2080789d4..2fabb4a6a 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -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: diff --git a/Cargo.lock b/Cargo.lock index 60148920f..f6e027f50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index ff49d4a41..dd358fb76 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 3d3a3f8e1..c06b4f230 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.10 + 0.42.0-beta.11 ``` diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 1fad723fe..431796843 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -704,6 +704,47 @@ so this is safe to call repeatedly. *** +### functionColumnStatus() + +```ts +abstract functionColumnStatus(column): Promise +``` + +Return exact freshness status for one Function-backed output column. + +#### Parameters + +* **column**: `string` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)> + +*** + +### functionColumnStatuses() + +```ts +abstract functionColumnStatuses(column?): Promise +``` + +Return exact freshness status for Function-backed output columns. + +All results describe one server table version. Omit `column` for every +Function output. Rows already failed remain visible and do not prevent +`waitFresh` from completing. A handle pinned to an exact version requests +that version; a latest handle retains normal read-freshness behavior. + +#### Parameters + +* **column?**: `string` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)[]> + +*** + ### functionErrors() ```ts @@ -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`<`void`> + +*** + +### waitFresh() + +```ts +abstract waitFresh(column, timeoutSeconds?): Promise +``` + +Poll until no stale or never-computed rows remain. + +Only HTTP 503 with the exact finalization-pending error code is retried; +every other error propagates. Failed rows do not block completion. + +#### Parameters + +* **column**: `string` + +* **timeoutSeconds?**: `number` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)> diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index dab1c61bc..19d7ceb97 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -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) diff --git a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md new file mode 100644 index 000000000..3a203026c --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.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"; +``` diff --git a/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md new file mode 100644 index 000000000..a7c1df2aa --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md @@ -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; +``` diff --git a/docs/src/js/interfaces/FunctionColumnStatus.md b/docs/src/js/interfaces/FunctionColumnStatus.md new file mode 100644 index 000000000..0c299ee2b --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnStatus.md @@ -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; +``` diff --git a/docs/src/js/interfaces/FunctionColumnVersionStatus.md b/docs/src/js/interfaces/FunctionColumnVersionStatus.md new file mode 100644 index 000000000..fa02139d2 --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnVersionStatus.md @@ -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; +``` diff --git a/docs/src/js/interfaces/FunctionWorkerResourceBudget.md b/docs/src/js/interfaces/FunctionWorkerResourceBudget.md new file mode 100644 index 000000000..0352bc833 --- /dev/null +++ b/docs/src/js/interfaces/FunctionWorkerResourceBudget.md @@ -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. diff --git a/docs/src/js/interfaces/JobFailureInfo.md b/docs/src/js/interfaces/JobFailureInfo.md index fe9ce04e3..cdea222c5 100644 --- a/docs/src/js/interfaces/JobFailureInfo.md +++ b/docs/src/js/interfaces/JobFailureInfo.md @@ -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 diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 840012040..c534e0fac 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -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 diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 7f28d8804..eccaae6ce 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -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 diff --git a/docs/web/basics/agentic-skills.mdx b/docs/web/basics/agentic-skills.mdx index d88b5dddf..638e39bdd 100644 --- a/docs/web/basics/agentic-skills.mdx +++ b/docs/web/basics/agentic-skills.mdx @@ -78,6 +78,24 @@ Not every agent supports project scope; `npx plugins targets` lists what it found and what each target supports. +## 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 diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index 0341ee333..84996ffe9 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -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`) | | --- | --- | diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 9f6370347..111eaf13f 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -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} diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 2c9e9be4c..851b37d9b 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -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: + + +```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?; +``` + + +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} diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 0dfe3b33d..1b809b91d 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -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: + + +```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); +``` + + +`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: + + +```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(); +``` + + +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: + + +```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(); +``` + + +`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( `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. 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: ```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} diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index c8fa0626c..bebbe1169 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -107,7 +107,9 @@ single `id` is the SQL query UUID. Repeated waits reuse the completed result. `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. 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`. ```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 ``` diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index c229e13f0..2a05b4a0f 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -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} diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 5bd9a3efe..ef462cbf7 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -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`: ```bash Python (pip) icon="terminal" diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 8cd45f8bc..95c2d4d6e 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -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. diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 758e41acd..903be2b77 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.10 + 0.42.0-beta.11 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 2f72f98a7..610c095b9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.10 + 0.42.0-beta.11 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.16 + 15.0.0-beta.17 2.18.12 false 2.30.0 diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 47fc92237..91d808647 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -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 diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 242be6101..4ac08b4c4 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -647,6 +647,100 @@ describe("remote connection", () => { ]); }); + it("passes a pinned version and decodes Function scheduler status", async () => { + const queries: Record[] = []; + 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 + }}`, + ), ]); }); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index c3888d6c0..b803e9043 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -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 () => { diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 9644b0060..35697dc8c 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -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, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 5ef298c8c..b38c2381c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -35,6 +35,7 @@ import { FunctionErrorsOptions, IndexConfig, IndexStatistics, + JobFailureInfo, Branches as NativeBranches, OptimizeStats, RTEStats, @@ -258,6 +259,76 @@ export interface RTEWriteSpec { writerConfigDefaults?: Record; } +/** 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; + /** + * 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; + + /** Return exact freshness status for one Function-backed output column. */ + abstract functionColumnStatus(column: string): Promise; + + /** + * 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; + /** * 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 { + return (await this.inner.functionColumnStatuses( + column, + )) as FunctionColumnStatus[]; + } + + async functionColumnStatus(column: string): Promise { + return (await this.inner.functionColumnStatus( + column, + )) as FunctionColumnStatus; + } + + async waitFresh( + column: string, + timeoutSeconds?: number, + ): Promise { + validateNonNegativeInteger(timeoutSeconds, "timeoutSeconds"); + return (await this.inner.waitForFunctionColumn( + column, + timeoutSeconds, + )) as FunctionColumnStatus; + } + async refreshMaterializedView( sourceVersion?: number, full?: boolean, diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 3761d6f4f..1a9011b34 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -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", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 5b7a167d0..00b2918d6 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -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", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index e902929bf..f94f27216 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -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", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index a54f47de3..e0eefa2e9 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -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", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index cc1894e70..f0891fbed 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -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", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index d5e0309d0..04b65ba86 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 5e9698e7f..e5e0effab 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -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", diff --git a/nodejs/package.json b/nodejs/package.json index 5579e1c55..a03e1a794 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -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", diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 485035d33..09b245f97 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -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 { - 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 for JobInfo { /// The server's account of why a job failed. #[napi(object)] +#[derive(Clone, Debug)] pub struct JobFailureInfo { pub phase: Option, pub message: Option, /// User-code traceback, possibly truncated by the server. pub traceback: Option, pub retryable: Option, + /// Isolated SQL job that raised this failure, when supplied by the server. + pub sql_job_id: Option, +} + +impl From 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, + } + } } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index ebbc4a060..e3bd22c0b 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -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, + ) -> napi::Result> { + 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 { + 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, + ) -> napi::Result { + 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, } +/// 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, +} + +fn positive_safe_integer(value: f64, name: &str) -> napi::Result { + 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) -> napi::Result { + 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, name: &str) -> napi::Result> { + 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, /// Maximum rows per Function call; must be greater than zero. pub batch_size: Option, + /// 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, + /// Override the registered Function's maximum concurrent user-code calls + /// for this logical execution. + pub max_concurrency: Option, /// GPU class for Function workers. pub gpu_class: Option, + /// Complete aggregate CPU and memory budget for a registered Function + /// refresh. `gpuCount` inside the budget defaults to zero. + pub resource_budget: Option, /// Positive aggregate GPU budget for Function workers. pub gpu_count: Option, /// `"fail"` (default) stops on a row error; `"skip"` writes null and @@ -1627,7 +1740,24 @@ impl TryFrom 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, + 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, + pub completed_at_millis: Option, + pub failure: Option, +} + +impl From 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, + pub active_job_id: Option, + pub state: String, + pub failure_streak: u32, + pub effective_cooldown_millis: Option, + pub blocked_reason: Option, + pub next_run_at_millis: Option, + pub next_run_at_reason: Option, +} + +/// 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, + pub last_failure_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +impl From 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 for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { Self { diff --git a/python/Cargo.toml b/python/Cargo.toml index 2574eae38..03c77d8c4 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -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" diff --git a/python/pyproject.toml b/python/pyproject.toml index 036acf075..5ba1d4bbf 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -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", diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 2208fd612..31285d100 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -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", diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 010c92009..2c545a17e 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -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, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index f2d5285fa..4029525e9 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -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: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index e73a44aec..73c8305ff 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -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, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index fe5a1a45a..6d0c2ff52 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -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, diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index 9f53f203b..f1626c540 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -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. diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 92b545ce7..094a7b8d5 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -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, *, diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 4a3fea2e2..bab40be95 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -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)) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 2cc6bf056..ebceba16b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -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 diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index a963ab55e..3f6bff45e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -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: diff --git a/python/python/lancedb/schema.py b/python/python/lancedb/schema.py index d92f7f692..5e36ffc86 100644 --- a/python/python/lancedb/schema.py +++ b/python/python/lancedb/schema.py @@ -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. diff --git a/python/python/lancedb/sql.py b/python/python/lancedb/sql.py index 7498cddcc..5da4d35dd 100644 --- a/python/python/lancedb/sql.py +++ b/python/python/lancedb/sql.py @@ -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()) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 06bace5b8..762f826c2 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -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 diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index ceb43522e..bb946c37c 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -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") diff --git a/python/python/tests/test_blob_query_without_pylance.py b/python/python/tests/test_blob_query_without_pylance.py index a5ce6db44..7c503d1ff 100644 --- a/python/python/tests/test_blob_query_without_pylance.py +++ b/python/python/tests/test_blob_query_without_pylance.py @@ -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 diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 27a9a9376..f8e225183 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -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 diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 53b0189f5..2cc731892 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -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(): diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 050aeb3ea..83dfdaeb3 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -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): diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 1b252f993..738a791ad 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -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 ( diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index c3189cbad..690f6414b 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -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") diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 40cfb9cdc..f49d98cb6 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -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", diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 671d0ff23..407596d26 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -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( diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index 0ed382d93..b4c555635 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -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( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 157870bb5..e3b69ced1 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -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): diff --git a/python/src/connection.rs b/python/src/connection.rs index bffa167d8..0be933cf2 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -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, namespace_path: Option>, ) -> PyResult> { 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() }) } diff --git a/python/src/index.rs b/python/src/index.rs index 3ec03b6fd..039440211 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -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>) -> PyResult 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::()?; let code_options = CodeAnalyzerOptions { @@ -291,7 +293,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult 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 ))), } diff --git a/python/src/job.rs b/python/src/job.rs index 79a9cd524..0d411072f 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -152,6 +152,13 @@ impl Job { self.inner.description().map(JobDescription::from) } + pub fn timeline(self_: PyRef<'_, Self>) -> PyResult> { + 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 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, message: Option, @@ -238,6 +245,18 @@ pub struct JobFailureInfo { sql_job_id: Option, } +impl From 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 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), } } } diff --git a/python/src/lib.rs b/python/src/lib.rs index 27ff4cb01..f78c4e7bb 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -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::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/python/src/sql.rs b/python/src/sql.rs index 612521207..166cf0df5 100644 --- a/python/src/sql.rs +++ b/python/src/sql.rs @@ -31,6 +31,11 @@ impl Query { self.inner.id() } + #[getter] + pub fn job_id(&self) -> Option { + self.inner.job_id() + } + pub fn describe(self_: PyRef<'_, Self>) -> PyResult> { 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, status: String, progress: Option, expires_at: Option>, @@ -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 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, diff --git a/python/src/table.rs b/python/src/table.rs index 23c5b69d7..c4211e44d 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -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, batch_size: Option, + max_concurrency: Option, publication_interval_rows: Option, + resource_budget: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -70,11 +75,97 @@ fn positive_count>(value: Option, name: &str) -> PyResult>, name: &str) -> PyResult> { + let Some(value) = value else { + return Ok(None); + }; + if value.is_none() || value.is_instance_of::() { + return Err(PyValueError::new_err(format!( + "{name} must be an integer between 1 and 4294967295" + ))); + } + let parsed = value.extract::().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 { + if value.is_none() || value.is_instance_of::() { + return Err(PyValueError::new_err(format!( + "resource_budget.{name} must be an integer" + ))); + } + let parsed = value + .extract::() + .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> { + let Some(budget) = budget else { + return Ok(None); + }; + for key in budget.keys() { + let key = key + .extract::() + .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 { 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 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, + pub object_id: String, + pub location: String, + pub version: String, + pub manifest_digest: String, +} + +impl From 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, + pub completed_at_millis: Option, + pub failure: Option, +} + +impl From 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, + pub active_job_id: Option, + pub state: String, + pub failure_streak: u32, + pub effective_cooldown_millis: Option, + pub blocked_reason: Option, + pub next_run_at_millis: Option, + pub next_run_at_reason: Option, +} + +impl From 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, + pub last_failure_job: Option, + 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 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, auto_refresh_interval_seconds: Option, - ) -> PyResult> { + auto_refresh_resource_budget: Option>, + ) -> PyResult> { 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, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, - ) -> PyResult> { + auto_refresh_resource_budget: Option>, + ) -> PyResult> { 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, batch_size: Option, + max_concurrency: Option>, publication_interval_rows: Option, + resource_budget: Option>, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2228,11 +2465,13 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, - ) -> PyResult> { + ) -> PyResult> { 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, batch_size: Option, + max_concurrency: Option>, publication_interval_rows: Option, + resource_budget: Option>, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2272,11 +2513,13 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, - ) -> PyResult> { + ) -> PyResult> { 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, + ) -> PyResult> { + 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::>()) + }) + } + + pub fn column_status(self_: PyRef<'_, Self>, column: String) -> PyResult> { + 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>, + ) -> PyResult> { + let timeout = timeout + .map(|timeout| timeout.extract::()) + .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( diff --git a/python/uv.lock b/python/uv.lock index a5ae1caf8..01693079f 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -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]] diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 96172787b..881130af3 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -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 } diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 051db741a..cde8b295a 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -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 diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index dec5e1359..a360818b5 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -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, @@ -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, + namespace_path: &[String], + ) -> Result { + 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. /// diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 44d038521..bcdfd94b8 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -552,6 +552,14 @@ pub trait Database: ) -> Result { 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 { + function_catalog_not_supported() + } /// Fetch one page of published immutable Function versions in one namespace. async fn list_functions( &self, diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 7499641fc..89ad7a229 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -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, /// A human-readable reason, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, /// User-code traceback, possibly truncated by the server. + #[serde(default, skip_serializing_if = "Option::is_none")] pub traceback: Option, /// Whether a retry could clear the failure, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub retryable: Option, /// 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, /// The underlying error from a job run in this process or a structured /// remote Flight SQL failure. + #[serde(skip)] pub source: Option>, } +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) -> 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 { + match self { + Self::Http { status_code, .. } => *status_code, + Self::Retry { status_code, .. } => *status_code, + Self::TableNotFound { source, .. } => { + source.downcast_ref::().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 diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 41a683c54..3566fc938 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -611,6 +611,13 @@ pub struct FunctionVersion { deserialize_with = "deserialize_batch_size" )] batch_size: Option, + /// 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, /// Per-call deadline in seconds. #[serde(default, skip_serializing_if = "Option::is_none")] row_timeout_seconds: Option, @@ -681,6 +688,11 @@ impl FunctionVersion { self.batch_size } + /// Default maximum concurrent user-code calls, when declared. + pub fn max_concurrency(&self) -> Option { + self.max_concurrency + } + /// Per-call deadline in seconds, when declared. pub fn row_timeout_seconds(&self) -> Option { 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, D::Error> +where + D: Deserializer<'de>, +{ + let value = Option::::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) -> 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) -> std::result::Result<(), &'st Ok(()) } +fn validate_max_concurrency_value(value: Option) -> 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) -> 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, + /// 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, /// 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] diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 8644c6a48..d178542b7 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -85,6 +85,11 @@ pub(crate) trait JobHandle: Send + Sync { async fn describe(&self) -> Result { job_detail_not_supported("describing a job") } + /// Chrome Trace Event JSON for a server-side Function job. + async fn timeline(&self) -> Result { + job_detail_not_supported("job timeline export") + } + /// The job's recorded lifecycle events. async fn events(&self, _request: JobEventsRequest) -> Result> { 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> { + /// let trace = job.timeline().await?; + /// std::fs::write("job.trace.json", trace.to_string())?; + /// # Ok(()) + /// # } + /// ``` + pub async fn timeline(&self) -> Result { + 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 `()`. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index c33c7267d..a9d55b511 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -887,7 +887,20 @@ impl Database for RemoteDatabase { 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 { + 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( diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 0c652a3ae..d27c9c666 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -235,6 +235,32 @@ impl JobHandle for RemoteJob { Ok(self.fetch_description().await?.1.into_description()) } + async fn timeline(&self) -> Result { + 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> { let mut body = serde_json::json!({ "job_id": self.job_id }); if let Some(limit) = request.limit { diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 724c813b3..0b87ff5a5 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -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, +} + +struct PollResult { + info: PollInfo, + job_id: Option, } 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> { + ) -> Result> { 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 { + ) -> Result { 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>, client: Arc, default_namespace_path: Vec, state: Mutex, @@ -713,6 +767,7 @@ impl RemoteQuery { client: Arc, default_namespace_path: Vec, poll_info: PollInfo, + job_id: Option, ) -> Result { 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 { + 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(&self, result: Result) -> Result { + if let Err(error) = &result { + self.observe_error_job_id(error)?; + } + result + } + async fn poll_next_state(&self, descriptor: FlightDescriptor) -> Result { 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) -> Result { @@ -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 { + self.query.job_id() + } + async fn describe(&self) -> Result { 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, poll_info: &PollInfo, lifecycle: QueryLifecycle, ) -> Result { 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 { + 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 { + 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>> { poll_info .expiration_time diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index e90792a8a..c2b5aba06 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -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 { 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, diff --git a/rust/lancedb/src/remote/sql/stream.rs b/rust/lancedb/src/remote/sql/stream.rs index 420eecd15..16155bf7c 100644 --- a/rust/lancedb/src/remote/sql/stream.rs +++ b/rust/lancedb/src/remote/sql/stream.rs @@ -55,6 +55,7 @@ pub(super) struct StreamingQuery { cancelled: Notify, terminal_at: OnceLock, last_accessed: StdMutex, + job_id: StdMutex>, } 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, } 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, response: ResultEndpointStream, + job_id: Option, ) -> 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 { + 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 { + self.query.job_id() + } + async fn describe(&self) -> Result { 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<()> { diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 65d08c984..efc2ba6a4 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -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::>().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(); } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index a69611306..3859cb830 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -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 crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::describe(&self.inner).await } + async fn timeline(&self) -> Result { + crate::job::JobHandle::timeline(&self.inner).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -369,6 +374,10 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::describe(&self.inner).await } + async fn timeline(&self) -> Result { + crate::job::JobHandle::timeline(&self.inner).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -3951,6 +3960,9 @@ impl BaseTable for RemoteTable { 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 BaseTable for RemoteTable { }) } + async fn function_column_statuses( + &self, + column: Option<&str>, + ) -> Result> { + 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 = + 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 { 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, + #[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 { 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![( + 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::(), 1); + assert_eq!(job.timeline().await.unwrap()["metadata"]["partial"], true); } /// A newly submitted refresh returns a freshness-wrapped handle. Waiting diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index 5c01fe898..bda5df085 100644 --- a/rust/lancedb/src/sql.rs +++ b/rust/lancedb/src/sql.rs @@ -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, /// 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 { + None + } async fn describe(&self) -> Result; async fn reader(&self) -> Result; 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, } @@ -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 { + 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 } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 80b6bd7ad..18a5b7ddf 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -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> { + 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; /// 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> { + 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 { + 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, + ) -> Result { + 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 diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 1b827bb37..a76c0d043 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -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; diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index e6d7d432c..d09a790a3 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -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, + /// 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, } 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 { 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::>(); @@ -145,7 +167,7 @@ impl ComputedColumnOptions { } /// Field metadata values shared by native and server declaration paths. - pub fn metadata(&self) -> HashMap { + pub fn metadata(&self) -> Result> { 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. diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 021abe5a9..477020fc3 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -21,14 +21,16 @@ //! removed by [`prune_sidecars`]. use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt; use std::io::{Cursor, Read}; use std::ops::Range; use arrow_array::{Array, UInt64Array}; +use arrow_schema::{DataType, Schema as ArrowSchema}; use futures::TryStreamExt; use lance::Dataset; use lance::dataset::refs::Ref; -use lance::dataset::transaction::Operation; +use lance::dataset::transaction::{Operation, UpdateMode}; use lance_core::ROW_ADDR; use lance_core::datatypes::{Field as LanceField, Schema as LanceSchema}; use lance_io::object_store::{ObjectStore, uri_to_url}; @@ -40,7 +42,8 @@ use sha2::{Digest, Sha256}; use uuid::Uuid; use crate::table::computed_columns::{ - DEFINITION_VERSION_META_KEY, RECORDED_AT_VERSION_META_KEY, SOURCE_SIGNATURE_META_KEY, + DEFINITION_VERSION_META_KEY, FUNCTION_BINDINGS_META_KEY, PENDING_FILL_SIGNATURE_META_KEY, + RECORDED_AT_VERSION_META_KEY, SOURCE_SIGNATURE_META_KEY, field_root, function_bindings, }; use crate::{Error, Result}; @@ -96,6 +99,56 @@ impl DirtyRows { /// `{fragment id -> row-level dirty state}`. A missing fragment is clean. pub type RowStateMap = BTreeMap; +/// Physical rows whose latest Function outcome is an unresolved failure. +pub type FailureRows = BTreeMap; + +/// Evidence for rows whose latest Function outcome is known. +/// +/// `known_rows` includes both successful and failed observations. +/// `failed_rows` is the failure subset. A missing row is unknown, not clean. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FailureEvidence { + pub known_rows: FailureRows, + pub failed_rows: FailureRows, +} + +impl FailureEvidence { + fn is_empty(&self) -> bool { + self.known_rows.is_empty() && self.failed_rows.is_empty() + } + + fn validate(&self) -> Result<()> { + if self.failed_rows.iter().any(|(fragment_id, failed)| { + !self + .known_rows + .get(fragment_id) + .is_some_and(|known| failed.is_subset(known)) + }) { + return Err(invalid( + "failed rows are not covered by the failure evidence update".to_string(), + )); + } + Ok(()) + } + + fn for_fragments(&self, fragments: &HashSet) -> Self { + Self { + known_rows: self + .known_rows + .iter() + .filter(|(fragment_id, _)| fragments.contains(fragment_id)) + .map(|(fragment_id, rows)| (*fragment_id, rows.clone())) + .collect(), + failed_rows: self + .failed_rows + .iter() + .filter(|(fragment_id, _)| fragments.contains(fragment_id)) + .map(|(fragment_id, rows)| (*fragment_id, rows.clone())) + .collect(), + } + } +} + /// The single owning value of the freshness sidecar. /// /// `SignatureMap` remains the public facade for callers that only need input @@ -105,6 +158,13 @@ pub type RowStateMap = BTreeMap; struct FreshnessState { signatures: SignatureMap, row_state: RowStateMap, + /// Physical offsets with an exact current-generation outcome. + failure_coverage: FailureRows, + /// The failed subset of `failure_coverage`. + failed_rows: FailureRows, + /// Whether the decoded source used the v3 sidecar format that carries + /// failure evidence. Older formats leave failure rows unclassified. + failure_evidence_recorded: bool, basis: String, // A fresh identity for each begin, even when the basis and dirty rows repeat. intent_id: Uuid, @@ -113,6 +173,8 @@ struct FreshnessState { impl FreshnessState { fn normalize(mut self) -> Result { self.row_state.retain(|_, rows| !rows.is_explicitly_empty()); + self.failure_coverage.retain(|_, rows| !rows.is_empty()); + self.failed_rows.retain(|_, rows| !rows.is_empty()); if self .row_state .keys() @@ -122,6 +184,26 @@ impl FreshnessState { "row state names a fragment without a signature".to_string(), )); } + if self + .failure_coverage + .keys() + .chain(self.failed_rows.keys()) + .any(|fragment_id| !self.signatures.contains_key(fragment_id)) + { + return Err(invalid( + "failure evidence names a fragment without a signature".to_string(), + )); + } + if self.failed_rows.iter().any(|(fragment_id, failed)| { + !self + .failure_coverage + .get(fragment_id) + .is_some_and(|covered| failed.is_subset(covered)) + }) { + return Err(invalid( + "failed rows are not covered by failure evidence".to_string(), + )); + } if self .signatures .values() @@ -136,6 +218,38 @@ impl FreshnessState { } Ok(self) } + + fn invalidate_failure_evidence(&mut self, fragments: impl IntoIterator) { + for fragment_id in fragments { + self.failure_coverage.remove(&fragment_id); + self.failed_rows.remove(&fragment_id); + } + } + + fn invalidate_failure_rows(&mut self, rows: &BTreeMap) { + for (fragment_id, rows) in rows { + if let Some(covered) = self.failure_coverage.get_mut(fragment_id) { + *covered -= rows; + } + if self + .failure_coverage + .get(fragment_id) + .is_some_and(RoaringBitmap::is_empty) + { + self.failure_coverage.remove(fragment_id); + } + if let Some(failed) = self.failed_rows.get_mut(fragment_id) { + *failed -= rows; + } + if self + .failed_rows + .get(fragment_id) + .is_some_and(RoaringBitmap::is_empty) + { + self.failed_rows.remove(fragment_id); + } + } + } } /// Opaque accepted-basis evidence returned by [`begin_row_repair`] and required by @@ -396,7 +510,8 @@ const SIDECAR_DIR: &str = "_computed"; const SIDECAR_REF: &str = "sidecar:"; const SIDECAR_MAGIC: &[u8; 4] = b"CSIG"; const SIDECAR_FORMAT_V1: u8 = 1; -const SIDECAR_FORMAT: u8 = 2; +const SIDECAR_FORMAT_V2: u8 = 2; +const SIDECAR_FORMAT: u8 = 3; /// How long an unreferenced sidecar is presumed to be a stamp in flight: /// lance's own threshold for unverified files, independent of how much /// version history a cleanup keeps. @@ -444,9 +559,85 @@ fn encode_legacy_sidecar(map: &SignatureMap) -> Result> { Ok(bytes) } +#[cfg(test)] +fn encode_v2_sidecar(state: &FreshnessState) -> Result> { + let state = state.clone().normalize()?; + let basis_len = u16::try_from(state.basis.len()) + .map_err(|_| invalid("freshness basis exceeds u16 bytes".to_string()))?; + let fragment_count = u32::try_from(state.signatures.len()) + .map_err(|_| invalid("too many fragments for a freshness sidecar".to_string()))?; + let mut bytes = Vec::new(); + bytes.extend_from_slice(SIDECAR_MAGIC); + bytes.push(SIDECAR_FORMAT_V2); + bytes.extend_from_slice(state.intent_id.as_bytes()); + bytes.extend_from_slice(&basis_len.to_le_bytes()); + bytes.extend_from_slice(state.basis.as_bytes()); + bytes.extend_from_slice(&fragment_count.to_le_bytes()); + for (fragment_id, signature) in &state.signatures { + let hash = u64::from_str_radix(signature, 16).map_err(|_| { + invalid(format!( + "signature '{signature}' is not a 64-bit hex digest" + )) + })?; + let rows = state + .row_state + .get(fragment_id) + .cloned() + .unwrap_or_else(|| DirtyRows::Rows(RoaringBitmap::new())); + let (kind, bitmap) = match rows { + DirtyRows::Rows(bitmap) => (0u8, bitmap), + DirtyRows::AllExcept(clean) => (1u8, clean), + }; + bytes.extend_from_slice(&fragment_id.to_le_bytes()); + bytes.extend_from_slice(&hash.to_le_bytes()); + bytes.push(kind); + encode_bitmap(&mut bytes, Some(&bitmap))?; + } + Ok(bytes) +} + +fn encode_bitmap(bytes: &mut Vec, bitmap: Option<&RoaringBitmap>) -> Result<()> { + let Some(bitmap) = bitmap.filter(|bitmap| !bitmap.is_empty()) else { + bytes.extend_from_slice(&0u32.to_le_bytes()); + return Ok(()); + }; + let mut encoded = Vec::with_capacity(bitmap.serialized_size()); + bitmap + .serialize_into(&mut encoded) + .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; + let bitmap_len = u32::try_from(encoded.len()) + .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; + bytes.extend_from_slice(&bitmap_len.to_le_bytes()); + bytes.extend_from_slice(&encoded); + Ok(()) +} + +fn decode_bitmap( + cursor: &mut Cursor<&[u8]>, + malformed: &impl Fn() -> Error, +) -> Result> { + let mut bitmap_len = [0u8; 4]; + cursor + .read_exact(&mut bitmap_len) + .map_err(|_| malformed())?; + let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; + if bitmap_len == 0 { + return Ok(None); + } + let mut encoded = vec![0u8; bitmap_len]; + cursor.read_exact(&mut encoded).map_err(|_| malformed())?; + let mut bitmap_reader = Cursor::new(encoded.as_slice()); + let bitmap = RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; + if bitmap_reader.position() != bitmap_len as u64 { + return Err(malformed()); + } + Ok(Some(bitmap)) +} + /// `CSIG`, format byte, 16-byte intent UUID, basis, entry count, then for each fragment its id, -/// 8-byte signature, dirty-row mode and serialized bitmap. All integers are -/// little-endian. Format 1 remains readable as clean row state. +/// 8-byte signature, dirty-row mode and serialized bitmap. Format 3 appends +/// failure-coverage and failed-row bitmaps. All integers are little-endian. +/// Format 1 remains readable as clean row state. fn encode_sidecar(state: &FreshnessState) -> Result> { let state = state.clone().normalize()?; let basis_len = u16::try_from(state.basis.len()) @@ -475,17 +666,12 @@ fn encode_sidecar(state: &FreshnessState) -> Result> { DirtyRows::Rows(bitmap) => (0u8, bitmap), DirtyRows::AllExcept(clean) => (1u8, clean), }; - let mut encoded = Vec::with_capacity(bitmap.serialized_size()); - bitmap - .serialize_into(&mut encoded) - .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; - let bitmap_len = u32::try_from(encoded.len()) - .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; bytes.extend_from_slice(&fragment_id.to_le_bytes()); bytes.extend_from_slice(&hash.to_le_bytes()); bytes.push(kind); - bytes.extend_from_slice(&bitmap_len.to_le_bytes()); - bytes.extend_from_slice(&encoded); + encode_bitmap(&mut bytes, Some(&bitmap))?; + encode_bitmap(&mut bytes, state.failure_coverage.get(fragment_id))?; + encode_bitmap(&mut bytes, state.failed_rows.get(fragment_id))?; } Ok(bytes) } @@ -524,7 +710,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { cursor.read_exact(&mut magic).map_err(|_| malformed())?; let mut format = [0u8; 1]; cursor.read_exact(&mut format).map_err(|_| malformed())?; - if &magic != SIDECAR_MAGIC || format[0] != SIDECAR_FORMAT { + if &magic != SIDECAR_MAGIC || !matches!(format[0], SIDECAR_FORMAT_V2 | SIDECAR_FORMAT) { return Err(malformed()); } let mut intent_id = [0u8; 16]; @@ -540,6 +726,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { let mut state = FreshnessState { basis, intent_id: Uuid::from_bytes(intent_id), + failure_evidence_recorded: format[0] == SIDECAR_FORMAT, ..Default::default() }; for _ in 0..count { @@ -552,19 +739,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { cursor.read_exact(&mut signature).map_err(|_| malformed())?; let mut kind = [0u8; 1]; cursor.read_exact(&mut kind).map_err(|_| malformed())?; - let mut bitmap_len = [0u8; 4]; - cursor - .read_exact(&mut bitmap_len) - .map_err(|_| malformed())?; - let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; - let mut encoded = vec![0u8; bitmap_len]; - cursor.read_exact(&mut encoded).map_err(|_| malformed())?; - let mut bitmap_reader = Cursor::new(encoded.as_slice()); - let bitmap = - RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; - if bitmap_reader.position() != bitmap_len as u64 { - return Err(malformed()); - } + let bitmap = decode_bitmap(&mut cursor, &malformed)?.unwrap_or_default(); let dirty = match kind[0] { 0 => DirtyRows::Rows(bitmap), 1 => DirtyRows::AllExcept(bitmap), @@ -580,6 +755,14 @@ fn decode_sidecar(bytes: &[u8]) -> Result { if !dirty.is_explicitly_empty() { state.row_state.insert(fragment_id, dirty); } + if format[0] == SIDECAR_FORMAT { + if let Some(covered) = decode_bitmap(&mut cursor, &malformed)? { + state.failure_coverage.insert(fragment_id, covered); + } + if let Some(failed) = decode_bitmap(&mut cursor, &malformed)? { + state.failed_rows.insert(fragment_id, failed); + } + } } if cursor.position() != bytes.len() as u64 { return Err(malformed()); @@ -738,12 +921,14 @@ async fn referenced_digests(dataset: &Dataset, into: &mut HashSet) -> Re for version in dataset.versions().await? { let at = dataset.checkout_version(version.version).await?; for field in at.schema().fields_pre_order() { - if let Some(digest) = field - .metadata - .get(SOURCE_SIGNATURE_META_KEY) - .and_then(|value| value.strip_prefix(SIDECAR_REF)) - { - into.insert(digest.to_string()); + for key in [SOURCE_SIGNATURE_META_KEY, PENDING_FILL_SIGNATURE_META_KEY] { + if let Some(digest) = field + .metadata + .get(key) + .and_then(|value| value.strip_prefix(SIDECAR_REF)) + { + into.insert(digest.to_string()); + } } } } @@ -759,12 +944,15 @@ enum StoredFreshnessState { Unreadable, } -async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { +async fn load_freshness_state( + dataset: &Dataset, + column: &str, +) -> Result)>> { let Some(encoded) = field_meta(dataset, column, SOURCE_SIGNATURE_META_KEY) else { - return StoredFreshnessState::Absent; + return Ok(None); }; // Inline JSON is the declaration's empty seed and the pre-sidecar form. - let (read, digest) = match encoded.strip_prefix(SIDECAR_REF) { + let read = match encoded.strip_prefix(SIDECAR_REF) { Some(digest) => ( read_sidecar(dataset, digest).await, Some(digest.to_string()), @@ -779,8 +967,14 @@ async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshn None, ), }; - match read { - Ok(state) => StoredFreshnessState::Present { state, digest }, + let (state, digest) = read; + Ok(Some((state?, digest))) +} + +async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { + match load_freshness_state(dataset, column).await { + Ok(Some((state, digest))) => StoredFreshnessState::Present { state, digest }, + Ok(None) => StoredFreshnessState::Absent, Err(error) => { log::warn!( "computed column '{column}' freshness state is unreadable ({error}); every fragment will be recomputed" @@ -820,6 +1014,10 @@ pub struct StalenessPlan { pub dirty: HashSet, /// Current-signature fragments with only some rows dirty. pub row_dirty: RowStateMap, + /// Retained values are current, but unassigned inserted rows need filling. + /// These signatures become completed stamps only after a full null-fill. + #[serde(default)] + pub pending_fill: SignatureMap, /// Fragments a compaction produced from fresh ones, at their current /// signature: not dirty, and for the seal to record. pub inherited: SignatureMap, @@ -845,6 +1043,38 @@ impl StalenessPlan { } } +/// Strict, internally consistent evidence for a Function-column status read. +/// +/// Unlike [`staleness_against`], this value never converts an unreadable +/// sidecar into a conservative recompute plan. Failure coverage may be +/// partial: the caller combines it with live-row freshness and value evidence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StrictFreshness { + /// No freshness certificate is recorded on this dataset version. + /// + /// This does not prove that no refresh was ever attempted; older failed + /// attempts may be untracked. Assignment and value evidence still decide + /// stale versus never computed. + Absent, + /// The sidecar predates failure evidence. Its staleness plan is still + /// usable; row classification may use freshness, values, and assignment + /// evidence outside this sidecar. + Uncertified { staleness: StalenessPlan }, + /// Exact staleness and current-generation failed rows. + Certified { + staleness: StalenessPlan, + failures: FailureEvidence, + }, +} + +fn incomplete_certificate(column: &str, reason: impl fmt::Display) -> Error { + Error::Runtime { + message: format!( + "computed column '{column}' has no complete freshness certificate: {reason}" + ), + } +} + /// A version of the log since the stamp that bears on carrying freshness /// forward: an append, whose fragments hold no computed value yet, or a /// compaction's rewrite groups, consumed and produced fragment ids. @@ -1150,6 +1380,16 @@ pub async fn staleness_against( } StoredFreshnessState::Present { state: stored, .. } => stored, }; + staleness_from_state(dataset, column, definition_version, inputs, stored).await +} + +async fn staleness_from_state( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + stored: FreshnessState, +) -> Result { let stored_version = field_meta(dataset, column, DEFINITION_VERSION_META_KEY); if stored_version.is_some_and(|version| version != definition_version) { return Ok(StalenessPlan { @@ -1174,13 +1414,29 @@ pub async fn staleness_against( let mut inherited = carried.inherited; let mut dirty = carried.dirty_products; let mut row_dirty = RowStateMap::new(); + let pending = match field_meta(dataset, column, PENDING_FILL_SIGNATURE_META_KEY) { + Some(reference) if unrecorded => { + let state = match reference.strip_prefix(SIDECAR_REF) { + Some(digest) => read_sidecar(dataset, digest).await.ok(), + None => None, + }; + state + .filter(|state| state.row_state.is_empty() && state.basis.is_empty()) + .map(|state| state.signatures) + .unwrap_or_default() + } + _ => SignatureMap::new(), + }; + let mut pending_fill = SignatureMap::new(); let mut live = HashSet::new(); let bases = Bases::of(dataset)?; for fragment in dataset.get_fragments() { let id = fragment.id() as u32; live.insert(id); let current = fragment_input_signature(&bases, fragment.metadata(), inputs)?; - if stored.get(&id).or_else(|| inherited.get(&id)) != Some(¤t) { + if !stored.contains_key(&id) && !dirty.contains(&id) && pending.get(&id) == Some(¤t) { + pending_fill.insert(id, current); + } else if stored.get(&id).or_else(|| inherited.get(&id)) != Some(¤t) { dirty.insert(id); } else if let Some(rows) = row_state.get(&id) { row_dirty.insert(id, rows.clone()); @@ -1192,10 +1448,76 @@ pub async fn staleness_against( recompute_all: false, dirty, row_dirty, + pending_fill, inherited, }) } +/// Read exact status evidence without the planner's conservative fallback. +/// +/// A missing metadata key returns [`StrictFreshness::Absent`]. A referenced +/// sidecar that cannot be read or decoded propagates the existing error. The +/// returned plan is certified when the sidecar records a definition and can be +/// decoded. Failure coverage is returned only for live fragments whose stored +/// input signature still matches; stale evidence is omitted. The status +/// provider remains responsible for classifying uncovered live rows as fresh, +/// stale, or never computed, and for reporting an error only when a row is +/// genuinely ambiguous. +pub async fn strict_freshness_against( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, +) -> Result { + let Some((stored, _)) = load_freshness_state(dataset, column).await? else { + return Ok(StrictFreshness::Absent); + }; + let Some(stored_definition) = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) else { + return Err(incomplete_certificate( + column, + "the recorded definition is missing", + )); + }; + let staleness = + staleness_from_state(dataset, column, definition_version, inputs, stored.clone()).await?; + if !stored.failure_evidence_recorded { + return Ok(StrictFreshness::Uncertified { staleness }); + } + if stored_definition != definition_version { + return Ok(StrictFreshness::Certified { + staleness, + failures: FailureEvidence::default(), + }); + } + let mut failures = FailureEvidence::default(); + for fragment in dataset.get_fragments() { + let fragment_id = fragment.id() as u32; + let current = signature_of(dataset, fragment_id, inputs)?.ok_or_else(|| { + incomplete_certificate(column, format!("fragment {fragment_id} is not live")) + })?; + if stored.signatures.get(&fragment_id) != Some(¤t) { + // The old generation's failure evidence no longer describes this + // fragment. Its live rows are stale or never computed, not + // ambiguously failed. + continue; + } + if let Some(covered) = stored.failure_coverage.get(&fragment_id) + && !covered.is_empty() + { + failures.known_rows.insert(fragment_id, covered.clone()); + } + if let Some(failed) = stored.failed_rows.get(&fragment_id) + && !failed.is_empty() + { + failures.failed_rows.insert(fragment_id, failed.clone()); + } + } + Ok(StrictFreshness::Certified { + staleness, + failures, + }) +} + /// What [`record_freshness`] wrote: the table version the stamp landed at, /// if it wrote one, and the entries recorded and dropped for having moved. #[derive(Debug, Default, PartialEq, Eq)] @@ -1226,6 +1548,55 @@ pub async fn record_freshness( definition_version: &str, inputs: &InputFields, computed: SignatureMap, +) -> Result { + record_freshness_impl( + latest, + pinned, + column, + definition_version, + inputs, + computed, + None, + ) + .await +} + +/// Record signatures and an explicit current-generation failure outcome in one +/// immutable sidecar transition. +/// +/// `failures.known_rows` must include only physical offsets whose final +/// outcome is known. `failures.failed_rows` is the failed subset. Rows omitted +/// from coverage remain unknown to failure classification; freshness, values, +/// and assignment evidence may still classify them. +pub async fn record_freshness_with_failures( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, + failures: &FailureEvidence, +) -> Result { + record_freshness_impl( + latest, + pinned, + column, + definition_version, + inputs, + computed, + Some(failures), + ) + .await +} + +async fn record_freshness_impl( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, + failures: Option<&FailureEvidence>, ) -> Result { let absent = matches!( stored_signatures(latest, column).await, @@ -1245,7 +1616,7 @@ pub async fn record_freshness( } } entries.extend(computed); - if entries.is_empty() && !absent { + if entries.is_empty() && !absent && failures.is_none_or(FailureEvidence::is_empty) { return Ok(FreshnessRecord::default()); } let fragments: Vec = entries.keys().copied().collect(); @@ -1255,7 +1626,19 @@ pub async fn record_freshness( .filter(|(fragment_id, signature)| current.get(fragment_id) == Some(signature)) .collect(); let recorded = verified.len(); - let version = write_signatures(latest, column, definition_version, verified).await?; + let verified_fragments: HashSet = verified.keys().copied().collect(); + let scoped_failures = failures + .map(|failures| failures.for_fragments(&verified_fragments)) + .filter(|failures| !failures.is_empty()); + let version = write_signatures_impl( + latest, + column, + definition_version, + Some(inputs), + verified, + scoped_failures.as_ref(), + ) + .await?; Ok(FreshnessRecord { version: Some(version), recorded, @@ -1263,18 +1646,321 @@ pub async fn record_freshness( }) } +/// The source of a just-committed write whose retained Function values may +/// still be fresh. The fields must describe the actual write, including its +/// join keys; they must not be inferred from a later table snapshot. +pub enum FunctionWrite<'a> { + /// Assignments executed by Lance's update builder. + Update { columns: &'a [String] }, + /// The source schema and join columns executed by Lance's merge builder. + Merge { + source_schema: &'a ArrowSchema, + on: &'a [String], + /// The insertion count from the same committed merge result. + num_inserted_rows: u64, + }, +} + +impl FunctionWrite<'_> { + fn writes_root(&self, root: &str) -> Result { + match self { + Self::Update { columns } => columns.iter().try_fold(false, |found, column| { + Ok(found || field_root(column)? == root) + }), + Self::Merge { source_schema, .. } => Ok(source_schema.field_with_name(root).is_ok()), + } + } + + fn preserves_input(&self, path: &str, schema: &ArrowSchema) -> Result { + let parts = lance_core::datatypes::parse_field_path(path)?; + let root = field_root(path)?; + if !self.writes_root(&root)? { + return Ok(true); + } + let Self::Merge { + source_schema, on, .. + } = self + else { + return Ok(false); + }; + if parts.len() != 1 || !on.contains(&root) { + return Ok(false); + } + let target = schema.field_with_name(&root)?; + let source = source_schema.field_with_name(&root)?; + // Join equality must preserve the Function's exact input. In particular, + // floating-point joins can equate different signed zeros or NaN payloads. + // Extension types can also define equality over a decoded representation. + Ok(source.data_type() == target.data_type() + && !source + .metadata() + .contains_key(lance_arrow::ARROW_EXT_NAME_KEY) + && !target + .metadata() + .contains_key(lance_arrow::ARROW_EXT_NAME_KEY) + && matches!( + target.data_type(), + DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Binary + | DataType::LargeBinary + | DataType::FixedSizeBinary(_) + )) + } +} + +/// Preserve Function freshness after an input-preserving update or merge. +/// +/// Call this on the exact dataset returned by the write, before any subsequent +/// operation. `write` must describe that write's real assignments or source. +/// The successful transaction's read version supplies the source freshness, +/// including when the write retried. Only fresh source fragments are carried; +/// partial repairs and unknown input equality remain stale. Inserted rows keep +/// NULL outputs and carry a pending-fill signature instead of a completed stamp. +/// +/// All siblings are stamped in one version-fenced metadata commit. Failure is +/// an optimization miss: callers must retain the successful data-write result, +/// rather than report a failed write that a client might repeat. +/// +/// ``` +/// use lance::Dataset; +/// use lancedb::table::freshness::{FunctionWrite, preserve_function_freshness}; +/// # async fn after_label_update(dataset: &mut Dataset) { +/// let columns = vec!["label".to_string()]; +/// if let Err(error) = preserve_function_freshness( +/// dataset, FunctionWrite::Update { columns: &columns }, +/// ).await { +/// log::warn!("freshness preservation skipped: {error}"); +/// } +/// # } +/// ``` +pub async fn preserve_function_freshness( + dataset: &mut Dataset, + write: FunctionWrite<'_>, +) -> Result<()> { + let schema = ArrowSchema::from(dataset.schema()); + let bindings = function_bindings(&schema)?; + if bindings.is_empty() { + return Ok(()); + } + let committed_version = dataset.version().version; + let Some(transaction) = dataset + .read_transaction_by_version(committed_version) + .await? + else { + return Ok(()); + }; + let Operation::Update { + removed_fragment_ids, + updated_fragments, + new_fragments, + update_mode: Some(UpdateMode::RewriteRows), + .. + } = &transaction.operation + else { + return Ok(()); + }; + if new_fragments.is_empty() { + return Ok(()); + } + let before = dataset.checkout_version(transaction.read_version).await?; + if before.schema().metadata.get(FUNCTION_BINDINGS_META_KEY) + != dataset.schema().metadata.get(FUNCTION_BINDINGS_META_KEY) + { + return Ok(()); + } + let before_schema = ArrowSchema::from(before.schema()); + let sources = removed_fragment_ids + .iter() + .copied() + .chain(updated_fragments.iter().map(|fragment| fragment.id)) + .collect::>(); + // Commit assigns fragment IDs. Match only this transaction's files, not + // unrelated appends that may have committed while it was being written. + let live_fragments = dataset.get_fragments(); + let produced = new_fragments + .iter() + .map(|fragment| { + live_fragments + .iter() + .find(|live| live.metadata().files == fragment.files) + .map(|live| live.id() as u32) + .ok_or_else(|| { + invalid("written Function fragment is missing from its commit".into()) + }) + }) + .collect::>>()?; + let live = live_fragments + .iter() + .map(|fragment| fragment.id() as u32) + .collect::>(); + let mut pending = Vec::new(); + for binding in bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let mut preserved = true; + for path in &paths { + preserved &= write.preserves_input(path, &before_schema)?; + } + // Even a join-key output can supply a non-NULL value to an insert. + // Those values were not computed under this binding. + for name in binding + .outputs() + .iter() + .map(|output| output.output_name.as_str()) + .chain( + binding + .assignment() + .map(|assignment| assignment.output_name.as_str()), + ) + { + preserved &= !write.writes_root(name)?; + } + if !preserved { + continue; + } + let old_inputs = fields_for_paths(before.schema(), &paths)?; + let new_inputs = fields_for_paths(dataset.schema(), &paths)?; + for output in binding.outputs() { + let column = &output.output_name; + let (Some(old_field), Some(new_field)) = ( + before.schema().field(column), + dataset.schema().field(column), + ) else { + continue; + }; + if old_field.metadata != new_field.metadata { + continue; + } + let StoredFreshnessState::Present { mut state, .. } = + stored_freshness_state(&before, column).await + else { + continue; + }; + let stale = + staleness_against(&before, column, binding.binding_id(), &old_inputs).await?; + if stale.recompute_all + || sources.iter().any(|id| { + before.get_fragment(*id as usize).is_none() || stale.needs_recompute(*id as u32) + }) + { + continue; + } + // Advancing recorded_at must also carry unrelated compactions + // already proven fresh at the write's source version. + for (id, signature) in stale.inherited { + if signature_of(dataset, id, &new_inputs)?.as_ref() == Some(&signature) { + state.signatures.insert(id, signature); + } + } + let needs_fill = matches!(write, FunctionWrite::Merge { num_inserted_rows, .. } if num_inserted_rows > 0) + || sources + .iter() + .any(|id| stale.pending_fill.contains_key(&(*id as u32))); + let mut pending_fill = stale.pending_fill; + let produced_signatures = signatures_for(dataset, &produced, &new_inputs)?; + if needs_fill { + pending_fill.extend(produced_signatures); + } else { + state.signatures.extend(produced_signatures); + } + pending_fill.retain(|id, _| live.contains(id)); + state.signatures.retain(|id, _| live.contains(id)); + state.row_state.retain(|id, _| live.contains(id)); + state.basis.clear(); + let reference = write_sidecar(dataset, &state.normalize()?).await?; + let fill_reference = if pending_fill.is_empty() { + None + } else { + Some( + write_sidecar( + dataset, + &FreshnessState { + signatures: pending_fill, + ..Default::default() + }, + ) + .await?, + ) + }; + pending.push(( + column.clone(), + binding.binding_id().to_string(), + reference, + fill_reference, + )); + } + } + if pending.is_empty() { + return Ok(()); + } + let mut metadata = dataset.update_field_metadata(); + for (column, definition, reference, fill_reference) in pending { + metadata = metadata.update( + &column, + [ + (SOURCE_SIGNATURE_META_KEY.to_string(), Some(reference)), + (PENDING_FILL_SIGNATURE_META_KEY.to_string(), fill_reference), + (DEFINITION_VERSION_META_KEY.to_string(), Some(definition)), + ( + RECORDED_AT_VERSION_META_KEY.to_string(), + Some(committed_version.to_string()), + ), + ], + )?; + } + metadata + .with_expected_latest_version(committed_version) + .await?; + Ok(()) +} + /// Merge `entries` into the column's stored map and stamp the definition and /// the version the map now describes. Merges rather than replaces: the /// entries cover only the fragments this refresh wrote, and every fragment it /// skipped keeps the entry an earlier one left. Entries for fragments no /// longer in the manifest are dropped, so compaction cannot grow the map -/// without bound. Returns the version the stamp landed at. +/// without bound. When the definition changes, only the newly computed entries +/// are trusted. Returns the version the stamp landed at. pub async fn write_signatures( dataset: &mut Dataset, column: &str, definition_version: &str, entries: SignatureMap, ) -> Result { + write_signatures_impl(dataset, column, definition_version, None, entries, None).await +} + +async fn write_signatures_impl( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: Option<&InputFields>, + entries: SignatureMap, + failures: Option<&FailureEvidence>, +) -> Result { + if let Some(failures) = failures { + failures.validate()?; + if inputs.is_none() { + return Err(invalid( + "failure evidence requires input fields for signature validation".to_string(), + )); + } + } + let definition_changed = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) + .is_some_and(|version| version != definition_version); let live: HashSet = dataset .get_fragments() .iter() @@ -1291,6 +1977,9 @@ pub async fn write_signatures( FreshnessState::default() } }; + if definition_changed { + state = FreshnessState::default(); + } let recomputed: HashSet = entries.keys().copied().collect(); let signatures_changed = entries .iter() @@ -1307,17 +1996,40 @@ pub async fn write_signatures( } // A signature entry written through this API means the fragment was // recomputed in full. Whole callers keep their old semantics while - // clearing any partial retry state left by a previous publication. + // clearing any partial retry state left by a previous publication. The + // old failure outcome is also unknown unless the failure-aware wrapper + // supplies it below. for fragment_id in &recomputed { state.row_state.remove(fragment_id); } - state.signatures.extend(entries); + state.invalidate_failure_evidence(recomputed.iter().copied()); + state.signatures.extend( + entries + .iter() + .map(|(fragment_id, signature)| (*fragment_id, signature.clone())), + ); state .signatures .retain(|fragment_id, _| live.contains(fragment_id)); state .row_state .retain(|fragment_id, _| live.contains(fragment_id)); + state + .failure_coverage + .retain(|fragment_id, _| live.contains(fragment_id)); + state + .failed_rows + .retain(|fragment_id, _| live.contains(fragment_id)); + if let Some(failures) = failures { + apply_failure_evidence( + dataset, + inputs.expect("failure evidence requires input fields"), + &entries, + &mut state, + failures, + ) + .await?; + } if state.row_state.is_empty() || state_unreadable || signatures_changed { state.basis.clear(); } @@ -1333,6 +2045,70 @@ struct FreshnessWrite { intent_digest: Option, } +async fn apply_failure_evidence( + dataset: &Dataset, + inputs: &InputFields, + accepted: &SignatureMap, + state: &mut FreshnessState, + update: &FailureEvidence, +) -> Result<()> { + update.validate()?; + let physical_rows: BTreeMap = { + let mut rows = BTreeMap::new(); + for fragment in dataset.get_fragments() { + rows.insert(fragment.id() as u32, fragment.physical_rows().await? as u64); + } + rows + }; + let mut applied = HashSet::new(); + for (fragment_id, covered) in &update.known_rows { + let Some(rows) = physical_rows.get(fragment_id) else { + continue; + }; + let Some(current) = signature_of(dataset, *fragment_id, inputs)? else { + continue; + }; + // Evidence belongs to the attempt that produced this accepted + // signature. A concurrent attempt may have stamped a newer signature + // into `state`; that does not make this attempt's rows valid for it. + if accepted.get(fragment_id) != Some(¤t) { + continue; + } + if state.signatures.get(fragment_id) != Some(¤t) { + continue; + } + if covered + .max() + .is_some_and(|offset| u64::from(offset) >= *rows) + { + return Err(invalid(format!( + "failure evidence for fragment {fragment_id} exceeds its {rows} physical rows" + ))); + } + if let Some(failed) = state.failed_rows.get_mut(fragment_id) { + *failed -= covered; + } + let coverage = state.failure_coverage.entry(*fragment_id).or_default(); + *coverage |= covered; + applied.insert(*fragment_id); + } + for (fragment_id, failed) in &update.failed_rows { + if !applied.contains(fragment_id) { + continue; + } + if !update.known_rows.contains_key(fragment_id) { + return Err(invalid(format!( + "failed rows for fragment {fragment_id} have no coverage update" + ))); + } + let current = state.failed_rows.entry(*fragment_id).or_default(); + *current |= failed; + } + state.failed_rows.retain(|_, rows| !rows.is_empty()); + state.failure_coverage.retain(|_, rows| !rows.is_empty()); + Ok(()) +} + async fn write_freshness_state( dataset: &mut Dataset, column: &str, @@ -1344,6 +2120,8 @@ async fn write_freshness_state( let state = state.normalize()?; let inline_empty = state.signatures.is_empty() && state.row_state.is_empty() + && state.failure_coverage.is_empty() + && state.failed_rows.is_empty() && state.basis.is_empty() && !retain_empty_sidecar; // The sidecar is durable before the metadata commit references it. @@ -1359,7 +2137,7 @@ async fn write_freshness_state( (reference, Some(digest)) }; let describes = dataset.version().version; - let updates = vec![ + let mut updates = vec![ (SOURCE_SIGNATURE_META_KEY.to_string(), Some(signature_ref)), ( DEFINITION_VERSION_META_KEY.to_string(), @@ -1370,6 +2148,13 @@ async fn write_freshness_state( Some(describes.to_string()), ), ]; + // Pending-fill proofs vouch for retained outputs under the old definition. + // A partial publication must not make them valid under its new stamp. + if field_meta(dataset, column, DEFINITION_VERSION_META_KEY) + .is_some_and(|version| version != definition_version) + { + updates.push((PENDING_FILL_SIGNATURE_META_KEY.to_string(), None)); + } let builder = dataset.update_field_metadata().update(column, updates)?; match expected_latest_version { Some(expected) => builder.with_expected_latest_version(expected).await?, @@ -1498,6 +2283,8 @@ pub async fn begin_row_repair( freshness.signatures = signatures_for(dataset, &live.iter().copied().collect::>(), inputs)?; freshness.row_state.clear(); + freshness.failure_coverage.clear(); + freshness.failed_rows.clear(); freshness.basis.clear(); } if state_unreadable || definition_changed { @@ -1507,6 +2294,8 @@ pub async fn begin_row_repair( .iter() .map(|id| (*id, DirtyRows::AllExcept(RoaringBitmap::new()))) .collect(); + freshness.failure_coverage.clear(); + freshness.failed_rows.clear(); } for (fragment_id, repair) in repairs { @@ -1523,6 +2312,9 @@ pub async fn begin_row_repair( let preserve = !state_unreadable && !definition_changed && freshness.signatures.get(fragment_id) == Some(¤t); + if !preserve { + freshness.invalidate_failure_evidence([*fragment_id]); + } let dirty = if preserve { freshness .row_state @@ -1546,6 +2338,12 @@ pub async fn begin_row_repair( freshness .row_state .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .failure_coverage + .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .failed_rows + .retain(|fragment_id, _| live.contains(fragment_id)); freshness.basis = basis.clone(); freshness.intent_id = Uuid::new_v4(); @@ -1639,6 +2437,66 @@ pub async fn finish_row_repair( filled_rows: &BTreeMap, skipped_rows: &BTreeMap, verified_version: Option, +) -> Result { + finish_row_repair_impl( + dataset, + column, + definition_version, + inputs, + token, + filled_rows, + skipped_rows, + None, + verified_version, + ) + .await +} + +/// Finalize a row repair together with the exact failure evidence observed for +/// those rows. +/// +/// `failures.known_rows` must be a subset of the rows assigned either a +/// value or an explicit skipped outcome. This permits a deferral to become +/// known non-failed without turning it into a failure. `failed_rows` must be a +/// subset of `known_rows`. The same token, input-signature and version +/// fences as [`finish_row_repair`] apply. +#[allow(clippy::too_many_arguments)] +pub async fn finish_row_repair_with_failures( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + failures: &FailureEvidence, + verified_version: Option, +) -> Result { + finish_row_repair_impl( + dataset, + column, + definition_version, + inputs, + token, + filled_rows, + skipped_rows, + Some(failures), + verified_version, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn finish_row_repair_impl( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + failures: Option<&FailureEvidence>, + verified_version: Option, ) -> Result { if !is_sha256_hex(&token.intent_digest) { return Err(invalid("row repair token is malformed".to_string())); @@ -1652,6 +2510,36 @@ pub async fn finish_row_repair( "row repair result names a fragment outside its token".to_string(), )); } + if let Some(failures) = failures { + failures.validate()?; + for (fragment_id, covered) in &failures.known_rows { + let selected = token.selected_rows.get(fragment_id).ok_or_else(|| { + invalid(format!( + "failure evidence names fragment {fragment_id} outside its token" + )) + })?; + let mut known = filled_rows.get(fragment_id).cloned().unwrap_or_default(); + if let Some(skipped) = skipped_rows.get(fragment_id) { + known |= skipped; + } + if !covered.is_subset(selected) || !covered.is_subset(&known) { + return Err(invalid(format!( + "failure evidence for fragment {fragment_id} covers rows without a final outcome" + ))); + } + } + for (fragment_id, failed) in &failures.failed_rows { + if !failures.known_rows.contains_key(fragment_id) + || skipped_rows + .get(fragment_id) + .is_none_or(|skipped| !failed.is_subset(skipped)) + { + return Err(invalid(format!( + "failed rows for fragment {fragment_id} must be an explicit skipped subset" + ))); + } + } + } dataset.checkout_latest().await?; if verified_version.is_some_and(|version| dataset.version().version != version) { return Err(invalid( @@ -1696,14 +2584,32 @@ pub async fn finish_row_repair( ))); } } - let before = state.row_state.clone(); + let before = state.clone(); + state.invalidate_failure_rows(&token.selected_rows); apply_row_repair( &mut state.row_state, &token.selected_rows, filled_rows, skipped_rows, )?; - if state.row_state == before { + if let Some(failures) = failures { + let accepted = token + .selected_rows + .keys() + .map(|fragment_id| { + state + .signatures + .get(fragment_id) + .cloned() + .map(|signature| (*fragment_id, signature)) + }) + .collect::>() + .ok_or_else(|| { + invalid("row repair failure evidence lost an accepted signature".to_string()) + })?; + apply_failure_evidence(dataset, inputs, &accepted, &mut state, failures).await?; + } + if state == before { return Ok(dataset.version().version); } if current_digest != token.intent_digest.as_str() { @@ -1741,6 +2647,742 @@ mod tests { const COLUMN: &str = "doubled"; const EXPRESSION: &str = "value * 2"; + async fn fresh_function_table() -> crate::Table { + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, [Some("x"), None, Some("z"), Some("w")]), + ("search_text", Utf8, ["a x", "b", "c z", "d w"]), + ("search_token_count", Int64, [2, 1, 2, 2]), + ("spare", Int32, [0, 0, 0, 0]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("fresh_functions", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let binding = text_features_binding(""); + stamp_bindings(&table, std::slice::from_ref(&binding)).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + native.dataset.update(dataset); + table + } + + async fn function_plan(dataset: &Dataset, column: &str) -> StalenessPlan { + staleness_against( + dataset, + column, + "fb_01K3TEXT", + &fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(), + ) + .await + .unwrap() + } + + #[rstest::rstest] + #[case::nullable_text("text")] + #[case::nested_text("nested")] + #[case::blob("blob")] + #[tokio::test] + async fn function_write_preserves_complex_omitted_inputs( + #[case] kind: &str, + #[values(false, true)] merge: bool, + ) { + use arrow_array::{ + ArrayRef, Int32Array, Int64Array, RecordBatch, StringArray, StructArray, + }; + + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + + let texts = Arc::new(StringArray::from(vec![ + Some("alpha"), + None, + Some(""), + Some("delta"), + ])); + let (body_field, body): (ArrowField, ArrayRef) = match kind { + "text" => (ArrowField::new("body", DataType::Utf8, true), texts), + "nested" => { + let fields = vec![ArrowField::new("text", DataType::Utf8, true)].into(); + let body = StructArray::new( + fields, + vec![texts], + Some(arrow_buffer::NullBuffer::from(vec![ + true, false, true, true, + ])), + ); + ( + ArrowField::new("body", body.data_type().clone(), true), + Arc::new(body), + ) + } + "blob" => { + let mut builder = lance::blob::BlobArrayBuilder::new(4); + builder.push_bytes(b"alpha").unwrap(); + builder.push_null().unwrap(); + builder.push_bytes(b"").unwrap(); + builder.push_bytes(b"delta").unwrap(); + ( + lance::blob::blob_field("body", true), + builder.finish().unwrap(), + ) + } + _ => unreachable!(), + }; + let batch = RecordBatch::try_new( + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("title", DataType::Utf8, false), + body_field.clone(), + ArrowField::new("search_text", DataType::Utf8, true), + ArrowField::new("search_token_count", DataType::Int64, true), + ArrowField::new("spare", DataType::Int32, false), + ])), + vec![ + Arc::new(StringArray::from(vec!["a", "b", "c", "d"])), + body, + Arc::new(StringArray::from(vec!["alpha", "null", "empty", "delta"])), + Arc::new(Int64Array::from(vec![5, 0, 0, 5])), + Arc::new(Int32Array::from(vec![0; 4])), + ], + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("complex_function_inputs", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + data_storage_version: Some(lance_file::version::LanceFileVersion::V2_2), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut raw = serde_json::to_value(text_features_binding("")).unwrap(); + let json_field = + lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![body_field])) + .unwrap() + .fields + .remove(0); + raw["input_schema"]["fields"][1] = serde_json::to_value(&json_field).unwrap(); + raw["inputs"][1]["arrow_type"] = serde_json::Value::String(match kind { + "text" => "utf8".into(), + "blob" => crate::function::FUNCTION_BLOB_V2_TYPE.into(), + _ => serde_json::to_string(&json_field.r#type).unwrap(), + }); + let binding = serde_json::from_value(raw).unwrap(); + stamp_bindings(&table, std::slice::from_ref(&binding)).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + native.dataset.update(dataset); + if merge { + let source = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("spare", Int32, [1, 1, 1, 1]) + ) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + } else { + table.update().column("spare", "1").execute().await.unwrap(); + } + let dataset = native.dataset.get().await.unwrap(); + for column in ["search_text", "search_token_count"] { + let plan = function_plan(&dataset, column).await; + assert!( + !plan.recompute_all && plan.dirty.is_empty() && plan.pending_fill.is_empty(), + "{plan:?}" + ); + } + let mut scan = dataset.scan(); + scan.with_row_address(); + scan.project(&["title", "search_text", "search_token_count", "body"]) + .unwrap(); + let mut actual = BTreeMap::new(); + for batch in scan + .try_into_stream() + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + { + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let text = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + let lengths = batch + .column(2) + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + assert!(!text.is_null(row) && !lengths.is_null(row)); + let body = batch.column_by_name("body").unwrap(); + let input = if kind == "blob" { + let addresses = batch + .column_by_name(ROW_ADDR) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + match dataset + .take_blobs_by_addresses(&[addresses.value(row)], "body") + .await + .unwrap() + .pop() + .unwrap() + { + Some(file) => Some(file.read().await.unwrap().to_vec()), + None => None, + } + } else { + let leaf = if kind == "nested" { + body.as_any() + .downcast_ref::() + .unwrap() + .column(0) + } else { + body + }; + let leaf = leaf.as_any().downcast_ref::().unwrap(); + (!body.is_null(row) && !leaf.is_null(row)) + .then(|| leaf.value(row).as_bytes().to_vec()) + }; + let expected_input = match titles.value(row) { + "a" => Some(b"alpha".to_vec()), + "b" => None, + "c" => Some(vec![]), + "d" => Some(b"delta".to_vec()), + _ => unreachable!(), + }; + assert_eq!(input, expected_input); + actual.insert( + titles.value(row).to_string(), + (text.value(row).to_string(), lengths.value(row)), + ); + } + } + assert_eq!( + actual, + BTreeMap::from([ + ("a".into(), ("alpha".into(), 5)), + ("b".into(), ("null".into(), 0)), + ("c".into(), ("empty".into(), 0)), + ("d".into(), ("delta".into(), 5)), + ]) + ); + } + + #[rstest::rstest] + #[case::label_update(false, 1, false)] + #[case::label_merge(true, 1, false)] + #[case::identical_merge(true, 0, false)] + #[case::mixed_update_insert(true, 1, true)] + #[tokio::test] + async fn function_write_preserves_unchanged_inputs( + #[case] merge: bool, + #[case] spare: i32, + #[case] insert: bool, + ) { + use crate::query::ExecutableQuery; + + let table = fresh_function_table().await; + let version = if merge { + let titles = if insert { + vec!["a", "c", "e"] + } else { + vec!["a", "c"] + }; + let batch = arrow_array::record_batch!( + ("title", Utf8, titles.clone()), + ("spare", Int32, vec![spare; titles.len()]) + ) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + if insert { + merge.when_not_matched_insert_all(); + } + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap() + .version + } else { + table + .update() + .only_if("title IN ('a', 'c')") + .column("spare", spare.to_string()) + .execute() + .await + .unwrap() + .version + }; + assert_eq!(version, table.version().await.unwrap()); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for column in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, column).await; + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + assert_eq!(stale.pending_fill.is_empty(), !insert, "{stale:?}"); + } + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut values = BTreeMap::new(); + for batch in batches { + let titles = batch + .column_by_name("title") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let outputs = batch + .column_by_name("search_text") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..batch.num_rows() { + values.insert( + titles.value(i).to_string(), + (!outputs.is_null(i)).then(|| outputs.value(i).to_string()), + ); + } + } + for (title, output) in [("a", "a x"), ("b", "b"), ("c", "c z"), ("d", "d w")] { + assert_eq!(values[title].as_deref(), Some(output)); + } + assert_eq!(values.len(), if insert { 5 } else { 4 }); + if insert { + assert_eq!(values["e"], None, "new rows still need Function evaluation"); + prune_sidecars(&dataset, true).await.unwrap(); + assert!( + !function_plan(&dataset, "search_text") + .await + .pending_fill + .is_empty() + ); + } + } + + #[rstest::rstest] + #[case::same_definition(false)] + #[case::changed_definition(true)] + #[tokio::test] + async fn partial_refresh_preserves_only_current_definition(#[case] changed: bool) { + let table = fresh_function_table().await; + let batch = + arrow_array::record_batch!(("title", Utf8, ["a", "e"]), ("spare", Int32, [1, 1])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge.when_not_matched_insert_all(); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap(); + let mut dataset = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .as_ref() + .clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let before = function_plan(&dataset, "search_text").await; + assert!(!before.pending_fill.is_empty()); + assert!(before.dirty.is_empty()); + // Refresh only the untouched fragment. Retained values elsewhere + // still belong to the old definition, even though their inputs match. + let definition = if changed { + "new-function-version" + } else { + "fb_01K3TEXT" + }; + let pinned = dataset.clone(); + let stale = staleness_against(&pinned, "search_text", definition, &inputs) + .await + .unwrap(); + let computed = signatures_for(&dataset, &[1], &inputs).unwrap(); + assert_eq!(computed.len(), 1); + record_freshness( + &mut dataset, + Some((&pinned, &stale)), + "search_text", + definition, + &inputs, + computed, + ) + .await + .unwrap(); + let after = staleness_against(&dataset, "search_text", definition, &inputs) + .await + .unwrap(); + assert!(!after.is_dirty(1), "{after:?}"); + if changed { + for fragment in dataset.get_fragments().iter().filter(|f| f.id() != 1) { + assert!(after.is_dirty(fragment.id() as u32), "{after:?}"); + } + assert!(after.pending_fill.is_empty(), "{after:?}"); + } else { + assert_eq!(after.pending_fill, before.pending_fill); + assert!(after.dirty.is_empty(), "{after:?}"); + } + } + + #[tokio::test] + async fn function_write_retains_pending_fill_across_another_update() { + let table = fresh_function_table().await; + let batch = + arrow_array::record_batch!(("title", Utf8, ["e"]), ("spare", Int32, [1])).unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_not_matched_insert_all(); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap(); + table + .update() + .only_if("title = 'e'") + .column("spare", "2") + .execute() + .await + .unwrap(); + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let stale = function_plan(&dataset, "search_text").await; + assert!(stale.dirty.is_empty(), "{stale:?}"); + assert_eq!( + stale.pending_fill.keys().copied().collect::>(), + vec![3] + ); + + write_signatures( + &mut dataset, + "search_text", + "fb_01K3TEXT", + stale.pending_fill, + ) + .await + .unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .pending_fill + .is_empty() + ); + // An older pending-fill reference must not override a later completed + // stamp or make a genuinely changed input fresh. + let changed = lance::dataset::UpdateBuilder::new(Arc::new(dataset)) + .update_where("title = 'e'") + .unwrap() + .set("body", "'changed'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + assert!( + function_plan(&changed.new_dataset, "search_text") + .await + .is_dirty(4) + ); + } + + #[rstest::rstest] + #[case::dirty_source("a", true)] + #[case::unrelated_dirty_fragment("c", false)] + #[tokio::test] + async fn function_write_preserves_pending_repairs( + #[case] title: &str, + #[case] dirty_product: bool, + ) { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signature = signatures_for(&dataset, &[0], &inputs).unwrap()[&0].clone(); + begin_row_repair( + &mut dataset, + "search_text", + "fb_01K3TEXT", + &inputs, + "pending-refresh", + &BTreeMap::from([( + 0, + RowRepair { + signature, + rows: RoaringBitmap::from_iter([0]), + }, + )]), + ) + .await + .unwrap(); + let prior = stored_row_states(&dataset, "search_text").await; + native.dataset.update(dataset); + table + .update() + .only_if(format!("title = '{title}'")) + .column("spare", "1") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + let stale = function_plan(&dataset, "search_text").await; + assert_eq!(stale.is_dirty(2), dirty_product, "{stale:?}"); + assert_eq!(stored_row_states(&dataset, "search_text").await, prior); + } + + #[rstest::rstest] + #[case::input("body", "'changed'")] + #[case::output("search_text", "'uncomputed'")] + #[tokio::test] + async fn function_write_does_not_certify_changed_values( + #[case] column: &str, + #[case] value: &str, + ) { + let table = fresh_function_table().await; + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let result = lance::dataset::UpdateBuilder::new(dataset) + .update_where("title = 'a'") + .unwrap() + .set(column, value) + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut after = result.new_dataset.as_ref().clone(); + let version = after.version().version; + preserve_function_freshness( + &mut after, + FunctionWrite::Update { + columns: &[column.into()], + }, + ) + .await + .unwrap(); + assert_eq!(after.version().version, version); + assert!(function_plan(&after, "search_text").await.is_dirty(2)); + } + + #[rstest::rstest] + #[case::input_same_rows("body", "a", true)] + #[case::input_other_rows("body", "c", false)] + #[case::output_same_rows("search_text", "a", true)] + #[case::output_other_rows("search_text", "c", false)] + #[tokio::test] + async fn function_write_preserves_prior_invalidation( + #[case] changed_column: &str, + #[case] title: &str, + #[case] dirty_product: bool, + ) { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let result = lance::dataset::UpdateBuilder::new(native.dataset.get().await.unwrap()) + .update_where("title = 'a'") + .unwrap() + .set(changed_column, "'changed'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + assert!( + function_plan(&result.new_dataset, "search_text") + .await + .is_dirty(2) + ); + native.dataset.update(result.new_dataset.as_ref().clone()); + + table + .update() + .only_if(format!("title = '{title}'")) + .column("spare", "1") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + let stale = function_plan(&dataset, "search_text").await; + assert_eq!(stale.is_dirty(3), dirty_product, "{stale:?}"); + if !dirty_product { + assert!( + stale.is_dirty(2), + "the earlier invalidation was lost: {stale:?}" + ); + } + } + + #[tokio::test] + async fn function_write_keeps_a_changed_definition_stale() { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + dataset + .update_field_metadata() + .update( + "search_text", + [(DEFINITION_VERSION_META_KEY, Some("old-function-version"))], + ) + .unwrap() + .await + .unwrap(); + native.dataset.update(dataset); + table.update().column("spare", "1").execute().await.unwrap(); + assert!( + function_plan(native.dataset.get().await.unwrap().as_ref(), "search_text") + .await + .recompute_all + ); + } + + #[rstest::rstest] + #[case::delete(false)] + #[case::restore(true)] + #[tokio::test] + async fn function_write_cannot_stamp_over_a_concurrent_commit(#[case] restore: bool) { + let table = fresh_function_table().await; + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let before_version = dataset.version().version; + let result = lance::dataset::UpdateBuilder::new(dataset) + .update_where("title = 'a'") + .unwrap() + .set("spare", "1") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut staged = result.new_dataset.as_ref().clone(); + let mut concurrent = staged.clone(); + if restore { + concurrent = concurrent.checkout_version(before_version).await.unwrap(); + concurrent.restore().await.unwrap(); + } else { + concurrent.delete("title = 'd'").await.unwrap(); + } + let current_version = concurrent.version().version; + let before = field_meta(&concurrent, "search_text", SOURCE_SIGNATURE_META_KEY); + assert!( + preserve_function_freshness( + &mut staged, + FunctionWrite::Update { + columns: &["spare".into()] + } + ) + .await + .is_err() + ); + concurrent.checkout_latest().await.unwrap(); + assert_eq!(concurrent.version().version, current_version); + assert_eq!( + field_meta(&concurrent, "search_text", SOURCE_SIGNATURE_META_KEY), + before + ); + } + + #[tokio::test] + async fn function_write_retains_inherited_compaction_freshness() { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + compact(&mut dataset).await; + assert!( + !function_plan(&dataset, "search_text") + .await + .inherited + .is_empty() + ); + native.dataset.update(dataset); + table + .update() + .only_if("title = 'a'") + .column("spare", "1") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + let stale = function_plan(&dataset, "search_text").await; + assert!(stale.dirty.is_empty(), "{stale:?}"); + assert_eq!(dataset.get_fragments().len(), 2); + } + /// Two fragments of 50 rows, `id` and `value`, with `doubled` declared /// all-null against `value`, tracked from birth. async fn table(uri: &str) -> Dataset { @@ -1813,6 +3455,41 @@ mod tests { .unwrap(); } + async fn stamp_v2( + dataset: &mut Dataset, + column: &str, + definition: &str, + entries: SignatureMap, + ) { + let reference = write_sidecar_bytes( + dataset, + encode_v2_sidecar(&FreshnessState { + signatures: entries, + ..Default::default() + }) + .unwrap(), + ) + .await + .unwrap(); + let describes = dataset.version().version.to_string(); + dataset + .update_field_metadata() + .update( + column, + [ + (SOURCE_SIGNATURE_META_KEY.to_string(), reference), + ( + DEFINITION_VERSION_META_KEY.to_string(), + definition.to_string(), + ), + (RECORDED_AT_VERSION_META_KEY.to_string(), describes), + ], + ) + .unwrap() + .await + .unwrap(); + } + fn fragment_signature(dataset: &Dataset, fragment_id: u32) -> String { signature_of(dataset, fragment_id, &inputs(dataset)) .unwrap() @@ -1839,6 +3516,15 @@ mod tests { (3, DirtyRows::Rows(RoaringBitmap::from_iter([1, 4, 9]))), (7, DirtyRows::AllExcept(RoaringBitmap::from_iter([0, 2]))), ]), + failure_coverage: FailureRows::from([ + (3, RoaringBitmap::from_iter([1, 2, 4, 9])), + (7, RoaringBitmap::from_iter([0, 1, 2, 3])), + ]), + failed_rows: FailureRows::from([ + (3, RoaringBitmap::from_iter([1])), + (7, RoaringBitmap::from_iter([1, 3])), + ]), + failure_evidence_recorded: true, }; let encoded = encode_sidecar(&state).unwrap(); assert_eq!(encoded[4], SIDECAR_FORMAT); @@ -1858,9 +3544,283 @@ mod tests { let state = decode_sidecar(&encode_legacy_sidecar(&signatures).unwrap()).unwrap(); assert_eq!(state.signatures, signatures); assert!(state.row_state.is_empty()); + assert!(state.failure_coverage.is_empty()); + assert!(state.failed_rows.is_empty()); + assert!(!state.failure_evidence_recorded); assert!(state.basis.is_empty()); } + #[test] + fn v2_sidecar_decodes_with_unknown_failure_evidence() { + let state = FreshnessState { + signatures: SignatureMap::from([(1, "0000000000000001".to_string())]), + row_state: RowStateMap::from([(1, DirtyRows::Rows(RoaringBitmap::from_iter([2, 3])))]), + basis: "legacy-intent".to_string(), + intent_id: Uuid::from_u128(1), + ..Default::default() + }; + let decoded = decode_sidecar(&encode_v2_sidecar(&state).unwrap()).unwrap(); + assert_eq!(decoded, state); + assert!(decoded.failure_coverage.is_empty()); + assert!(decoded.failed_rows.is_empty()); + assert!(!decoded.failure_evidence_recorded); + } + + #[tokio::test] + async fn a_first_partial_write_keeps_untouched_legacy_rows_unknown() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let entries = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + stamp_v2(&mut dataset, COLUMN, &definition, entries).await; + + let StrictFreshness::Uncertified { staleness } = + strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("the v2 sidecar should yield a readable uncertified plan"); + }; + assert_eq!(staleness, StalenessPlan::default()); + + let selected = RoaringBitmap::from_iter([1, 2]); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, selected.clone()))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "legacy-partial", + &repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, selected)]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + None, + ) + .await + .unwrap(); + + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("partial v3 evidence is still readable"); + }; + assert_eq!( + staleness.row_dirty.get(&0), + Some(&DirtyRows::Rows(RoaringBitmap::from_iter([1]))) + ); + assert_eq!( + failures.known_rows.get(&0), + Some(&RoaringBitmap::from_iter([1, 2])), + "only the rows this partial publication observed are covered" + ); + assert_eq!( + failures.failed_rows.get(&0), + Some(&RoaringBitmap::from_iter([1])) + ); + assert!( + !failures.known_rows.contains_key(&1), + "the untouched legacy fragment remains unknown" + ); + } + + #[tokio::test] + async fn a_successful_retry_clears_only_its_failed_rows() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let signatures = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + stamp_v2(&mut dataset, COLUMN, &definition, signatures).await; + + let first_selected = RoaringBitmap::from_iter([1, 2]); + let first_repairs = BTreeMap::from([(0, repair(&dataset, 0, first_selected.clone()))]); + let first = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "failed-wave", + &first_repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &first, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, first_selected)]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + None, + ) + .await + .unwrap(); + + let retry_selected = RoaringBitmap::from_iter([1]); + let retry_repairs = BTreeMap::from([(0, repair(&dataset, 0, retry_selected.clone()))]); + let retry = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "successful-retry", + &retry_repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &retry, + &BTreeMap::from([(0, retry_selected.clone())]), + &BTreeMap::new(), + &FailureEvidence { + known_rows: BTreeMap::from([(0, retry_selected)]), + failed_rows: BTreeMap::new(), + }, + None, + ) + .await + .unwrap(); + + let StrictFreshness::Certified { failures, .. } = + strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("status should remain readable"); + }; + assert!(!failures.failed_rows.contains_key(&0)); + assert_eq!( + failures.known_rows.get(&0), + Some(&RoaringBitmap::from_iter([1, 2])) + ); + } + + #[tokio::test] + async fn an_old_attempt_cannot_rewrite_a_newer_signature_evidence() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let old = dataset.clone(); + let old_inputs = ids.clone(); + let old_signature = signature_of(&old, 0, &old_inputs).unwrap().unwrap(); + + rewrite_value(&mut dataset, 0).await; + let new_signature = signature_of(&dataset, 0, &inputs(&dataset)) + .unwrap() + .unwrap(); + assert_ne!(old_signature, new_signature); + + let current_entries = signatures_for(&dataset, &[0, 1], &inputs(&dataset)).unwrap(); + write_signatures(&mut dataset, COLUMN, &definition, current_entries.clone()) + .await + .unwrap(); + let StoredFreshnessState::Present { + state: mut current_state, + .. + } = stored_freshness_state(&dataset, COLUMN).await + else { + panic!("new attempt state"); + }; + current_state + .failure_coverage + .insert(0, RoaringBitmap::from_iter([3, 4])); + current_state + .failed_rows + .insert(0, RoaringBitmap::from_iter([4])); + let write = write_freshness_state( + &mut dataset, + COLUMN, + &definition, + current_state.clone(), + false, + None, + ) + .await + .unwrap(); + assert!(write.version > 0); + let new_evidence = FailureEvidence { + known_rows: current_state.failure_coverage.clone(), + failed_rows: current_state.failed_rows.clone(), + }; + + let record = record_freshness_with_failures( + &mut dataset, + None, + COLUMN, + &definition, + &old_inputs, + SignatureMap::from([(0, old_signature)]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1, 2]))]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + ) + .await + .unwrap(); + assert_eq!((record.recorded, record.moved), (0, 1)); + + let StrictFreshness::Certified { failures, .. } = + strict_freshness_against(&dataset, COLUMN, &definition, &inputs(&dataset)) + .await + .unwrap() + else { + panic!("current signature evidence should remain readable"); + }; + assert_eq!(failures.known_rows, new_evidence.known_rows); + assert_eq!(failures.failed_rows, new_evidence.failed_rows); + assert_eq!( + failures.failed_rows.get(&0), + Some(&RoaringBitmap::from_iter([4])), + "old S1 failure must not replace the S2 failure" + ); + assert!(!failures.known_rows.contains_key(&1)); + } + + #[test] + fn failure_evidence_must_be_a_subset_of_coverage() { + let state = FreshnessState { + signatures: SignatureMap::from([(3, "0000000000000003".to_string())]), + failure_coverage: FailureRows::from([(3, RoaringBitmap::from_iter([1]))]), + failed_rows: FailureRows::from([(3, RoaringBitmap::from_iter([2]))]), + ..Default::default() + }; + let error = encode_sidecar(&state).unwrap_err(); + assert!( + error + .to_string() + .contains("failed rows are not covered by failure evidence"), + "{error}" + ); + } + #[tokio::test] async fn a_row_repair_clears_filled_rows_and_retains_skipped_rows() { let dir = tempfile::tempdir().unwrap(); diff --git a/rust/lancedb/src/table/function_column_status.rs b/rust/lancedb/src/table/function_column_status.rs new file mode 100644 index 000000000..15703f4e9 --- /dev/null +++ b/rust/lancedb/src/table/function_column_status.rs @@ -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, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed_at_millis: Option, + /// Why this Job failed, when the server retained a structured failure. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure: Option, +} + +/// 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, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub active_job_id: Option, + pub state: FunctionColumnAutoRefreshState, + pub failure_streak: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effective_cooldown_millis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub blocked_reason: Option, + /// Null is intentional until the Lance Agent exposes its scheduler decision. + pub next_run_at_millis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_run_at_reason: Option, +} + +/// 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, + /// 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, + 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") + ); + } +} diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 1f0b80829..3f37c540d 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -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, diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index a8be34b17..ff73e6366 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -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, + /// 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, /// 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, + /// 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, /// 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) -> 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)?; } diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index aa325cd7c..d9828fff1 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -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::>(); 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, }) } diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index fe8fc27c5..829486015 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -71,6 +71,7 @@ fn execution_controls_match_shared_canonical_golden() { let value: Value = serde_json::from_str(&request.to_canonical_json().unwrap()).unwrap(); assert_eq!(value["batch_size"], 2); + assert_eq!(value["max_concurrency"], 4); assert_eq!(value["row_timeout_seconds"], 0.75); } @@ -80,6 +81,10 @@ fn execution_controls_require_their_positive_ranges() { for (field, value) in [ ("batch_size", Value::from(0)), ("batch_size", Value::from(4_294_967_296_u64)), + ("max_concurrency", Value::from(0)), + ("max_concurrency", Value::from(4_294_967_296_u64)), + ("max_concurrency", Value::from(-1)), + ("max_concurrency", Value::from(1.5)), ("row_timeout_seconds", Value::from(0)), ("row_timeout_seconds", Value::from(-0.25)), ] { @@ -107,6 +112,11 @@ fn execution_controls_are_validated_before_canonical_serialization() { request.batch_size = Some(0); let error = request.to_canonical_json().unwrap_err(); assert!(error.to_string().contains("batch_size"), "{error}"); + + let mut request = FunctionRegistrationRequest::from_json(&source).unwrap(); + request.max_concurrency = Some(0); + let error = request.to_canonical_json().unwrap_err(); + assert!(error.to_string().contains("max_concurrency"), "{error}"); } /// The same shared golden as the Python suite builds from `@function(secrets=...)` @@ -156,11 +166,15 @@ async fn local_function_catalog_operations_return_stable_not_supported() { .get_function("normalize_score", "1", &[]) .await .unwrap_err(); + let latest_lookup_error = connection + .get_function_latest("normalize_score", &[]) + .await + .unwrap_err(); let drop_error = connection .drop_function("normalize_score", "1", &[]) .await .unwrap_err(); - for error in [create_error, lookup_error, drop_error] { + for error in [create_error, lookup_error, latest_lookup_error, drop_error] { assert!(matches!( error, Error::NotSupported { message } diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json index 9ce9a289f..b5bdff2a8 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json @@ -1 +1 @@ -{"artifact":{"adapter":{"kind":"scalar_to_arrow_batch","version":1},"content":{"data":"ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK","encoding":"base64"},"digest":"sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f","entrypoint":"normalize_score","kind":"python_callable"},"batch_size":2,"name":"normalize_score","row_timeout_seconds":0.75,"runtime":{"env":{"MODE":"test"},"environment":{"kind":"pip","packages":["numpy>=2"]},"kind":"python","python_version":"3.12"},"signature":{"inputs":[{"arrow_type":"float64","name":"value","nullable":false}],"output":{"arrow_type":"float64","kind":"scalar","nullable":false}}} +{"artifact":{"adapter":{"kind":"scalar_to_arrow_batch","version":1},"content":{"data":"ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK","encoding":"base64"},"digest":"sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f","entrypoint":"normalize_score","kind":"python_callable"},"batch_size":2,"max_concurrency":4,"name":"normalize_score","row_timeout_seconds":0.75,"runtime":{"env":{"MODE":"test"},"environment":{"kind":"pip","packages":["numpy>=2"]},"kind":"python","python_version":"3.12"},"signature":{"inputs":[{"arrow_type":"float64","name":"value","nullable":false}],"output":{"arrow_type":"float64","kind":"scalar","nullable":false}}} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json index cb0961eba..ce21edb51 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json @@ -1,6 +1,7 @@ { "name": "normalize_score", "batch_size": 2, + "max_concurrency": 4, "row_timeout_seconds": 0.75, "artifact": { "kind": "python_callable", diff --git a/rust/lancedb/vendor/lance-linalg/Cargo.toml b/rust/lancedb/vendor/lance-linalg/Cargo.toml index 0d0ae9f05..9650a3a1b 100644 --- a/rust/lancedb/vendor/lance-linalg/Cargo.toml +++ b/rust/lancedb/vendor/lance-linalg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lance-linalg" -version = "15.0.0-beta.16" +version = "15.0.0-beta.17" publish = false edition = { workspace = true } license = { workspace = true } diff --git a/rust/lancedb/vendor/lance-linalg/README.lancedb.md b/rust/lancedb/vendor/lance-linalg/README.lancedb.md index 553154f44..b706acd1f 100644 --- a/rust/lancedb/vendor/lance-linalg/README.lancedb.md +++ b/rust/lancedb/vendor/lance-linalg/README.lancedb.md @@ -1,5 +1,5 @@ -This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.16` -(commit `03b7ff329e656636c581f1e3547048101990bc1f`), licensed under Apache-2.0. +This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.17` +(commit `471352665e1e5ce453af154efd53b4d65c931127`), licensed under Apache-2.0. LanceDB patches `src/distance/cosine.rs` to recompute FLOAT32 cosine distances in FLOAT64 when squared norms or dot products overflow or underflow. Ordinary