diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml
index e83c8d29f..4d28ca4a1 100644
--- a/.github/workflows/nodejs.yml
+++ b/.github/workflows/nodejs.yml
@@ -234,7 +234,8 @@ jobs:
NODE_OPTIONS: "--experimental-vm-modules"
run: node_modules/.bin/jest --verbose
macos:
- timeout-minutes: 30
+ # Cold native builds can take 28 minutes; reserve time for setup and Jest.
+ timeout-minutes: 35
# macos-15 ships a newer linker; the older macos-14 linker fails to insert
# branch islands when the debug cdylib's __text section exceeds the 128 MB
# AArch64 B/BL branch range.
@@ -257,7 +258,11 @@ jobs:
node-version: 24
cache: 'pnpm'
cache-dependency-path: nodejs/pnpm-lock.yaml
- - uses: dtolnay/rust-toolchain@stable
+ # Use the same pinned compiler for cache selection and the native build.
+ - uses: actions-rust-lang/setup-rust-toolchain@v1
+ with:
+ cache: false
+ rustflags: ""
- uses: Swatinem/rust-cache@v2
with:
# Restore everywhere, but only save from main. Per-PR saves are
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
index 4c275240f..9bbc4d581 100644
--- a/.github/workflows/rust.yml
+++ b/.github/workflows/rust.yml
@@ -291,8 +291,6 @@ jobs:
sudo apt update
sudo apt install -y protobuf-compiler libssl-dev
- uses: rui314/setup-mold@v1
- - name: Test the default local Functions gate
- run: cargo test --profile ci -p lancedb --features remote --test experimental_functions --locked
- name: Run remote tests
run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests
diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md
index 3150d94ec..f93c1b7cd 100644
--- a/docs/src/js/classes/Table.md
+++ b/docs/src/js/classes/Table.md
@@ -1225,12 +1225,18 @@ LanceDB Enterprise it is the server's backfill job.
`REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
`errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
- `maxConcurrency`, `resourceBudget` and
- `maxExecutorProcessesPerWorker` size registered Function refreshes.
+ `maxConcurrency`, `resourceBudget`, `supervisorResources`,
+ `planningWorkers` and `maxExecutorProcessesPerWorker` size registered
+ Function refreshes. `retryPolicy` overrides user-code retries only when
+ repeating partial work is safe; set `maxAttempts: 1` to disable retries.
`maxConcurrency` overrides the registered default for this logical
execution only and is a positive integer; it is not an account-wide
quota. A `resourceBudget` requires `cpuMillis` and
`memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function.
+ `supervisorResources` and each `planningWorkers.resources` entry require
+ positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`.
+ `planningWorkers` also requires positive `maxWorkers`,
+ `rowsPerWorker` and `fragmentsPerWorker`.
The budget applies only to this explicit refresh and does not configure
a later automatic refresh.
`gpuCount` at the top level is the shorthand that preserves the
diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md
index beed7c8af..23e576877 100644
--- a/docs/src/js/globals.md
+++ b/docs/src/js/globals.md
@@ -103,6 +103,9 @@
- [FunctionErrorRecord](interfaces/FunctionErrorRecord.md)
- [FunctionErrors](interfaces/FunctionErrors.md)
- [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md)
+- [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md)
+- [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md)
+- [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md)
- [FunctionWorkerResourceBudget](interfaces/FunctionWorkerResourceBudget.md)
- [HnswPqOptions](interfaces/HnswPqOptions.md)
- [HnswSqOptions](interfaces/HnswSqOptions.md)
diff --git a/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md b/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md
new file mode 100644
index 000000000..48a8a209d
--- /dev/null
+++ b/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md
@@ -0,0 +1,50 @@
+[**@lancedb/lancedb**](../README.md) • **Docs**
+
+***
+
+[@lancedb/lancedb](../globals.md) / FunctionRefreshPlanningConfig
+
+# Interface: FunctionRefreshPlanningConfig
+
+Resources and sizing policy for the planning fleet of one registered
+Function refresh.
+
+## Properties
+
+### fragmentsPerWorker
+
+```ts
+fragmentsPerWorker: number;
+```
+
+Maximum fragments assigned to one planning worker.
+
+***
+
+### maxWorkers
+
+```ts
+maxWorkers: number;
+```
+
+Maximum number of planning workers.
+
+***
+
+### resources
+
+```ts
+resources: FunctionRefreshPodResources;
+```
+
+CPU, memory, and ephemeral-storage limits for one planning worker.
+
+***
+
+### rowsPerWorker
+
+```ts
+rowsPerWorker: number;
+```
+
+Maximum rows assigned to one planning worker.
diff --git a/docs/src/js/interfaces/FunctionRefreshPodResources.md b/docs/src/js/interfaces/FunctionRefreshPodResources.md
new file mode 100644
index 000000000..99d55512e
--- /dev/null
+++ b/docs/src/js/interfaces/FunctionRefreshPodResources.md
@@ -0,0 +1,40 @@
+[**@lancedb/lancedb**](../README.md) • **Docs**
+
+***
+
+[@lancedb/lancedb](../globals.md) / FunctionRefreshPodResources
+
+# Interface: FunctionRefreshPodResources
+
+CPU, memory, and ephemeral-storage limits for one Function refresh
+control-plane pod.
+
+## Properties
+
+### cpuMillis
+
+```ts
+cpuMillis: number;
+```
+
+CPU limit in millicores; 1000 is one CPU.
+
+***
+
+### ephemeralStorageBytes
+
+```ts
+ephemeralStorageBytes: number;
+```
+
+Ephemeral storage limit in bytes.
+
+***
+
+### memoryBytes
+
+```ts
+memoryBytes: number;
+```
+
+Memory limit in bytes.
diff --git a/docs/src/js/interfaces/FunctionRetryPolicy.md b/docs/src/js/interfaces/FunctionRetryPolicy.md
new file mode 100644
index 000000000..43d4ed8b2
--- /dev/null
+++ b/docs/src/js/interfaces/FunctionRetryPolicy.md
@@ -0,0 +1,91 @@
+[**@lancedb/lancedb**](../README.md) • **Docs**
+
+***
+
+[@lancedb/lancedb](../globals.md) / FunctionRetryPolicy
+
+# Interface: FunctionRetryPolicy
+
+Overrides retries of failed user-code calls for one refresh. Omitted
+fields use the Function refresh defaults.
+
+## Properties
+
+### errorCodes?
+
+```ts
+optional errorCodes: string[];
+```
+
+Structured provider error codes or HTTP status codes.
+
+***
+
+### exceptionTypes?
+
+```ts
+optional exceptionTypes: string[];
+```
+
+Exception class names, preferably qualified.
+
+***
+
+### honorRetryAfter?
+
+```ts
+optional honorRetryAfter: boolean;
+```
+
+Honor Retry-After within the configured maximum.
+
+***
+
+### initialBackoffSeconds?
+
+```ts
+optional initialBackoffSeconds: number;
+```
+
+Initial exponential-backoff ceiling, in seconds.
+
+***
+
+### maxAttempts?
+
+```ts
+optional maxAttempts: number;
+```
+
+Total calls, including the first; 1 disables retries, maximum 100.
+
+***
+
+### maxBackoffSeconds?
+
+```ts
+optional maxBackoffSeconds: number;
+```
+
+Maximum backoff, in seconds.
+
+***
+
+### messagePattern?
+
+```ts
+optional messagePattern: string;
+```
+
+Regular expression matched against the exception class and message.
+
+***
+
+### transient?
+
+```ts
+optional transient: boolean;
+```
+
+Match connection/timeouts, HTTP 429/503, SlowDown and
+ServiceUnavailable.
diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md
index fb9bada29..cd36343b8 100644
--- a/docs/src/js/interfaces/QueryExecutionOptions.md
+++ b/docs/src/js/interfaces/QueryExecutionOptions.md
@@ -29,8 +29,10 @@ Selecting a parent struct or directly aliasing a blob or struct also returns
bytes. Blobs inside lists keep their descriptors. Arbitrary projection
expressions are not materialized as bytes.
-The rows and the bytes come from the same table version. If the table
-changes while the query runs, the query runs again, up to three times.
+The rows and bytes come from the same snapshot. Remote queries require
+authoritative query version and snapshot identity headers, verified again
+by the blob response. Older servers can still return `"descriptions"`.
+Local queries retry up to three times if the table changes while they run.
#### Example
diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md
index c534e0fac..07157e4ab 100644
--- a/docs/src/js/interfaces/RefreshColumnOptions.md
+++ b/docs/src/js/interfaces/RefreshColumnOptions.md
@@ -117,6 +117,16 @@ Worker count for an expression column; Function columns reject it.
***
+### planningWorkers?
+
+```ts
+optional planningWorkers: FunctionRefreshPlanningConfig;
+```
+
+Resources and sizing for the refresh planning fleet.
+
+***
+
### publicationIntervalRows?
```ts
@@ -141,6 +151,16 @@ refresh. `gpuCount` inside the budget defaults to zero.
***
+### retryPolicy?
+
+```ts
+optional retryPolicy: FunctionRetryPolicy;
+```
+
+Override retries of failed user-code calls for this refresh.
+
+***
+
### rowTimeoutSeconds?
```ts
@@ -151,6 +171,16 @@ Deadline for one Function call, in seconds.
***
+### supervisorResources?
+
+```ts
+optional supervisorResources: FunctionRefreshPodResources;
+```
+
+CPU, memory, and ephemeral-storage limits for the refresh supervisor.
+
+***
+
### where?
```ts
diff --git a/docs/src/python/python.md b/docs/src/python/python.md
index 36f47c8f0..5aa21f691 100644
--- a/docs/src/python/python.md
+++ b/docs/src/python/python.md
@@ -578,6 +578,8 @@ with BlobReader(read_range, len(payload)) as reader:
::: lancedb.functions.InputBinding
+::: lancedb.functions.LiteralInputBinding
+
::: lancedb.functions.OutputMapping
::: lancedb.functions.AssignmentMapping
diff --git a/docs/web-tests/py/test_function.py b/docs/web-tests/py/test_function.py
index 147520b18..ff4c6b9a3 100644
--- a/docs/web-tests/py/test_function.py
+++ b/docs/web-tests/py/test_function.py
@@ -154,13 +154,27 @@ def test_function_output_nullability():
("note", True),
]
- # A scalar output, and a struct declared as one nullable field, may not be.
- for nullable in (
- pa.field("result", pa.float64(), nullable=True),
- pa.field("result", pa.struct(fields), nullable=True),
- ):
- with pytest.raises(ValueError, match="non-nullable"):
- function(input_schema=inputs, output_schema=nullable)(describe)
+ # A scalar output may be nullable.
+ @function(input_schema=inputs)
+ def maybe_double(value: float) -> float | None:
+ return None if value == 0 else value * 2
+
+ output = maybe_double.registration_request.signature.output
+ assert (output.kind, output.arrow_type, output.nullable) == (
+ "scalar",
+ "float64",
+ True,
+ )
+ assert json.loads(maybe_double.registration_request.signature.to_canonical_json())[
+ "output"
+ ] == {"kind": "scalar", "arrow_type": "float64", "nullable": True}
+
+ # A struct declared as one nullable field may not be.
+ with pytest.raises(ValueError, match="non-nullable"):
+ function(
+ input_schema=inputs,
+ output_schema=pa.field("result", pa.struct(fields), nullable=True),
+ )(describe)
def test_function_registration_is_remote(tmp_path):
diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx
index 9ee7d572a..0342849b4 100644
--- a/docs/web/curation/create-function.mdx
+++ b/docs/web/curation/create-function.mdx
@@ -295,11 +295,12 @@ extract_frame_version = db.create_function_async(extract_frame).wait(
```
-An empty byte string is a filled result. A scalar output cannot be nullable,
-because a physical NULL marks an unfilled computed row. To return a nullable
-blob as a value, use a named-struct output schema with a nullable blob field;
-the struct itself records whether the result has been filled. Read a nested
-blob with `table.fetch_blobs("payload.image", hits)`.
+An empty byte string is a filled result. A top-level Blob v2 output cannot be
+nullable; to return a nullable blob as a value, use a named-struct output
+schema with a nullable blob field. The struct itself records whether the
+result has been filled. A nullable non-Blob scalar output is declared with
+`Optional[T]` or `T | None`; see [Functions](/management/function#define).
+Read a nested blob with `table.fetch_blobs("payload.image", hits)`.
A list or large-list output may also contain Blob v2 elements; inputs and
fixed-size lists do not support this layout. List-nested values are queryable
diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx
index d82fb1eef..f893118fc 100644
--- a/docs/web/feature-engineering/refresh-column.mdx
+++ b/docs/web/feature-engineering/refresh-column.mdx
@@ -400,6 +400,101 @@ for changing only the aggregate GPU budget. It cannot be combined with the
complete resource budget. Omitting both preserves the server's existing
defaults.
+{/*
+Draft for the Function refresh control-plane resource release.
+
+`resource_budget` above sizes the Function workers. Two independent options
+size the refresh control plane for a registered Function.
+`supervisor_resources` sets the CPU, memory and ephemeral-storage limits of
+the supervisor pod. `planning_workers` sets the resources of one planning
+worker and the sizing of the CPU-only planning fleet: `max_workers`,
+`rows_per_worker` and `fragments_per_worker`. Every field is required and
+must be positive. Omitting either option leaves the server's configured
+defaults unchanged, and either can be combined with `resource_budget`.
+
+
+```python Python icon="python"
+job = table.refresh_column_async(
+ "embedding",
+ supervisor_resources={
+ "cpu_millis": 2_000,
+ "memory_bytes": 4 * 1024**3,
+ "ephemeral_storage_bytes": 10 * 1024**3,
+ },
+ planning_workers={
+ "resources": {
+ "cpu_millis": 1_000,
+ "memory_bytes": 2 * 1024**3,
+ "ephemeral_storage_bytes": 5 * 1024**3,
+ },
+ "max_workers": 4,
+ "rows_per_worker": 100_000,
+ "fragments_per_worker": 8,
+ },
+)
+job.wait()
+```
+
+```rust Rust icon="rust"
+use lancedb::table::{
+ FunctionRefreshPlanningConfig,
+ FunctionRefreshPodResources,
+ RefreshColumnOptions,
+};
+
+let _job = table
+ .refresh_column_async_with_options(
+ "embedding",
+ RefreshColumnOptions::default()
+ .supervisor_resources(
+ FunctionRefreshPodResources::new(
+ 2_000,
+ 4 * 1024 * 1024 * 1024,
+ 10 * 1024 * 1024 * 1024,
+ ),
+ )
+ .planning_workers(
+ FunctionRefreshPlanningConfig::new(
+ FunctionRefreshPodResources::new(
+ 1_000,
+ 2 * 1024 * 1024 * 1024,
+ 5 * 1024 * 1024 * 1024,
+ ),
+ 4,
+ 100_000,
+ 8,
+ ),
+ ),
+ )
+ .await?;
+```
+
+```typescript TypeScript icon="typescript"
+const job = await table.refreshColumnAsync("embedding", {
+ supervisorResources: {
+ cpuMillis: 2_000,
+ memoryBytes: 4 * 1024 ** 3,
+ ephemeralStorageBytes: 10 * 1024 ** 3,
+ },
+ planningWorkers: {
+ resources: {
+ cpuMillis: 1_000,
+ memoryBytes: 2 * 1024 ** 3,
+ ephemeralStorageBytes: 5 * 1024 ** 3,
+ },
+ maxWorkers: 4,
+ rowsPerWorker: 100_000,
+ fragmentsPerWorker: 8,
+ },
+});
+await job.wait();
+```
+
+
+The SDK validates the shape and sends these values only with this explicit
+refresh request. A supporting LanceDB Enterprise server is required.
+*/}
+
These examples configure only the explicit refresh shown. A registered
Function declaration can separately set `auto_refresh_resource_budget` on
`add_columns`; that declaration controls the budget for its automatic
@@ -457,6 +552,39 @@ from `lancedb.functions`. Use `FunctionRetryPolicy(max_attempts=1)` to
disable user-error retries. Omitting the override preserves the registered
policy.
+
+```python Python icon="python"
+from lancedb.functions import FunctionRetryPolicy
+
+job = table.refresh_column_async(
+ "embedding",
+ retry_policy=FunctionRetryPolicy(transient=True, max_attempts=3),
+)
+job.wait()
+```
+
+```rust Rust icon="rust"
+use lancedb::{function::FunctionRetryPolicy, table::RefreshColumnOptions};
+
+let mut retry_policy = FunctionRetryPolicy::transient();
+retry_policy.max_attempts = 3;
+
+let _job = table
+ .refresh_column_async_with_options(
+ "embedding",
+ RefreshColumnOptions::default().retry_policy(retry_policy),
+ )
+ .await?;
+```
+
+```typescript TypeScript icon="typescript"
+const job = await table.refreshColumnAsync("embedding", {
+ retryPolicy: { transient: true, maxAttempts: 3 },
+});
+await job.wait();
+```
+
+
This requires a supporting LanceDB Enterprise server as well as an SDK
that exposes these options. An older Function image may need
re-registration before it accepts a refresh override. Only enable retries
diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx
index 923a71b0e..7633584c6 100644
--- a/docs/web/ingestion/insert.mdx
+++ b/docs/web/ingestion/insert.mdx
@@ -150,9 +150,10 @@ Python and TypeScript report elapsed time in seconds; Rust returns a `Duration`.
The expected row count may be unknown for streaming input. On the final update,
it falls back to the number of rows written.
-For remote multipart writes, rows count input scanning, while bytes count
-acknowledged IPC parts. Bytes start at zero and a retried part is counted once,
-after acknowledgement. Scanned rows and staged bytes do not imply a commit.
+For remote multipart writes, both rows and IPC bytes count acknowledged parts.
+Both start at zero; a retried part is counted once, after acknowledgement.
+Scanning input or sending a rejected part does not advance these counts.
+Acknowledged parts are staged and do not imply a successful commit.
Keep callbacks short and use the write operation's result to determine success.
The final `done` update means progress reporting has ended; it can also occur
diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx
index 27f45cb6a..41e64d482 100644
--- a/docs/web/management/function.mdx
+++ b/docs/web/management/function.mdx
@@ -66,11 +66,43 @@ your process, without the database, so unit tests stay ordinary tests:
Where annotations cannot express the Arrow type precisely, pass `input_schema`
and `output_schema` together: one without the other is rejected. A scalar
-output must be non-nullable, because a physical NULL is what marks a
-computed-column row as unfilled. A named-struct output may declare nullable
-fields: whether a row has a result at all is the struct's own validity, which
-Enterprise keeps in a separate internal column when it expands the result into
-sibling columns, so a null field is a value rather than a missing row.
+output is non-nullable by default. Annotate the return as `Optional[T]` or
+`T | None`, or pass a nullable output field, to declare a nullable scalar:
+
+```python
+import pyarrow as pa
+
+from lancedb import function
+
+
+@function(
+ input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
+ output_schema=pa.field("result", pa.int64(), nullable=True),
+)
+def maybe_double(value: int) -> int | None:
+ return None if value == 0 else value * 2
+```
+
+The signature sent in the registration request then carries the nullable
+scalar:
+
+```json
+{
+ "inputs": [{"name": "value", "arrow_type": "int64", "nullable": false}],
+ "output": {"kind": "scalar", "arrow_type": "int64", "nullable": true}
+}
+```
+
+
+Nullable scalar outputs require an Enterprise server that supports them;
+older servers reject the registration. On a supporting server, a computed
+`NULL` counts as a filled result, independently of its stored value.
+
+
+A named-struct output may declare nullable fields: whether a row has a result
+at all is the struct's own validity, which Enterprise keeps in a separate
+internal column when it expands the result into sibling columns, so a null
+field is a value rather than a missing row.
## Connect and create a table {#table}
@@ -213,6 +245,52 @@ function application keeps its scalar or named-struct result in the named
column. A bare named-struct application expands its result fields as one atomic
binding, with aliases from `rename(columns=...)`.
+{/* Draft for the Function literal binding release.
+
+### Bind a constant input {#literal-inputs}
+
+
+Literal inputs require an SDK that supports binding metadata version 2 and an
+Enterprise deployment with matching literal declaration and execution support.
+Upgrading the SDK alone does not enable this server capability. Older clients
+reject version 2 bindings; column-only bindings continue to use version 1.
+
+
+Use `lit(...)` to pass the same value for every row while another parameter
+reads a column. For example, using the table above:
+
+
+```python Python icon="python"
+from lancedb import col, function, lit
+
+
+@function
+def multiply(value: float, factor: int) -> float:
+ return value * factor
+
+
+multiplier = db.create_function_async(multiply).wait()
+table.add_columns(
+ {"scaled": multiplier(value=col("value"), factor=lit(16))},
+ auto_refresh_enabled=False,
+)
+```
+
+
+Supported scalar constants are booleans, strings, integers from `-(2**63)`
+through `2**64 - 1`, and `None` for a nullable parameter. Each value must match
+the parameter's declared type. Floating-point, binary, date, datetime and
+decimal constants are not supported in Function input bindings, even though
+`lit(...)` accepts them in other SQL expressions. Bind a direct literal;
+expressions such as `lit(16) + lit(8)` are not supported here.
+
+The constant belongs to the column binding, so the Function version and its
+image stay the same. Only column inputs contribute table dependencies. Refresh
+`scaled` to fill it. To change the constant to `lit(8)`, drop and redeclare the
+column using the same `multiplier` version; the new binding needs a refresh.
+
+*/}
+
### Bind more than one input, or fill more than one column {#multi}
Parameters bind by name, so a function that takes several arguments binds
diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx
index 8031a4c49..facb9bdfe 100644
--- a/docs/web/management/table.mdx
+++ b/docs/web/management/table.mdx
@@ -720,6 +720,25 @@ table changes while the query runs, the query runs again, up to three times:
+{/* Draft for the Enterprise TypeScript bytes release. Replace the retry guidance above only after SDK and serving-node rollout.
+
+Local queries retry up to three times if the table changes while they run.
+Remote queries instead bind payload fetches to the version and immutable
+snapshot identity from the executed query response. They do not rerun the query
+against a newer version to recover missing payloads. Both `toArray()` and
+`toArrow()` discover Blob fields from that response, including fields added
+after the table handle was opened.
+
+Every serving node must support `x-lancedb-query-version` and
+`x-lancedb-query-snapshot`, enforce the requested identity when fetching bytes,
+and echo it in the fetch response. Proxies must forward these headers. Missing
+or mismatched provenance fails explicitly; use `blobMode: "descriptions"` until
+the rollout is complete. Keep queried versions available for deferred reads:
+snapshot identities do not prevent version deletion. Dropping and recreating a
+table cannot substitute the replacement's bytes, even if its version is reused.
+Hybrid byte queries require matching snapshot provenance from both responses.
+*/}
+
#### Read blobs on demand {#multimodal-read-blobs}
Query the rows you want and pass their `_rowid` values to a fetch method.
diff --git a/nodejs/__test__/blob_ranges.test.ts b/nodejs/__test__/blob_ranges.test.ts
index 7d2fab566..9e7b0e53d 100644
--- a/nodejs/__test__/blob_ranges.test.ts
+++ b/nodejs/__test__/blob_ranges.test.ts
@@ -51,9 +51,10 @@ async function withRangeServer(
run: (db: Connection, calls: Request[], paths: string[]) => Promise,
fault?: string | number,
capability: string | null = "1",
- onStall?: () => void,
+ onStall?: (response: http.ServerResponse) => void,
) {
let takes = 0;
+ let rangeReads = 0;
const calls: Request[] = [];
const paths: string[] = [];
const server = http.createServer((req, res) => {
@@ -91,13 +92,18 @@ async function withRangeServer(
expect(url.searchParams.get("version")).toBe("3");
const [start, end] = req.headers.range!.slice(6).split("-").map(Number);
const bytes = Buffer.from("alpha").subarray(start, end + 1);
- res
- .writeHead(206, {
- "Content-Range": `bytes ${start}-${end}/5`,
- "Content-Length": bytes.length,
- "x-lancedb-version": "3",
- })
- .end(bytes);
+ res.writeHead(206, {
+ "Content-Range": `bytes ${start}-${end}/5`,
+ "Content-Length": bytes.length,
+ "x-lancedb-version": "3",
+ });
+ if (fault === "stall-read" && ++rangeReads === 1) {
+ // Withhold the rest of the body so native completion cannot win the abort.
+ res.write(bytes.subarray(0, 1));
+ onStall?.(res);
+ return;
+ }
+ res.end(bytes);
return;
}
expect(req.method).toBe("POST");
@@ -191,7 +197,7 @@ async function withRangeServer(
"x-lancedb-query-snapshot": IDENTITY,
});
res.flushHeaders();
- onStall?.();
+ onStall?.(res);
return;
}
if (typeof failure === "number") {
@@ -327,6 +333,55 @@ describe("fetchBlobRanges", () => {
});
});
+ it("cancels an in-flight BlobFile read and leaves the handle usable", async () => {
+ let responseTimedOut = false;
+ let markStalled!: () => void;
+ const stalled = new Promise((resolve) => {
+ markStalled = resolve;
+ });
+ let markDisconnected!: () => void;
+ const disconnected = new Promise((resolve) => {
+ markDisconnected = resolve;
+ });
+ await withRangeServer(
+ async (db) => {
+ const table = await open(db, 3);
+ const [handle] = await table.fetchBlobFiles("image", [10n]);
+ const controller = new AbortController();
+ try {
+ const pending = handle!.readRange(0n, handle!.size(), {
+ signal: controller.signal,
+ });
+ const rejected = expect(pending).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ await stalled;
+ controller.abort();
+ await rejected;
+ await disconnected;
+ expect(responseTimedOut).toBe(false);
+ expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
+ expect(handle!.isClosed()).toBe(false);
+ expect(await handle!.tell()).toBe(0n);
+ // The single request permit must also be released by cancellation.
+ expect(await handle!.readRange(0n, 5n)).toEqual(Buffer.from("alpha"));
+ } finally {
+ controller.abort();
+ await handle!.close();
+ }
+ },
+ "stall-read",
+ null,
+ (response) => {
+ response.once("timeout", () => {
+ responseTimedOut = true;
+ });
+ response.once("close", markDisconnected);
+ markStalled();
+ },
+ );
+ });
+
it("cancels while waiting for a later response body and releases the only permit", async () => {
let markStalled!: () => void;
const stalled = new Promise((resolve) => {
diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts
index a9989b84e..3e8d5a79b 100644
--- a/nodejs/__test__/remote.test.ts
+++ b/nodejs/__test__/remote.test.ts
@@ -979,6 +979,42 @@ describe("remote connection", () => {
},
"resourceBudget.gpuCount",
],
+ [
+ {
+ supervisorResources: {
+ cpuMillis: 0,
+ memoryBytes: 1_024,
+ ephemeralStorageBytes: 2_048,
+ },
+ },
+ "supervisorResources.cpuMillis",
+ ],
+ [
+ {
+ supervisorResources: {
+ cpuMillis: 1_000,
+ memoryBytes: 1_024,
+ ephemeralStorageBytes: 0,
+ },
+ },
+ "supervisorResources.ephemeralStorageBytes",
+ ],
+ [
+ {
+ planningWorkers: {
+ resources: {
+ cpuMillis: 1_000,
+ memoryBytes: 1_024,
+ ephemeralStorageBytes: 2_048,
+ },
+ maxWorkers: 0,
+ rowsPerWorker: 100,
+ fragmentsPerWorker: 1,
+ },
+ },
+ "planningWorkers.maxWorkers",
+ ],
+ [{ retryPolicy: { maxAttempts: 0 } }, "retry_policy.max_attempts"],
] as const) {
await expect(
table.refreshColumnAsync("embedding", options),
@@ -1016,6 +1052,91 @@ describe("remote connection", () => {
]);
});
+ it("forwards structured Function refresh options and Node retry policy", async () => {
+ const bodies: unknown[] = [];
+ await withMockDatabase(
+ (req, res) => {
+ const path = req.url ?? "";
+ if (path.endsWith("/describe/")) {
+ res.writeHead(200, { "Content-Type": "application/json" }).end(
+ JSON.stringify({
+ name: "docs",
+ version: 1,
+ schema: { fields: [] },
+ }),
+ );
+ return;
+ }
+ if (path === "/v1/table/docs/backfill_column") {
+ let body = "";
+ req.on("data", (chunk) => {
+ body += chunk;
+ });
+ req.on("end", () => {
+ bodies.push(JSON.parse(body));
+ res
+ .writeHead(202, { "Content-Type": "application/json" })
+ .end('{"job_id": "j-structured"}');
+ });
+ return;
+ }
+ res.writeHead(404).end();
+ },
+ async (db) => {
+ const table = await db.openTable("docs");
+ const job = await table.refreshColumnAsync("embedding", {
+ supervisorResources: {
+ cpuMillis: 2_000,
+ memoryBytes: 4 * 1024 ** 3,
+ ephemeralStorageBytes: 10 * 1024 ** 3,
+ },
+ planningWorkers: {
+ resources: {
+ cpuMillis: 1_000,
+ memoryBytes: 2 * 1024 ** 3,
+ ephemeralStorageBytes: 5 * 1024 ** 3,
+ },
+ maxWorkers: 4,
+ rowsPerWorker: 100_000,
+ fragmentsPerWorker: 8,
+ },
+ retryPolicy: { transient: true },
+ });
+ expect(job.id).toBe("j-structured");
+ },
+ );
+ expect(bodies).toEqual([
+ {
+ column: "embedding",
+ ["supervisor_resources"]: {
+ ["cpu_millis"]: 2_000,
+ ["memory_bytes"]: 4 * 1024 ** 3,
+ ["ephemeral_storage_bytes"]: 10 * 1024 ** 3,
+ },
+ ["planning_workers"]: {
+ resources: {
+ ["cpu_millis"]: 1_000,
+ ["memory_bytes"]: 2 * 1024 ** 3,
+ ["ephemeral_storage_bytes"]: 5 * 1024 ** 3,
+ },
+ ["max_workers"]: 4,
+ ["rows_per_worker"]: 100_000,
+ ["fragments_per_worker"]: 8,
+ },
+ ["retry_policy"]: {
+ ["max_attempts"]: 3,
+ ["initial_backoff_seconds"]: 0.2,
+ ["max_backoff_seconds"]: 30,
+ ["exception_types"]: [],
+ ["message_pattern"]: null,
+ ["error_codes"]: [],
+ transient: true,
+ ["honor_retry_after"]: true,
+ },
+ },
+ ]);
+ });
+
it("surfaces JSON server errors from remote table operations", async () => {
await withMockDatabase(
(req, res) => {
diff --git a/nodejs/__test__/remote_blob_snapshot.test.ts b/nodejs/__test__/remote_blob_snapshot.test.ts
new file mode 100644
index 000000000..908dfa9de
--- /dev/null
+++ b/nodejs/__test__/remote_blob_snapshot.test.ts
@@ -0,0 +1,642 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright The LanceDB Authors
+
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { type Table, connect } from "../lancedb";
+import {
+ Table as ArrowTable,
+ DataType,
+ Field,
+ Float32,
+ LargeBinary,
+ RecordBatch,
+ Schema,
+ Struct,
+ Uint8,
+ Uint32,
+ Uint64,
+ Utf8,
+ makeArrowTable,
+ tableToIPC,
+ vectorFromArray,
+} from "../lancedb/arrow";
+
+const IDENTITY_A = `v1:${"a".repeat(64)}`;
+const IDENTITY_B = `v1:${"b".repeat(64)}`;
+const image = new Field(
+ "image",
+ new Struct([
+ new Field("kind", new Uint8(), false),
+ new Field("position", new Uint64(), true),
+ new Field("size", new Uint64(), true),
+ new Field("blob_id", new Uint32(), false),
+ new Field("blob_uri", new Utf8(), false),
+ ]),
+ true,
+ // Native descriptor scans replace the logical extension metadata.
+ new Map([
+ ["lance-encoding:blob", "true"],
+ ["lance-encoding:packed", "true"],
+ ]),
+);
+const schema = new Schema([new Field("label", new Utf8(), false), image]);
+const description = {
+ fields: [
+ { name: "label", type: { type: "string" }, nullable: false },
+ {
+ name: "image",
+ nullable: true,
+ metadata: { "ARROW:extension:name": "lance.blob.v2" },
+ type: {
+ type: "struct",
+ fields: ["position", "size"].map((name) => ({
+ name,
+ type: { type: "uint64" },
+ nullable: true,
+ })),
+ },
+ },
+ ],
+};
+
+type Request = {
+ path: string;
+ body: Record;
+ raw: string;
+ identity: string | string[] | undefined;
+};
+
+interface ServerOptions {
+ queryBlob?: Field;
+ describeBlobName?: string | null;
+ nestedBlob?: boolean;
+ queryVersion?: string | null;
+ queryIdentity?: string | null;
+ echo?: string | null;
+ empty?: boolean;
+ values?: boolean;
+ advanceQueries?: boolean;
+ otherLegIdentity?: string | null;
+ otherLegVersion?: string;
+}
+
+// A real HTTP service: the query finishes on A, then the logical table changes
+// before the deferred blob request. Recreating B reuses both version and row IDs.
+async function withSnapshotServer(
+ change: "recreate" | "overwrite",
+ run: (table: Table, requests: Request[]) => Promise,
+ options: ServerOptions = {},
+) {
+ const requests: Request[] = [];
+ let changed = false;
+ const queryBlob = options.queryBlob ?? image;
+ const queryOutputSchema = options.nestedBlob
+ ? new Schema([
+ schema.fields[0],
+ new Field("extra", new Struct([queryBlob]), true),
+ ])
+ : new Schema([schema.fields[0], queryBlob]);
+ const server = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (chunk) => chunks.push(chunk));
+ req.on("end", () => {
+ try {
+ const raw = Buffer.concat(chunks).toString() || "{}";
+ const body = JSON.parse(raw);
+ const path = req.url ?? "";
+ const identity = req.headers["x-lancedb-query-snapshot"];
+ requests.push({ path, body, raw, identity });
+ res.setHeader("phalanx-version", "0.5.0");
+ if (path.endsWith("/describe/")) {
+ res.setHeader("content-type", "application/json");
+ res.end(
+ JSON.stringify({
+ version: changed && change === "overwrite" ? 2 : 1,
+ schema: {
+ fields: description.fields.flatMap((field) => {
+ if (field.name !== "image") return [field];
+ if (options.describeBlobName === null) return [];
+ return [
+ { ...field, name: options.describeBlobName ?? "image" },
+ ];
+ }),
+ },
+ }),
+ );
+ } else if (path.endsWith("/query/")) {
+ const vector = (body.vector?.length ?? 0) > 0;
+ const advanced = options.advanceQueries === true && changed;
+ const label = advanced ? "B" : "A";
+ const columns: [string, string][] =
+ body.columns === undefined
+ ? queryOutputSchema.fields.map((field) => [
+ field.name,
+ field.name,
+ ])
+ : Array.isArray(body.columns)
+ ? body.columns.map((name: string) => [name, name])
+ : Object.entries(body.columns);
+ const queryFields = columns.map(([output, source]) =>
+ queryOutputSchema.fields
+ .find((field) => field.name === source)!
+ .clone({ name: output }),
+ );
+ if (body.with_row_id) {
+ queryFields.push(new Field("_rowid", new Uint64(), false));
+ }
+ if (vector || body.full_text_query) {
+ queryFields.push(
+ new Field(vector ? "_distance" : "_score", new Float32(), false),
+ );
+ }
+ // Forged IPC metadata must never substitute for authoritative headers.
+ const querySchema = new Schema(
+ queryFields,
+ new Map([
+ ["lancedb:query_version", "999"],
+ ["lancedb:query_snapshot", IDENTITY_B],
+ ]),
+ );
+ const values = options.empty
+ ? []
+ : options.values
+ ? ["A", null, ""]
+ : [label];
+ const rows = values.map((value, index) => {
+ const row: Record = {};
+ for (const [output, source] of columns) {
+ const descriptor =
+ value === null
+ ? null
+ : {
+ kind: 0,
+ position: 0n,
+ size: BigInt(value.length),
+ // biome-ignore lint/style/useNamingConvention: Native Arrow field name.
+ blob_id: 0,
+ // biome-ignore lint/style/useNamingConvention: Native Arrow field name.
+ blob_uri: "",
+ };
+ row[output] =
+ source === "image"
+ ? descriptor
+ : source === "extra"
+ ? descriptor === null
+ ? null
+ : { image: descriptor }
+ : label;
+ }
+ if (body.with_row_id) row._rowid = BigInt(index);
+ if (vector || body.full_text_query) {
+ row[vector ? "_distance" : "_score"] = 0.5;
+ }
+ return row;
+ });
+ const result =
+ rows.length === 0
+ ? new ArrowTable(querySchema)
+ : new ArrowTable(
+ querySchema,
+ Object.fromEntries(
+ queryFields.map((field) => [
+ field.name,
+ vectorFromArray(
+ rows.map((row) => row[field.name]),
+ field.type,
+ ),
+ ]),
+ ),
+ );
+ res.setHeader("content-type", "application/vnd.apache.arrow.stream");
+ const version =
+ vector && options.otherLegVersion !== undefined
+ ? options.otherLegVersion
+ : options.queryVersion;
+ const snapshot =
+ vector && options.otherLegIdentity !== undefined
+ ? options.otherLegIdentity
+ : options.queryIdentity;
+ res.setHeader("x-lancedb-version", "1");
+ if (version !== null) {
+ res.setHeader(
+ "x-lancedb-query-version",
+ version ?? (advanced ? "2" : "1"),
+ );
+ }
+ if (snapshot !== null) {
+ res.setHeader(
+ "x-lancedb-query-snapshot",
+ snapshot ?? (advanced ? IDENTITY_B : IDENTITY_A),
+ );
+ }
+ changed = true;
+ res.end(tableToIPC(result, "stream"));
+ } else if (path.endsWith("/fetch_blobs/")) {
+ const requestedVersion = /"version":([0-9]+)/.exec(raw)?.[1];
+ const readsOriginal =
+ change === "overwrite" &&
+ requestedVersion === (options.queryVersion ?? "1");
+ const actualIdentity = readsOriginal ? IDENTITY_A : IDENTITY_B;
+ // An older serving node may ignore the guard and answer successfully;
+ // its echo must still be verified before the client uses any bytes.
+ if (options.echo !== null) {
+ res.setHeader(
+ "x-lancedb-query-snapshot",
+ options.echo ?? actualIdentity,
+ );
+ }
+ res.setHeader("content-type", "application/vnd.apache.arrow.stream");
+ const payloads = options.values
+ ? ["A", null, ""]
+ : [readsOriginal ? "A" : "B"];
+ res.end(
+ tableToIPC(
+ makeArrowTable(
+ (body.row_ids as number[]).map((id) => ({
+ [String(body.column)]:
+ payloads[id] === null ? null : Buffer.from(payloads[id]!),
+ })),
+ {
+ schema: new Schema([
+ new Field(String(body.column), new LargeBinary(), true),
+ ]),
+ },
+ ),
+ "stream",
+ ),
+ );
+ } else {
+ res.writeHead(404).end(path);
+ }
+ } catch (error) {
+ res.writeHead(500).end(String(error));
+ }
+ });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const db = await connect("db://dev", {
+ apiKey: "fake",
+ hostOverride: `http://127.0.0.1:${
+ (server.address() as AddressInfo).port
+ }`,
+ });
+ await run(await db.openTable("test"), requests);
+ } finally {
+ server.closeAllConnections();
+ await new Promise((resolve) => server.close(() => resolve()));
+ }
+}
+
+const fetchRequests = (requests: Request[]) =>
+ requests.filter((request) => request.path.endsWith("/fetch_blobs/"));
+const queryRequests = (requests: Request[]) =>
+ requests.filter((request) => request.path.endsWith("/query/"));
+
+const keepFtsReranker = {
+ async rerankHybrid(_query: string, _vector: RecordBatch, fts: RecordBatch) {
+ const fields = fts.schema.fields.map((field) =>
+ field.name === "_score"
+ ? field.clone({ name: "_relevance_score" })
+ : field,
+ );
+ return new RecordBatch(
+ new Schema(fields, fts.schema.metadata),
+ fts.data.clone(new Struct(fields)),
+ );
+ },
+};
+
+describe("remote blob query snapshot", () => {
+ it.each([
+ image.clone({ metadata: new Map() }),
+ new Field(
+ "image",
+ new Struct(image.type.children.slice(1, 3)),
+ true,
+ image.metadata,
+ ),
+ ])(
+ "leaves plain structs and v1 descriptors unchanged: %s",
+ async (queryBlob) => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const result = await table.query().toArrow({ blobMode: "bytes" });
+ expect(DataType.isStruct(result.getChild("image")!.type)).toBe(true);
+ expect(result.toArray()[0].image.size).toBe(1n);
+ expect(fetchRequests(requests)).toHaveLength(0);
+ },
+ { queryBlob },
+ );
+ },
+ );
+
+ it("still recognizes extension-marked Blob results", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const rows = await table.query().toArray({ blobMode: "bytes" });
+ expect(Buffer.from(rows[0].image).toString()).toBe("A");
+ expect(fetchRequests(requests)).toHaveLength(1);
+ },
+ {
+ queryBlob: image.clone({
+ metadata: new Map([["ARROW:extension:name", "lance.blob.v2"]]),
+ }),
+ },
+ );
+ });
+
+ it.each([
+ [null, false],
+ [null, true],
+ ["old_image", false],
+ ["old_image", true],
+ ] as const)(
+ "uses the query schema after cached blob %s changes (alias: %s)",
+ async (describeBlobName, alias) => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ expect(await table.blobColumns()).toEqual(
+ describeBlobName === null ? [] : [describeBlobName],
+ );
+ const query = table.query();
+ if (alias) query.select({ "photo.image": "image" });
+ const output = alias ? "photo.image" : "image";
+ const result = await query.toArrow({ blobMode: "bytes" });
+ expect(DataType.isLargeBinary(result.getChild(output)!.type)).toBe(
+ true,
+ );
+ expect(
+ result
+ .toArray()
+ .map((row) =>
+ row[output] === null
+ ? null
+ : Buffer.from(row[output]).toString(),
+ ),
+ ).toEqual(["A", null, ""]);
+ expect(
+ result.schema.fields.some((field) => field.name === "_rowid"),
+ ).toBe(false);
+ expect(queryRequests(requests)).toHaveLength(1);
+ expect(fetchRequests(requests)).toHaveLength(1);
+ expect(fetchRequests(requests)[0].body.column).toBe("image");
+ expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
+ },
+ { describeBlobName, values: true },
+ );
+ },
+ );
+
+ it("maps nested query fields through literal aliases despite a stale schema", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ expect(await table.blobColumns()).toEqual([]);
+ const rows = await table
+ .query()
+ .select({ "container.alias": "extra" })
+ .toArray({ blobMode: "bytes" });
+ expect(
+ rows.map((row) =>
+ row["container.alias"] === null
+ ? null
+ : Buffer.from(row["container.alias"].image).toString(),
+ ),
+ ).toEqual(["A", null, ""]);
+ expect(queryRequests(requests)).toHaveLength(1);
+ expect(fetchRequests(requests)[0].body.column).toBe("extra.image");
+ expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
+ },
+ { nestedBlob: true, describeBlobName: null, values: true },
+ );
+ });
+
+ it.each(["toArrow", "toArray"] as const)(
+ "%s rejects payloads from a recreated table with reused version and row IDs",
+ async (terminal) => {
+ await withSnapshotServer("recreate", async (table, requests) => {
+ await expect(
+ table.query()[terminal]({ blobMode: "bytes" }),
+ ).rejects.toThrow(/snapshot identity/);
+ const [fetch] = fetchRequests(requests);
+ expect(fetch.body.version).toBe(1);
+ expect(fetch.body.row_ids).toEqual([0]);
+ expect(fetch.body.column).toBe("image");
+ expect(fetch.identity).toBe(IDENTITY_A);
+ });
+ },
+ );
+
+ it("keeps the producing snapshot after an overwrite without rerunning the query", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const rows = await table.query().toArray({ blobMode: "bytes" });
+ expect(rows[0].label).toBe("A");
+ expect(Buffer.from(rows[0].image).toString()).toBe("A");
+ expect(queryRequests(requests)).toHaveLength(1);
+ const [fetch] = fetchRequests(requests);
+ expect(fetch.body.version).toBe(1);
+ expect(fetch.identity).toBe(IDENTITY_A);
+ expect(await table.version()).toBe(2);
+ const [latest] = await table.query().toArray({ blobMode: "bytes" });
+ expect(latest.label).toBe("B");
+ expect(Buffer.from(latest.image).toString()).toBe("B");
+ expect(fetchRequests(requests)[1].identity).toBe(IDENTITY_B);
+ },
+ { advanceQueries: true },
+ );
+ });
+
+ it.each([
+ { queryVersion: null },
+ { queryVersion: "0" },
+ { queryVersion: "18446744073709551616" },
+ { queryVersion: "invalid" },
+ { queryIdentity: null },
+ { queryIdentity: "v2:unsupported" },
+ ])("refuses bytes without authoritative capability %j", async (options) => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const [descriptor] = await table.query().toArray();
+ expect(descriptor.image.size).toBe(1n);
+ await expect(
+ table.query().toArray({ blobMode: "bytes" }),
+ ).rejects.toThrow(/blobMode.*bytes.*requires.*snapshot/);
+ expect(fetchRequests(requests)).toHaveLength(0);
+ },
+ options,
+ );
+ });
+
+ it("rejects a serving node without the snapshot echo", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table) => {
+ await expect(
+ table.query().toArray({ blobMode: "bytes" }),
+ ).rejects.toThrow(/snapshot identity/);
+ },
+ { echo: null },
+ );
+ });
+
+ it("keeps aliases, NULL, empty bytes, and explicit row IDs", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const query = table
+ .query()
+ .select({ caption: "label", "photo.image": "image" });
+ const rows = await query.withRowId().toArray({ blobMode: "bytes" });
+ expect(rows.map((row) => row._rowid)).toEqual([0n, 1n, 2n]);
+ expect(
+ rows.map((row) =>
+ row["photo.image"] === null
+ ? null
+ : Buffer.from(row["photo.image"]).toString(),
+ ),
+ ).toEqual(["A", null, ""]);
+ expect(rows[0].caption).toBe("A");
+ expect(fetchRequests(requests)[0].body.column).toBe("image");
+ const [descriptor] = await query.toArray();
+ expect(descriptor["photo.image"].size).toBe(1n);
+ },
+ { values: true },
+ );
+ });
+
+ it("preserves an empty bytes schema without fetching payloads", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const result = await table.query().toArrow({ blobMode: "bytes" });
+ expect(result.numRows).toBe(0);
+ expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe(
+ true,
+ );
+ expect(result.schema.fields.map((field) => field.name)).toEqual([
+ "label",
+ "image",
+ ]);
+ expect(fetchRequests(requests)).toHaveLength(0);
+ },
+ { empty: true },
+ );
+ });
+
+ it("passes the query version without rounding through a JS number", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ await table.query().toArray({ blobMode: "bytes" });
+ expect(fetchRequests(requests)[0].raw).toContain(
+ '"version":9007199254740993',
+ );
+ },
+ { queryVersion: "9007199254740993" },
+ );
+ });
+
+ it.each(["vector", "hybrid"])(
+ "materializes the actual %s query entry point",
+ async (kind) => {
+ await withSnapshotServer("overwrite", async (table, requests) => {
+ const query = table.query().nearestTo([0.1, 0.2]);
+ if (kind === "hybrid") query.fullTextSearch("A");
+ const rows = await query.toArray({ blobMode: "bytes" });
+ expect(Buffer.from(rows[0].image).toString()).toBe("A");
+ expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
+ expect(queryRequests(requests)).toHaveLength(kind === "hybrid" ? 2 : 1);
+ });
+ },
+ );
+
+ it("allows scalar-only bytes queries on older servers", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const [row] = await table
+ .query()
+ .select(["label"])
+ .toArray({ blobMode: "bytes" });
+ expect(row.label).toBe("A");
+ expect(Object.keys(row)).toEqual(["label"]);
+ expect(fetchRequests(requests)).toHaveLength(0);
+ // Row IDs are requested before the executed output schema is known,
+ // then hidden from scalar-only results without requiring capability.
+ expect(queryRequests(requests)[0].body.with_row_id).toBe(true);
+ },
+ { queryIdentity: null, queryVersion: null },
+ );
+ });
+
+ it.each([false, true])(
+ "preserves snapshot proof across a custom reranker (empty: %s)",
+ async (empty) => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const result = await table
+ .query()
+ .nearestTo([0.1, 0.2])
+ .fullTextSearch("A")
+ .rerank(keepFtsReranker)
+ .toArrow({ blobMode: "bytes" });
+ expect(result.numRows).toBe(empty ? 0 : 1);
+ expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe(
+ true,
+ );
+ expect(fetchRequests(requests)).toHaveLength(empty ? 0 : 1);
+ },
+ { empty },
+ );
+ },
+ );
+
+ it("does not trust a custom reranker's first-leg snapshot when the legs disagree", async () => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const query = table
+ .query()
+ .nearestTo([0.1, 0.2])
+ .fullTextSearch("A")
+ .rerank(keepFtsReranker);
+ await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow(
+ /snapshot/,
+ );
+ expect(fetchRequests(requests)).toHaveLength(0);
+ },
+ { otherLegIdentity: IDENTITY_B },
+ );
+ });
+
+ it.each([
+ { otherLegIdentity: IDENTITY_B },
+ { otherLegIdentity: null },
+ { otherLegVersion: "2" },
+ ])(
+ "refuses hybrid bytes when its actual query legs disagree %j",
+ async (options) => {
+ await withSnapshotServer(
+ "overwrite",
+ async (table, requests) => {
+ const query = table.query().nearestTo([0.1, 0.2]).fullTextSearch("A");
+ await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow(
+ /snapshot/,
+ );
+ expect(fetchRequests(requests)).toHaveLength(0);
+ expect(await query.toArray()).toHaveLength(1);
+ },
+ options,
+ );
+ },
+ );
+});
diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts
index 59d6929b4..e97b32e78 100644
--- a/nodejs/__test__/table.test.ts
+++ b/nodejs/__test__/table.test.ts
@@ -3271,29 +3271,6 @@ describe("when dealing with blob columns", () => {
expect(await handle!.read()).toEqual(alpha);
});
- it("cancels an in-flight read", async () => {
- const db = await connect(tmpDir.name);
- const schema = new Schema([
- new Field("id", new Int64(), true),
- blob("payload", { inlineSizeThreshold: 0, dedicatedSizeThreshold: 1 }),
- ]);
- const payload = Buffer.alloc(32 * 1024 * 1024, 7);
- const table = await db.createTable("large_blobs", [{ id: 1n, payload }], {
- schema,
- });
- const [row] = await table.query().withRowId().toArray();
- const [handle] = await table.fetchBlobFiles("payload", [
- row._rowid as bigint,
- ]);
- const controller = new AbortController();
- const pending = handle!.readRange(0n, handle!.size(), {
- signal: controller.signal,
- });
- controller.abort();
- await expect(pending).rejects.toMatchObject({ name: "AbortError" });
- expect(await handle!.readRange(0n, 4n)).toEqual(payload.subarray(0, 4));
- });
-
it("toArrow returns blob bytes with blobMode bytes", async () => {
const { table, alpha, beta } = await openBlobTable();
const result = await table.query().toArrow({ blobMode: "bytes" });
@@ -5739,6 +5716,31 @@ describe("computed columns", () => {
resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 },
}),
).rejects.toThrow("resource_budget requires a LanceDB Enterprise refresh");
+ await expect(
+ table.refreshColumn("x", {
+ supervisorResources: {
+ cpuMillis: 1_000,
+ memoryBytes: 1_024,
+ ephemeralStorageBytes: 2_048,
+ },
+ }),
+ ).rejects.toThrow(
+ "supervisor_resources requires a LanceDB Enterprise refresh",
+ );
+ await expect(
+ table.refreshColumnAsync("x", {
+ planningWorkers: {
+ resources: {
+ cpuMillis: 1_000,
+ memoryBytes: 1_024,
+ ephemeralStorageBytes: 2_048,
+ },
+ maxWorkers: 2,
+ rowsPerWorker: 100,
+ fragmentsPerWorker: 1,
+ },
+ }),
+ ).rejects.toThrow("planning_workers requires a LanceDB Enterprise refresh");
});
it("records Function errors only on remote tables", async () => {
diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts
index a46484314..be26f6121 100644
--- a/nodejs/lancedb/blob.ts
+++ b/nodejs/lancedb/blob.ts
@@ -1,7 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
-import { Field, LargeBinary, Struct, Uint64, Utf8 } from "apache-arrow";
+import {
+ DataType,
+ Field,
+ LargeBinary,
+ Struct,
+ Uint64,
+ Utf8,
+} from "apache-arrow";
import { BlobFile as NativeBlobFile } from "./native";
const BLOB_V2_EXTENSION_NAME = "lance.blob.v2";
@@ -178,6 +185,39 @@ export function isBlobField(field: Field): boolean {
return field.metadata?.get("ARROW:extension:name") === BLOB_V2_EXTENSION_NAME;
}
+/** @ignore */
+export function isBlobDescriptorField(field: Field): boolean {
+ // Native descriptor scans replace the logical extension metadata. Require
+ // both the encoding marker and the v2 layout to exclude v1 and plain structs.
+ if (
+ field.metadata?.get("lance-encoding:blob") !== "true" ||
+ !DataType.isStruct(field.type)
+ ) {
+ return false;
+ }
+ const children = field.type.children;
+ const integers = [
+ ["kind", 8],
+ ["position", 64],
+ ["size", 64],
+ ["blob_id", 32],
+ ] as const;
+ return (
+ children.length === 5 &&
+ integers.every(([name, width], index) => {
+ const child = children[index];
+ return (
+ child.name === name &&
+ DataType.isInt(child.type) &&
+ !child.type.isSigned &&
+ child.type.bitWidth === width
+ );
+ }) &&
+ children[4].name === "blob_uri" &&
+ DataType.isUtf8(children[4].type)
+ );
+}
+
/**
* A lazy handle to blob bytes. Create one with {@link Table.fetchBlobFiles}.
*
diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts
index 08a254bdb..a6bcd68f5 100644
--- a/nodejs/lancedb/index.ts
+++ b/nodejs/lancedb/index.ts
@@ -57,6 +57,9 @@ export {
AddResult,
AddColumnsResult,
RefreshColumnOptions,
+ FunctionRefreshPlanningConfig,
+ FunctionRefreshPodResources,
+ FunctionRetryPolicy,
FunctionWorkerResourceBudget,
RefreshColumnResult,
FunctionErrors,
diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts
index bb845276f..6b72f19fd 100644
--- a/nodejs/lancedb/query.ts
+++ b/nodejs/lancedb/query.ts
@@ -17,6 +17,7 @@ import {
tableFromIPC,
vectorFromArray,
} from "./arrow";
+import { isBlobDescriptorField, isBlobField } from "./blob";
import { Expr } from "./expr";
import { type IvfPqOptions } from "./indices";
import {
@@ -148,6 +149,34 @@ async function readBlobBytes(
);
}
+// Discover descriptors from the executed query, not the live table's cached
+// schema. Projection names are literal aliases; only source paths use dots.
+function projectedBlobSources(
+ schema: Schema,
+ projection: [string, string][] | undefined,
+): BlobSource[] {
+ const sources: BlobSource[] = [];
+ for (const field of schema.fields) {
+ const source =
+ projection?.find(([output]) => output === field.name)?.[1] ?? field.name;
+ const visit = (child: Field, path: string[]) => {
+ if (isBlobField(child) || isBlobDescriptorField(child)) {
+ sources.push({
+ output: field.name,
+ path,
+ source: [source, ...path].join("."),
+ });
+ } else if (DataType.isStruct(child.type)) {
+ for (const nested of child.type.children) {
+ visit(nested, [...path, nested.name]);
+ }
+ }
+ };
+ visit(field, []);
+ }
+ return sources;
+}
+
function withBinaryColumns(
table: ArrowTable,
replacements: Map,
@@ -257,8 +286,10 @@ export interface QueryExecutionOptions {
* bytes. Blobs inside lists keep their descriptors. Arbitrary projection
* expressions are not materialized as bytes.
*
- * The rows and the bytes come from the same table version. If the table
- * changes while the query runs, the query runs again, up to three times.
+ * The rows and bytes come from the same snapshot. Remote queries require
+ * authoritative query version and snapshot identity headers, verified again
+ * by the blob response. Older servers can still return `"descriptions"`.
+ * Local queries retry up to three times if the table changes while they run.
*
* @example
* ```ts
@@ -499,6 +530,34 @@ export class QueryBase<
if (context === undefined) {
return this.collect(options, false);
}
+ if (!context.table.isNative()) {
+ // Request row IDs in the same query so newly added Blob columns can be
+ // fetched without rerunning the query against a different snapshot.
+ const addRowId = !context.withRowId;
+ const table = await this.collect(options, addRowId);
+ const sources = projectedBlobSources(table.schema, context.projection);
+ if (sources.length === 0) {
+ return addRowId
+ ? table.select(
+ table.schema.fields
+ .map((field) => field.name)
+ .filter((name) => name !== "_rowid"),
+ )
+ : table;
+ }
+ const version = table.schema.metadata.get("lancedb:query_version");
+ const identity = table.schema.metadata.get("lancedb:query_snapshot");
+ if (version === undefined || identity === undefined) {
+ throw new Error(
+ 'blobMode "bytes" requires a trustworthy query snapshot: missing, invalid, or inconsistent x-lancedb-query-version or x-lancedb-query-snapshot. Upgrade every serving node, or use blobMode "descriptions".',
+ );
+ }
+ const snapshot = await context.table.querySnapshotWithIdentity(
+ version,
+ identity,
+ );
+ return readBlobBytes(table, sources, snapshot, addRowId);
+ }
for (let attempt = 1; ; attempt++) {
// The snapshot pins the bytes. The query runs on the live table, so an
// unchanged version afterwards proves it read the snapshot's version.
@@ -533,10 +592,10 @@ export class QueryBase<
for await (const batch of RecordBatchIterator(iterator)) {
batches.push(batch);
}
- if (batches.length === 0) {
- return tableFromIPC((await iterator).schema());
- }
- return new ArrowTable(batches);
+ // Read metadata from the executed stream, including empty results and
+ // query types whose individual batches do not carry the stream metadata.
+ const schema = tableFromIPC((await iterator).schema()).schema;
+ return new ArrowTable(schema, batches);
}
private blobBytesContext(
diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts
index 136eb1d6c..f949bd00a 100644
--- a/nodejs/lancedb/table.ts
+++ b/nodejs/lancedb/table.ts
@@ -831,12 +831,18 @@ export abstract class Table {
* `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
* `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
* and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
- * `maxConcurrency`, `resourceBudget` and
- * `maxExecutorProcessesPerWorker` size registered Function refreshes.
+ * `maxConcurrency`, `resourceBudget`, `supervisorResources`,
+ * `planningWorkers` and `maxExecutorProcessesPerWorker` size registered
+ * Function refreshes. `retryPolicy` overrides user-code retries only when
+ * repeating partial work is safe; set `maxAttempts: 1` to disable retries.
* `maxConcurrency` overrides the registered default for this logical
* execution only and is a positive integer; it is not an account-wide
* quota. A `resourceBudget` requires `cpuMillis` and
* `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function.
+ * `supervisorResources` and each `planningWorkers.resources` entry require
+ * positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`.
+ * `planningWorkers` also requires positive `maxWorkers`,
+ * `rowsPerWorker` and `fragmentsPerWorker`.
* The budget applies only to this explicit refresh and does not configure
* a later automatic refresh.
* `gpuCount` at the top level is the shorthand that preserves the
diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs
index f6abeb553..a0a220e24 100644
--- a/nodejs/src/table.rs
+++ b/nodejs/src/table.rs
@@ -9,6 +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,
+ FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig,
+ FunctionRefreshPodResources as LanceFunctionRefreshPodResources,
FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref,
Table as LanceDbTable,
};
@@ -349,6 +351,31 @@ impl Table {
Ok(Query::new(self.inner_ref()?.query()))
}
+ /// Whether this handle reads an in-process dataset.
+ #[napi]
+ pub fn is_native(&self) -> napi::Result {
+ Ok(self.inner_ref()?.as_native().is_some())
+ }
+
+ /// Constrain deferred blob reads by the producing query response.
+ #[napi(catch_unwind)]
+ pub async fn query_snapshot_with_identity(
+ &self,
+ version: String,
+ identity: String,
+ ) -> napi::Result {
+ // Keep u64 query versions exact across the JavaScript boundary.
+ let version = version
+ .parse::()
+ .map_err(|_| napi::Error::from_reason("Invalid query snapshot version"))?;
+ let snapshot = self
+ .inner_ref()?
+ .query_snapshot_with_identity(version, &identity)
+ .await
+ .default_error()?;
+ Ok(Self::new(snapshot))
+ }
+
/// Return a read-only table handle pinned to the current query revision.
#[napi(catch_unwind)]
pub async fn query_snapshot(&self) -> napi::Result {
@@ -1680,6 +1707,58 @@ pub struct FunctionWorkerResourceBudget {
pub gpu_count: Option,
}
+/// CPU, memory, and ephemeral-storage limits for one Function refresh
+/// control-plane pod.
+#[napi(object)]
+#[derive(Clone, Debug)]
+pub struct FunctionRefreshPodResources {
+ /// CPU limit in millicores; 1000 is one CPU.
+ pub cpu_millis: f64,
+ /// Memory limit in bytes.
+ pub memory_bytes: f64,
+ /// Ephemeral storage limit in bytes.
+ pub ephemeral_storage_bytes: f64,
+}
+
+/// Resources and sizing policy for the planning fleet of one registered
+/// Function refresh.
+#[napi(object)]
+#[derive(Clone, Debug)]
+pub struct FunctionRefreshPlanningConfig {
+ /// CPU, memory, and ephemeral-storage limits for one planning worker.
+ pub resources: FunctionRefreshPodResources,
+ /// Maximum number of planning workers.
+ pub max_workers: f64,
+ /// Maximum rows assigned to one planning worker.
+ pub rows_per_worker: f64,
+ /// Maximum fragments assigned to one planning worker.
+ pub fragments_per_worker: f64,
+}
+
+/// Overrides retries of failed user-code calls for one refresh. Omitted
+/// fields use the Function refresh defaults.
+#[napi(object)]
+#[derive(Clone, Debug, Default)]
+pub struct FunctionRetryPolicy {
+ /// Total calls, including the first; 1 disables retries, maximum 100.
+ pub max_attempts: Option,
+ /// Initial exponential-backoff ceiling, in seconds.
+ pub initial_backoff_seconds: Option,
+ /// Maximum backoff, in seconds.
+ pub max_backoff_seconds: Option,
+ /// Exception class names, preferably qualified.
+ pub exception_types: Option>,
+ /// Regular expression matched against the exception class and message.
+ pub message_pattern: Option,
+ /// Structured provider error codes or HTTP status codes.
+ pub error_codes: Option>,
+ /// Match connection/timeouts, HTTP 429/503, SlowDown and
+ /// ServiceUnavailable.
+ pub transient: Option,
+ /// Honor Retry-After within the configured maximum.
+ pub honor_retry_after: Option,
+}
+
fn positive_safe_integer(value: f64, name: &str) -> napi::Result {
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
if !value.is_finite() || value.fract() != 0.0 || !(1.0..=MAX_SAFE_INTEGER).contains(&value) {
@@ -1743,8 +1822,14 @@ pub struct RefreshColumnOptions {
/// Complete aggregate CPU and memory budget for a registered Function
/// refresh. `gpuCount` inside the budget defaults to zero.
pub resource_budget: Option,
+ /// CPU, memory, and ephemeral-storage limits for the refresh supervisor.
+ pub supervisor_resources: Option,
+ /// Resources and sizing for the refresh planning fleet.
+ pub planning_workers: Option,
/// Positive aggregate GPU budget for Function workers.
pub gpu_count: Option,
+ /// Override retries of failed user-code calls for this refresh.
+ pub retry_policy: Option,
/// `"fail"` (default) stops on a row error; `"skip"` writes null and
/// records the error, subject to the failure limits.
pub error_policy: Option,
@@ -1789,7 +1874,87 @@ impl TryFrom for lancedb::table::RefreshColumnOptions {
)
})
.transpose()?;
+ options.supervisor_resources = value
+ .supervisor_resources
+ .map(|resources| {
+ Ok::<_, napi::Error>(LanceFunctionRefreshPodResources::new(
+ positive_safe_integer(resources.cpu_millis, "supervisorResources.cpuMillis")?,
+ positive_safe_integer(
+ resources.memory_bytes,
+ "supervisorResources.memoryBytes",
+ )?,
+ positive_safe_integer(
+ resources.ephemeral_storage_bytes,
+ "supervisorResources.ephemeralStorageBytes",
+ )?,
+ ))
+ })
+ .transpose()?;
+ options.planning_workers = value
+ .planning_workers
+ .map(|planning| {
+ let resources = LanceFunctionRefreshPodResources::new(
+ positive_safe_integer(
+ planning.resources.cpu_millis,
+ "planningWorkers.resources.cpuMillis",
+ )?,
+ positive_safe_integer(
+ planning.resources.memory_bytes,
+ "planningWorkers.resources.memoryBytes",
+ )?,
+ positive_safe_integer(
+ planning.resources.ephemeral_storage_bytes,
+ "planningWorkers.resources.ephemeralStorageBytes",
+ )?,
+ );
+ let max_workers = usize::try_from(positive_safe_integer(
+ planning.max_workers,
+ "planningWorkers.maxWorkers",
+ )?)
+ .map_err(|_| napi::Error::from_reason("planningWorkers.maxWorkers is too large"))?;
+ Ok::<_, napi::Error>(LanceFunctionRefreshPlanningConfig::new(
+ resources,
+ max_workers,
+ positive_safe_integer(
+ planning.rows_per_worker,
+ "planningWorkers.rowsPerWorker",
+ )?,
+ positive_safe_integer(
+ planning.fragments_per_worker,
+ "planningWorkers.fragmentsPerWorker",
+ )?,
+ ))
+ })
+ .transpose()?;
options.gpu_count = value.gpu_count;
+ options.retry_policy = value.retry_policy.map(|policy| {
+ let mut converted = lancedb::function::FunctionRetryPolicy::default();
+ if let Some(max_attempts) = policy.max_attempts {
+ converted.max_attempts = max_attempts;
+ }
+ if let Some(seconds) = policy.initial_backoff_seconds {
+ converted.initial_backoff_seconds = seconds;
+ }
+ if let Some(seconds) = policy.max_backoff_seconds {
+ converted.max_backoff_seconds = seconds;
+ }
+ if let Some(exception_types) = policy.exception_types {
+ converted.exception_types = exception_types;
+ }
+ if let Some(pattern) = policy.message_pattern {
+ converted.message_pattern = Some(pattern);
+ }
+ if let Some(error_codes) = policy.error_codes {
+ converted.error_codes = error_codes;
+ }
+ if let Some(transient) = policy.transient {
+ converted.transient = transient;
+ }
+ if let Some(honor_retry_after) = policy.honor_retry_after {
+ converted.honor_retry_after = honor_retry_after;
+ }
+ converted
+ });
options.error_policy = match value.error_policy.as_deref() {
None => None,
Some("fail") => Some(lancedb::function::FunctionErrorPolicy::Fail),
diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi
index 1e811d865..a87b82a21 100644
--- a/python/python/lancedb/_lancedb.pyi
+++ b/python/python/lancedb/_lancedb.pyi
@@ -117,7 +117,7 @@ class PyExpr:
def expr_col(name: str) -> PyExpr: ...
def expr_lit(
- value: Union[bool, int, float, str, bytes, date, datetime, Decimal],
+ value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
) -> PyExpr: ...
def expr_func(name: str, args: List[PyExpr]) -> PyExpr: ...
@@ -663,6 +663,8 @@ class Table:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
+ supervisor_resources: Optional[dict[str, int]] = None,
+ planning_workers: Optional[dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
@@ -683,6 +685,8 @@ class Table:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
+ supervisor_resources: Optional[dict[str, int]] = None,
+ planning_workers: Optional[dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
diff --git a/python/python/lancedb/expr.py b/python/python/lancedb/expr.py
index f65fbd21a..b25e5d012 100644
--- a/python/python/lancedb/expr.py
+++ b/python/python/lancedb/expr.py
@@ -29,6 +29,8 @@ from lancedb._lancedb import PyExpr, expr_col, expr_lit, expr_func
__all__ = ["Expr", "col", "lit", "func"]
+_NOT_LITERAL = object()
+
_STR_TO_PA_TYPE: dict = {
"bool": pa.bool_(),
"boolean": pa.bool_(),
@@ -92,9 +94,16 @@ class Expr:
# for dict keys / set membership.
__hash__ = None # type: ignore[assignment]
- def __init__(self, inner: PyExpr, *, column_path: str | None = None) -> None:
+ def __init__(
+ self,
+ inner: PyExpr,
+ *,
+ column_path: str | None = None,
+ literal_value: object = _NOT_LITERAL,
+ ) -> None:
self._inner = inner
self._column_path = column_path
+ self._literal_value = literal_value
def __bool__(self) -> bool:
# An Expr describes a predicate that the query engine evaluates per row,
@@ -301,14 +310,16 @@ def col(name: str) -> Expr:
return Expr(expr_col(name), column_path=name)
-def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> Expr:
+def lit(
+ value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
+) -> Expr:
"""Create a literal (constant) value expression.
Parameters
----------
value:
A Python ``bool``, ``int``, ``float``, ``str``, ``bytes``, ``date``,
- ``datetime``, or ``Decimal``.
+ ``datetime``, ``Decimal``, or ``None`` for SQL NULL.
Examples
--------
@@ -316,10 +327,12 @@ def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) ->
>>> col("price") * lit(1.1)
Expr((price * 1.1))
"""
- if not isinstance(value, (bool, int, float, str, bytes, date, datetime, Decimal)):
+ if value is not None and not isinstance(
+ value, (bool, int, float, str, bytes, date, datetime, Decimal)
+ ):
raise TypeError(f"Unsupported literal type: {type(value).__name__}")
- return Expr(expr_lit(value))
+ return Expr(expr_lit(value), literal_value=value)
def func(name: str, *args: ExprLike) -> Expr:
diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py
index f04d3d481..471fc2437 100644
--- a/python/python/lancedb/functions.py
+++ b/python/python/lancedb/functions.py
@@ -158,11 +158,15 @@ def _validate_literal(value):
"Function integer literal is outside the canonical JSON range"
)
elif isinstance(value, Mapping):
+ if not all(isinstance(key, str) for key in value):
+ raise TypeError("Function literal object keys must be strings")
for child in value.values():
_validate_literal(child)
elif isinstance(value, (list, tuple)):
for child in value:
_validate_literal(child)
+ elif value is not None and not isinstance(value, (bool, str)):
+ raise TypeError(f"unsupported Function literal type: {type(value).__name__}")
return value
@@ -193,7 +197,7 @@ class _RemoteValue(BaseModel):
known = {}
for name, field in self.__class__.model_fields.items():
value = getattr(self, name)
- if value is None:
+ if value is None and not field.is_required():
continue
if not field.is_required():
default_factory = field.default_factory
@@ -312,7 +316,11 @@ class FunctionResultField(_OpenRemoteValue):
class FunctionOutput(_OpenRemoteValue):
- """Scalar or ordered named-struct output; unknown kinds remain decodable."""
+ """Scalar or ordered named-struct output; unknown kinds remain decodable.
+
+ A scalar output may be nullable. A named-struct output has no top-level
+ nullability; its fields carry their own flags.
+ """
kind: str
arrow_type: Optional[str] = None
@@ -622,10 +630,17 @@ class FunctionVersion(_RemoteValue):
return _validate_row_timeout(value)
def __call__(self, **arguments: Any) -> FunctionApplication:
- """Bind this exact version to named table columns.
+ """Bind this exact version to named table columns and constant inputs.
Every input must be a direct [lancedb.col][lancedb.expr.col]
- reference. A Function that declares initialization fields takes their
+ reference or [lancedb.lit][lancedb.expr.lit] constant. Constants support
+ integers, strings, booleans, and null; floating-point, binary and
+ temporal literals are not in the canonical Function input contract.
+ The Enterprise service must support literal bindings and validates
+ constants against this exact version's input signature. To change a
+ constant, redeclare the column using the same Function version.
+
+ A Function that declares initialization fields takes their
values as further keyword arguments; they are constants of this
binding, fixed for every row, and every instance the binding runs is
created with them. A non-nullable field without a default must be
@@ -654,7 +669,7 @@ class FunctionVersion(_RemoteValue):
... "embedding": embed(text=col("body"), model="small", dimensions=512)
... })
"""
- from lancedb.expr import Expr
+ from lancedb.expr import Expr, _NOT_LITERAL
parameters = tuple(parameter.name for parameter in self.signature.inputs)
fields = {field.name: field for field in self.signature.initialization}
@@ -678,17 +693,27 @@ class FunctionVersion(_RemoteValue):
bindings = []
for parameter in parameters:
value = arguments[parameter]
- if not isinstance(value, Expr) or value._column_path is None:
+ if isinstance(value, Expr) and value._literal_value is not _NOT_LITERAL:
+ bindings.append(
+ ApplicationInput(
+ parameter=parameter,
+ kind="literal",
+ value=value._literal_value,
+ )
+ )
+ elif isinstance(value, Expr) and value._column_path is not None:
+ bindings.append(
+ ApplicationInput(
+ parameter=parameter,
+ kind="column",
+ value={"path": value._column_path},
+ )
+ )
+ else:
raise TypeError(
- f"Function input {parameter!r} must be a direct col(...) reference"
+ f"Function input {parameter!r} must be a direct col(...) reference "
+ "or lit(...) constant"
)
- bindings.append(
- ApplicationInput(
- parameter=parameter,
- kind="column",
- value={"path": value._column_path},
- )
- )
initialization = {}
for name in fields:
if name in arguments:
@@ -872,6 +897,18 @@ class InputBinding(_RemoteValue):
nullable: bool
+class LiteralInputBinding(_RemoteValue):
+ """Constant supplied to a Function parameter for every input row."""
+
+ parameter: str
+ value: Any
+
+ @field_validator("value")
+ @classmethod
+ def _validate_value(cls, value):
+ return _validate_literal(value)
+
+
class OutputMapping(_RemoteValue):
"""One stable result-field mapping."""
@@ -896,6 +933,7 @@ class FunctionBinding(_RemoteValue):
binding_id: str
function: FunctionVersionRef
inputs: tuple[InputBinding, ...]
+ literal_inputs: tuple[LiteralInputBinding, ...] = ()
outputs: tuple[OutputMapping, ...]
assignment: Optional[AssignmentMapping] = None
input_schema: Optional[Mapping[str, Any]] = None
@@ -903,6 +941,13 @@ class FunctionBinding(_RemoteValue):
initialization: Optional[str] = None
"""Standard base64 of the validated one-row Arrow IPC initialization stream."""
+ @model_validator(mode="after")
+ def _validate_input_parameters(self):
+ parameters = [input.parameter for input in (*self.inputs, *self.literal_inputs)]
+ if len(parameters) != len(set(parameters)):
+ raise ValueError("Function binding input parameters must be unique")
+ return self
+
def initialization_row(self) -> Optional[dict[str, Any]]:
"""The initialization values this binding creates instances with."""
if self.initialization is None:
@@ -1399,12 +1444,12 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp
"output_schema must be a PyArrow DataType, Field, or Schema"
)
_validate_exact_arrow_field(field)
- if field.nullable:
- raise ValueError("Function output must be non-nullable")
+ if field.nullable and _is_blob_v2_field(field):
+ raise ValueError("Blob v2 Function output must be non-nullable")
return FunctionOutput(
kind="scalar",
arrow_type=_canonical_arrow_field(field, collection_blobs=True),
- nullable=False,
+ nullable=field.nullable,
)
if not fields:
@@ -1504,9 +1549,9 @@ def _infer_signature(
output = _function_output(output_schema)
else:
output_type, output_nullable = _annotation_type(annotations["return"])
- if output_nullable:
- raise ValueError("Function output must be non-nullable")
- output = _function_output(pa.field("result", output_type, nullable=False))
+ output = _function_output(
+ pa.field("result", output_type, nullable=output_nullable)
+ )
if inputs is not None:
return FunctionSignature(inputs=inputs, output=output)
@@ -2650,9 +2695,13 @@ def function(
``None`` for a null value. PyArrow fields are nullable unless declared
otherwise, so most columns need ``Optional``. For Arrow types annotations
cannot express precisely, pass ``input_schema``, ``output_schema``, or
- both; the one omitted is inferred. Scalar outputs must be non-nullable.
- Every named-struct field may be nullable; Enterprise preserves the
- struct's validity when the result is expanded into sibling columns.
+ both; the one omitted is inferred. A scalar output is non-nullable by
+ default; annotate the return as ``Optional[T]`` or ``T | None``, or pass a
+ nullable ``output_schema`` field, to declare a nullable scalar. The
+ deployment must accept nullable scalar outputs; an older server rejects
+ the registration. Every named-struct field may be nullable; Enterprise
+ preserves the struct's validity when the result is expanded into sibling
+ columns.
**Large values.** A ``bytes`` parameter receives the whole value, which
is held in memory with its row and counts against the server's per-row
@@ -2757,9 +2806,10 @@ def function(
Required for batch annotations. When omitted, inputs are inferred from
the parameter annotations.
output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional
- Explicit scalar or named-struct output. Scalar outputs must be
- non-nullable. Required for batch annotations. When omitted, the output
- is inferred from the return annotation.
+ Explicit scalar or named-struct output. A scalar field's ``nullable``
+ flag is preserved; a top-level named-struct field and a Blob v2 output
+ must be non-nullable. Required for batch annotations. When omitted, the
+ output is inferred from the return annotation.
pip : sequence of str, optional
Pip requirements for the remote environment. Syntax is validated at
decoration time, including extras and environment markers. Named direct
@@ -2970,6 +3020,7 @@ __all__ = [
"FunctionVersionRef",
"HuggingFaceModel",
"InputBinding",
+ "LiteralInputBinding",
"OutputMapping",
"PythonEnvironmentSpec",
"PythonAdapterSpec",
diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py
index dbfd127ee..b5d97eb62 100644
--- a/python/python/lancedb/remote/table.py
+++ b/python/python/lancedb/remote/table.py
@@ -1164,6 +1164,8 @@ class RemoteTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
+ supervisor_resources: Optional[Dict[str, int]] = None,
+ planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1183,6 +1185,8 @@ class RemoteTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
+ supervisor_resources=supervisor_resources,
+ planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -1205,6 +1209,8 @@ class RemoteTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
+ supervisor_resources: Optional[Dict[str, int]] = None,
+ planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1225,6 +1231,8 @@ class RemoteTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
+ supervisor_resources=supervisor_resources,
+ planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py
index e0b96e476..45b2eb4f6 100644
--- a/python/python/lancedb/table.py
+++ b/python/python/lancedb/table.py
@@ -3258,6 +3258,8 @@ class Table(ABC):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
+ supervisor_resources: Optional[Dict[str, int]] = None,
+ planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3315,6 +3317,17 @@ class Table(ABC):
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
+ supervisor_resources: dict[str, int], optional
+ CPU, memory, and ephemeral-storage limits for the Function refresh
+ supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
+ ``ephemeral_storage_bytes``; all are required and positive.
+ LanceDB Enterprise only; local refreshes reject it.
+ planning_workers: dict[str, object], optional
+ Resources and sizing for the Function refresh planning fleet.
+ ``resources`` has the same keys as ``supervisor_resources``; the
+ other keys are ``max_workers``, ``rows_per_worker`` and
+ ``fragments_per_worker``. 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.
@@ -3367,6 +3380,8 @@ class Table(ABC):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
+ supervisor_resources: Optional[Dict[str, int]] = None,
+ planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3423,6 +3438,17 @@ class Table(ABC):
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
+ supervisor_resources: dict[str, int], optional
+ CPU, memory, and ephemeral-storage limits for the Function refresh
+ supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
+ ``ephemeral_storage_bytes``; all are required and positive.
+ LanceDB Enterprise only; local refreshes reject it.
+ planning_workers: dict[str, object], optional
+ Resources and sizing for the Function refresh planning fleet.
+ ``resources`` has the same keys as ``supervisor_resources``; the
+ other keys are ``max_workers``, ``rows_per_worker`` and
+ ``fragments_per_worker``. 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.
@@ -5632,6 +5658,8 @@ class LanceTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
+ supervisor_resources: Optional[Dict[str, int]] = None,
+ planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5654,6 +5682,8 @@ class LanceTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
+ supervisor_resources=supervisor_resources,
+ planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -5676,6 +5706,8 @@ class LanceTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
+ supervisor_resources: Optional[Dict[str, int]] = None,
+ planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5700,6 +5732,8 @@ class LanceTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
+ supervisor_resources=supervisor_resources,
+ planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -8109,6 +8143,8 @@ class AsyncTable:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
+ supervisor_resources: Optional[Dict[str, int]] = None,
+ planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8166,6 +8202,17 @@ class AsyncTable:
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
+ supervisor_resources: dict[str, int], optional
+ CPU, memory, and ephemeral-storage limits for the Function refresh
+ supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
+ ``ephemeral_storage_bytes``; all are required and positive.
+ LanceDB Enterprise only; local refreshes reject it.
+ planning_workers: dict[str, object], optional
+ Resources and sizing for the Function refresh planning fleet.
+ ``resources`` has the same keys as ``supervisor_resources``; the
+ other keys are ``max_workers``, ``rows_per_worker`` and
+ ``fragments_per_worker``. 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.
@@ -8213,6 +8260,8 @@ class AsyncTable:
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
+ supervisor_resources=supervisor_resources,
+ planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8351,6 +8400,8 @@ class AsyncTable:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
+ supervisor_resources: Optional[Dict[str, int]] = None,
+ planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8407,6 +8458,17 @@ class AsyncTable:
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
+ supervisor_resources: dict[str, int], optional
+ CPU, memory, and ephemeral-storage limits for the Function refresh
+ supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
+ ``ephemeral_storage_bytes``; all are required and positive.
+ LanceDB Enterprise only; local refreshes reject it.
+ planning_workers: dict[str, object], optional
+ Resources and sizing for the Function refresh planning fleet.
+ ``resources`` has the same keys as ``supervisor_resources``; the
+ other keys are ``max_workers``, ``rows_per_worker`` and
+ ``fragments_per_worker``. 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.
@@ -8471,6 +8533,8 @@ class AsyncTable:
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
+ supervisor_resources=supervisor_resources,
+ planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py
index 867672fe9..07be57e15 100644
--- a/python/python/tests/test_first_class_function_slice1.py
+++ b/python/python/tests/test_first_class_function_slice1.py
@@ -8,7 +8,7 @@ from types import MappingProxyType
import pytest
-from lancedb import col
+from lancedb import col, lit
import lancedb.functions as functions
from lancedb.functions import (
FunctionApplication,
@@ -58,6 +58,7 @@ def assert_no_secret_values(value):
def test_public_function_values_are_in_api_reference():
+ assert "LiteralInputBinding" in functions.__all__
docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md"
rendered = docs.read_text()
for name in functions.__all__:
@@ -286,6 +287,67 @@ def test_function_version_binding_validates_names_and_direct_columns():
version(text=col("text").lower())
+@pytest.mark.parametrize("constant", [16, 8, True, "prompt", None, 2**64 - 1])
+def test_function_version_binds_direct_literals_without_changing_identity(constant):
+ value = job_result("remote_function_job.json")
+ value["signature"]["inputs"].append(
+ {
+ "name": "option",
+ "arrow_type": "bool"
+ if type(constant) is bool
+ else "utf8"
+ if isinstance(constant, str)
+ else "uint64"
+ if constant == 2**64 - 1
+ else "int64",
+ "nullable": True,
+ }
+ )
+ version = FunctionVersion.from_json(json.dumps(value))
+ expression = lit(constant)
+ application = version(text=col("body"), option=expression)
+ encoded = json.loads(application.to_canonical_json())
+ assert encoded["inputs"] == [
+ {"parameter": "text", "kind": "column", "value": {"path": "body"}},
+ {"parameter": "option", "kind": "literal", "value": constant},
+ ]
+ assert application.function.version == version.version
+ assert application.function.object_id == version.object_id
+ assert application.function.manifest_digest == version.image.manifest_digest
+ assert FunctionApplication.from_json(application.to_canonical_json()) == application
+ if constant is None:
+ assert expression.to_sql() == "NULL"
+ if type(constant) is int:
+ assert expression.to_sql() == str(constant)
+
+
+def test_function_literals_reject_expressions_and_unsupported_values():
+ version = FunctionVersion.from_json(
+ json.dumps(job_result("remote_function_job.json"))
+ )
+ with pytest.raises(TypeError, match="direct col"):
+ version(text=lit(16) + lit(8))
+ with pytest.raises(ValueError, match="floating-point Function literals"):
+ version(text=lit(1.5))
+ with pytest.raises(TypeError, match="unsupported Function literal type"):
+ version(text=lit(b"data"))
+
+
+def test_function_literal_binding_preserves_null_and_rejects_duplicate_parameters():
+ value = json.loads((FIXTURES / "remote_function_binding.json").read_text())
+ value["inputs"] = value["inputs"][:1]
+ value["literal_inputs"] = [{"parameter": "body", "value": None}]
+ binding = FunctionBinding.from_json(json.dumps(value))
+ assert binding.literal_inputs[0].value is None
+ assert json.loads(binding.to_canonical_json())["literal_inputs"] == [
+ {"parameter": "body", "value": None}
+ ]
+ assert FunctionBinding.from_json(binding.to_canonical_json()) == binding
+ value["literal_inputs"][0]["parameter"] = "title"
+ with pytest.raises(ValueError, match="input parameters must be unique"):
+ FunctionBinding.from_json(json.dumps(value))
+
+
def test_function_version_keeps_named_struct_outputs_in_one_application():
value = job_result("remote_function_job.json")
value["name"] = "text_features"
diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py
index a3a9e3e20..7e089a96d 100644
--- a/python/python/tests/test_first_class_function_slice2.py
+++ b/python/python/tests/test_first_class_function_slice2.py
@@ -28,6 +28,7 @@ import lancedb
from lancedb import BlobReader
from lancedb.db import AsyncConnection
from lancedb.functions import (
+ FunctionSignature,
FunctionVersion,
HuggingFaceModel,
PythonRuntimeSpec,
@@ -1214,6 +1215,42 @@ def test_explicit_arrow_schema_is_deterministic():
assert signature.output.nullable is False
+def test_nullable_scalar_output_annotation_and_explicit_schema():
+ input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)])
+
+ @function(input_schema=input_schema)
+ def optional_annotation(value: int) -> Optional[int]:
+ return None if value == 0 else value * 2
+
+ @function(input_schema=input_schema)
+ def optional_union(value: int) -> int | None:
+ return None if value == 0 else value * 2
+
+ @function(
+ input_schema=input_schema,
+ output_schema=pa.field("result", pa.int64(), nullable=True),
+ )
+ def explicit_schema(value: int):
+ return None if value == 0 else value * 2
+
+ for definition in (optional_annotation, optional_union, explicit_schema):
+ signature = definition.registration_request.signature
+ assert (signature.output.kind, signature.output.arrow_type) == (
+ "scalar",
+ "int64",
+ )
+ assert signature.output.nullable is True
+ assert json.loads(signature.to_canonical_json())["output"] == {
+ "kind": "scalar",
+ "arrow_type": "int64",
+ "nullable": True,
+ }
+ assert (
+ FunctionSignature.from_json(signature.to_canonical_json()).output.nullable
+ is True
+ )
+
+
def test_blob_fields_use_the_scalar_function_semantic_type():
@function(
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
@@ -1848,12 +1885,6 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
def unsupported(value: set[str]) -> str:
return ""
- with pytest.raises(ValueError, match="output must be non-nullable"):
-
- @function
- def nullable_output(value: int) -> Optional[int]:
- return value
-
with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"):
@function(input_schema=pa.schema([pa.field("value", pa.int64())]))
@@ -1873,10 +1904,25 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
@function(
input_schema=pa.schema([pa.field("value", pa.int64())]),
- output_schema=pa.field("result", pa.int64(), nullable=True),
+ output_schema=pa.field(
+ "result",
+ pa.struct([pa.field("value", pa.int64(), nullable=False)]),
+ nullable=True,
+ ),
)
- def nullable_explicit(value):
- return value
+ def nullable_struct(value):
+ return {"value": value}
+
+ with pytest.raises(
+ ValueError, match="Blob v2 Function output must be non-nullable"
+ ):
+
+ @function(
+ input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
+ output_schema=lancedb.blob("result", nullable=True),
+ )
+ def nullable_blob(image):
+ return image
for invalid_field in [
pa.field("", pa.int32(), nullable=False),
diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py
index b38ae4a5b..fc5b5df73 100644
--- a/python/python/tests/test_remote_db.py
+++ b/python/python/tests/test_remote_db.py
@@ -2076,6 +2076,23 @@ def test_remote_create_index_async_returns_job():
"gpu_count": 2,
}
},
+ {
+ "supervisor_resources": {
+ "cpu_millis": 2000,
+ "memory_bytes": 4 * 1024**3,
+ "ephemeral_storage_bytes": 10 * 1024**3,
+ },
+ "planning_workers": {
+ "resources": {
+ "cpu_millis": 1000,
+ "memory_bytes": 2 * 1024**3,
+ "ephemeral_storage_bytes": 5 * 1024**3,
+ },
+ "max_workers": 4,
+ "rows_per_worker": 100_000,
+ "fragments_per_worker": 8,
+ },
+ },
{"gpu_class": "a10g", "gpu_count": 2},
{
"retry_policy": {"transient": True, "max_attempts": 3},
@@ -2122,6 +2139,9 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
**budget,
"gpu_count": budget.get("gpu_count", 0),
}
+ for key in ("supervisor_resources", "planning_workers"):
+ if refresh_kwargs.get(key) is not None:
+ expected[key] = refresh_kwargs[key]
if refresh_kwargs.get("retry_policy") is not None:
expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate(
refresh_kwargs["retry_policy"]
@@ -2350,6 +2370,51 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle():
},
"unsupported key 'unknown'",
),
+ (
+ {
+ "supervisor_resources": {
+ "cpu_millis": 0,
+ "memory_bytes": 1,
+ "ephemeral_storage_bytes": 1,
+ }
+ },
+ "supervisor_resources.cpu_millis",
+ ),
+ (
+ {
+ "supervisor_resources": {
+ "cpu_millis": 1,
+ "memory_bytes": 1,
+ }
+ },
+ "supervisor_resources.ephemeral_storage_bytes",
+ ),
+ (
+ {
+ "supervisor_resources": {
+ "cpu_millis": 1,
+ "memory_bytes": 1,
+ "ephemeral_storage_bytes": 1,
+ "unknown": 1,
+ }
+ },
+ "unsupported key 'unknown'",
+ ),
+ (
+ {
+ "planning_workers": {
+ "resources": {
+ "cpu_millis": 1,
+ "memory_bytes": 1,
+ "ephemeral_storage_bytes": 1,
+ },
+ "max_workers": 0,
+ "rows_per_worker": 1,
+ "fragments_per_worker": 1,
+ }
+ },
+ "planning_workers.max_workers",
+ ),
(
{"max_executor_processes_per_worker": -2},
"max_executor_processes_per_worker",
@@ -2991,6 +3056,69 @@ def test_remote_job_wait_raises_on_failure():
assert exc_info.value.sql_job_id is None
+@pytest.mark.asyncio
+@pytest.mark.parametrize("sync", [True, False])
+@pytest.mark.parametrize("with_terminal_server", [True, False])
+async def test_remote_job_wait_preserves_terminal_build(sync, with_terminal_server):
+ from lancedb.exceptions import JobFailedError
+
+ message = "ValueError: corrupt frame at frame_index=207"
+ server = {
+ "release": "1.13.0-beta.0",
+ "git_sha": "2a7874ecd589",
+ "build_date": "2026-11-12T22:45:43Z",
+ }
+ result = {"terminal_server": server} if with_terminal_server else None
+
+ def handler(request):
+ assert request.path == "/v1/jobs/describe"
+ request.send_response(200)
+ request.send_header("Content-Type", "application/json")
+ request.send_header(
+ "x-lancedb-server-build",
+ json.dumps({"release": "2.0.0", "git_sha": "new-query-node"}),
+ )
+ request.end_headers()
+ request.wfile.write(
+ json.dumps(
+ {
+ "job_id": "job-provenance",
+ "job_state": "FAILED",
+ "failure": {
+ "phase": "function_refresh_attempt_failed",
+ "message": message,
+ "traceback": "Traceback: original user code",
+ "retryable": False,
+ },
+ "result": result,
+ }
+ ).encode()
+ )
+
+ if sync:
+ with mock_lancedb_connection(handler) as db:
+ job = db.open_job("job-provenance")
+ with pytest.raises(JobFailedError) as caught:
+ job.wait()
+ else:
+ async with mock_lancedb_connection_async(handler) as db:
+ job = await db.open_job("job-provenance")
+ with pytest.raises(JobFailedError) as caught:
+ await job.wait()
+
+ expected = f"Job job-provenance failed: {message}"
+ if with_terminal_server:
+ expected += (
+ " [server: 1.13.0-beta.0 (git 2a7874ecd589, built 2026-11-12T22:45:43Z)]"
+ )
+ expected += " (in function_refresh_attempt_failed)"
+ assert str(caught.value) == expected
+ assert caught.value.job_id == "job-provenance"
+ assert job.failure.message == message
+ assert job.failure.traceback == "Traceback: original user code"
+ assert job.result == result
+
+
@pytest.mark.parametrize("server_version", ["0.2.0", "0.6.0"])
def test_remote_json_fts_config(server_version):
from lancedb.index import FTS
diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py
index 604d6afb3..ce4f57c48 100644
--- a/python/python/tests/test_table.py
+++ b/python/python/tests/test_table.py
@@ -6013,6 +6013,31 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
{"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}},
"resource_budget",
),
+ (
+ {
+ "supervisor_resources": {
+ "cpu_millis": 1000,
+ "memory_bytes": 1024,
+ "ephemeral_storage_bytes": 2048,
+ }
+ },
+ "supervisor_resources",
+ ),
+ (
+ {
+ "planning_workers": {
+ "resources": {
+ "cpu_millis": 1000,
+ "memory_bytes": 1024,
+ "ephemeral_storage_bytes": 2048,
+ },
+ "max_workers": 2,
+ "rows_per_worker": 100,
+ "fragments_per_worker": 1,
+ }
+ },
+ "planning_workers",
+ ),
({"num_workers": 2}, "num_workers"),
({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
],
diff --git a/python/src/expr.rs b/python/src/expr.rs
index bb779bc1d..c4c7cbbb1 100644
--- a/python/src/expr.rs
+++ b/python/src/expr.rs
@@ -164,9 +164,12 @@ pub fn expr_col(name: &str) -> PyExpr {
/// Create a literal value expression.
///
/// Supported Python types: `bool`, `int`, `float`, `str`, `bytes`, `date`,
-/// `datetime`, `Decimal`.
+/// `datetime`, `Decimal`, and `None` (SQL NULL).
#[pyfunction]
pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult {
+ if value.is_none() {
+ return Ok(PyExpr(df_lit(ScalarValue::Null)));
+ }
// bool must be checked before int because bool is a subclass of int in Python
if let Ok(b) = value.extract::() {
return Ok(PyExpr(df_lit(b)));
@@ -174,6 +177,9 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult {
if let Ok(i) = value.extract::() {
return Ok(PyExpr(df_lit(i)));
}
+ if let Ok(i) = value.extract::() {
+ return Ok(PyExpr(df_lit(i)));
+ }
// Decimal must be checked before f64: Python's Decimal implements __float__,
// so value.extract::() would succeed and silently truncate the value to
// f64, losing precision. Build a Decimal128 scalar to preserve it instead.
diff --git a/python/src/table.rs b/python/src/table.rs
index f77ff5a7f..f5270a594 100644
--- a/python/src/table.rs
+++ b/python/src/table.rs
@@ -30,8 +30,9 @@ use lancedb::connection::LanceFileVersion;
use lancedb::index::scalar::FtsIndexBuilder;
use lancedb::table::{
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
- FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionWorkerResourceBudget, IndexRemapMode,
- NewColumnTransform, Ref, RefreshColumnOptions, Table as LanceDbTable,
+ FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig,
+ FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform,
+ Ref, RefreshColumnOptions, Table as LanceDbTable,
};
use lancedb::tokenize as lancedb_tokenize;
use pyo3::{
@@ -52,6 +53,8 @@ struct RefreshColumnArgs {
max_concurrency: Option,
publication_interval_rows: Option,
resource_budget: Option,
+ supervisor_resources: Option,
+ planning_workers: Option,
gpu_class: Option,
gpu_count: Option,
retry_policy: Option,
@@ -159,6 +162,101 @@ fn parse_resource_budget(
))
}
+fn structured_integer(value: &Bound<'_, PyAny>, name: &str) -> PyResult {
+ if value.is_none() || value.is_instance_of::() {
+ return Err(PyValueError::new_err(format!("{name} must be an integer")));
+ }
+ let parsed = value
+ .extract::()
+ .map_err(|_| PyValueError::new_err(format!("{name} must be an integer")))?;
+ if parsed == 0 {
+ return Err(PyValueError::new_err(format!(
+ "{name} must be greater than zero"
+ )));
+ }
+ Ok(parsed)
+}
+
+fn parse_pod_resources(
+ resources: &Bound<'_, PyDict>,
+ prefix: &str,
+) -> PyResult {
+ for key in resources.keys() {
+ let key = key
+ .extract::()
+ .map_err(|_| PyValueError::new_err(format!("{prefix} keys must be strings")))?;
+ if !matches!(
+ key.as_str(),
+ "cpu_millis" | "memory_bytes" | "ephemeral_storage_bytes"
+ ) {
+ return Err(PyValueError::new_err(format!(
+ "{prefix} contains unsupported key '{key}'"
+ )));
+ }
+ }
+ let get = |name: &str| -> PyResult {
+ let value = resources
+ .get_item(name)?
+ .ok_or_else(|| PyValueError::new_err(format!("{prefix}.{name} is required")))?;
+ structured_integer(&value, &format!("{prefix}.{name}"))
+ };
+ Ok(FunctionRefreshPodResources::new(
+ get("cpu_millis")?,
+ get("memory_bytes")?,
+ get("ephemeral_storage_bytes")?,
+ ))
+}
+
+fn parse_supervisor_resources(
+ resources: Option<&Bound<'_, PyDict>>,
+) -> PyResult