From 2f496322ef23bdb27d57e7aea9d151336ab570a4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:51:25 +0800 Subject: [PATCH 01/10] fix: report multipart rows only after part acknowledgement (#5020) Remote multipart progress currently counts every scanned row before the corresponding IPC part is acknowledged. A rejected first part can therefore report uploaded rows, even though its acknowledged byte count remains zero. Count both rows and IPC bytes only after each part succeeds, including parts assembled from multiple batches or split from one batch. Retried parts count once. Native and single-request writes retain their existing accounting; acknowledged multipart progress describes staged data, not a successful commit. Validation follows the actual TCP upload path: one scanned batch becomes six decoded IPC parts, the sixth response is lost, and each request/retry observes only previously acknowledged rows and bytes. Rejection and complete-outcome cases preserve the same accounting boundary. This validation covers local HTTP behavior; deployed service throughput and the original disconnect investigation remain outside its scope. Frozen candidate validation: 839 remote tests and 7 progress tests passed. Scoped Clippy (`lancedb`, remote feature, lib/tests/examples, warnings denied) passed with unchanged source. Python/Node bindings were unchanged and were not rebuilt for this patch. --- docs/web/ingestion/insert.mdx | 7 ++- rust/lancedb/src/remote/table.rs | 2 +- rust/lancedb/src/remote/table/insert.rs | 19 ++++-- rust/lancedb/src/remote/table/write_tests.rs | 63 ++++++++++++++++++-- rust/lancedb/src/table/write_progress.rs | 38 ++++++++---- 5 files changed, 103 insertions(+), 26 deletions(-) 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/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index a7cf3f80d..5c00232f7 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2262,7 +2262,7 @@ impl RemoteTable { num_partitions: usize, ) -> Result { if let Some(tracker) = &output.tracker { - tracker.use_wire_bytes(); + tracker.use_acknowledged_parts(); } let freshness_request = self.snapshot_freshness_headers(); let upload_id = self.create_multipart_write(output.retries).await?; diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index 0de1c21cc..0801880f2 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -480,6 +480,7 @@ impl PartRequestCtx<'_, S> { let started = Instant::now(); let mut pending = Some(first); let mut has_batch = false; + let mut part_rows = 0; let mut input_ended = false; loop { let batch = match pending.take().or_else(|| queued.pop_front()) { @@ -520,6 +521,7 @@ impl PartRequestCtx<'_, S> { // A single row and its schema cannot be split further. } has_batch = true; + part_rows += batch.num_rows(); if writer.get_ref().len() as u64 >= max_bytes || max_duration.is_some_and(|limit| started.elapsed() >= limit) { @@ -536,7 +538,7 @@ impl PartRequestCtx<'_, S> { match self.send_part_request(request, freshness).await { Ok(()) => { if let Some(tracker) = tracker { - tracker.record_bytes(body.len()); + tracker.record_acknowledged_part(part_rows, body.len()); } return Ok(input_ended); } @@ -1648,7 +1650,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_records_acknowledged_bytes() { + async fn test_multipart_records_acknowledged_rows_and_bytes() { use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; use futures::StreamExt; @@ -1667,14 +1669,18 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - let observed = Arc::new(Mutex::new(Vec::::new())); + let observed = Arc::new(Mutex::new(Vec::<(usize, usize)>::new())); let observed_cb = observed.clone(); let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { - observed_cb.lock().unwrap().push(p.output_bytes()); + observed_cb + .lock() + .unwrap() + .push((p.output_rows(), p.output_bytes())); })); let tracker = Arc::new(WriteProgressTracker::new(callback, None)); - // Count encoded bytes once when the part is acknowledged. + tracker.use_acknowledged_parts(); + // Count rows from all encoded batches once when the part is acknowledged. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1697,6 +1703,7 @@ mod tests { "batches should all land in a single part" ); let observed = observed.lock().unwrap(); + assert_eq!(observed.last().unwrap().0, 6); assert!( observed.len() == 1, "expected one progress update per acknowledged part: {observed:?}" @@ -1706,7 +1713,7 @@ mod tests { "progress bytes should be monotonic: {observed:?}" ); assert!( - *observed.last().unwrap() > 0, + observed.last().unwrap().1 > 0, "final progress should report bytes: {observed:?}" ); } diff --git a/rust/lancedb/src/remote/table/write_tests.rs b/rust/lancedb/src/remote/table/write_tests.rs index c97619af1..2e0ca1d45 100644 --- a/rust/lancedb/src/remote/table/write_tests.rs +++ b/rust/lancedb/src/remote/table/write_tests.rs @@ -267,17 +267,44 @@ async fn multipart_http_faults_preserve_committed_blob_payloads() { #[tokio::test] async fn multipart_retries_sixth_part_after_reused_connection_closes() { + use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; use datafusion_execution::TaskContext; use datafusion_physical_plan::ExecutionPlan; use futures::TryStreamExt; + let progress = Arc::new(Mutex::new(Vec::new())); + let observed = progress.clone(); + let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { + observed + .lock() + .unwrap() + .push((p.output_rows(), p.output_bytes())); + })); + let tracker = Arc::new(WriteProgressTracker::new(callback, Some(6))); + tracker.use_acknowledged_parts(); + let during_request = progress.clone(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { let mut attempts = Vec::new(); + let mut acknowledged_bytes = 0; let (mut socket, _) = listener.accept().await.unwrap(); for n in 0..6 { let (path, body) = read_request(&mut socket).await; + let rows = StreamReader::try_new(body.as_slice(), None) + .unwrap() + .map(|batch| batch.unwrap().num_rows()) + .sum::(); + assert_eq!(rows, 1, "one scanned batch must split into six parts"); + let reported = *during_request.lock().unwrap().last().unwrap(); + assert_eq!( + reported, + (n, acknowledged_bytes), + "progress must exclude the unacknowledged part" + ); + if n < 5 { + acknowledged_bytes += body.len(); + } attempts.push((path, body)); if n == 5 { break; @@ -291,9 +318,17 @@ async fn multipart_retries_sixth_part_after_reused_connection_closes() { // The sixth part was staged, but the peer closes before response headers. drop(socket); let (mut socket, _) = listener.accept().await.unwrap(); - attempts.push(read_request(&mut socket).await); + let (path, body) = read_request(&mut socket).await; + let reported = *during_request.lock().unwrap().last().unwrap(); + assert_eq!( + reported, + (5, acknowledged_bytes), + "retry must not report the lost acknowledgement" + ); + acknowledged_bytes += body.len(); + attempts.push((path, body)); respond(&mut socket, 200, "{}").await; - attempts + (attempts, acknowledged_bytes) }); let client = RestfulLanceDbClient::try_new( &crate::remote::client::parse_db_url("db://test").unwrap(), @@ -316,7 +351,10 @@ async fn multipart_retries_sixth_part_after_reused_connection_closes() { .unwrap(); let input = arrow_array::record_batch!(("id", Int32, [1, 2, 3, 4, 5, 6])).unwrap(); let plan = Arc::new( - crate::table::datafusion::scannable_exec::ScannableExec::new(Box::new(input), None), + crate::table::datafusion::scannable_exec::ScannableExec::new( + Box::new(input), + Some(tracker.clone()), + ), ); let exec = super::insert::RemoteWriteExec::new_multipart( "test".into(), @@ -325,7 +363,7 @@ async fn multipart_retries_sixth_part_after_reused_connection_closes() { plan, false, "upload-1".into(), - None, + Some(tracker), None, Some(1), None, @@ -335,7 +373,15 @@ async fn multipart_retries_sixth_part_after_reused_connection_closes() { .try_collect::>() .await .unwrap(); - let attempts = server.await.unwrap(); + let (attempts, acknowledged_bytes) = server.await.unwrap(); + let progress = progress.lock().unwrap(); + assert_eq!(*progress.first().unwrap(), (0, 0)); + assert_eq!(*progress.last().unwrap(), (6, acknowledged_bytes)); + assert!( + progress + .windows(2) + .all(|pair| pair[0].0 <= pair[1].0 && pair[0].1 <= pair[1].1) + ); assert_eq!(attempts.len(), 7); assert_eq!( attempts[5], attempts[6], @@ -424,7 +470,12 @@ async fn multipart_rejections_preserve_progress_and_cleanup_boundaries() { let progress = progress.lock().unwrap(); let last = progress.last().unwrap(); assert!(last.2); - assert_eq!(last.0, 2); + assert_eq!( + progress.first().unwrap().0, + 0, + "scan is not an acknowledgement" + ); + assert_eq!(last.0, if stage_status == 200 { 2 } else { 0 }); if stage_status != 200 { assert!( progress.iter().all(|p| p.1 == 0), diff --git a/rust/lancedb/src/table/write_progress.rs b/rust/lancedb/src/table/write_progress.rs index 12e4dd62c..efea4586c 100644 --- a/rust/lancedb/src/table/write_progress.rs +++ b/rust/lancedb/src/table/write_progress.rs @@ -30,9 +30,11 @@ impl WriteProgress { self.elapsed } - /// Number of rows processed by the input scan. + /// Number of rows processed by the writer. /// - /// This does not indicate that the rows have been committed. + /// Remote multipart writes count rows in acknowledged IPC parts, starting + /// at zero and counting retransmissions once. Other writers report rows + /// processed by the input scan. Neither indicates a successful commit. pub fn output_rows(&self) -> usize { self.output_rows } @@ -101,8 +103,8 @@ pub(crate) struct WriteProgressTracker { /// Wire bytes tracked separately by the insert layer. When set (> 0), /// this takes precedence over the in-memory bytes from `rows_and_bytes`. wire_bytes: AtomicUsize, - /// Multipart writes select this before scanning, including zero acknowledgements. - wire_bytes_enabled: AtomicBool, + /// Multipart progress excludes input scanning and counts only acknowledged parts. + acknowledged_parts: AtomicBool, active_tasks: Arc, total_tasks: AtomicUsize, start: Instant, @@ -116,7 +118,7 @@ impl WriteProgressTracker { Self { rows_and_bytes: std::sync::Mutex::new((0, 0)), wire_bytes: AtomicUsize::new(0), - wire_bytes_enabled: AtomicBool::new(false), + acknowledged_parts: AtomicBool::new(false), active_tasks: Arc::new(AtomicUsize::new(0)), total_tasks: AtomicUsize::new(1), start: Instant::now(), @@ -125,9 +127,9 @@ impl WriteProgressTracker { } } - /// Select wire-byte progress, including zero, before polling the input plan. - pub fn use_wire_bytes(&self) { - self.wire_bytes_enabled.store(true, Ordering::Relaxed); + /// Select acknowledged rows and wire bytes before polling the input plan. + pub fn use_acknowledged_parts(&self) { + self.acknowledged_parts.store(true, Ordering::Relaxed); } /// Set the total number of parallel write tasks (the write parallelism). @@ -145,13 +147,29 @@ impl WriteProgressTracker { pub fn record_batch(&self, rows: usize, bytes: usize) { // Lock order: callback first, then rows_and_bytes. This is the only // order used anywhere, so deadlocks cannot occur. + let mut cb = self.callback.lock().unwrap_or_else(|e| e.into_inner()); + let mut guard = self + .rows_and_bytes + .lock() + .unwrap_or_else(|e| e.into_inner()); + if !self.acknowledged_parts.load(Ordering::Relaxed) { + guard.0 += rows; + guard.1 += bytes; + } + let progress = self.snapshot(guard.0, guard.1, false); + drop(guard); + cb(&progress); + } + + /// Record one successfully staged part, after any retries have finished. + pub fn record_acknowledged_part(&self, rows: usize, bytes: usize) { let mut cb = self.callback.lock().unwrap_or_else(|e| e.into_inner()); let mut guard = self .rows_and_bytes .lock() .unwrap_or_else(|e| e.into_inner()); guard.0 += rows; - guard.1 += bytes; + self.wire_bytes.fetch_add(bytes, Ordering::Relaxed); let progress = self.snapshot(guard.0, guard.1, false); drop(guard); cb(&progress); @@ -194,7 +212,7 @@ impl WriteProgressTracker { let wire = self.wire_bytes.load(Ordering::Relaxed); // Prefer wire bytes (actual I/O size) when the insert layer is // tracking them; fall back to in-memory Arrow size otherwise. - let output_bytes = if self.wire_bytes_enabled.load(Ordering::Relaxed) || wire > 0 { + let output_bytes = if self.acknowledged_parts.load(Ordering::Relaxed) || wire > 0 { wire } else { in_memory_bytes From beda423318a33ec70515b6baf4ae92e95918c2d5 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:52:50 +0800 Subject: [PATCH 02/10] fix(node): bind blob byte queries to their response snapshot (#5019) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TypeScript remote `toArrow` and `toArray` could combine scalar values from query snapshot A with Blob payloads from a later snapshot B. Cached table schemas and native descriptor layouts could also leave descriptors in a `blobMode: "bytes"` result. Discover Blob fields and snapshot provenance from the executed query stream, recognizing canonical native v2 descriptors as well as extension-marked fields. Fetch payloads through an independent Rust snapshot handle bound to the query version and immutable dataset identity, without changing the live table. Preserve aliases, nested fields, NULL/empty values, explicit row IDs, and scalar-only results. Hybrid byte queries require matching provenance from both actual responses. Missing or mismatched server provenance fails explicitly; logical-input validation and local materialization remain unchanged. Manual integration validation at `4daf354df`: all five real SDK/NAPI → Sophon REST scenarios passed. Both `toArrow` and `toArray` retain A bytes across overwrite and reject same-name/same-URI recreation even when version and row IDs are reused. A previously cached handle discovers a subsequently added Blob field. Ten actual payload fetches include the two expected identity rejections; later queries on the same live handle read B. The canonical-descriptor and Blob regression suites pass 119 tests, with independent source and wire-evidence review. Earlier broader SDK and hybrid evidence is retained within its unchanged-source scope. This is local REST interoperability evidence, not deployed Cloud/header-forwarding acceptance. Remote bytes require the authoritative server version/identity and fetch-echo contract. CI and formal review remain merge requirements; this follow-up does not close ENT-3556 or Blob V2 GA. --- .../js/interfaces/QueryExecutionOptions.md | 6 +- docs/web/management/table.mdx | 19 + nodejs/__test__/remote_blob_snapshot.test.ts | 642 ++++++++++++++++++ nodejs/lancedb/blob.ts | 42 +- nodejs/lancedb/query.ts | 71 +- nodejs/src/table.rs | 25 + rust/lancedb/src/query.rs | 36 +- 7 files changed, 828 insertions(+), 13 deletions(-) create mode 100644 nodejs/__test__/remote_blob_snapshot.test.ts 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/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__/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/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/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/src/table.rs b/nodejs/src/table.rs index f6abeb553..c82c2cd93 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -349,6 +349,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 { diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index f96e84e96..157440910 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -42,7 +42,7 @@ use lance_index::vector::DIST_COL; use crate::error::{Error, Result}; use crate::rerankers::rrf::RRFReranker; use crate::rerankers::{NormalizeMethod, Reranker, check_reranker_result}; -use crate::table::BaseTable; +use crate::table::{BaseTable, NativeTableExt}; use crate::utils::{MaxBatchLengthStream, TimeoutStream}; use crate::{ApproxMode, DistanceType}; use crate::{ @@ -1564,14 +1564,32 @@ impl VectorQuery { vector_query.inner_execute_with_options(internal_options) )?; + // A reranker can replace schema metadata. Only the two producing + // streams can establish the snapshot of a remote hybrid result. + let snapshot = |schema: SchemaRef| { + schema + .metadata() + .get("lancedb:query_version") + .zip(schema.metadata().get("lancedb:query_snapshot")) + .map(|(version, identity)| (version.clone(), identity.clone())) + }; + let stream_schemas = (fts_results.schema(), vec_results.schema()); + let fts_snapshot = snapshot(stream_schemas.0.clone()); + let vec_snapshot = snapshot(stream_schemas.1.clone()); + let query_snapshot = fts_snapshot.filter(|value| Some(value) == vec_snapshot.as_ref()); + let (fts_results, vec_results) = try_join!( fts_results.try_collect::>(), vec_results.try_collect::>() )?; - // try to get the schema to use when combining batches. - // if either - let (fts_schema, vec_schema) = hybrid::query_schemas(&fts_results, &vec_results); + // Preserve remote output schemas even when a leg has no batches. + // The WAL primary-key fallback retains its synthesized score schema. + let (fts_schema, vec_schema) = if self.parent.as_native().is_none() && pk_fusion.is_none() { + stream_schemas + } else { + hybrid::query_schemas(&fts_results, &vec_results) + }; // concatenate all the batches together let mut fts_results = concat_batches(&fts_schema, fts_results.iter())?; @@ -1612,6 +1630,16 @@ impl VectorQuery { check_reranker_result(&results)?; + if self.parent.as_native().is_none() { + let metadata = results.schema_metadata_mut(); + metadata.remove("lancedb:query_version"); + metadata.remove("lancedb:query_snapshot"); + if let Some((version, identity)) = query_snapshot { + metadata.insert("lancedb:query_version".into(), version); + metadata.insert("lancedb:query_snapshot".into(), identity); + } + } + let limit = self.request.base.limit.unwrap_or(DEFAULT_TOP_K); if results.num_rows() > limit { results = results.slice(0, limit); From 193f203b720e6825299e9cf72f9d9695c5d4c72d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:54:19 +0800 Subject: [PATCH 03/10] ci: run remote Functions gate only in the full test suite (#5022) The remote job runs the default local Functions gate twice: once before building the remaining test targets, and again in the full remote suite. Run it only through the existing full suite, removing the serial Cargo invocation barrier while retaining the same features, authentication wrapper, targets, and 30-minute deadline. The [hosted remote job](https://github.com/lancedb/lancedb/actions/runs/43302507952/job/131477104217) at `7886d79e` completed successfully in 25m36s within the unchanged 30-minute limit. Its full suite passed 2,164 unit, 114 integration, and 120 doctests, including the three default gate tests. This single run establishes completion for that workload, not a general timing improvement or cold-build guarantee. The branch now includes main's Cargo artifact fixture repair (#5010). The workflow, full-suite command, authentication wrapper, three default Functions gate tests, and 30-minute deadline are unchanged from that hosted run. The 2,398-test result remains evidence for `7886d79e`. On the updated head `810d6558`, the [hosted remote job](https://github.com/lancedb/lancedb/actions/runs/43382023177/job/131741745645) completed in 17m58s with 2,171 unit tests, 119 integration tests, and 122 doctests passing (82 ignored), including all three default Functions gate tests. This is current-head execution evidence, not a controlled speedup comparison. --- .github/workflows/rust.yml | 2 -- 1 file changed, 2 deletions(-) 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 From 56c4b3a6f2886b62e246e0a04da89ddf002dd7a8 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:55:23 +0800 Subject: [PATCH 04/10] ci: stabilize macOS Node toolchain and build budget (#5017) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The macOS Node job installed floating stable before restoring the Rust cache, although native builds use the repository-pinned compiler. Use the existing file-aware Rust setup action with its implicit cache disabled so setup, cache selection and compilation use the same pin and one cache owner. Preserve the existing native build flags. Allow 35 minutes for the complete macOS job. In the [pinned-toolchain cold run](https://github.com/lancedb/lancedb/actions/runs/43291714333/job/131439350321), native compilation finished in 28m02s, but setup and packaging exhausted the former 30-minute job limit before TypeScript checking and Jest. Retained full Jest runs took 38–59 seconds; the new bound covers the measured work with a small margin. The runner, build profile, features, targets and complete test commands are preserved. Hosted acceptance at `ff718c03`: the [complete macOS job](https://github.com/lancedb/lancedb/actions/runs/43300424344/job/131469805138) succeeded within the 35-minute limit (20:27:07–20:56:58 UTC). Native compilation took 27m38s; the complete applicable Jest suite passed 1,695 tests, with 22 skipped, in 46.129s. This single successful run does not guarantee every cold-build duration, validate the separate beta19 composition, or establish the cause of the DynamoDB timeout. --- .github/workflows/nodejs.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) 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 From 0d55457d9e030c901da64fdd24d3c88ae255e06e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:57:49 +0800 Subject: [PATCH 05/10] test(node): make blob read cancellation deterministic (#5029) The Node blob cancellation test assumes a 32 MiB local read is still in flight when JavaScript immediately aborts. The native future can finish first, in which case returning its completed buffer is valid. Replace that timing assumption with the existing HTTP fixture: send one byte of a five-byte range response, hold back the remaining body, then abort. Verify `AbortError`, response disconnection, listener cleanup, and a subsequent read on the same handle with the single request permit. Existing local pre-abort, successful-read, cursor, and close coverage remains in place; production cancellation semantics are unchanged. Validated the 97 scoped Blob tests on Linux x64 / Node 22.23.4 with both a locally built beta18 binding and the [beta19 native binding built for #4967](https://github.com/lancedb/lancedb/actions/runs/43381450237/job/131739908253). The beta19 run used the published repair tests at `8096f848`, passed all 97 cases with exit 0, and verified the downloaded artifact digest, loaded binding hash, and native build checkout against #4967's source tree. The pre-existing `CustomGC` import diagnostic remains; the process exited normally. The [hosted macOS ARM64 job](https://github.com/lancedb/lancedb/actions/runs/43395339041/job/131784902005) also passed the cancellation regression and the complete applicable Jest suite: 1,695 tests passed and 22 were skipped on Node 24.22.2 / beta18. Its actual merge checkout `e906a2da` has matching test, native Blob, dependency, and workflow sources to PR head `8096f848`. A separate [macOS ARM64 / Node 22.23.4 / beta19 composition run](https://github.com/lancedb/lancedb/actions/runs/43559120836/job/132353156252) now passed 1,694 tests (23 skipped), including both in-flight cancellation and later-response-body cancellation/permit release. It tested the normal merge of #4967 `6b175764` and this repair `8096f848`, at validation head `144e5294` whose only subsequent change narrows the workflow and disables publication. The loaded native binding hash and downloaded artifact digest were captured. The original failed #4967 job is preserved; this separate validation does not replace normal prerequisite integration or current-branch CI on #4967. --- nodejs/__test__/blob_ranges.test.ts | 73 +++++++++++++++++++++++++---- nodejs/__test__/table.test.ts | 23 --------- 2 files changed, 64 insertions(+), 32 deletions(-) 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__/table.test.ts b/nodejs/__test__/table.test.ts index 59d6929b4..2c45dbccd 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" }); From 005b33fa8b8884356ba465ebe93bdbbb4831329a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:10 +0800 Subject: [PATCH 06/10] fix: preserve terminal server identity in failed job waits (#5024) A failed remote Function job loses its persisted build identity when converted into the exception from `job.wait()`. Append `result.terminal_server` to that error using the existing server-build format, preserving its message, row location, traceback and job ID. Do not substitute the responding query node's version for the writer of the saved terminal result; missing or malformed historical identity leaves the error unchanged. The reported failure was independently reproduced against a deployed server with a real Function job. The new exact Rust regression reproduces the missing terminal identity on the unpatched code. At `59c1f3e`, all 10 remote Job Rust tests and five tests using the matching native Python extension passed, including sync/async waits with known or unknown terminal identity. These transport tests use mocked HTTP responses; the original deployed Function job remains with independent acceptance for recheck after delivery. This change does not establish whole-ticket acceptance. --- python/python/tests/test_remote_db.py | 63 +++++++++++++++++ rust/lancedb/src/remote/job.rs | 98 +++++++++++++++++++++++++-- 2 files changed, 155 insertions(+), 6 deletions(-) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b38ae4a5b..c5afac308 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2991,6 +2991,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/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index c546ce4d1..7e59834d0 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -322,14 +322,32 @@ impl JobHandle for RemoteJob { match description.state() { JobState::Done => return Ok(description.into_terminal_result(request_id)), JobState::Failed => { + let mut failure = description + .failure + .map(ReportedFailure::into_job_failure) + .unwrap_or_default(); + // The responding query node may have upgraded since this job + // failed. Only its persisted terminal writer identifies the failure. + if let Some(server) = description + .result + .as_ref() + .and_then(|result| result.get("terminal_server")) + .and_then(|server| { + serde_json::from_value::( + server.clone(), + ) + .ok() + }) + { + let provenance = format!("[server: {server}]"); + failure.message = Some(match failure.message { + Some(message) => format!("{message} {provenance}"), + None => provenance, + }); + } return Err(Error::JobFailed { job_id: Some(self.job_id.clone()), - failure: Box::new( - description - .failure - .map(ReportedFailure::into_job_failure) - .unwrap_or_default(), - ), + failure: Box::new(failure), }); } JobState::Cancelled => { @@ -662,4 +680,72 @@ mod tests { assert_eq!(failure.retryable, Some(true)); assert_eq!(failure.sql_job_id.as_deref(), Some("job-1")); } + + #[tokio::test] + async fn wait_failure_uses_persisted_terminal_build() { + let server = serde_json::json!({ + "release": "1.13.0-beta.0", + "git_sha": "2a7874ecd589", + "build_date": "2026-11-12T22:45:43Z" + }); + for result in [ + serde_json::Value::Null, + serde_json::json!({"terminal_server": null}), + serde_json::json!({"terminal_server": {"release": "incomplete"}}), + serde_json::json!({"terminal_server": server}), + ] { + let known_build = result["terminal_server"] == server; + let response = serde_json::json!({ + "job_id": "job-1", + "job_state": "FAILED", + "failure": { + "phase": "function_refresh_attempt_failed", + "message": "ValueError: corrupt frame at frame_index=207", + "traceback": "Traceback: original user code", + "retryable": false + }, + "result": result + }); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + http::Response::builder() + .status(200) + .header( + "x-lancedb-server-build", + r#"{"release":"2.0.0","git_sha":"new-query-node"}"#, + ) + .body(response.to_string()) + .unwrap() + }); + let job = RemoteJob::new(client, "job-1".to_string()); + let description = job.describe().await.unwrap(); + assert_eq!( + description.result.as_ref(), + (!result.is_null()).then_some(&result) + ); + assert_eq!( + description.failure.unwrap().message.as_deref(), + Some("ValueError: corrupt frame at frame_index=207") + ); + let error = job.wait().await.err().expect("failed job"); + let mut expected = + "Job job-1 failed: ValueError: corrupt frame at frame_index=207".to_string(); + if known_build { + expected.push_str( + " [server: 1.13.0-beta.0 (git 2a7874ecd589, built 2026-11-12T22:45:43Z)]", + ); + } + expected.push_str(" (in function_refresh_attempt_failed)"); + assert_eq!(error.to_string(), expected); + let crate::error::Error::JobFailed { job_id, failure } = error else { + panic!("expected JobFailed"); + }; + assert_eq!(job_id.as_deref(), Some("job-1")); + assert_eq!( + failure.traceback.as_deref(), + Some("Traceback: original user code") + ); + assert_eq!(failure.retryable, Some(false)); + } + } } From e5a5b67212ccc75ca7b69f3ac53de3dc045ffb34 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:20 +0800 Subject: [PATCH 07/10] feat: support nullable scalar Function declarations (#5030) Function declarations currently reject nullable scalar returns. Accept `Optional[T]`, `T | None`, and explicit nullable Arrow fields, preserving `nullable: true` in registration signatures, JSON round trips, and remote `add_columns` requests. The Rust planner accepts nullable scalar outputs, and binding readback recognizes the server-owned assignment marker for a single nullable scalar result. Clients do not allocate that marker. Non-nullable whole results, whole structs, and Blob v2 retain their existing assignment restrictions. Validated with 127 Python tests, 30 documentation tests (1 skipped), and seven focused Rust tests covering planning, binding readback, rejection boundaries, and the remote request body. The final condition-collapse change addresses strict Clippy; its delta check and CI are pending. Python tests use a source overlay on a retained native extension, and Rust remote coverage uses HTTP mocks. Server support and end-to-end validation remain separate. This PR does not claim that server publication distinguishes computed NULL values from pending rows. --- docs/web-tests/py/test_function.py | 28 +- docs/web/curation/create-function.mdx | 11 +- docs/web/management/function.mdx | 42 ++- python/python/lancedb/functions.py | 35 +- .../tests/test_first_class_function_slice2.py | 64 +++- rust/lancedb/src/function.rs | 4 +- rust/lancedb/src/remote/table.rs | 77 +++++ rust/lancedb/src/table/computed_columns.rs | 306 +++++++++++++++++- 8 files changed, 517 insertions(+), 50 deletions(-) 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/management/function.mdx b/docs/web/management/function.mdx index 27f45cb6a..57a16dbf2 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} diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index f04d3d481..86230be52 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -312,7 +312,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 @@ -1399,12 +1403,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 +1508,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 +2654,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 +2765,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 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/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index d1b63f2ad..387c80364 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1032,8 +1032,8 @@ pub struct OutputMapping { pub nullable: bool, } -/// Internal physical column preserving the parent validity of a flattened -/// named-struct result. +/// Internal physical column preserving assignment of a nullable scalar result +/// or the parent validity of a flattened named-struct result. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AssignmentMapping { pub output_name: String, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 5c00232f7..72d67fb5a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -10802,6 +10802,83 @@ mod tests { assert_eq!(result.version, 8); } + #[tokio::test] + async fn test_add_nullable_scalar_function_column_sends_atomic_null_declaration() { + let table = Table::new_with_handler("my_table", |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body( + r#"{"version":1,"schema":{"fields":[{"name":"description","nullable":true,"type":{"type":"string"}}]}}"#, + ) + .unwrap(), + "/v1/table/my_table/add_columns/" => { + let actual: serde_json::Value = serde_json::from_slice( + request.body().unwrap().as_bytes().unwrap(), + ) + .unwrap(); + assert_eq!( + actual["new_columns"], + serde_json::json!([ + {"name": "maybe", "all_null": true} + ]) + ); + assert_eq!( + actual["function"]["application"]["output"], + serde_json::json!({ + "kind": "scalar", + "arrow_type": "int64", + "nullable": true + }) + ); + assert_eq!( + actual["function"]["output_schema"], + serde_json::json!({ + "fields": [{ + "name": "maybe", + "nullable": true, + "type": {"type": "int64"} + }] + }) + ); + assert_eq!( + actual["function"]["outputs"], + serde_json::json!([ + { + "result_field": "$value", + "output_name": "maybe", + "output_ordinal": 0 + } + ]) + ); + assert!(actual["function"].get("assignment").is_none()); + assert_eq!(actual["auto_refresh_enabled"], serde_json::json!(true)); + http::Response::builder() + .status(200) + .body(r#"{"version":8}"#) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + } + }); + let application = crate::function::FunctionApplication::from_json( + r#"{ + "function":{"name":"nullable_scalar","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], + "output":{"kind":"scalar","arrow_type":"int64","nullable":true} + }"#, + ) + .unwrap(); + + let result = table + .add_columns() + .function_as("maybe", application) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 8); + } + /// The fixture binding's table: `title` and `body` bound as inputs, its /// two outputs declared, plus an unbound `spare`. fn fixture_bound_schema() -> Schema { diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 64e90b246..b01f45d06 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -40,7 +40,7 @@ use lance_namespace::models::{JsonArrowDataType, JsonArrowField, JsonArrowSchema use serde::{Deserialize, Serialize}; use serde_json::Value; -use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding}; +use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding, OutputMapping}; use crate::materialized_view::without_declarations; use crate::table::FunctionWorkerResourceBudget; use crate::utils::resolve_arrow_field_path; @@ -1289,6 +1289,21 @@ fn function_output_type_matches(expected: &DataType, actual: &DataType) -> bool } } +/// Whether a whole-result binding may carry the server-owned assignment marker. +/// +/// Only a nullable scalar result needs a marker to distinguish a computed NULL +/// from an unfilled row. A non-nullable result, a whole named-struct column, +/// and a Blob v2 value keep their existing rejection. +fn nullable_scalar_allows_assignment(output: &OutputMapping) -> Result { + if !output.nullable || output.arrow_type == FUNCTION_BLOB_V2_TYPE { + return Ok(false); + } + let json = parse_output_arrow_type(&output.arrow_type)?; + let data_type = lance_namespace::schema::convert_json_arrow_type(&json) + .map_err(|e| invalid_function(format!("invalid Function output type: {e}")))?; + Ok(!matches!(data_type, DataType::Struct(_))) +} + fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding) -> Result<()> { let mut input_fields = Vec::with_capacity(binding.inputs().len()); for input in binding.inputs() { @@ -1419,13 +1434,14 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding } let mut declared_output_schema = binding.output_schema().cloned(); if let Some(assignment) = binding.assignment() { - if binding + if let Some(whole_result) = binding .outputs() .iter() - .any(|output| output.result_field == WHOLE_RESULT_FIELD) + .find(|output| output.result_field == WHOLE_RESULT_FIELD) + && (binding.outputs().len() != 1 || !nullable_scalar_allows_assignment(whole_result)?) { return Err(invalid_function(format!( - "Function binding '{}' cannot attach an assignment column to a whole result", + "Function binding '{}' cannot attach an assignment column to a whole result; only a single nullable scalar output permits one", binding.binding_id() ))); } @@ -1552,14 +1568,17 @@ pub(crate) fn plan_function_application( "a scalar Function application must be mapped to one output column", ) })?; - if output.nullable != Some(false) { - return Err(invalid_function( - "Function logical outputs must be non-nullable during NULL assignment", - )); - } + let nullable = output.nullable.ok_or_else(|| { + invalid_function("scalar Function output must declare nullability") + })?; let arrow_type = output.arrow_type.as_deref().ok_or_else(|| { invalid_function("scalar Function output is missing its Arrow type") })?; + if nullable && arrow_type == FUNCTION_BLOB_V2_TYPE { + return Err(invalid_function( + "Blob v2 Function outputs cannot be nullable", + )); + } outputs.push(FunctionOutputTarget { result_field: WHOLE_RESULT_FIELD.to_string(), output_name: name.to_string(), @@ -4054,6 +4073,22 @@ mod tests { .unwrap() } + fn nullable_scalar_application() -> FunctionApplication { + FunctionApplication::from_json( + &serde_json::json!({ + "function": {"name": "nullable_scalar", "version": "1", "object_id": "fixture", "location": "memory:///fixture", "manifest_digest": "sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "inputs": [{ + "parameter": "value", + "kind": "column", + "value": {"path": "value"} + }], + "output": {"kind": "scalar", "arrow_type": "int64", "nullable": true} + }) + .to_string(), + ) + .unwrap() + } + fn binding_from_plan(plan: &FunctionDeclarationPlan) -> FunctionBinding { let inputs = plan .input_bindings @@ -4363,6 +4398,259 @@ mod tests { )); } + #[test] + fn test_nullable_scalar_application_plans_one_nullable_output() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input]), + &nullable_scalar_application(), + Some("maybe"), + ) + .unwrap(); + + assert_eq!(plan.application.output().nullable, Some(true)); + assert_eq!(plan.outputs.len(), 1); + assert_eq!(plan.outputs[0].result_field, WHOLE_RESULT_FIELD); + assert_eq!(plan.outputs[0].output_name, "maybe"); + assert_eq!(plan.outputs[0].output_ordinal, 0); + assert_eq!(plan.output_schema.fields.len(), 1); + assert!(plan.output_schema.fields[0].nullable); + assert_eq!(plan.output_schema.fields[0].r#type.r#type, "int64"); + } + + #[test] + fn test_invalid_nullable_scalar_applications_fail_closed() { + let input = ArrowField::new("value", DataType::Int64, false); + let schema = ArrowSchema::new(vec![input]); + + let mut missing_nullability = serde_json::to_value(nullable_scalar_application()).unwrap(); + missing_nullability["output"] + .as_object_mut() + .unwrap() + .remove("nullable"); + let application = FunctionApplication::from_json(&missing_nullability.to_string()).unwrap(); + let err = plan_function_application(&schema, &application, Some("maybe")).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("declare nullability")), + "{err:?}" + ); + + let nullable_blob = + blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":true}"#); + let err = plan_function_application( + &ArrowSchema::new(vec![crate::blob("image", false)]), + &nullable_blob, + Some("copy"), + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("Blob v2") && message.contains("nullable")), + "{err:?}" + ); + } + + #[test] + fn test_nullable_scalar_binding_accepts_server_owned_assignment() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &nullable_scalar_application(), + Some("maybe"), + ) + .unwrap(); + let assignment_name = "__function_assignment_nullable_scalar"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = ArrowField::new("maybe", DataType::Int64, true).with_metadata( + function_computed_column_metadata(binding.binding_id(), 0, &["value".into()]), + ); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["value".into()], + ), + ); + + let schema = ArrowSchema::new(vec![input.clone(), output.clone(), assignment]); + ensure_binding_matches_schema(&schema, &binding).unwrap(); + let hidden = ArrowSchema::new(vec![input, output]); + ensure_binding_matches_schema(&hidden, &binding).unwrap(); + + let schema = ArrowSchema::new_with_metadata( + schema.fields().to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + function_bindings_metadata(std::slice::from_ref(&binding)).unwrap(), + )]), + ); + ensure_supported_function_metadata(&schema).unwrap(); + } + + #[test] + fn test_non_nullable_scalar_binding_rejects_server_owned_assignment() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &single_input_application("value"), + Some("maybe"), + ) + .unwrap(); + let assignment_name = "__function_assignment_non_nullable_scalar"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = ArrowField::new("maybe", DataType::Int64, true).with_metadata( + function_computed_column_metadata(binding.binding_id(), 0, &["value".into()]), + ); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["value".into()], + ), + ); + + let err = ensure_binding_matches_schema( + &ArrowSchema::new(vec![input, output, assignment]), + &binding, + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + + #[test] + fn test_named_struct_whole_binding_rejects_server_owned_assignment() { + let plan = plan_function_application( + &function_input_schema(), + &named_struct_application("{}"), + Some("features"), + ) + .unwrap(); + let assignment_name = "__function_assignment_whole_struct"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = + lance_namespace::schema::convert_json_arrow_field(&plan.output_schema.fields[0]) + .unwrap() + .with_metadata(function_computed_column_metadata( + binding.binding_id(), + 0, + &["title".into(), "body".into()], + )); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["title".into(), "body".into()], + ), + ); + let mut fields = function_input_schema() + .fields() + .iter() + .map(|field| field.as_ref().clone()) + .collect::>(); + fields.push(output); + fields.push(assignment); + + let err = ensure_binding_matches_schema(&ArrowSchema::new(fields), &binding).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + + #[test] + fn test_blob_whole_binding_rejects_server_owned_assignment() { + let input = crate::blob("image", false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#), + Some("thumbnail"), + ) + .unwrap(); + let assignment_name = "__function_assignment_whole_blob"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let mut metadata = full_blob_field("thumbnail", true).metadata().clone(); + metadata.extend(function_computed_column_metadata( + binding.binding_id(), + 0, + &["image".into()], + )); + let output = full_blob_field("thumbnail", true).with_metadata(metadata); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["image".into()], + ), + ); + + let err = ensure_binding_matches_schema( + &ArrowSchema::new(vec![input, output, assignment]), + &binding, + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + #[test] fn test_nullable_function_input_cannot_bind_to_non_nullable_parameter() { let mut raw_binding: Value = serde_json::from_str(include_str!( From 4843ac4c7e32785a03f5382bffb4a34a82bf8e26 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:41 +0800 Subject: [PATCH 08/10] fix(remote): observe new publications while waiting for Function freshness (#5033) Remote `wait_fresh()` could keep observing a cached table version after automatic refresh published new outputs. Each poll on a latest handle now requests a current snapshot, so the wait can finish without an external `checkout_latest()` call. Explicit version, tag, and query-snapshot selections remain pinned. The wait preserves existing finalization-pending and error handling and continues to perform read-only status requests. --- rust/lancedb/src/remote/table.rs | 288 ++++++++++++++++++++++++++++++- rust/lancedb/src/table.rs | 13 ++ 2 files changed, 300 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 72d67fb5a..4e9458870 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2799,6 +2799,20 @@ impl BaseTable for RemoteTable { Ok(()) } + async fn checkout_latest_if_latest(&self) -> Result<()> { + let write_guard = self.version.write().await; + if write_guard.is_some() || self.expected_query_snapshot.is_some() { + return Ok(()); + } + // Poll within the same timeline: in-flight writes must still advance + // its watermarks. Only an explicit checkout changes the generation. + let mut state = self.freshness.lock().unwrap(); + let now = SystemTime::now(); + state.checkout_baseline = Some(state.checkout_baseline.map_or(now, |t| t.max(now))); + drop(state); + self.invalidate_schema_cache(); + Ok(()) + } async fn snapshot_at_current_version(&self) -> Result>> { // A checked-out handle already names its snapshot. Otherwise resolve // latest exactly once before creating the independent pinned handle. @@ -4756,8 +4770,8 @@ impl TryFrom for MergeInsertRequest { #[cfg(test)] mod tests { - use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; use std::time::Duration; use std::{collections::HashMap, pin::Pin}; @@ -12023,6 +12037,278 @@ mod tests { assert_eq!(calls.load(Ordering::SeqCst), 1); } + #[tokio::test] + async fn test_wait_for_function_column_observes_latest_publications_without_checkout() { + let calls = Arc::new(AtomicUsize::new(0)); + let observed_headers = Arc::new(Mutex::new(Vec::new())); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + let observed_headers = observed_headers.clone(); + move |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().path(), + "/v1/table/my_table/function_columns/status" + ); + let query: std::collections::BTreeMap<_, _> = request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert!( + !query.contains_key("version"), + "a latest status poll must not use an explicit version" + ); + + let min_timestamp = request + .headers() + .get("x-lancedb-min-timestamp") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let min_read_version = request + .headers() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + observed_headers + .lock() + .unwrap() + .push((min_timestamp.clone(), min_read_version)); + + let call = calls.fetch_add(1, Ordering::SeqCst); + let (version, fresh, never_computed) = if call > 0 && min_timestamp.is_some() { + (11, 2, 0) + } else { + (4, 0, 2) + }; + http::Response::builder() + .status(200) + .header("x-lancedb-version", version.to_string()) + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":{version}, + "rows":2, + "fresh":{fresh}, + "stale":0, + "never_computed":{never_computed}, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + }); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 11); + assert_eq!(status.fresh, 2); + assert_eq!(status.never_computed, 0); + assert_eq!(calls.load(Ordering::SeqCst), 2); + + let observed_headers = observed_headers.lock().unwrap(); + assert_eq!(observed_headers.len(), 2); + assert!( + observed_headers[0].0.is_some(), + "the first latest poll must establish a current timestamp baseline" + ); + assert!( + observed_headers[1].0.is_some(), + "each latest poll must advance the timestamp baseline" + ); + assert_eq!( + observed_headers[1].1.as_deref(), + Some("4"), + "the latest poll must retain the monotonic read watermark" + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_wait_for_function_column_preserves_inflight_write_fence() { + let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = std::sync::Arc::new(std::sync::Mutex::new(release_rx)); + let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let captured = requests.clone(); + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/update/" => { + arrived_tx.send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(std::time::Duration::from_secs(15)) + .unwrap(); + http::Response::builder() + .status(200) + .header("x-lancedb-version", "5") + .body(r#"{"rows_updated":2,"version":5}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + // This node caches version 4 during the status request, + // after its timestamp fence and before the write commits. + assert!(request.headers().contains_key("x-lancedb-min-timestamp")); + http::Response::builder() + .status(200) + .header("x-lancedb-version", "4") + .body( + r#"[{"column":"embedding","binding_id":"fb_01", + "function":{"name":"embed","object_id":"embed", + "location":"objects/embed","version":"7", + "manifest_digest":"sha256:abc"}, + "table_version":4,"rows":2,"fresh":2,"stale":0, + "never_computed":0,"failed":0, + "auto_refresh":{"enabled":false,"state":"disabled", + "failure_streak":0,"next_run_at_millis":null}}]"# + .to_string(), + ) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + captured.lock().unwrap().push(request.headers().clone()); + // The timestamp still admits the cached pre-write view. + // The write-version fence is what must force a refresh. + let count = if request + .headers() + .get("x-lancedb-min-version") + .and_then(|v| v.to_str().ok()) + == Some("5") + { + "2" + } else { + "1" + }; + http::Response::builder() + .status(200) + .body(count.to_string()) + .unwrap() + } + path => panic!("unexpected path: {path}"), + } + }); + let update = tokio::spawn({ + let table = table.clone(); + async move { table.update().column("a", "a + 1").execute().await } + }); + tokio::task::spawn_blocking(move || { + arrived_rx + .recv_timeout(std::time::Duration::from_secs(15)) + .unwrap() + }) + .await + .unwrap(); + table + .wait_for_function_column("embedding", Some(std::time::Duration::from_secs(2))) + .await + .unwrap(); + release_tx.send(()).unwrap(); + assert_eq!(update.await.unwrap().unwrap().version, 5); + // With initial values [0, 1], a += 1 changes a > 0 from one row to two. + let count = table.count_rows(Some("a > 0".to_string())).await.unwrap(); + let requests = requests.lock().unwrap(); + let headers = &requests[0]; + assert_eq!( + headers + .get("x-lancedb-min-version") + .and_then(|v| v.to_str().ok()), + Some("5"), + "polling must not discard an in-flight write's returned version" + ); + assert_eq!( + count, 2, + "read after completed write must observe the write" + ); + } + + #[tokio::test] + async fn test_wait_for_function_column_does_not_unpin_a_pinned_handle() { + let status_calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let status_calls = status_calls.clone(); + move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + assert_eq!(request_body_json(&request)["version"], 42); + http::Response::builder() + .status(200) + .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + let query: std::collections::BTreeMap<_, _> = + request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert_eq!(query.get("version").map(|value| value.as_ref()), Some("42")); + assert!( + !request.headers().contains_key("x-lancedb-min-timestamp"), + "a pinned status poll must not carry latest freshness headers" + ); + let call = status_calls.fetch_add(1, Ordering::SeqCst); + let (fresh, never_computed) = if call == 0 { (0, 2) } else { (2, 0) }; + http::Response::builder() + .status(200) + .header("x-lancedb-version", "42") + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":42, + "rows":2, + "fresh":{fresh}, + "stale":0, + "never_computed":{never_computed}, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + table.checkout(42).await.unwrap(); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(status.fresh, 2); + assert_eq!(status.never_computed, 0); + assert_eq!(status_calls.load(Ordering::SeqCst), 2); + } + #[tokio::test] async fn test_function_column_status_decodes_agent_up_to_date() { let table = Table::new_with_handler("my_table", |_request| { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index ff0ab8b94..b9708f16b 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1009,6 +1009,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn checkout_tag(&self, tag: &str) -> Result<()>; /// Checkout the latest version of the table. async fn checkout_latest(&self) -> Result<()>; + /// Advance a latest handle to the current snapshot before a polling read. + /// + /// Pinned version, tag, and snapshot handles must remain unchanged. This + /// lets a freshness wait observe publications that arrive after it starts + /// without changing an explicit time-travel selection. + #[doc(hidden)] + async fn checkout_latest_if_latest(&self) -> Result<()> { + Ok(()) + } /// Return an independent handle pinned to the version currently selected. /// /// Backends that can advance between requests should override this for @@ -2328,6 +2337,9 @@ impl Table { /// Failed rows do not keep the call pending. A typed /// `function_column_status_finalization_pending` response is retried with /// bounded exponential backoff; every other error is returned immediately. + /// Latest handles checkout the current snapshot before each poll so they + /// observe publications that happened after the wait started. Pinned + /// handles keep their explicit version. pub async fn wait_for_function_column( &self, column: &str, @@ -2336,6 +2348,7 @@ impl Table { let started = std::time::Instant::now(); let mut delay = std::time::Duration::from_millis(250); loop { + self.inner.checkout_latest_if_latest().await?; let result = self.function_column_status(column).await; match result { Ok(status) if status.stale == 0 && status.never_computed == 0 => return Ok(status), From f6f8119ba4fc285914f084fde560ea4e7affd9af Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:44 +0800 Subject: [PATCH 09/10] feat: expose structured Function refresh options in SDKs (#5047) ## Problem ENT-3267 still lacks typed refresh controls for `supervisor_resources` and `planning_workers` in Python, Rust, and Node, and Node has no `retry_policy` refresh option. Callers must drop to SQL for those controls. ## Change - Add canonical Rust `FunctionRefreshPodResources` and `FunctionRefreshPlanningConfig`, and serialize them through `RefreshColumnOptions`. - Expose both options in the Python sync/async wrappers and PyO3 binding. - Expose both options in the Node NAPI object and add a Node `retryPolicy` object backed by the existing Rust `FunctionRetryPolicy`. - Omitted options stay omitted; branch targeting continues through the table handle. No server, dependency, or pin changes are included. Client-side checks only reject non-positive structural values. Deployment resource limits and column-kind validation remain server-side. ## Validation `cargo fmt --all -- --check`, `python3 -m py_compile`, and `git diff --check` pass. No native build was run locally; CI compiles and tests the change. Generated JS API pages are unchanged. --- docs/src/js/classes/Table.md | 10 +- docs/src/js/globals.md | 3 + .../FunctionRefreshPlanningConfig.md | 50 +++++++ .../interfaces/FunctionRefreshPodResources.md | 40 +++++ docs/src/js/interfaces/FunctionRetryPolicy.md | 91 ++++++++++++ .../src/js/interfaces/RefreshColumnOptions.md | 30 ++++ .../feature-engineering/refresh-column.mdx | 128 ++++++++++++++++ nodejs/__test__/remote.test.ts | 121 +++++++++++++++ nodejs/__test__/table.test.ts | 25 ++++ nodejs/lancedb/index.ts | 3 + nodejs/lancedb/table.ts | 10 +- nodejs/src/table.rs | 140 ++++++++++++++++++ python/python/lancedb/_lancedb.pyi | 4 + python/python/lancedb/remote/table.py | 8 + python/python/lancedb/table.py | 64 ++++++++ python/python/tests/test_remote_db.py | 65 ++++++++ python/python/tests/test_table.py | 25 ++++ python/src/table.rs | 118 ++++++++++++++- rust/lancedb/src/remote/table.rs | 106 ++++++++++++- rust/lancedb/src/table.rs | 5 +- rust/lancedb/src/table/refresh.rs | 128 ++++++++++++++++ 21 files changed, 1164 insertions(+), 10 deletions(-) create mode 100644 docs/src/js/interfaces/FunctionRefreshPlanningConfig.md create mode 100644 docs/src/js/interfaces/FunctionRefreshPodResources.md create mode 100644 docs/src/js/interfaces/FunctionRetryPolicy.md 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/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/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/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__/table.test.ts b/nodejs/__test__/table.test.ts index 2c45dbccd..e97b32e78 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5716,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/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/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 c82c2cd93..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, }; @@ -1705,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) { @@ -1768,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, @@ -1814,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..cce3efeef 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -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/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_remote_db.py b/python/python/tests/test_remote_db.py index c5afac308..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", 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/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> { + resources + .map(|resources| parse_pod_resources(resources, "supervisor_resources")) + .transpose() +} + +fn parse_planning_workers( + planning: Option<&Bound<'_, PyDict>>, +) -> PyResult> { + let Some(planning) = planning else { + return Ok(None); + }; + for key in planning.keys() { + let key = key + .extract::() + .map_err(|_| PyValueError::new_err("planning_workers keys must be strings"))?; + if !matches!( + key.as_str(), + "resources" | "max_workers" | "rows_per_worker" | "fragments_per_worker" + ) { + return Err(PyValueError::new_err(format!( + "planning_workers contains unsupported key '{key}'" + ))); + } + } + let resources = planning + .get_item("resources")? + .ok_or_else(|| PyValueError::new_err("planning_workers.resources is required"))?; + let resources = resources + .cast::() + .map_err(|_| PyValueError::new_err("planning_workers.resources must be a dict"))?; + let resources = parse_pod_resources(resources, "planning_workers.resources")?; + let get = |name: &str| -> PyResult { + let value = planning + .get_item(name)? + .ok_or_else(|| PyValueError::new_err(format!("planning_workers.{name} is required")))?; + structured_integer(&value, &format!("planning_workers.{name}")) + }; + let max_workers = usize::try_from(get("max_workers")?) + .map_err(|_| PyValueError::new_err("planning_workers.max_workers is too large"))?; + Ok(Some(FunctionRefreshPlanningConfig::new( + resources, + max_workers, + get("rows_per_worker")?, + get("fragments_per_worker")?, + ))) +} + fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { let RefreshColumnArgs { where_clause, @@ -166,6 +264,8 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult PyResult( self_: PyRef<'py, Self>, @@ -2502,6 +2604,8 @@ impl Table { 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, @@ -2519,6 +2623,8 @@ impl Table { max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, publication_interval_rows, resource_budget: parse_resource_budget(resource_budget.as_ref())?, + supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?, + planning_workers: parse_planning_workers(planning_workers.as_ref())?, gpu_class, gpu_count, retry_policy, @@ -2540,7 +2646,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async<'py>( self_: PyRef<'py, Self>, @@ -2550,6 +2656,8 @@ impl Table { 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, @@ -2567,6 +2675,8 @@ impl Table { max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, publication_interval_rows, resource_budget: parse_resource_budget(resource_budget.as_ref())?, + supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?, + planning_workers: parse_planning_workers(planning_workers.as_ref())?, gpu_class, gpu_count, retry_policy, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 4e9458870..e556d131c 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11560,6 +11560,59 @@ mod tests { assert_eq!(job.id(), Some("j-budget")); } + #[tokio::test] + async fn test_refresh_column_async_structured_resource_options() { + use crate::table::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, RefreshColumnOptions, + }; + + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "supervisor_resources": { + "cpu_millis": 2_000, + "memory_bytes": 4_294_967_296_u64, + "ephemeral_storage_bytes": 10_737_418_240_u64, + }, + "planning_workers": { + "resources": { + "cpu_millis": 1_000, + "memory_bytes": 2_147_483_648_u64, + "ephemeral_storage_bytes": 5_368_709_120_u64, + }, + "max_workers": 4, + "rows_per_worker": 100_000, + "fragments_per_worker": 8, + }, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j-structured"}"#) + .unwrap() + }); + let supervisor = FunctionRefreshPodResources::new(2_000, 4_294_967_296, 10_737_418_240); + let planning = FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1_000, 2_147_483_648, 5_368_709_120), + 4, + 100_000, + 8, + ); + let job = table + .refresh_column_async_with_options( + "quality", + RefreshColumnOptions::default() + .supervisor_resources(supervisor) + .planning_workers(planning), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-structured")); + } + #[tokio::test] async fn test_refresh_column_async_retry_policy() { use crate::function::{FunctionErrorPolicy, FunctionRetryPolicy}; @@ -11640,7 +11693,9 @@ mod tests { #[tokio::test] async fn test_refresh_column_rejects_invalid_filter_and_limit_options_before_request() { - use crate::table::RefreshColumnOptions; + use crate::table::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, RefreshColumnOptions, + }; let table = Table::new_with_handler("my_table", |_| -> http::Response { panic!("invalid refresh options must not send a request") @@ -11679,6 +11734,55 @@ mod tests { RefreshColumnOptions::default().publication_interval_rows(0), "publication_interval_rows", ), + ( + RefreshColumnOptions::default() + .supervisor_resources(FunctionRefreshPodResources::new(0, 1, 1)), + "supervisor_resources.cpu_millis", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 0), + 1, + 1, + 1, + ), + ), + "planning_workers.resources.ephemeral_storage_bytes", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 0, + 1, + 1, + ), + ), + "planning_workers.max_workers", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 1, + 0, + 1, + ), + ), + "planning_workers.rows_per_worker", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 1, + 1, + 0, + ), + ), + "planning_workers.fragments_per_worker", + ), ] { let error = table .refresh_column_async_with_options("quality", options) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index b9708f16b..00505220b 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -120,7 +120,10 @@ pub use optimize::{ CompactionMode, CompactionOptions, CompactionOverrides, IndexRemapMode, OptimizeAction, OptimizeStats, }; -pub use refresh::{FunctionWorkerResourceBudget, RefreshColumnOptions, RefreshColumnResult}; +pub use refresh::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget, + RefreshColumnOptions, RefreshColumnResult, +}; pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats}; pub use schema_evolution::{ AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate, diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index ff73e6366..f38509002 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -104,6 +104,106 @@ impl FunctionWorkerResourceBudget { } } +/// CPU, memory, and ephemeral-storage limits for one Function refresh +/// control-plane pod. +/// +/// This sizes the supervisor or planning worker pod for a registered +/// Function refresh. LanceDB Embedded rejects it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRefreshPodResources { + /// CPU limit in millicores; 1000 is one CPU. + pub cpu_millis: u64, + /// Memory limit in bytes. + pub memory_bytes: u64, + /// Ephemeral storage limit in bytes. + pub ephemeral_storage_bytes: u64, +} + +impl FunctionRefreshPodResources { + /// Create positive CPU, memory, and ephemeral-storage limits. + pub fn new(cpu_millis: u64, memory_bytes: u64, ephemeral_storage_bytes: u64) -> Self { + Self { + cpu_millis, + memory_bytes, + ephemeral_storage_bytes, + } + } + + fn validate(&self, prefix: &str) -> Result<()> { + for (name, value) in [ + ("cpu_millis", self.cpu_millis), + ("memory_bytes", self.memory_bytes), + ("ephemeral_storage_bytes", self.ephemeral_storage_bytes), + ] { + if value == 0 { + return Err(Error::InvalidInput { + message: format!("{prefix}.{name} must be greater than zero"), + }); + } + } + Ok(()) + } +} + +/// Resources and sizing policy for the CPU-only planning fleet of one +/// registered Function refresh. +/// +/// `resources` describes one planning worker pod. The remaining fields bound +/// how many workers may run and how much work each worker receives. LanceDB +/// Embedded rejects this option. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRefreshPlanningConfig { + /// CPU, memory, and ephemeral-storage limits for one planning worker. + pub resources: FunctionRefreshPodResources, + /// Maximum number of planning workers. + pub max_workers: usize, + /// Maximum rows assigned to one planning worker. + pub rows_per_worker: u64, + /// Maximum fragments assigned to one planning worker. + pub fragments_per_worker: u64, +} + +impl FunctionRefreshPlanningConfig { + /// Create a planning configuration; every value must be positive. + pub fn new( + resources: FunctionRefreshPodResources, + max_workers: usize, + rows_per_worker: u64, + fragments_per_worker: u64, + ) -> Self { + Self { + resources, + max_workers, + rows_per_worker, + fragments_per_worker, + } + } + + fn validate(&self) -> Result<()> { + self.resources.validate("planning_workers.resources")?; + if self.max_workers == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.max_workers must be greater than zero".into(), + }); + } + if self.rows_per_worker == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.rows_per_worker must be greater than zero".into(), + }); + } + if self.fragments_per_worker == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.fragments_per_worker must be greater than zero".into(), + }); + } + Ok(()) + } +} + /// Options for refreshing a computed column. /// /// Serializes to the Enterprise backfill request body, one key per set @@ -167,6 +267,14 @@ pub struct RefreshColumnOptions { /// Function refresh. Cannot be combined with `gpu_count`. #[serde(skip_serializing_if = "Option::is_none")] pub resource_budget: Option, + /// CPU, memory, and ephemeral-storage limits for the Function refresh + /// supervisor pod. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub supervisor_resources: Option, + /// Resources and sizing limits for the Function refresh planning fleet. + /// Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub planning_workers: Option, /// GPU class for Function workers in LanceDB Enterprise. /// /// `None` keeps the Function's registered class, or the deployment default @@ -264,6 +372,18 @@ impl RefreshColumnOptions { self } + /// Set the Function refresh supervisor pod resources. + pub fn supervisor_resources(mut self, resources: FunctionRefreshPodResources) -> Self { + self.supervisor_resources = Some(resources); + self + } + + /// Set the Function refresh planning fleet resources and sizing. + pub fn planning_workers(mut self, planning: FunctionRefreshPlanningConfig) -> Self { + self.planning_workers = Some(planning); + self + } + /// Request Function workers from `gpu_class`. pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { self.gpu_class = Some(gpu_class.into()); @@ -297,6 +417,8 @@ impl RefreshColumnOptions { self.publication_interval_rows.is_some(), ), ("resource_budget", self.resource_budget.is_some()), + ("supervisor_resources", self.supervisor_resources.is_some()), + ("planning_workers", self.planning_workers.is_some()), ] .into_iter() .find_map(|(name, set)| set.then_some(name)) @@ -367,6 +489,12 @@ impl RefreshColumnOptions { if let Some(budget) = &self.resource_budget { budget.validate()?; } + if let Some(resources) = &self.supervisor_resources { + resources.validate("supervisor_resources")?; + } + if let Some(planning) = &self.planning_workers { + planning.validate()?; + } if let Some(gpu_class) = &self.gpu_class { validate_gpu_class_name(gpu_class)?; } From 12b95b59ab170a248b263d2a36eb21f678986e53 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:52 +0800 Subject: [PATCH 10/10] feat(function): support literal inputs in column declarations (#5021) Function-column declarations now preserve constants such as `fn(video=col("mp4"), num_frames=lit(16))` without changing its Function version. Constants travel in the application inputs; column bindings, request input schemas, and dependency tracking contain only columns. Changing a constant uses a new column binding rather than rebaking the Function. Persisted bindings with literals use metadata version 2, which older readers reject. Column-only bindings retain version 1. Python preserves scalar literal identity, including null and unsigned integers, and rejects composed expressions or values outside the canonical literal domain. This SDK change requires matching server declaration and execution support, after a dedicated SDK dependency update. Native validation passed 48 Rust metadata tests, four request-transport cases and 57 rebuilt Python tests on `a42d680`; 32 pre-existing experimental tests remained ignored. The test-assertion correction passed its exact regression and strict Clippy on `53ff80a2`. On `993fae7d`, the three remote metadata compatibility regressions, native Python public-export test and strict Clippy passed. These review corrections use v3 for unknown-version rejection, cover existing v2 literal bindings through remote mutation guards, and export `LiteralInputBinding`. The unchanged native implementation and verified extension are reused. Matching server execution and original-workload acceptance are not established by this PR. Refs ENT-3667. --- docs/src/python/python.md | 2 + docs/web/management/function.mdx | 46 ++++ python/python/lancedb/_lancedb.pyi | 2 +- python/python/lancedb/expr.py | 23 +- python/python/lancedb/functions.py | 68 ++++- .../tests/test_first_class_function_slice1.py | 64 ++++- python/src/expr.rs | 8 +- rust/lancedb/src/function.rs | 55 +++- rust/lancedb/src/remote/table.rs | 119 +++++++-- rust/lancedb/src/table/computed_columns.rs | 247 +++++++++++++++++- 10 files changed, 576 insertions(+), 58 deletions(-) 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/management/function.mdx b/docs/web/management/function.mdx index 57a16dbf2..41e64d482 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -245,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/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index cce3efeef..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: ... 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 86230be52..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 @@ -626,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 @@ -658,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} @@ -682,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: @@ -876,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.""" @@ -900,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 @@ -907,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: @@ -2979,6 +3020,7 @@ __all__ = [ "FunctionVersionRef", "HuggingFaceModel", "InputBinding", + "LiteralInputBinding", "OutputMapping", "PythonEnvironmentSpec", "PythonAdapterSpec", 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/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/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 387c80364..582b5b08a 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -111,7 +111,7 @@ fn from_json(json: &str) -> Result { serde_json::from_str(json).map_err(invalid_json) } -fn validate_literal(value: &Value) -> Result<()> { +pub(crate) fn validate_literal(value: &Value) -> Result<()> { match value { Value::Number(number) if number.is_f64() => Err(Error::InvalidInput { message: "floating-point Function literals are not part of the Slice 1 canonical wire contract" @@ -1018,6 +1018,18 @@ pub struct InputBinding { pub nullable: bool, } +/// Constant value bound to a Function parameter for every input row. +/// +/// Values use the same canonical JSON domain as [`ApplicationInput`]. The +/// Enterprise service validates their types against the exact Function version. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LiteralInputBinding { + /// Function parameter name, distinct from all column-bound parameters. + pub parameter: String, + /// Immutable canonical JSON value. + pub value: Value, +} + /// Ordered result-field to table-field mapping for a Function binding. /// /// `nullable` describes the logical Function result. Physical computed-column @@ -1046,6 +1058,8 @@ pub struct FunctionBinding { binding_id: String, function: FunctionVersionRef, inputs: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + literal_inputs: Vec, outputs: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] assignment: Option, @@ -1076,6 +1090,30 @@ impl FunctionBinding { &self.inputs } + /// Constants supplied for every row; these are not table dependencies. + pub fn literal_inputs(&self) -> &[LiteralInputBinding] { + &self.literal_inputs + } + + pub(crate) fn validate_inputs(&self) -> Result<()> { + let mut parameters = std::collections::HashSet::new(); + for parameter in self + .inputs + .iter() + .map(|input| &input.parameter) + .chain(self.literal_inputs.iter().map(|input| &input.parameter)) + { + if !parameters.insert(parameter) { + return Err(invalid_json(format!( + "duplicate Function parameter '{parameter}'" + ))); + } + } + self.literal_inputs + .iter() + .try_for_each(|input| validate_literal(&input.value)) + } + pub fn outputs(&self) -> &[OutputMapping] { &self.outputs } @@ -1098,7 +1136,20 @@ impl FunctionBinding { } } -impl_json!(FunctionBinding); +impl FunctionBinding { + /// Decode an immutable binding, validating its canonical input values. + pub fn from_json(json: &str) -> Result { + let binding: Self = from_json(json)?; + binding.validate_inputs()?; + Ok(binding) + } + + /// Encode this binding without dropping its constant inputs. + pub fn to_canonical_json(&self) -> Result { + self.validate_inputs()?; + canonical_json(self) + } +} /// Stable terminal result of an expression-backed or Function-backed column /// refresh [`crate::Job`]. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index e556d131c..29f3ab50e 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -10769,9 +10769,17 @@ mod tests { } } + #[rstest] + #[case::column_only(None)] + #[case::sixteen(Some(serde_json::json!(16)))] + #[case::eight(Some(serde_json::json!(8)))] + #[case::null(Some(serde_json::Value::Null))] #[tokio::test] - async fn test_add_scalar_function_column_sends_atomic_null_declaration() { - let table = Table::new_with_handler("my_table", |request| { + async fn test_add_scalar_function_column_sends_atomic_null_declaration( + #[case] literal: Option, + ) { + let expected_literal = literal.clone(); + let table = Table::new_with_handler("my_table", move |request| { match request.url().path() { "/v1/table/my_table/describe/" => http::Response::builder() .status(200) @@ -10789,6 +10797,13 @@ mod tests { )) .unwrap(); expected["auto_refresh_enabled"] = serde_json::json!(true); + if let Some(literal) = &expected_literal { + expected["function"]["binding_metadata_version"] = serde_json::json!(2); + expected["function"]["application"]["inputs"] + .as_array_mut().unwrap().push(serde_json::json!({ + "parameter": "num_frames", "kind": "literal", "value": literal, + })); + } assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -10798,7 +10813,7 @@ mod tests { path => panic!("Unexpected path: {path}"), } }); - let application = crate::function::FunctionApplication::from_json( + let mut application: serde_json::Value = serde_json::from_str( r#"{ "function":{"name":"embed","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], @@ -10806,6 +10821,18 @@ mod tests { }"#, ) .unwrap(); + if let Some(literal) = literal { + application["inputs"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "parameter": "num_frames", "kind": "literal", "value": literal, + })); + } + let application = crate::function::FunctionApplication::from_json( + &serde_json::to_string(&application).unwrap(), + ) + .unwrap(); let result = table .add_columns() @@ -10934,19 +10961,64 @@ mod tests { /// Only a column the binding uses is refused, and it is refused before /// any request goes out; the rest reach the server as usual. + #[rstest] + #[case::column_only(false)] + #[case::literal(true)] #[tokio::test] - async fn test_add_columns_scopes_to_the_columns_a_binding_uses() { - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_response(&fixture_bound_schema())) - .unwrap(), - "/v1/table/my_table/add_columns/" => http::Response::builder() - .status(200) - .body(r#"{"version":10}"#.to_string()) - .unwrap(), - path => panic!("Unexpected path: {path}"), - }); + async fn test_add_columns_scopes_to_the_columns_a_binding_uses(#[case] literal: bool) { + let mut schema = fixture_bound_schema(); + if literal { + let key = crate::table::computed_columns::FUNCTION_BINDINGS_META_KEY; + let mut metadata = schema.metadata().clone(); + let mut envelope: serde_json::Value = + serde_json::from_str(metadata.get(key).unwrap()).unwrap(); + envelope["version"] = serde_json::json!(2); + envelope["bindings"][0]["inputs"] + .as_array_mut() + .unwrap() + .pop(); + envelope["bindings"][0]["literal_inputs"] = + serde_json::json!([{"parameter": "body", "value": null}]); + let binding = + crate::function::FunctionBinding::from_json(&envelope["bindings"][0].to_string()) + .unwrap(); + let fields = schema + .fields() + .iter() + .map(|field| { + let mut field = field.as_ref().clone(); + if let Some(output) = binding + .outputs() + .iter() + .find(|output| output.output_name == *field.name()) + { + field = field.with_metadata( + crate::table::computed_columns::function_computed_column_metadata( + binding.binding_id(), + output.output_ordinal, + &["title".into()], + ), + ); + } + field + }) + .collect::>(); + metadata.insert(key.to_string(), envelope.to_string()); + schema = Schema::new_with_metadata(fields, metadata); + } + let allowed_schema = schema.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&allowed_schema)) + .unwrap(), + "/v1/table/my_table/add_columns/" => http::Response::builder() + .status(200) + .body(r#"{"version":10}"#.to_string()) + .unwrap(), + path => panic!("Unexpected path: {path}"), + }); table .add_columns() .computed("doubled", "spare * 2") @@ -10963,13 +11035,14 @@ mod tests { .await .unwrap(); - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_response(&fixture_bound_schema())) - .unwrap(), - path => panic!("mutation request must not be sent: {path}"), - }); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(), + path => panic!("mutation request must not be sent: {path}"), + }); for name in ["title", "search_text"] { let err = table .add_columns() @@ -11327,7 +11400,7 @@ mod tests { "/v1/table/my_table/describe/" => http::Response::builder() .status(200) .body( - r#"{"version":1,"schema":{"fields":[{"name":"x","nullable":true,"type":{"type":"int32"}}],"metadata":{"lancedb::function_bindings":"{\"version\":2,\"bindings\":[]}"}}}"#, + r#"{"version":1,"schema":{"fields":[{"name":"x","nullable":true,"type":{"type":"int32"}}],"metadata":{"lancedb::function_bindings":"{\"version\":3,\"bindings\":[]}"}}}"#, ) .unwrap(), path => panic!("mutation request must not be sent: {path}"), diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index b01f45d06..7348e659d 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -203,6 +203,10 @@ pub const FUNCTION_BINDINGS_META_KEY: &str = "lancedb::function_bindings"; /// Version of the schema-level Function binding envelope. pub const FUNCTION_BINDINGS_VERSION: u32 = 1; +/// Envelope version required when a Function binding contains constant inputs. +/// Older readers reject this version instead of dropping those inputs. +pub const FUNCTION_LITERAL_BINDINGS_VERSION: u32 = 2; + /// Field metadata key holding `{fragment id -> input signature}` as JSON, /// recorded by the refresh that last computed each fragment. Outside the /// declaration namespace on purpose: a declaration is immutable through @@ -329,6 +333,17 @@ struct FunctionBindingEnvelope { /// Encode immutable Function bindings for schema-level persistence. pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result { + bindings + .iter() + .try_for_each(FunctionBinding::validate_inputs)?; + let version = if bindings + .iter() + .any(|binding| !binding.literal_inputs().is_empty()) + { + FUNCTION_LITERAL_BINDINGS_VERSION + } else { + FUNCTION_BINDINGS_VERSION + }; let bindings = bindings .iter() .map(serde_json::to_value) @@ -336,12 +351,10 @@ pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result Result> { .bindings .into_iter() .map(|binding| { - serde_json::from_value(binding).map_err(|e| Error::InvalidInput { - message: format!("invalid Function binding metadata: {e}"), - }) + let binding: FunctionBinding = + serde_json::from_value(binding).map_err(|e| Error::InvalidInput { + message: format!("invalid Function binding metadata: {e}"), + })?; + binding.validate_inputs()?; + Ok(binding) }) .collect() } @@ -370,7 +386,10 @@ fn function_binding_envelope(schema: &ArrowSchema) -> Result Result Result .collect::>>()?; let mut binding_ids = BTreeSet::new(); for binding in &bindings { + binding.validate_inputs()?; if !binding_ids.insert(binding.binding_id().to_string()) { return Err(Error::InvalidInput { message: format!("duplicate Function binding '{}'", binding.binding_id()), @@ -821,6 +853,7 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { "binding_id", "function", "inputs", + "literal_inputs", "outputs", "assignment", "input_schema", @@ -830,6 +863,14 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { "binding", )?; let object = value.as_object().unwrap(); + if let Some(inputs) = object.get("literal_inputs") { + for input in inputs + .as_array() + .ok_or_else(|| invalid_function("Function literal_inputs must be an array"))? + { + reject_unknown_object_fields(input, &["parameter", "value"], "literal input binding")?; + } + } reject_unknown_object_fields( object .get("function") @@ -1305,6 +1346,7 @@ fn nullable_scalar_allows_assignment(output: &OutputMapping) -> Result { } fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding) -> Result<()> { + binding.validate_inputs()?; let mut input_fields = Vec::with_capacity(binding.inputs().len()); for input in binding.inputs() { let resolved = resolve_field_path(schema, &input.field_path)?; @@ -1350,6 +1392,52 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding } input_fields.push(parameter_field); } + if !binding.literal_inputs().is_empty() { + // Column types still come from the table. Literal types come from the + // complete signature schema persisted by the Enterprise service. + let declared: JsonArrowSchema = + serde_json::from_value(binding.input_schema().cloned().ok_or_else(|| { + invalid_function("literal Function binding requires an input schema") + })?) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + let mut columns = input_fields + .into_iter() + .map(|field| (field.name().clone(), field)) + .collect::>(); + let mut literals = binding + .literal_inputs() + .iter() + .map(|input| (input.parameter.as_str(), &input.value)) + .collect::>(); + input_fields = Vec::with_capacity(declared.fields.len()); + for field in &declared.fields { + if let Some(column) = columns.remove(&field.name) { + input_fields.push(column); + } else if let Some(value) = literals.remove(field.name.as_str()) { + let field = + lance_namespace::schema::convert_json_arrow_field(field).map_err(|e| { + invalid_function(format!("invalid Function literal field: {e}")) + })?; + if field.is_blob_v2() || (value.is_null() && !field.is_nullable()) { + return Err(invalid_function(format!( + "invalid literal for Function parameter '{}'", + field.name() + ))); + } + input_fields.push(field); + } else { + return Err(invalid_function(format!( + "Function input schema has an unknown or duplicate parameter '{}'", + field.name + ))); + } + } + if !columns.is_empty() || !literals.is_empty() { + return Err(invalid_function( + "Function input schema is missing bound parameters", + )); + } + } let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(input_fields)) .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; @@ -1502,6 +1590,10 @@ pub(crate) fn plan_function_application( input.parameter ))); } + if input.kind == "literal" { + crate::function::validate_literal(&input.value)?; + continue; + } if input.kind != "column" { return Err(Error::NotSupported { message: format!( @@ -1680,7 +1772,15 @@ pub(crate) fn plan_function_application( Ok(FunctionDeclarationPlan { application: application.clone(), - binding_metadata_version: FUNCTION_BINDINGS_VERSION, + binding_metadata_version: if application + .inputs() + .iter() + .any(|input| input.kind == "literal") + { + FUNCTION_LITERAL_BINDINGS_VERSION + } else { + FUNCTION_BINDINGS_VERSION + }, input_bindings, input_schema, output_schema: JsonArrowSchema::new(output_fields), @@ -4738,6 +4838,129 @@ mod tests { ensure_binding_matches_schema(&ArrowSchema::new(fields), &binding).unwrap(); } + #[test] + fn test_literal_function_application_keeps_only_column_dependencies() { + let mut value = serde_json::to_value(single_input_application("title")).unwrap(); + value["inputs"] = serde_json::json!([ + {"parameter": "count", "kind": "literal", "value": 16}, + {"parameter": "text", "kind": "column", "value": {"path": "title"}}, + {"parameter": "optional", "kind": "literal", "value": null} + ]); + let application = FunctionApplication::from_json(&value.to_string()).unwrap(); + let plan = + plan_function_application(&function_input_schema(), &application, Some("result")) + .unwrap(); + assert_eq!(plan.binding_metadata_version, 2); + assert_eq!(plan.input_bindings.len(), 1); + assert_eq!(plan.input_bindings[0].parameter, "text"); + assert_eq!(plan.input_bindings[0].field_path, "title"); + assert_eq!(plan.input_schema.fields.len(), 1); + assert_eq!(plan.input_schema.fields[0].name, "text"); + assert_eq!( + serde_json::to_value(plan.application).unwrap()["inputs"], + value["inputs"] + ); + value["inputs"][0]["parameter"] = serde_json::json!("text"); + let duplicate = FunctionApplication::from_json(&value.to_string()).unwrap(); + assert!( + plan_function_application(&function_input_schema(), &duplicate, Some("result")) + .unwrap_err() + .to_string() + .contains("duplicate Function parameter") + ); + } + + #[test] + fn test_literal_function_metadata_survives_schema_mutation_guards() { + let legacy = FunctionBinding::from_json(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + let legacy_envelope: Value = serde_json::from_str( + &function_bindings_metadata(std::slice::from_ref(&legacy)).unwrap(), + ) + .unwrap(); + assert_eq!(legacy_envelope["version"], 1); + let mut value = serde_json::to_value(&legacy).unwrap(); + value["inputs"].as_array_mut().unwrap().pop(); + value["literal_inputs"] = serde_json::json!([{"parameter": "body", "value": null}]); + let binding = FunctionBinding::from_json(&value.to_string()).unwrap(); + let raw = function_bindings_metadata(std::slice::from_ref(&binding)).unwrap(); + let mut envelope: Value = serde_json::from_str(&raw).unwrap(); + assert_eq!(envelope["version"], 2); + assert_eq!( + envelope["bindings"][0]["literal_inputs"], + value["literal_inputs"] + ); + let schema = valid_function_binding_schema(true, true, &binding); + let schema = schema.with_metadata(HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + raw.clone(), + )])); + ensure_supported_function_metadata(&schema).unwrap(); + let decoded = function_bindings(&schema).unwrap(); + assert_eq!(decoded.as_slice(), std::slice::from_ref(&binding)); + assert_eq!(function_bindings_metadata(&decoded).unwrap(), raw); + assert!(!protected_roots(&decoded).unwrap().contains("body")); + + envelope["version"] = serde_json::json!(1); + let downgraded = schema.clone().with_metadata(HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + envelope.to_string(), + )])); + assert!( + function_bindings(&downgraded) + .unwrap_err() + .to_string() + .contains("require metadata version 2") + ); + + value["literal_inputs"][0]["parameter"] = serde_json::json!("title"); + assert!( + FunctionBinding::from_json(&value.to_string()) + .unwrap_err() + .to_string() + .contains("duplicate Function parameter") + ); + } + + #[test] + fn test_literal_function_binding_requires_complete_input_schema() { + let mut value: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + value["inputs"].as_array_mut().unwrap().pop(); + value["literal_inputs"] = serde_json::json!([{"parameter": "body", "value": null}]); + value["input_schema"]["fields"][1]["nullable"] = serde_json::json!(false); + let binding = FunctionBinding::from_json(&value.to_string()).unwrap(); + let schema = valid_function_binding_schema(true, true, &binding); + assert!( + ensure_binding_matches_schema(&schema, &binding) + .unwrap_err() + .to_string() + .contains("invalid literal") + ); + value["input_schema"]["fields"] + .as_array_mut() + .unwrap() + .pop(); + let missing = FunctionBinding::from_json(&value.to_string()).unwrap(); + assert!( + ensure_binding_matches_schema(&schema, &missing) + .unwrap_err() + .to_string() + .contains("missing bound parameters") + ); + value["literal_inputs"][0]["value"] = serde_json::json!(1.5); + assert!( + FunctionBinding::from_json(&value.to_string()) + .unwrap_err() + .to_string() + .contains("floating-point Function literals") + ); + } + #[test] fn test_function_binding_metadata_survives_schema_round_trip() { let binding = FunctionBinding::from_json(include_str!( @@ -5391,7 +5614,7 @@ mod tests { function_input_schema().fields().to_vec(), HashMap::from([( FUNCTION_BINDINGS_META_KEY.to_string(), - r#"{"version":2,"bindings":[]}"#.to_string(), + r#"{"version":3,"bindings":[]}"#.to_string(), )]), ); let err = plan_function_application(&mixed_schema, &named_struct_application("{}"), None)