diff --git a/.bumpversion.toml b/.bumpversion.toml index bbf036dc8..992d126d0 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.9" +current_version = "0.42.0-beta.10" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index b2db765d0..5aea2ca30 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -44,7 +44,7 @@ jobs: - platform: x86_64 manylinux: "2_28" extra_args: "--features fp16kernels" - runner: ubuntu-22.04 + runner: ubuntu-2404-8x-x64 package_name: "lancedb" rustflags: "" # For successful fat LTO builds, we need a large runner to avoid OOM errors. diff --git a/Cargo.lock b/Cargo.lock index 893fb21d6..56642301c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,7 +5342,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.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5356,7 +5356,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.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5365,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrayref", "crunchy", @@ -5376,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5415,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5447,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5473,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5491,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "proc-macro2", "quote", @@ -5501,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-arith", "arrow-array", @@ -5535,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,8 +5567,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5599,8 +5599,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5671,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5695,8 +5695,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5741,8 +5741,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "byteorder", "ethnum", @@ -5759,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5775,8 +5775,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "async-trait", @@ -5790,8 +5790,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5845,8 +5845,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5860,8 +5860,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5902,8 +5902,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "frostem", "icu_segmenter", @@ -5930,7 +5930,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "ahash", "anyhow", @@ -6041,7 +6041,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "anyhow", "arrow-array", @@ -6084,7 +6084,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "arrow-array", "arrow-buffer", @@ -6109,7 +6109,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "arc-swap", "arrow", diff --git a/Cargo.toml b/Cargo.toml index ab8e86f97..e77e0ffd6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } 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 6b0ac9492..3d3a3f8e1 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.9 + 0.42.0-beta.10 ``` diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 1fad723fe..27acc9847 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1141,11 +1141,21 @@ 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`. #### Returns @@ -1156,6 +1166,11 @@ 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, errorPolicy: "skip", maxFailedFraction: 0.01, rowTimeoutSeconds: 30, diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index dab1c61bc..50f55f937 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -99,6 +99,7 @@ - [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/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/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 840012040..6cc8f7f8f 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,17 @@ Worker count for an expression column; Function columns reject it. *** +### 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/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 ac4ff93fe..b3fcdc937 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -166,8 +166,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 +337,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 @@ -261,6 +351,38 @@ release. TypeScript does not expose GPU class discovery; pass `gpuClass` 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: + + +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + publication_interval_rows=60, +) +job.wait() +``` + +```rust Rust icon="rust" +use lancedb::table::RefreshColumnOptions; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().publication_interval_rows(60), + ) + .await?; +``` + + +The threshold is opt-in and must be greater than zero. The number of rows in an +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. + 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 to new rows (see [what a filter recomputes](#partial)) and told to skip rows @@ -309,7 +431,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 f915a6a64..758e41acd 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.9 + 0.42.0-beta.10 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 88b66b3ad..2f72f98a7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.9 + 0.42.0-beta.10 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.15 + 15.0.0-beta.16 2.18.12 false 2.30.0 diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index d8f16adb1..47fc92237 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.9" +version = "0.42.0-beta.10" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 242be6101..280905897 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -682,6 +682,7 @@ describe("remote connection", () => { const job = await table.refreshColumnAsync("embedding", { where: "id % 2 = 0", batchSize: 16, + maxConcurrency: 3, gpuClass: "a10g", gpuCount: 2, errorPolicy: "skip", @@ -693,6 +694,17 @@ describe("remote connection", () => { }); expect(job.id).toBe("j-9"); await table.refreshColumnAsync("embedding"); + 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(); // Invalid options reject before any request is sent. for (const [options, message] of [ [{ maxFailedRows: -1 }, "maxFailedRows"], @@ -700,8 +712,83 @@ describe("remote connection", () => { [{ where: " " }, "where"], [{ maxFailedFraction: 2 }, "max_failed_fraction"], [{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"], + [{ 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 +799,21 @@ 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", + "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" }, + 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..80d8296e2 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5686,6 +5686,14 @@ describe("computed columns", () => { await expect( table.refreshColumnAsync("x", { errorPolicy: "skip" }), ).rejects.toThrow("error_policy 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..6bd46c9c8 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -57,6 +57,7 @@ export { AddResult, AddColumnsResult, RefreshColumnOptions, + FunctionWorkerResourceBudget, RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 5ef298c8c..d56f66cde 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -722,15 +722,30 @@ 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`. * @example * ```ts * const job = await table.refreshColumnAsync("embedding", { * where: "published_at > '2026-01-01'", + * resourceBudget: { + * cpuMillis: 8000, + * memoryBytes: 16 * 1024 ** 3, + * }, + * maxConcurrency: 4, * errorPolicy: "skip", * maxFailedFraction: 0.01, * rowTimeoutSeconds: 30, diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index f04147d46..3761d6f4f 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.9", + "version": "0.42.0-beta.10", "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 af781ae92..5b7a167d0 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.9", + "version": "0.42.0-beta.10", "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 c08a81137..e902929bf 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.9", + "version": "0.42.0-beta.10", "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 624b22de3..a54f47de3 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.9", + "version": "0.42.0-beta.10", "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 d200c24c3..cc1894e70 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.9", + "version": "0.42.0-beta.10", "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 a0b3cfd48..d5e0309d0 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.9", + "version": "0.42.0-beta.10", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 0544af0c7..5e9698e7f 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.9", + "version": "0.42.0-beta.10", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index c2424cd55..5579e1c55 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index ebbc4a060..5b52c0d16 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::*; @@ -1586,9 +1587,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 resource_budget_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 +1649,14 @@ pub struct RefreshColumnOptions { pub where_clause: Option, /// Maximum rows per Function call; must be greater than zero. pub batch_size: 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 +1685,20 @@ 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.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( + resource_budget_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?, + resource_budget_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, diff --git a/python/Cargo.toml b/python/Cargo.toml index 2c577766b..102b0f67b 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/python/pyproject.toml b/python/pyproject.toml index 153d138b4..036acf075 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.0b15", + "pylance==15.0.0b16", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", 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 2ac4dde58..dfb887461 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, @@ -501,6 +505,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 +515,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 +557,7 @@ class Table: LabelList, Fm, NGram, + ZoneMap, FTS, ], replace: Optional[bool], @@ -572,6 +581,7 @@ class Table: LabelList, Fm, NGram, + ZoneMap, FTS, ], replace: Optional[bool], @@ -605,6 +615,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 +623,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,6 +631,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, @@ -636,6 +651,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, 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..86a1295cc 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -4,7 +4,7 @@ """Handles to asynchronous registry jobs, SQL queries, and local operations.""" import asyncio -import json +import reprlib import time from datetime import timedelta from typing import Any, Callable, Generic, Optional, TypeVar, cast @@ -461,43 +461,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)" 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 8f1f741fb..af648c45c 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1127,6 +1127,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 +1135,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,6 +1145,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, @@ -1159,6 +1164,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, @@ -1178,6 +1186,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, @@ -1195,6 +1206,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, 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 75975a2c3..609e116ba 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -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,6 +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, @@ -3216,15 +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. @@ -3244,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. @@ -3263,6 +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, @@ -3300,15 +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. @@ -3328,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. @@ -4118,7 +4181,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) @@ -4131,8 +4194,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 ------- @@ -4271,7 +4334,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 @@ -5426,6 +5489,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( @@ -5433,6 +5497,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, ) ) @@ -5442,6 +5507,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, @@ -5461,6 +5529,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, @@ -5480,6 +5551,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, @@ -5501,6 +5575,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, @@ -6590,7 +6667,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) @@ -6602,8 +6679,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 ------- @@ -6644,6 +6721,7 @@ class AsyncTable: LabelList, Fm, NGram, + ZoneMap, FTS, ] ] = None, @@ -6720,12 +6798,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: @@ -6764,6 +6843,7 @@ class AsyncTable: LabelList, Fm, NGram, + ZoneMap, FTS, ] ] = None, @@ -7407,7 +7487,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: @@ -7702,6 +7785,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. @@ -7768,6 +7852,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 -------- @@ -7796,6 +7886,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 @@ -7824,6 +7915,7 @@ class AsyncTable: function_output_name, auto_refresh_enabled, auto_refresh_interval_seconds, + auto_refresh_resource_budget, ) if isinstance(transforms, pa.Field): @@ -7844,6 +7936,7 @@ class AsyncTable: list(computed.items()), auto_refresh_enabled, auto_refresh_interval_seconds, + auto_refresh_resource_budget, ) if options_supplied: raise ValueError( @@ -7865,6 +7958,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, @@ -7903,15 +7999,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. @@ -7931,7 +8047,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. @@ -7945,6 +8062,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 @@ -8054,6 +8174,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, @@ -8091,15 +8214,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. @@ -8119,7 +8262,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. @@ -8150,6 +8294,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 @@ -8707,6 +8854,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..07b8a8c5e 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -4,6 +4,7 @@ import asyncio import time from datetime import timedelta +from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock import pytest @@ -13,6 +14,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): diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 95148dcf9..aee67d32a 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 685bc809d..5224e5482 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,6 +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}, @@ -1903,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"] @@ -1911,6 +1929,8 @@ 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", "row_timeout_seconds", @@ -2088,7 +2108,47 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"max_failed_rows": -1}, "max_failed_rows"), ({"row_timeout_seconds": 0}, "row_timeout_seconds"), ({"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", @@ -4954,8 +5014,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 @@ -5535,9 +5599,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(", @@ -5545,12 +5606,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},", ")", ] ) @@ -5783,6 +5840,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 = [] @@ -5958,6 +6101,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 2a502fe62..7146ed86b 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5995,6 +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"), ], @@ -6250,6 +6256,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/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 a4af55161..5752dec16 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -29,15 +29,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,6 +48,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, @@ -69,10 +74,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, @@ -114,6 +206,10 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult, + #[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 { @@ -2179,20 +2279,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 { @@ -2209,13 +2313,16 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=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, @@ -2226,10 +2333,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, @@ -2251,13 +2361,16 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=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, @@ -2268,10 +2381,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, diff --git a/python/uv.lock b/python/uv.lock index 2cd4ac496..a5ae1caf8 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.0b15" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b16" }, { 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.0b15" +version = "15.0.0b16" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,11 +4312,11 @@ 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_29HO58/pylance-15.0.0b15-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:46c870c3d650f911eccb7406ec77f72fa448f80b2f827ff35dd86bbc0b9e08ca" }, - { url = "https://pypi.fury.io/lance-format/-/ver_OBkXR/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3f418584cdee98d27aac538ebe5203051a0b78a98668aff22bc29aebe3dd3c9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_TMbLm/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3656d52ba65d297b41f1973d1a3efbb888f761cf7c934ff15e0c1aecc560b2d5" }, - { url = "https://pypi.fury.io/lance-format/-/ver_mmYmR/pylance-15.0.0b15-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a50d06e3a86d68acf8edf5a83736890a648a16a1cb8c8ccde9ef5b6c82ebef76" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1aYiTc/pylance-15.0.0b15-cp310-abi3-win_amd64.whl", hash = "sha256:6451499f0612d0326d54168bedcc6df29c1e0700c4f92902f5f00a6ecdf17745" }, + { 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" }, ] [[package]] diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 6f5d45232..783216243 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 601d0f58b..051db741a 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.9" +version = "0.42.0-beta.10" edition = "2021" license.workspace = true repository.workspace = true diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 1efd1fa1c..c557c8e4b 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -681,9 +681,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, @@ -695,6 +696,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/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index d93f73c64..4e61710ff 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -336,6 +336,9 @@ impl Database for LanceNamespaceDatabase { // Refuse a bad declaration before the namespace records a table. crate::table::computed_columns::ensure_declarations_are_planned( &request.data.arrow_schema(), + self.session + .as_deref() + .and_then(lance::session::Session::datafusion_session), )?; let mut table_id = request.namespace_path.clone(); table_id.push(request.name.clone()); 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/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index c263dc001..bd7fbb942 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -958,7 +958,7 @@ fn is_declaration(key: &str) -> bool { || crate::table::computed_columns::is_declaration_key(key) } -fn without_declarations(field: &ArrowField) -> ArrowField { +pub(crate) fn without_declarations(field: &ArrowField) -> ArrowField { let metadata: HashMap = field .metadata() .iter() @@ -1123,6 +1123,10 @@ impl PreparedDeclaration { /// are validated over the assembled schema, and read only columns the /// view holds (see [`PreparedDeclaration::input_column`]). /// + /// `session` holds the DataFusion functions a declaration may call, as + /// for [`AddColumnsBuilder::computed`](crate::table::AddColumnsBuilder::computed); + /// `None` plans against Lance's built-in functions only. + /// /// ```no_run /// # #![recursion_limit = "256"] /// # use std::collections::HashMap; @@ -1148,7 +1152,7 @@ impl PreparedDeclaration { /// (INPUTS_META_KEY.into(), format!("[\"{text}\"]")), /// ])); /// let view = prepared - /// .with_computed_columns(vec![(1, length)], &[])? + /// .with_computed_columns(vec![(1, length)], &[], None)? /// .create("lengths") /// .await?; /// view.refresh().execute().await?; // rows land with `length` NULL @@ -1160,6 +1164,7 @@ impl PreparedDeclaration { mut self, columns: Vec<(usize, ArrowField)>, bindings: &[FunctionBinding], + session: Option<&datafusion::execution::context::SessionContext>, ) -> Result { let invalid = |message: String| Error::InvalidInput { message }; if columns.is_empty() { @@ -1223,7 +1228,7 @@ impl PreparedDeclaration { } rewrite_column_definitions(&mut metadata, self.schema.as_ref(), &fields)?; let schema = ArrowSchema::new_with_metadata(fields, metadata); - ensure_declarations_are_planned(&schema)?; + ensure_declarations_are_planned(&schema, session)?; self.schema = Arc::new(schema); Ok(self) } @@ -2685,7 +2690,7 @@ mod tests { (INPUTS_META_KEY.into(), "[\"x\"]".into()), ])); let view = prepared - .with_computed_columns(vec![(1, doubled)], &[]) + .with_computed_columns(vec![(1, doubled)], &[], None) .unwrap() .create("m") .await diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 1072b7684..8851d071e 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -133,7 +133,7 @@ pub(crate) async fn execute_refresh( })?; let physical = Arc::new(ArrowSchema::from(view_ds.schema())); - ensure_declarations_are_planned(&physical)?; + ensure_declarations_are_planned(&physical, view_ds.session().datafusion_session())?; if let Some(field) = physical .fields() .iter() diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index c33c7267d..a4952593b 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) } 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 9ba767bb1..d07271ea0 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3954,6 +3954,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 @@ -10389,6 +10392,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 @@ -10825,6 +10829,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) @@ -10852,6 +10861,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(); @@ -11056,6 +11073,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}; @@ -11100,6 +11159,8 @@ 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, "max_failed_rows": 50, @@ -11116,6 +11177,8 @@ 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) .max_failed_rows(50) @@ -11159,10 +11222,18 @@ 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", ), + ( + RefreshColumnOptions::default().publication_interval_rows(0), + "publication_interval_rows", + ), ] { let error = table .refresh_column_async_with_options("quality", options) @@ -11177,7 +11248,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") @@ -11192,6 +11263,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) 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 c51199b50..bfb712ecd 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -114,7 +114,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, @@ -2156,10 +2156,18 @@ impl Table { /// /// [`RefreshColumnOptions::batch_size()`] caps rows per Function call in /// LanceDB Enterprise and must be greater than zero when set. + /// [`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. - /// These options have no effect on expression-backed columns in LanceDB - /// Embedded. Remote refreshes require + /// [`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 resource budget and publication threshold are + /// rejected there. + /// Remote refreshes require /// [`Table::refresh_column_async_with_options`]. /// /// ``` @@ -2216,12 +2224,18 @@ impl Table { /// Set [`RefreshColumnOptions::batch_size()`] to cap the rows each remote /// Function call receives, for example to keep slow Functions within the /// executor's per-call deadline. 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 all three options. + /// [`RefreshColumnOptions::publication_interval_rows()`] to publish + /// completed Function outputs at a row-count threshold; unset keeps + /// whole-fragment publication. Set + /// [`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}; @@ -3428,7 +3442,11 @@ impl NativeTable { namespace_client: Option>, pushdown_operations: HashSet, ) -> Result { - let batches = computed_columns::admit_create_source(batches)?; + let session = params.as_ref().and_then(|p| p.session.as_deref()); + let batches = computed_columns::admit_create_source( + batches, + session.and_then(lance::session::Session::datafusion_session), + )?; // Default params uses format v1. let params = params.unwrap_or(WriteParams { ..Default::default() @@ -3529,7 +3547,12 @@ impl NativeTable { pushdown_operations: HashSet, session: Option>, ) -> Result { - let batches = computed_columns::admit_create_source(batches)?; + let batches = computed_columns::admit_create_source( + batches, + session + .as_deref() + .and_then(lance::session::Session::datafusion_session), + )?; // Build table_id from namespace + name for the storage options provider let mut table_id = namespace.clone(); table_id.push(name.to_string()); diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index be319a8be..a76c0d043 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -89,6 +89,30 @@ impl AddColumnsBuilder { /// # Ok(()) /// # } /// ``` + /// + /// In LanceDB Embedded, an expression can also call functions registered + /// on a DataFusion `SessionContext` attached to the connection's Lance + /// session. They are not stored with the table, so attach them on every + /// connection that opens it. + /// + /// ```no_run + /// # use std::sync::Arc; + /// # use datafusion::execution::context::SessionContext; + /// # use datafusion::logical_expr::ScalarUDF; + /// # async fn declare(my_udf: ScalarUDF) -> Result<(), Box> { + /// let functions = SessionContext::new(); + /// functions.register_udf(my_udf); + /// let session = lance::session::Session::default().with_datafusion_session(functions); + /// let db = lancedb::connect("data/db") + /// .session(Arc::new(session)) + /// .execute() + /// .await?; + /// let table = db.open_table("t").execute().await?; + /// table.add_columns().computed("y", "my_udf(x)").execute().await?; + /// table.refresh_column("y").await?; + /// # Ok(()) + /// # } + /// ``` pub fn computed(mut self, name: impl Into, expression: impl Into) -> Self { self.computed.push((name.into(), expression.into())); self @@ -147,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}; @@ -156,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(()) /// # } @@ -183,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(); @@ -265,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() @@ -349,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 d2fdd165b..e243676b8 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; use arrow_schema::{DataType, Field as ArrowField, Fields, Schema as ArrowSchema, SchemaRef}; +use datafusion::execution::context::SessionContext; use datafusion_common::{ScalarValue, tree_node::TreeNode}; use datafusion_expr::Expr; use datafusion_physical_plan::PhysicalExpr; @@ -40,6 +41,8 @@ use serde::{Deserialize, Serialize}; 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}; @@ -59,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. @@ -71,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 { @@ -78,6 +88,7 @@ impl Default for ComputedColumnOptions { Self { auto_refresh_enabled: true, auto_refresh_interval_seconds: None, + auto_refresh_resource_budget: None, } } } @@ -93,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(()) } @@ -110,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) } @@ -117,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() @@ -132,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::>(); @@ -143,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(), @@ -151,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) } } @@ -179,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"; @@ -1640,8 +1677,12 @@ pub(crate) fn plan_function_application( /// /// Paths are compared at their root: a declaration reading `metadata` is /// invalidated by a change to `metadata.age` just as surely. -pub(crate) fn ensure_not_an_input(schema: &SchemaRef, paths: &[&str]) -> Result<()> { - ensure_not_an_input_of(schema, paths, &[]) +pub(crate) fn ensure_not_an_input( + schema: &SchemaRef, + paths: &[&str], + session: Option<&SessionContext>, +) -> Result<()> { + ensure_not_an_input_of(schema, paths, &[], session) } /// [`ensure_not_an_input`] where `removed` names columns whose own @@ -1651,6 +1692,7 @@ pub(crate) fn ensure_not_an_input_of( schema: &SchemaRef, paths: &[&str], removed: &[&str], + session: Option<&SessionContext>, ) -> Result<()> { // By identity, not spelling: a quoted path names the same column, while // a path *into* one removes no declaration at all. @@ -1668,7 +1710,7 @@ pub(crate) fn ensure_not_an_input_of( // The expression, not stored inputs, is the source of truth; an // expression that no longer parses proves nothing, so refuse. let inputs = match &declaration.kind { - ComputedColumnKind::Sql { expression } => Planner::new(schema.clone()) + ComputedColumnKind::Sql { expression } => session_planner(schema.clone(), session) .parse_expr(expression) .map(|parsed| Planner::column_names_in_expr(&parsed)) .map_err(|e| Error::InvalidInput { @@ -1760,7 +1802,10 @@ pub(crate) fn ensure_batch_writes_no_computed_values( /// Function declaration satisfies the binding contract, and no SQL /// declaration reads another computed column. What passes here is what /// `refresh_column` can execute. -pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<()> { +pub(crate) fn ensure_declarations_are_planned( + schema: &ArrowSchema, + session: Option<&SessionContext>, +) -> Result<()> { let invalid = |message: String| Error::InvalidInput { message }; // A field with any declaration key is a declaration; a partial one is // not "no declaration", it is a broken one. @@ -1794,7 +1839,12 @@ pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<() .filter(|f| f.name() != &column.name) .map(|f| f.as_ref().clone()) .collect(); - let bound = bind(Arc::new(ArrowSchema::new(others)), &column.name, expression)?; + let bound = bind( + Arc::new(ArrowSchema::new(others)), + &column.name, + expression, + session, + )?; if let Some(input) = bound.roots.iter().find(|r| declared.contains(*r)) { return Err(invalid(format!( "computed column '{}' reads computed column '{input}'", @@ -1944,6 +1994,17 @@ pub(crate) struct BoundExpression { pub blob_paths: Vec, /// A directly projected Blob v2 field whose semantics the output inherits. projected_blob_field: Option, + /// Field metadata of the expression's return field, e.g. a function's + /// logical type. + return_metadata: HashMap, +} + +/// Plans against `session`'s functions when given, else Lance's defaults. +fn session_planner(schema: SchemaRef, session: Option<&SessionContext>) -> Planner { + match session { + Some(session) => Planner::new_with_session(schema, session.clone()), + None => Planner::new(schema), + } } fn is_direct_field_projection(expr: &Expr) -> bool { @@ -2089,7 +2150,12 @@ fn referenced_blob_paths(schema: &ArrowSchema, inputs: &[String]) -> Result 0`), /// and the guard protecting the stored SQL has to see every column the text /// names, not just the ones the simplified form still reads. -pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result { +pub(crate) fn bind( + schema: SchemaRef, + column: &str, + expression: &str, + session: Option<&SessionContext>, +) -> Result { let invalid = |message: String| Error::InvalidExpression { column: column.to_string(), message, @@ -2102,7 +2168,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .into_iter() .collect::>(); let parsing_schema = blob_runtime_schema(schema.as_ref(), &all_blob_paths); - let planner = Planner::new(parsing_schema); + let planner = session_planner(parsing_schema, session); let parsed = planner .parse_expr(expression) .map_err(|e| invalid(e.to_string()))?; @@ -2171,22 +2237,22 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .map(|field| field.name().clone()) .collect(); - let runtime_planner = Planner::new(runtime_schema); + let runtime_planner = session_planner(runtime_schema, session); let optimized = runtime_planner .optimize_expr(parsed) .map_err(|e| invalid(e.to_string()))?; - let physical = Planner::new(read_schema.clone()) + let physical = session_planner(read_schema.clone(), session) .create_physical_expr(&optimized) .map_err(|e| invalid(e.to_string()))?; - let data_type = physical - .data_type(read_schema.as_ref()) + let return_field = physical + .return_field(read_schema.as_ref()) .map_err(|e| invalid(e.to_string()))?; Ok(BoundExpression { inputs, roots, physical, - data_type, + data_type: return_field.data_type().clone(), blob_paths: blob_paths .iter() .map(|path| { @@ -2195,6 +2261,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< }) .collect(), projected_blob_field, + return_metadata: return_field.metadata().clone(), }) } @@ -2210,7 +2277,11 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< /// batch may declare `a` and then `b = a + 1` in one commit. Refresh order /// then matters, and refresh enforces it: `b` is refused while `a` still has /// unfilled rows. -fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result> { +fn plan_declarations( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result> { if columns.is_empty() { return Err(Error::InvalidInput { message: "at least one computed column is required".into(), @@ -2225,23 +2296,22 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< return Err(Error::ColumnAlreadyExists { name: name.clone() }); } - let bound = bind(schema.clone(), name, expression)?; + let bound = bind(schema.clone(), name, expression, session)?; // Declared columns start entirely null, so nullability is a property // of the declaration rather than of what the expression yields. let computed_metadata = computed_column_metadata(expression, &bound.inputs); - let field = match bound.projected_blob_field { - Some(source) => { - let mut metadata = source.metadata().clone(); - metadata.retain(|key, _| !is_declaration_key(key)); - metadata.extend(computed_metadata); - source - .with_name(name) - .with_nullable(true) - .with_metadata(metadata) + let projected = match bound.projected_blob_field { + Some(source) => source.with_name(name), + None => { + ArrowField::new(name, bound.data_type, true).with_metadata(bound.return_metadata) } - None => ArrowField::new(name, bound.data_type, true).with_metadata(computed_metadata), }; + // Keep the source's descriptive metadata, not its schema declarations. + let projected = without_declarations(&projected); + let mut metadata = projected.metadata().clone(); + metadata.extend(computed_metadata); + let field = projected.with_nullable(true).with_metadata(metadata); schema = Arc::new(ArrowSchema::new_with_metadata( schema .fields() @@ -2257,8 +2327,12 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< Ok(fields) } -pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result> { - plan_declarations(schema, columns) +pub(crate) fn plan( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result> { + plan_declarations(schema, columns, session) } /// Run the schema-level checks of @@ -2267,6 +2341,11 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result Result Result<()> { +pub fn validate_declarations( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result<()> { ensure_not_function_bound( schema.as_ref(), "schema evolution", columns.iter().map(|(name, _)| name), )?; - plan(schema, columns).map(drop) + plan(schema, columns, session).map(drop) } /// Build the transform that declares `columns` against `schema`. @@ -2302,8 +2385,9 @@ pub fn validate_declarations(schema: SchemaRef, columns: &[(String, String)]) -> pub(crate) fn declare( schema: SchemaRef, columns: &[(String, String)], + session: Option<&SessionContext>, ) -> Result { - let fields = plan_declarations(schema, columns)?; + let fields = plan_declarations(schema, columns, session)?; Ok(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( fields, )))) @@ -2334,9 +2418,10 @@ pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &st /// created. pub(crate) fn admit_create_source( batches: S, + session: Option<&SessionContext>, ) -> Result> { let schema = batches.arrow_schema(); - ensure_declarations_are_planned(&schema)?; + ensure_declarations_are_planned(&schema, session)?; let declared = computed_columns(&schema) .into_iter() .map(|c| c.name) @@ -2483,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. @@ -2496,7 +2704,7 @@ mod tests { )]), )); let declarations = vec![("a".to_string(), "x + 1".to_string())]; - assert!(super::validate_declarations(schema, &declarations).is_err()); + assert!(super::validate_declarations(schema, &declarations, None).is_err()); } #[test] @@ -2588,7 +2796,7 @@ mod tests { } } - use arrow_array::record_batch; + use arrow_array::{RecordBatch, record_batch}; use arrow_schema::{DataType, TimeUnit}; use futures::TryStreamExt; use lance::dataset::ColumnAlteration; @@ -2618,6 +2826,137 @@ mod tests { computed_columns(table.schema().await.unwrap().as_ref()) } + /// Echoes an Int32 and tags its return field, like a function with a + /// logical type. + #[derive(Debug, PartialEq, Eq, Hash)] + struct Tagged(datafusion_expr::Signature); + + impl datafusion_expr::ScalarUDFImpl for Tagged { + fn name(&self) -> &str { + "tagged" + } + + fn signature(&self) -> &datafusion_expr::Signature { + &self.0 + } + + fn return_type(&self, _: &[DataType]) -> datafusion_common::Result { + Ok(DataType::Int32) + } + + fn return_field_from_args( + &self, + _: datafusion_expr::ReturnFieldArgs, + ) -> datafusion_common::Result { + Ok(Arc::new( + ArrowField::new("tagged", DataType::Int32, true) + .with_metadata(HashMap::from([("tag".into(), "yes".into())])), + )) + } + + fn invoke_with_args( + &self, + args: datafusion_expr::ScalarFunctionArgs, + ) -> datafusion_common::Result { + Ok(args.args[0].clone()) + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_declarations_plan_against_the_session_functions() { + let functions = SessionContext::new(); + functions.register_udf(datafusion_expr::ScalarUDF::new_from_impl(Tagged( + datafusion_expr::Signature::exact( + vec![DataType::Int32], + datafusion_expr::Volatility::Immutable, + ), + ))); + let session = + Arc::new(lance::session::Session::default().with_datafusion_session(functions)); + let conn = connect("memory://") + .session(session) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1, 2, 3]), ("y", Int32, [4, 5, 6])).unwrap(); + let table = conn + .create_table("session_functions", batch) + .execute() + .await + .unwrap(); + + add_computed(&table, &[("t".into(), "tagged(x)".into())]) + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + assert_eq!( + schema.field_with_name("t").unwrap().metadata().get("tag"), + Some(&"yes".to_string()) + ); + table.refresh_column("t").await.unwrap(); + // Dropping a column re-plans every declaration on the table. + table.drop_columns(&["y"]).await.unwrap(); + + let batches = table + .query() + .select(Select::columns(&["t"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let expected = record_batch!(("t", Int32, [1, 2, 3])).unwrap(); + assert_eq!(batches[0].column(0).as_ref(), expected.column(0).as_ref()); + + let plain = table_with_ints("no_session").await; + let err = add_computed(&plain, &[("t".into(), "tagged(x)".into())]) + .await + .unwrap_err(); + assert!(err.to_string().contains("tagged"), "{err}"); + } + + /// A projection keeps its source's descriptive metadata, not its schema + /// declarations: a copy of the primary key is not a primary key. + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_projecting_the_primary_key_drops_its_declaration() { + let conn = connect("memory://").execute().await.unwrap(); + let ints = record_batch!(("x", Int32, [1, 2, 3])).unwrap(); + let schema = ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, false) + .with_metadata(HashMap::from([("note".into(), "kept".into())])), + ]); + let batch = RecordBatch::try_new(Arc::new(schema), ints.columns().to_vec()).unwrap(); + let table = conn + .create_table("key_projection", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + + add_computed(&table, &[("copy".into(), "x".into())]) + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + let copy = schema.field_with_name("copy").unwrap(); + assert!( + !copy + .metadata() + .keys() + .any(|key| key.starts_with("lance-schema:")), + "{copy:?}" + ); + assert_eq!(copy.metadata().get("note"), Some(&"kept".to_string())); + } + #[tokio::test] #[cfg_attr( not(feature = "experimental-functions"), @@ -2658,6 +2997,7 @@ mod tests { ("first".to_string(), "image".to_string()), ("second".to_string(), "first".to_string()), ], + None, ) .unwrap(); @@ -2680,6 +3020,7 @@ mod tests { let fields = plan( schema, &[("payload".to_string(), "coalesce(image, image)".to_string())], + None, ) .unwrap(); @@ -2914,7 +3255,8 @@ mod tests { assert!( validate_declarations( table.schema().await.unwrap(), - &[("e".into(), "random()".into())] + &[("e".into(), "random()".into())], + None, ) .is_err() ); @@ -4794,7 +5136,7 @@ mod tests { let schema = declare_plan(&schema, &downstream, "fb_downstream"); ensure_supported_function_metadata(&schema).unwrap(); - ensure_declarations_are_planned(&schema).unwrap(); + ensure_declarations_are_planned(&schema, None).unwrap(); let bindings = function_bindings(&schema).unwrap(); assert!( computed_function_inputs(&schema, &bindings[0]) @@ -4859,7 +5201,7 @@ mod tests { let base = ArrowSchema::new(vec![ArrowField::new("x", DataType::Int32, true)]); let mut fields = base.fields().to_vec(); fields.extend( - plan(Arc::new(base), &[("doubled".into(), "x * 2".into())]) + plan(Arc::new(base), &[("doubled".into(), "x * 2".into())], None) .unwrap() .into_iter() .map(Arc::new), @@ -4878,7 +5220,7 @@ mod tests { .is_none_or(|metadata| !metadata.keys().any(|key| is_declaration_key(key))) ); let schema = Arc::new(declare_plan(&schema, &downstream, "fb_downstream")); - ensure_declarations_are_planned(&schema).unwrap(); + ensure_declarations_are_planned(&schema, None).unwrap(); let batch = RecordBatch::try_new( schema, vec![ diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 021abe5a9..194401e58 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -25,10 +25,11 @@ 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 +41,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}; @@ -738,12 +740,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()); + } } } } @@ -820,6 +824,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, @@ -1174,13 +1182,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,6 +1216,7 @@ pub async fn staleness_against( recompute_all: false, dirty, row_dirty, + pending_fill, inherited, }) } @@ -1263,18 +1288,302 @@ 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 { + 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 +1600,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() @@ -1359,7 +1671,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 +1682,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?, @@ -1741,6 +2060,746 @@ 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(), + )) + as Box) + .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(), + )) + as Box) + .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(), + )) + as Box) + .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(), + )) + as Box) + .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 { diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index f6063e8ca..228ba2cdd 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -428,6 +428,10 @@ pub(crate) async fn execute_merge_insert( let collect_threshold_bytes = params .source_collect_threshold_bytes .unwrap_or(DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES); + let rescannable = new_data.rescannable(); + let source_plan = merge_source_plan(new_data, cast_schema)?; + let source_schema = source_plan.schema(); + let on = params.on.clone(); let mut builder = LanceMergeInsertBuilder::try_new(dataset.clone(), params.on)?; match ( params.when_matched_update_all, @@ -468,7 +472,7 @@ pub(crate) async fn execute_merge_insert( // Reading the source used to happen inside `execute`, so collecting it // stays under the same timeout. let future = async move { - match prepare_merge_source(new_data, cast_schema, collect_threshold_bytes).await? { + match prepare_merge_plan(source_plan, rescannable, collect_threshold_bytes).await? { MergeSource::Provider(provider) => job.execute_provider(provider).await, MergeSource::Batches(batches) => job.execute_batches(batches).await, } @@ -485,8 +489,21 @@ pub(crate) async fn execute_merge_insert( Either::Right(future) }; 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, @@ -523,6 +540,18 @@ fn merge_source_plan( } } +/// Plan `source` with [`merge_source_plan`] and prepare it with [`prepare_merge_plan`]. +#[cfg(test)] +pub(crate) async fn prepare_merge_source( + source: Box, + cast_schema: Option<&arrow_schema::Schema>, + collect_threshold_bytes: usize, +) -> Result { + let rescannable = source.rescannable(); + let plan = merge_source_plan(source, cast_schema)?; + prepare_merge_plan(plan, rescannable, collect_threshold_bytes).await +} + /// Prepare a merge source so the merge join can see its statistics. /// /// * A rescannable source becomes a provider reporting its exact row count. @@ -532,14 +561,13 @@ fn merge_source_plan( /// spilled so retries can replay it, and reported with the prefix row count /// as a lower bound. /// -/// When `cast_schema` is set, the source is cast to it on every scan. -pub(crate) async fn prepare_merge_source( - source: Box, - cast_schema: Option<&arrow_schema::Schema>, +/// `plan` comes from [`merge_source_plan`], and `rescannable` from the source it +/// was planned from. +async fn prepare_merge_plan( + plan: Arc, + rescannable: bool, collect_threshold_bytes: usize, ) -> Result { - let rescannable = source.rescannable(); - let plan = merge_source_plan(source, cast_schema)?; if rescannable { return Ok(MergeSource::Provider(Arc::new(ScannableProvider::new( plan, diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 6191c60db..8856372c8 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,24 @@ 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. + /// Actual publication boundaries can be larger than this threshold because + /// they also depend on completed work and Function batching. LanceDB Embedded + /// 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 @@ -174,6 +241,29 @@ 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 { + self.publication_interval_rows = Some(rows); + 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()); @@ -201,6 +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)) @@ -253,6 +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)?; } @@ -308,6 +422,7 @@ async fn execute_refresh_column_with_source( schema.clone(), column, &expression, + dataset.session().datafusion_session(), )?); ensure_inputs_filled(&dataset, &schema, column, &bound).await?; let field = dataset @@ -490,7 +605,12 @@ async fn ensure_inputs_filled( ), }); }; - let input_bound = super::computed_columns::bind(schema.clone(), input, expression)?; + let input_bound = super::computed_columns::bind( + schema.clone(), + input, + expression, + dataset.session().datafusion_session(), + )?; let mut unfilled = 0u64; for fragment in dataset.get_fragments() { unfilled += count_fragment_gains(dataset, &fragment, &input_bound, input) diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index db4d6b91f..ab872c7fc 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -166,7 +166,9 @@ pub(crate) async fn execute_declare( .into(), }); } - let transform = computed_columns::declare(table.schema().await?, columns)?; + let session = table.dataset.get().await?.session(); + let transform = + computed_columns::declare(table.schema().await?, columns, session.datafusion_session())?; let NewColumnTransform::AllNulls(schema) = transform else { unreachable!("declarations are all-null") }; @@ -307,7 +309,11 @@ pub(crate) async fn execute_alter_columns( .filter(|alteration| alteration.rename.is_some() || alteration.data_type.is_some()) .map(|alteration| alteration.path.as_str()) .collect::>(); - computed_columns::ensure_not_an_input(&schema, &rebinding)?; + computed_columns::ensure_not_an_input( + &schema, + &rebinding, + dataset.session().datafusion_session(), + )?; let retyped = alterations .iter() .filter(|alteration| alteration.data_type.is_some()) @@ -344,7 +350,12 @@ pub(crate) async fn execute_drop_columns( let dropped = names.iter().map(String::as_str).collect::>(); ensure_not_embedding_column(&schema, "drop", dropped.iter().copied())?; computed_columns::ensure_not_bound_by(&unbinding.retained, "schema evolution", &dropped)?; - computed_columns::ensure_not_an_input_of(&schema, &dropped, &dropped)?; + computed_columns::ensure_not_an_input_of( + &schema, + &dropped, + &dropped, + dataset.session().datafusion_session(), + )?; if !unbinding.is_noop() { // The retirement commits before the projection, so the whole 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",