From 7cc3904a7e98b18062a28f7841fa613002e13061 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 19:12:06 +0800 Subject: [PATCH 01/75] feat: expose exact Function column freshness (#4958) ## Problem Function-backed columns need an exact `fresh`, `stale`, `never_computed`, and `failed` partition for the table version a caller is reading. The existing error listing is capped, and composing it with job and schema listings cannot prove which rows currently failed. ## Behavior - Adds a strict freshness reader beside the existing permissive planner. It distinguishes an absent certificate from legacy evidence that omits failures, and from a current certificate carrying failure coverage. - Extends the immutable freshness sidecar with per-fragment known and failed row bitmaps. Partial or `WHERE` publications cover only observed rows; untouched rows stay unknown. Deleted rows do not block classification. - Adds failure-aware whole-fragment and row-repair writers. A rejected older attempt cannot overwrite failure evidence already recorded for a newer input signature. - Adds `column_status`, `column_statuses`, and `wait_fresh` to Python and the corresponding Node methods. The client calls the server's exact status endpoint, validates the four-way partition and one-version guarantee, and preserves the complete Function version, last-job, and automatic-refresh metadata. - Adds an MDX-commented draft usage section to the Enterprise computed-column refresh guide, covering Python, Rust, and TypeScript and remaining hidden until the server integration ships. - Sends `column`, `branch`, and exact `version` selectors to the status route. A pinned handle rejects a nonempty response from any other table version; latest handles keep the existing read-freshness headers. - Retries `wait_fresh` only for HTTP 503 with `function_column_status_finalization_pending`. Existing failed rows remain visible and do not keep the wait pending; other errors propagate. - Models the shared scheduler projection, including `up_to_date`, real `blocked` states, their reason, failure streak, and effective cooldown. ## Validation This is the SDK side of ENT-3563. Sophon's failure-coverage publication and status endpoint are a separate integration; deployed end-to-end and whole-ticket acceptance remain pending. - Rust: 9 exact freshness/status tests passed, plus 1 exact latest-handle freshness-header test. The pinned transport test was extended with a wrong-version response and rerun at `ebd6649a` (1 passed). Coverage includes untouched partial rows, selected-row failure clearing, cross-generation evidence, typed and non-retried errors, `up_to_date`, blocked scheduler fields, and exact-version requests. - Python: 2 native PyO3 remote-transport tests passed together, including typed retry; one local facade test reaches the existing unsupported boundary. - Node: the NAPI addon built successfully, TypeScript and Biome passed, and the selected native remote-transport test passed 1/0, including exact-version selection and blocked scheduler metadata. - `cargo fmt`, `git diff --check`, Ruff format/lint, Python compile, Biome, and TypeScript checks passed. Validation is mapped by the relevant unchanged source rather than treated as one final-head run: the nine Rust tests ran at `e4d51fc8`, the latest-header and Python remote tests at `31e68b7d`, the local Python test and Node build at `6f213584`, and the final TypeScript/Jest delta at `4f2d5c27`. The final product tree excludes those five private EC2 runner files and adds six generated TypeDoc files plus one hidden draft usage section in the computed-column refresh guide. The Node delta corrected a private TypeScript command and reused the unchanged native addon. --- docs/src/js/classes/Table.md | 64 ++ docs/src/js/globals.md | 4 + .../FunctionColumnAutoRefreshStatus.md | 95 ++ .../FunctionColumnLastRefreshJob.md | 41 + .../src/js/interfaces/FunctionColumnStatus.md | 97 ++ .../interfaces/FunctionColumnVersionStatus.md | 57 + docs/src/python/python.md | 8 + .../feature-engineering/refresh-column.mdx | 51 + nodejs/__test__/remote.test.ts | 63 ++ nodejs/lancedb/index.ts | 4 + nodejs/lancedb/table.ts | 111 ++ nodejs/src/table.rs | 151 +++ python/python/lancedb/__init__.py | 14 + python/python/lancedb/_lancedb.pyi | 45 + python/python/lancedb/remote/table.py | 14 + python/python/lancedb/table.py | 71 +- python/python/tests/test_remote_db.py | 131 +++ python/python/tests/test_table.py | 10 + python/src/lib.rs | 11 +- python/src/table.rs | 175 ++++ rust/lancedb/src/error.rs | 19 + rust/lancedb/src/remote/table.rs | 495 ++++++++- rust/lancedb/src/table.rs | 85 ++ rust/lancedb/src/table/freshness.rs | 977 +++++++++++++++++- .../src/table/function_column_status.rs | 303 ++++++ 25 files changed, 3055 insertions(+), 41 deletions(-) create mode 100644 docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md create mode 100644 docs/src/js/interfaces/FunctionColumnLastRefreshJob.md create mode 100644 docs/src/js/interfaces/FunctionColumnStatus.md create mode 100644 docs/src/js/interfaces/FunctionColumnVersionStatus.md create mode 100644 rust/lancedb/src/table/function_column_status.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 27acc9847..aba747a7c 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -704,6 +704,47 @@ so this is safe to call repeatedly. *** +### functionColumnStatus() + +```ts +abstract functionColumnStatus(column): Promise +``` + +Return exact freshness status for one Function-backed output column. + +#### Parameters + +* **column**: `string` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)> + +*** + +### functionColumnStatuses() + +```ts +abstract functionColumnStatuses(column?): Promise +``` + +Return exact freshness status for Function-backed output columns. + +All results describe one server table version. Omit `column` for every +Function output. Rows already failed remain visible and do not prevent +`waitFresh` from completing. A handle pinned to an exact version requests +that version; a latest handle retains normal read-freshness behavior. + +#### Parameters + +* **column?**: `string` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)[]> + +*** + ### functionErrors() ```ts @@ -1598,3 +1639,26 @@ Waits for asynchronous indexing to complete on the table. #### Returns `Promise`<`void`> + +*** + +### waitFresh() + +```ts +abstract waitFresh(column, timeoutSeconds?): Promise +``` + +Poll until no stale or never-computed rows remain. + +Only HTTP 503 with the exact finalization-pending error code is retried; +every other error propagates. Failed rows do not block completion. + +#### Parameters + +* **column**: `string` + +* **timeoutSeconds?**: `number` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)> diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 50f55f937..19d7ceb97 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -95,6 +95,10 @@ - [FtsToken](interfaces/FtsToken.md) - [FullTextQuery](interfaces/FullTextQuery.md) - [FullTextSearchOptions](interfaces/FullTextSearchOptions.md) +- [FunctionColumnAutoRefreshStatus](interfaces/FunctionColumnAutoRefreshStatus.md) +- [FunctionColumnLastRefreshJob](interfaces/FunctionColumnLastRefreshJob.md) +- [FunctionColumnStatus](interfaces/FunctionColumnStatus.md) +- [FunctionColumnVersionStatus](interfaces/FunctionColumnVersionStatus.md) - [FunctionErrorFragment](interfaces/FunctionErrorFragment.md) - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md) - [FunctionErrors](interfaces/FunctionErrors.md) diff --git a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md new file mode 100644 index 000000000..bc8f7daab --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md @@ -0,0 +1,95 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionColumnAutoRefreshStatus + +# Interface: FunctionColumnAutoRefreshStatus + +Automatic-refresh projection for a Function output. + +## Properties + +### activeJobId? + +```ts +optional activeJobId: string; +``` + +*** + +### blockedReason? + +```ts +optional blockedReason: + | "table_has_mem_wal" + | "inputs_not_settled" + | "dependency_in_flight" + | "table_capacity" + | "cancelled" + | "preparation_backoff"; +``` + +*** + +### effectiveCooldownMillis? + +```ts +optional effectiveCooldownMillis: bigint; +``` + +*** + +### enabled + +```ts +enabled: boolean; +``` + +*** + +### failureStreak + +```ts +failureStreak: number; +``` + +*** + +### intervalSeconds? + +```ts +optional intervalSeconds: bigint; +``` + +*** + +### nextRunAtMillis + +```ts +nextRunAtMillis: null | bigint; +``` + +*** + +### nextRunAtReason? + +```ts +optional nextRunAtReason: string; +``` + +*** + +### state + +```ts +state: + | "running" + | "disabled" + | "ready" + | "up_to_date" + | "waiting_interval" + | "waiting_backoff" + | "blocked" + | "unobservable"; +``` diff --git a/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md new file mode 100644 index 000000000..1d7d3b300 --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md @@ -0,0 +1,41 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionColumnLastRefreshJob + +# Interface: FunctionColumnLastRefreshJob + +Latest matching refresh Job projected for a Function output. + +## Properties + +### automatic? + +```ts +optional automatic: boolean; +``` + +*** + +### completedAtMillis? + +```ts +optional completedAtMillis: bigint; +``` + +*** + +### jobId + +```ts +jobId: string; +``` + +*** + +### state + +```ts +state: string; +``` diff --git a/docs/src/js/interfaces/FunctionColumnStatus.md b/docs/src/js/interfaces/FunctionColumnStatus.md new file mode 100644 index 000000000..755a8af81 --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnStatus.md @@ -0,0 +1,97 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionColumnStatus + +# Interface: FunctionColumnStatus + +Exact four-way status of one Function output at one table version. + +## Properties + +### autoRefresh + +```ts +autoRefresh: FunctionColumnAutoRefreshStatus; +``` + +*** + +### bindingId + +```ts +bindingId: string; +``` + +*** + +### column + +```ts +column: string; +``` + +*** + +### failed + +```ts +failed: bigint; +``` + +*** + +### fresh + +```ts +fresh: bigint; +``` + +*** + +### function + +```ts +function: FunctionColumnVersionStatus; +``` + +*** + +### lastRefreshJob? + +```ts +optional lastRefreshJob: FunctionColumnLastRefreshJob; +``` + +*** + +### neverComputed + +```ts +neverComputed: bigint; +``` + +*** + +### rows + +```ts +rows: bigint; +``` + +*** + +### stale + +```ts +stale: bigint; +``` + +*** + +### tableVersion + +```ts +tableVersion: bigint; +``` diff --git a/docs/src/js/interfaces/FunctionColumnVersionStatus.md b/docs/src/js/interfaces/FunctionColumnVersionStatus.md new file mode 100644 index 000000000..fa02139d2 --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnVersionStatus.md @@ -0,0 +1,57 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionColumnVersionStatus + +# Interface: FunctionColumnVersionStatus + +Exact immutable Function revision attached to a table output. + +## Properties + +### location + +```ts +location: string; +``` + +*** + +### manifestDigest + +```ts +manifestDigest: string; +``` + +*** + +### name + +```ts +name: string; +``` + +*** + +### namespacePath + +```ts +namespacePath: string[]; +``` + +*** + +### objectId + +```ts +objectId: string; +``` + +*** + +### version + +```ts +version: string; +``` diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 7f28d8804..eccaae6ce 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -523,6 +523,14 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.FunctionErrorFragment +::: lancedb.FunctionColumnStatus + +::: lancedb.FunctionColumnVersionStatus + +::: lancedb.FunctionColumnLastRefreshJob + +::: lancedb.FunctionColumnAutoRefreshStatus + ::: lancedb.job.Job ::: lancedb.job.AsyncJob diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index b3fcdc937..e1a9c43f3 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -150,6 +150,57 @@ does not raise, which is what makes it safe in a loop; `wait()` raises A long backfill can therefore be started, left, and checked on from a different process. +{/* +Draft for the Function freshness release. Keep this section hidden until the +Enterprise status endpoint and its integration acceptance are deployed. + +### Check Function column freshness {#freshness} + +For a Function-backed column, the SDK can report how many live rows are +`fresh`, `stale`, `never_computed`, or `failed` at the table version it +reads. `wait_fresh`, `waitFresh`, and `wait_for_function_column` poll until no +stale or never-computed rows remain. Rows that already failed stay in the +returned status and do not keep the wait pending, so inspect `failed` after a +successful wait: + + +```python Python icon="python" +status = table.column_status("embedding") +print(status.fresh, status.stale, status.never_computed, status.failed) + +final_status = table.wait_fresh("embedding") +print(final_status.failed) +``` + +```typescript TypeScript icon="typescript" +const status = await table.functionColumnStatus("embedding"); +console.log( + status.fresh, + status.stale, + status.neverComputed, + status.failed, +); + +const finalStatus = await table.waitFresh("embedding"); +console.log(finalStatus.failed); +``` + +```rust Rust icon="rust" +let status = table.function_column_status("embedding").await?; +println!( + "{} {} {} {}", + status.fresh, status.stale, status.never_computed, status.failed +); + +let final_status = table.wait_for_function_column("embedding", None).await?; +println!("{}", final_status.failed); +``` + + +The wait helpers do not submit or cancel a refresh. They retry only the typed +finalization-pending response and propagate other errors. +*/} + ### Configure workers and resources {#resources} SQL exposes the worker budget directly, which is the lever when a backfill is diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 280905897..6c160ed03 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -647,6 +647,69 @@ describe("remote connection", () => { ]); }); + it("passes a pinned version and decodes Function scheduler status", async () => { + const queries: Record[] = []; + await withMockDatabase( + (req, res) => { + const url = new URL(req.url ?? "/", "http://localhost"); + if (url.pathname.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "docs", + version: 42, + schema: { fields: [] }, + }), + ); + return; + } + if (url.pathname === "/v1/table/docs/function_columns/status") { + queries.push(Object.fromEntries(url.searchParams.entries())); + res.writeHead(200, { "Content-Type": "application/json" }).end( + `[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":2, + "stale":2, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":3, + "effective_cooldown_millis":8000, + "blocked_reason":"preparation_backoff", + "next_run_at_millis":null + } + }]`, + ); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("docs"); + await table.checkout(42); + const status = await table.functionColumnStatus("embedding"); + expect(status.tableVersion).toBe(42n); + expect(status.autoRefresh.state).toBe("blocked"); + expect(status.autoRefresh.failureStreak).toBe(3); + expect(status.autoRefresh.effectiveCooldownMillis).toBe(8000n); + expect(status.autoRefresh.blockedReason).toBe("preparation_backoff"); + }, + ); + expect(queries).toEqual([{ column: "embedding", version: "42" }]); + }); + it("forwards refresh options to the backfill request", async () => { const bodies: unknown[] = []; await withMockDatabase( diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 6bd46c9c8..35697dc8c 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -154,6 +154,10 @@ export { export { Table, + FunctionColumnAutoRefreshStatus, + FunctionColumnLastRefreshJob, + FunctionColumnStatus, + FunctionColumnVersionStatus, Branches, BranchColumnSummary, BranchColumnChange, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index d56f66cde..99eb0d1f9 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -258,6 +258,66 @@ export interface RTEWriteSpec { writerConfigDefaults?: Record; } +/** Exact immutable Function revision attached to a table output. */ +export interface FunctionColumnVersionStatus { + name: string; + namespacePath: string[]; + objectId: string; + location: string; + version: string; + manifestDigest: string; +} + +/** Latest matching refresh Job projected for a Function output. */ +export interface FunctionColumnLastRefreshJob { + jobId: string; + state: string; + automatic?: boolean; + completedAtMillis?: bigint; +} + +/** Automatic-refresh projection for a Function output. */ +export interface FunctionColumnAutoRefreshStatus { + enabled: boolean; + intervalSeconds?: bigint; + activeJobId?: string; + state: + | "disabled" + | "running" + | "ready" + | "up_to_date" + | "waiting_interval" + | "waiting_backoff" + | "blocked" + | "unobservable"; + failureStreak: number; + effectiveCooldownMillis?: bigint; + blockedReason?: + | "table_has_mem_wal" + | "inputs_not_settled" + | "dependency_in_flight" + | "table_capacity" + | "cancelled" + | "preparation_backoff"; + nextRunAtMillis: bigint | null; + nextRunAtReason?: string; +} + +/** Exact four-way status of one Function output at one table version. */ +export interface FunctionColumnStatus { + column: string; + bindingId: string; + function: FunctionColumnVersionStatus; + tableVersion: bigint; + rows: bigint; + fresh: bigint; + stale: bigint; + neverComputed: bigint; + failed: bigint; + lastRefreshJob?: FunctionColumnLastRefreshJob; + autoRefresh: FunctionColumnAutoRefreshStatus; +} + /** * A Table is a collection of Records in a LanceDB Database. * @@ -780,6 +840,32 @@ export abstract class Table { options?: FunctionErrorsOptions, ): Promise; + /** + * Return exact freshness status for Function-backed output columns. + * + * All results describe one server table version. Omit `column` for every + * Function output. Rows already failed remain visible and do not prevent + * `waitFresh` from completing. A handle pinned to an exact version requests + * that version; a latest handle retains normal read-freshness behavior. + */ + abstract functionColumnStatuses( + column?: string, + ): Promise; + + /** Return exact freshness status for one Function-backed output column. */ + abstract functionColumnStatus(column: string): Promise; + + /** + * Poll until no stale or never-computed rows remain. + * + * Only HTTP 503 with the exact finalization-pending error code is retried; + * every other error propagates. Failed rows do not block completion. + */ + abstract waitFresh( + column: string, + timeoutSeconds?: number, + ): Promise; + /** * Recompute this table's contents from its materialized-view definition. * @@ -1557,6 +1643,31 @@ export class LocalTable extends Table { return await this.inner.functionErrors(options); } + async functionColumnStatuses( + column?: string, + ): Promise { + return (await this.inner.functionColumnStatuses( + column, + )) as FunctionColumnStatus[]; + } + + async functionColumnStatus(column: string): Promise { + return (await this.inner.functionColumnStatus( + column, + )) as FunctionColumnStatus; + } + + async waitFresh( + column: string, + timeoutSeconds?: number, + ): Promise { + validateNonNegativeInteger(timeoutSeconds, "timeoutSeconds"); + return (await this.inner.waitForFunctionColumn( + column, + timeoutSeconds, + )) as FunctionColumnStatus; + } + async refreshMaterializedView( sourceVersion?: number, full?: boolean, diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 5b52c0d16..f6d3e538e 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -534,6 +534,55 @@ impl Table { Ok(errors.into()) } + #[napi(catch_unwind)] + pub async fn function_column_statuses( + &self, + column: Option, + ) -> napi::Result> { + let statuses = self + .inner_ref()? + .function_column_statuses(column.as_deref()) + .await + .default_error()?; + Ok(statuses.into_iter().map(Into::into).collect()) + } + + #[napi(catch_unwind)] + pub async fn function_column_status( + &self, + column: String, + ) -> napi::Result { + let status = self + .inner_ref()? + .function_column_status(&column) + .await + .default_error()?; + Ok(status.into()) + } + + #[napi(catch_unwind)] + pub async fn wait_for_function_column( + &self, + column: String, + timeout_seconds: Option, + ) -> napi::Result { + let timeout = timeout_seconds + .map(|seconds| { + u64::try_from(seconds) + .map(std::time::Duration::from_secs) + .map_err(|_| { + napi::Error::from_reason("timeoutSeconds must be a non-negative integer") + }) + }) + .transpose()?; + let status = self + .inner_ref()? + .wait_for_function_column(&column, timeout) + .await + .default_error()?; + Ok(status.into()) + } + #[napi(catch_unwind)] pub async fn refresh_materialized_view( &self, @@ -1799,6 +1848,108 @@ pub struct FunctionErrors { pub truncated: bool, } +/// One exact immutable Function revision attached to a table output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnVersionStatus { + pub name: String, + pub namespace_path: Vec, + pub object_id: String, + pub location: String, + pub version: String, + pub manifest_digest: String, +} + +/// Latest matching refresh Job projected for a Function output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + pub automatic: Option, + pub completed_at_millis: Option, +} + +/// Automatic-refresh projection for a Function output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + pub interval_seconds: Option, + pub active_job_id: Option, + pub state: String, + pub failure_streak: u32, + pub effective_cooldown_millis: Option, + pub blocked_reason: Option, + pub next_run_at_millis: Option, + pub next_run_at_reason: Option, +} + +/// Exact four-way status of one Function output at one table version. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: BigInt, + pub rows: BigInt, + pub fresh: BigInt, + pub stale: BigInt, + pub never_computed: BigInt, + pub failed: BigInt, + pub last_refresh_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +impl From for FunctionColumnStatus { + fn from(status: lancedb::table::FunctionColumnStatus) -> Self { + Self { + column: status.column, + binding_id: status.binding_id, + function: FunctionColumnVersionStatus { + name: status.function.name, + namespace_path: status.function.namespace_path, + object_id: status.function.object_id, + location: status.function.location, + version: status.function.version, + manifest_digest: status.function.manifest_digest, + }, + table_version: BigInt::from(status.table_version), + rows: BigInt::from(status.rows), + fresh: BigInt::from(status.fresh), + stale: BigInt::from(status.stale), + never_computed: BigInt::from(status.never_computed), + failed: BigInt::from(status.failed), + last_refresh_job: status + .last_refresh_job + .map(|job| FunctionColumnLastRefreshJob { + job_id: job.job_id, + state: job.state, + automatic: job.automatic, + completed_at_millis: job.completed_at_millis.map(BigInt::from), + }), + auto_refresh: FunctionColumnAutoRefreshStatus { + enabled: status.auto_refresh.enabled, + interval_seconds: status.auto_refresh.interval_seconds.map(BigInt::from), + active_job_id: status.auto_refresh.active_job_id, + state: status.auto_refresh.state.as_str().to_string(), + failure_streak: status.auto_refresh.failure_streak, + effective_cooldown_millis: status + .auto_refresh + .effective_cooldown_millis + .map(BigInt::from), + blocked_reason: status + .auto_refresh + .blocked_reason + .map(|reason| reason.as_str().to_string()), + next_run_at_millis: status.auto_refresh.next_run_at_millis.map(BigInt::from), + next_run_at_reason: status.auto_refresh.next_run_at_reason, + }, + } + } +} + impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { Self { diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 2208fd612..31285d100 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -17,6 +17,16 @@ __version__ = str(_Version(_native_version)) from ._lancedb import connect as lancedb_connect from ._lancedb import FtsToken +from ._lancedb import ( + FunctionColumnAutoRefreshStatus as FunctionColumnAutoRefreshStatus, +) +from ._lancedb import ( + FunctionColumnLastRefreshJob as FunctionColumnLastRefreshJob, +) +from ._lancedb import FunctionColumnStatus as FunctionColumnStatus +from ._lancedb import ( + FunctionColumnVersionStatus as FunctionColumnVersionStatus, +) from ._lancedb import FunctionErrorFragment as FunctionErrorFragment from ._lancedb import FunctionErrorRecord as FunctionErrorRecord from ._lancedb import FunctionErrors as FunctionErrors @@ -660,6 +670,10 @@ __all__ = [ "AsyncTable", "CompactionOptions", "FtsToken", + "FunctionColumnAutoRefreshStatus", + "FunctionColumnLastRefreshJob", + "FunctionColumnStatus", + "FunctionColumnVersionStatus", "col", "Expr", "func", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index dfb887461..07306c1d9 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -671,6 +671,13 @@ class Table: column: Optional[str] = None, limit: Optional[int] = None, ) -> FunctionErrors: ... + async def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: ... + async def column_status(self, column: str) -> FunctionColumnStatus: ... + async def wait_column_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: ... async def refresh_materialized_view( self, source_version: Optional[int] = None, @@ -1088,6 +1095,44 @@ class FunctionErrors: fragments: list[FunctionErrorFragment] truncated: bool +class FunctionColumnVersionStatus: + name: str + namespace_path: list[str] + object_id: str + location: str + version: str + manifest_digest: str + +class FunctionColumnLastRefreshJob: + job_id: str + state: str + automatic: Optional[bool] + completed_at_millis: Optional[int] + +class FunctionColumnAutoRefreshStatus: + enabled: bool + interval_seconds: Optional[int] + active_job_id: Optional[str] + state: str + failure_streak: int + effective_cooldown_millis: Optional[int] + blocked_reason: Optional[str] + next_run_at_millis: Optional[int] + next_run_at_reason: Optional[str] + +class FunctionColumnStatus: + column: str + binding_id: str + function: FunctionColumnVersionStatus + table_version: int + rows: int + fresh: int + stale: int + never_computed: int + failed: int + last_refresh_job: Optional[FunctionColumnLastRefreshJob] + auto_refresh: FunctionColumnAutoRefreshStatus + class RefreshMaterializedViewResult: @staticmethod def from_json(value: str) -> RefreshMaterializedViewResult: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index af648c45c..3f6bff45e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -34,6 +34,7 @@ from lancedb._lancedb import ( DeleteResult, DropColumnsResult, FtsToken, + FunctionColumnStatus, IndexConfig, RTEWriteSpec, MergeResult, @@ -1233,6 +1234,19 @@ class RemoteTable(Table): self._table.function_errors(job_id=job_id, column=column, limit=limit) ) + def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: + return LOOP.run(self._table.column_statuses(column=column)) + + def column_status(self, column: str) -> FunctionColumnStatus: + return LOOP.run(self._table.column_status(column)) + + def wait_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: + return LOOP.run(self._table.wait_fresh(column, timeout)) + def alter_columns( self, *alterations: Iterable[Dict[str, str]] ) -> AlterColumnsResult: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 609e116ba..762f826c2 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -35,7 +35,7 @@ from urllib.parse import urlparse from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable from . import __version__ -from ._lancedb import _parse_field_path +from ._lancedb import FunctionColumnStatus, _parse_field_path from ._blob import ( BlobFile, _normalize_blob_descriptor, @@ -3504,6 +3504,36 @@ class Table(ABC): ... print("listing stopped at the limit") """ + @abstractmethod + def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: + """Return exact status for Function-backed output columns. + + All statuses describe one server table version. ``column=None`` returns + every Function output. This operation is available on LanceDB + Enterprise tables. A table handle pinned to an exact version requests + that version; a latest handle retains the normal read-freshness + behavior. + """ + + @abstractmethod + def column_status(self, column: str) -> FunctionColumnStatus: + """Return exact status for one Function-backed output column.""" + + @abstractmethod + def wait_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: + """Poll until the column has no stale or never-computed rows. + + Rows already failed remain visible in the returned status and do not + keep this method waiting. The method never submits or cancels work. + Transport errors and unrecoverable status-evidence errors propagate. + A typed finalization-pending response is retried; arbitrary failure + responses are not. + """ + @abstractmethod def alter_columns(self, *alterations: Iterable[Dict[str, str]]): """ @@ -5604,6 +5634,19 @@ class LanceTable(Table): self._table.function_errors(job_id=job_id, column=column, limit=limit) ) + def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: + return LOOP.run(self._table.column_statuses(column=column)) + + def column_status(self, column: str) -> FunctionColumnStatus: + return LOOP.run(self._table.column_status(column)) + + def wait_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: + return LOOP.run(self._table.wait_fresh(column, timeout)) + def alter_columns( self, *alterations: Iterable[Dict[str, str]] ) -> AlterColumnsResult: @@ -8168,6 +8211,32 @@ class AsyncTable: job_id=job_id, column=column, limit=limit ) + async def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: + """Return exact status for Function-backed output columns. + + All results describe one server table version. ``column=None`` returns + every Function output. A handle pinned to an exact version requests + that version. + """ + return await self._inner.column_statuses(column=column) + + async def column_status(self, column: str) -> FunctionColumnStatus: + """Return exact status for one Function-backed output column.""" + return await self._inner.column_status(column) + + async def wait_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: + """Poll until no stale or never-computed rows remain. + + Failed rows do not block completion. Server and transport errors are + not retried. Only the typed finalization-pending response is retried + with bounded backoff; arbitrary 500 responses surface immediately. + """ + return await self._inner.wait_column_fresh(column, timeout) + async def refresh_column_async( self, column: str, diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 5224e5482..fd933b43c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2288,6 +2288,137 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(attempts): assert everything.truncated is True +def test_remote_function_column_status_passes_pinned_version(): + queries = [] + status = { + "column": "embedding", + "binding_id": "fb_01", + "function": { + "name": "embed", + "object_id": "embed", + "location": "objects/embed", + "version": "7", + "manifest_digest": "sha256:abc", + }, + "table_version": 42, + "rows": 4, + "fresh": 2, + "stale": 2, + "never_computed": 0, + "failed": 0, + "auto_refresh": { + "enabled": True, + "interval_seconds": 60, + "active_job_id": None, + "state": "blocked", + "failure_streak": 3, + "effective_cooldown_millis": 8000, + "blocked_reason": "preparation_backoff", + "next_run_at_millis": None, + }, + } + + def handler(request): + parsed = urlparse(request.path) + if parsed.path == "/v1/table/test/describe/": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps({"version": 42, "schema": {"fields": []}}).encode() + ) + elif parsed.path == "/v1/table/test/function_columns/status": + queries.append(parse_qs(parsed.query)) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps([status]).encode()) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + table.checkout(42) + result = table.column_status("embedding") + + assert queries == [{"column": ["embedding"], "version": ["42"]}] + assert result.table_version == 42 + assert (result.fresh, result.stale, result.never_computed, result.failed) == ( + 2, + 2, + 0, + 0, + ) + assert result.auto_refresh.state == "blocked" + assert result.auto_refresh.failure_streak == 3 + assert result.auto_refresh.effective_cooldown_millis == 8000 + assert result.auto_refresh.blocked_reason == "preparation_backoff" + + +def test_remote_wait_fresh_retries_only_typed_finalization_pending(): + calls = 0 + status = { + "column": "embedding", + "binding_id": "fb_01", + "function": { + "name": "embed", + "object_id": "embed", + "location": "objects/embed", + "version": "7", + "manifest_digest": "sha256:abc", + }, + "table_version": 42, + "rows": 1, + "fresh": 1, + "stale": 0, + "never_computed": 0, + "failed": 0, + "auto_refresh": { + "enabled": False, + "state": "disabled", + "failure_streak": 0, + "next_run_at_millis": None, + }, + } + + def handler(request): + nonlocal calls + parsed = urlparse(request.path) + if parsed.path == "/v1/table/test/describe/": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps({"version": 42, "schema": {"fields": []}}).encode() + ) + elif parsed.path == "/v1/table/test/function_columns/status": + calls += 1 + if calls == 1: + request.send_response(503) + request.send_header( + "x-lancedb-error-code", + "function_column_status_finalization_pending", + ) + request.end_headers() + request.wfile.write(b"finalization pending") + else: + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps([status]).encode()) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + result = table.wait_fresh("embedding", timeout=timedelta(seconds=2)) + + assert calls == 2 + assert result.fresh == result.rows == 1 + + @pytest.mark.asyncio @pytest.mark.parametrize("sync", [False, True]) @pytest.mark.parametrize("failure", ["send", "read"]) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 7146ed86b..e3b69ced1 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6036,6 +6036,16 @@ def test_function_errors_are_remote_only(tmp_path): table.function_errors() +def test_function_column_status_is_remote_only(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("t", [{"x": 1}]) + with pytest.raises( + NotImplementedError, + match="exact Function column status is supported only in LanceDB Enterprise", + ): + table.wait_fresh("x") + + @pytest.mark.experimental_functions @pytest.mark.parametrize("batch_size", [None, 8]) def test_refresh_column_async_returns_job(tmp_path, batch_size): diff --git a/python/src/lib.rs b/python/src/lib.rs index 27ff4cb01..f78c4e7bb 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -16,9 +16,10 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery}; use session::Session; use table::{ AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken, - FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, MergeResult, PyBlobFile, - RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, Table, - UpdateFieldMetadataResult, UpdateResult, + FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, + FunctionColumnVersionStatus, FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, + MergeResult, PyBlobFile, RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, + Table, UpdateFieldMetadataResult, UpdateResult, }; pub mod arrow; @@ -117,6 +118,10 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/python/src/table.rs b/python/src/table.rs index 24cc9ae5c..cf627961c 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -892,6 +892,136 @@ impl From for FunctionErrors { } } +/// Exact immutable Function revision attached to a table output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnVersionStatus { + pub name: String, + pub namespace_path: Vec, + pub object_id: String, + pub location: String, + pub version: String, + pub manifest_digest: String, +} + +impl From for FunctionColumnVersionStatus { + fn from(function: lancedb::function::FunctionVersionRef) -> Self { + Self { + name: function.name, + namespace_path: function.namespace_path, + object_id: function.object_id, + location: function.location, + version: function.version, + manifest_digest: function.manifest_digest, + } + } +} + +/// Latest matching refresh Job projected for a Function output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + pub automatic: Option, + pub completed_at_millis: Option, +} + +impl From for FunctionColumnLastRefreshJob { + fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self { + Self { + job_id: job.job_id, + state: job.state, + automatic: job.automatic, + completed_at_millis: job.completed_at_millis, + } + } +} + +/// Automatic-refresh projection for a Function output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + pub interval_seconds: Option, + pub active_job_id: Option, + pub state: String, + pub failure_streak: u32, + pub effective_cooldown_millis: Option, + pub blocked_reason: Option, + pub next_run_at_millis: Option, + pub next_run_at_reason: Option, +} + +impl From for FunctionColumnAutoRefreshStatus { + fn from(status: lancedb::table::FunctionColumnAutoRefreshStatus) -> Self { + Self { + enabled: status.enabled, + interval_seconds: status.interval_seconds, + active_job_id: status.active_job_id, + state: status.state.as_str().to_string(), + failure_streak: status.failure_streak, + effective_cooldown_millis: status.effective_cooldown_millis, + blocked_reason: status + .blocked_reason + .map(|reason| reason.as_str().to_string()), + next_run_at_millis: status.next_run_at_millis, + next_run_at_reason: status.next_run_at_reason, + } + } +} + +/// Exact four-way status of one Function output at one table version. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: u64, + pub rows: u64, + pub fresh: u64, + pub stale: u64, + pub never_computed: u64, + pub failed: u64, + pub last_refresh_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +#[pymethods] +impl FunctionColumnStatus { + pub fn __repr__(&self) -> String { + format!( + "FunctionColumnStatus(column={:?}, table_version={}, rows={}, fresh={}, stale={}, never_computed={}, failed={})", + self.column, + self.table_version, + self.rows, + self.fresh, + self.stale, + self.never_computed, + self.failed + ) + } +} + +impl From for FunctionColumnStatus { + fn from(status: lancedb::table::FunctionColumnStatus) -> Self { + Self { + column: status.column, + binding_id: status.binding_id, + function: status.function.into(), + table_version: status.table_version, + rows: status.rows, + fresh: status.fresh, + stale: status.stale, + never_computed: status.never_computed, + failed: status.failed, + last_refresh_job: status.last_refresh_job.map(Into::into), + auto_refresh: status.auto_refresh.into(), + } + } +} + #[pyclass(get_all, from_py_object)] #[derive(Clone, Debug)] pub struct RefreshMaterializedViewResult { @@ -2425,6 +2555,51 @@ impl Table { }) } + #[pyo3(signature = (column=None))] + pub fn column_statuses( + self_: PyRef<'_, Self>, + column: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let statuses = inner + .function_column_statuses(column.as_deref()) + .await + .infer_error()?; + Ok(statuses + .into_iter() + .map(FunctionColumnStatus::from) + .collect::>()) + }) + } + + pub fn column_status(self_: PyRef<'_, Self>, column: String) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let status = inner.function_column_status(&column).await.infer_error()?; + Ok(FunctionColumnStatus::from(status)) + }) + } + + #[pyo3(signature = (column, timeout=None))] + pub fn wait_column_fresh<'py>( + self_: PyRef<'py, Self>, + column: String, + timeout: Option>, + ) -> PyResult> { + let timeout = timeout + .map(|timeout| timeout.extract::()) + .transpose()?; + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let status = inner + .wait_for_function_column(&column, timeout) + .await + .infer_error()?; + Ok(FunctionColumnStatus::from(status)) + }) + } + #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_materialized_view( diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 7499641fc..853ca831f 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -543,6 +543,25 @@ fn has_unsupported_local_filesystem_source(error: &(dyn std::error::Error + 'sta } impl Error { + /// HTTP status associated with a remote request error. + /// + /// Retry wrappers preserve the underlying status. Other error variants do + /// not represent an HTTP response and return `None`. + #[cfg(feature = "remote")] + pub fn status_code(&self) -> Option { + match self { + Self::Http { status_code, .. } => *status_code, + Self::Retry { status_code, .. } => *status_code, + Self::TableNotFound { source, .. } => { + source.downcast_ref::().and_then(Self::status_code) + } + Self::JobFailed { failure, .. } => { + failure.source.as_deref().and_then(Self::status_code) + } + _ => None, + } + } + /// Structured resource details reported by a remote HTTP error. /// /// Older servers do not include these fields, in which case this returns diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 247b1925c..222ff527b 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -42,7 +42,8 @@ use crate::table::query::create_multi_vector_plan; use crate::table::rte_stats::GetRTEStatsResponse; use crate::table::write_progress::FinishOnDrop; use crate::table::{ - AlterColumnsResult, FieldMetadataUpdate, RefreshColumnResult, UpdateFieldMetadataResult, + AlterColumnsResult, FieldMetadataUpdate, FunctionColumnStatus, RefreshColumnResult, + UpdateFieldMetadataResult, }; use crate::table::{AnyQuery, Filter, Predicate, PreprocessingOutput, TableStatistics}; use crate::utils::background_cache::BackgroundCache; @@ -4077,6 +4078,54 @@ impl BaseTable for RemoteTable { }) } + async fn function_column_statuses( + &self, + column: Option<&str>, + ) -> Result> { + let mut request = self.apply_branch_query(self.client.get(&format!( + "/v1/table/{}/function_columns/status", + self.identifier + ))); + if let Some(column) = column { + request = request.query(&[("column", column)]); + } + let read_snapshot = self.snapshot_read_state().await; + if let Some(version) = read_snapshot.version { + request = request.query(&[("version", version)]); + } + let request = read_snapshot.freshness.apply(request); + // A typed finalization-pending 503 is a domain result. Let the caller's + // bounded wait policy handle it instead of a generic 5xx retry loop. + let (request_id, response) = self.client.send_with_retry(request, None, false).await?; + if response.status().is_success() { + read_snapshot + .freshness + .observe_headers(&self.freshness, response.headers()); + } + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let statuses: Vec = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse Function column status response: {error}").into(), + request_id, + status_code: None, + })?; + crate::table::function_column_status::validate_statuses(&statuses)?; + if let Some(requested_version) = read_snapshot.version + && let Some(returned_version) = statuses + .iter() + .map(|status| status.table_version) + .find(|version| *version != requested_version) + { + return Err(Error::Runtime { + message: format!( + "Function column status response returned table version {returned_version}, but the table handle is pinned to version {requested_version}" + ), + }); + } + Ok(statuses) + } + async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result { self.check_mutable().await?; let body = alterations @@ -11350,6 +11399,450 @@ mod tests { assert_eq!(schema_requests.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn test_function_column_status_decodes_one_exact_snapshot() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().path(), + "/v1/table/my_table/function_columns/status" + ); + assert_eq!(request.url().query(), None); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":10, + "fresh":6, + "stale":2, + "never_computed":1, + "failed":1, + "last_refresh_job":{ + "job_id":"job-7", + "state":"finished", + "automatic":true, + "completed_at_millis":1790000000000 + }, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "active_job_id":null, + "state":"unobservable", + "failure_streak":0, + "next_run_at_millis":null, + "next_run_at_reason":"authoritative_scheduler_projection_unavailable" + } + }]"#, + ) + .unwrap() + }); + + let statuses = table.function_column_statuses(None).await.unwrap(); + assert_eq!(statuses.len(), 1); + assert_eq!(statuses[0].table_version, 42); + assert_eq!(statuses[0].failed, 1); + assert_eq!( + statuses[0] + .last_refresh_job + .as_ref() + .map(|job| job.job_id.as_str()), + Some("job-7") + ); + assert_eq!( + statuses[0].auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Unobservable + ); + } + + #[tokio::test] + async fn test_function_column_status_filters_with_a_get_query() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "GET"); + assert_eq!(request.url().query(), Some("column=embedding")); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!(status.column, "embedding"); + assert!(status.last_refresh_job.is_none()); + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Disabled + ); + } + + #[tokio::test] + async fn test_wait_for_function_column_retries_only_typed_finalization_pending() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .header( + "x-lancedb-error-code", + crate::table::function_column_status::FINALIZATION_PENDING_ERROR_CODE, + ) + .body(b"finalization pending".to_vec()) + .unwrap() + } else { + http::Response::builder() + .status(200) + .body( + br#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"# + .to_vec(), + ) + .unwrap() + } + } + }); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_finalization_code_on_other_status_is_not_retried() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + calls.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .header( + "x-lancedb-error-code", + crate::table::function_column_status::FINALIZATION_PENDING_ERROR_CODE, + ) + .body(b"misclassified pending".to_vec()) + .unwrap() + } + }); + + let error = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap_err(); + assert!(error.to_string().contains("misclassified pending")); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_wait_for_function_column_does_not_retry_generic_500() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + calls.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(b"corrupt freshness evidence".to_vec()) + .unwrap() + } + }); + + let error = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap_err(); + assert!(error.to_string().contains("corrupt freshness evidence")); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_function_column_status_decodes_agent_up_to_date() { + let table = Table::new_with_handler("my_table", |_request| { + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":4, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"up_to_date", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::UpToDate + ); + } + + #[tokio::test] + async fn test_function_column_status_decodes_blocked_scheduler_fields() { + let table = Table::new_with_handler("my_table", |_request| { + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":2, + "stale":2, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":3, + "effective_cooldown_millis":8000, + "blocked_reason":"preparation_backoff", + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Blocked + ); + assert_eq!(status.auto_refresh.failure_streak, 3); + assert_eq!(status.auto_refresh.effective_cooldown_millis, Some(8000)); + assert_eq!( + status.auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::PreparationBackoff) + ); + } + + #[tokio::test] + async fn test_function_column_status_passes_a_pinned_version() { + let calls = Arc::new(AtomicUsize::new(0)); + let status_calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + let status_calls = status_calls.clone(); + move |request| { + calls.fetch_add(1, Ordering::SeqCst); + match request.url().path() { + "/v1/table/my_table/describe/" => { + assert_eq!(request_body_json(&request)["version"], 42); + http::Response::builder() + .status(200) + .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + assert_eq!(request.method(), "GET"); + let query: std::collections::BTreeMap<_, _> = + request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert_eq!(query.get("version").map(|value| value.as_ref()), Some("42")); + let returned_version = if status_calls.fetch_add(1, Ordering::SeqCst) == 0 { + 42 + } else { + 43 + }; + http::Response::builder() + .status(200) + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":{returned_version}, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + } + }); + table.checkout(42).await.unwrap(); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(calls.load(Ordering::SeqCst), 2); + + let error = table.function_column_status("embedding").await.unwrap_err(); + assert!( + error.to_string().contains( + "returned table version 43, but the table handle is pinned to version 42" + ) + ); + assert_eq!(status_calls.load(Ordering::SeqCst), 2); + assert_eq!(calls.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn test_function_column_status_keeps_latest_freshness_headers() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().query_pairs().collect::>(), + vec![( + std::borrow::Cow::Borrowed("column"), + std::borrow::Cow::Borrowed("embedding") + )] + ); + assert_eq!( + request + .headers() + .get("x-lancedb-min-version") + .and_then(|value| value.to_str().ok()), + Some("7") + ); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }, + None, + ); + table.freshness.lock().unwrap().min_version = Some(7); + + let statuses = table + .function_column_statuses(Some("embedding")) + .await + .unwrap(); + assert_eq!(statuses.len(), 1); + } + /// The error listing is table-addressed with optional job and column /// filters, mirroring the server's SQL surface, and the two non-record /// signals come back as their own fields rather than as rows. diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index bd9220754..18a5b7ddf 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -83,6 +83,7 @@ pub mod datafusion; pub(crate) mod dataset; pub mod delete; pub mod freshness; +pub mod function_column_status; pub mod merge; pub mod optimize; pub(crate) mod primary_key; @@ -106,6 +107,11 @@ pub use computed_columns::{ ComputedColumn, ComputedColumnKind, computed_column_from_field, computed_columns, }; pub use delete::DeleteResult; +pub use function_column_status::{ + FunctionColumnAutoRefreshBlockedReason, FunctionColumnAutoRefreshState, + FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, + FunctionColumnVersionStatus, +}; use futures::future::join_all; pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags}; pub use lance::dataset::scanner::DatasetRecordBatchStream; @@ -961,6 +967,19 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("per-row Function errors are recorded only in LanceDB Enterprise"), }) } + /// Exact four-way freshness status for Function-backed output columns. + /// + /// `column` filters to one user-visible output; `None` returns every + /// Function output. The default returns `NotSupported`. + async fn function_column_statuses( + &self, + _column: Option<&str>, + ) -> Result> { + Err(Error::NotSupported { + message: DocLink::Functions + .append_to("exact Function column status is supported only in LanceDB Enterprise"), + }) + } /// Alter columns in the table. async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result; /// Drop columns from the table. @@ -2246,6 +2265,72 @@ impl Table { .await } + /// Return exact freshness status for all Function-backed output columns. + /// + /// The server evaluates all counts at one table version. Clients never + /// derive counts by joining schema, Job, and error listings. A handle + /// pinned with `checkout` sends that exact version, while a latest handle + /// keeps the existing read-freshness headers. + pub async fn function_column_statuses( + &self, + column: Option<&str>, + ) -> Result> { + let statuses = self.inner.function_column_statuses(column).await?; + function_column_status::validate_statuses(&statuses)?; + Ok(statuses) + } + + /// Return exact freshness status for one Function-backed output column. + pub async fn function_column_status(&self, column: &str) -> Result { + let mut statuses = self.function_column_statuses(Some(column)).await?; + if statuses.len() != 1 || statuses[0].column != column { + return Err(Error::ColumnNotFound { + name: column.to_string(), + }); + } + Ok(statuses.remove(0)) + } + + /// Poll until a Function output has no stale or never-computed rows. + /// + /// Failed rows do not keep the call pending. A typed + /// `function_column_status_finalization_pending` response is retried with + /// bounded exponential backoff; every other error is returned immediately. + pub async fn wait_for_function_column( + &self, + column: &str, + timeout: Option, + ) -> Result { + let started = std::time::Instant::now(); + let mut delay = std::time::Duration::from_millis(250); + loop { + let result = self.function_column_status(column).await; + match result { + Ok(status) if status.stale == 0 && status.never_computed == 0 => return Ok(status), + Ok(_) => {} + Err(error) if function_column_status::is_finalization_pending(&error) => {} + Err(error) => return Err(error), + } + + let sleep_for = match timeout { + Some(timeout) => { + let remaining = timeout.saturating_sub(started.elapsed()); + if remaining.is_zero() { + return Err(Error::Timeout { + message: format!( + "Function column '{column}' did not become fresh before timeout" + ), + }); + } + delay.min(remaining) + } + None => delay, + }; + tokio::time::sleep(sleep_for).await; + delay = std::cmp::min(delay * 2, std::time::Duration::from_secs(1)); + } + } + /// The per-row errors Function refreshes recorded on this table: the /// rows a refresh skipped under its skip policy, with the failing input /// and the error, plus a summary for any fragment whose detail was diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 50434143e..477020fc3 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -21,6 +21,7 @@ //! removed by [`prune_sidecars`]. use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt; use std::io::{Cursor, Read}; use std::ops::Range; @@ -98,6 +99,56 @@ impl DirtyRows { /// `{fragment id -> row-level dirty state}`. A missing fragment is clean. pub type RowStateMap = BTreeMap; +/// Physical rows whose latest Function outcome is an unresolved failure. +pub type FailureRows = BTreeMap; + +/// Evidence for rows whose latest Function outcome is known. +/// +/// `known_rows` includes both successful and failed observations. +/// `failed_rows` is the failure subset. A missing row is unknown, not clean. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FailureEvidence { + pub known_rows: FailureRows, + pub failed_rows: FailureRows, +} + +impl FailureEvidence { + fn is_empty(&self) -> bool { + self.known_rows.is_empty() && self.failed_rows.is_empty() + } + + fn validate(&self) -> Result<()> { + if self.failed_rows.iter().any(|(fragment_id, failed)| { + !self + .known_rows + .get(fragment_id) + .is_some_and(|known| failed.is_subset(known)) + }) { + return Err(invalid( + "failed rows are not covered by the failure evidence update".to_string(), + )); + } + Ok(()) + } + + fn for_fragments(&self, fragments: &HashSet) -> Self { + Self { + known_rows: self + .known_rows + .iter() + .filter(|(fragment_id, _)| fragments.contains(fragment_id)) + .map(|(fragment_id, rows)| (*fragment_id, rows.clone())) + .collect(), + failed_rows: self + .failed_rows + .iter() + .filter(|(fragment_id, _)| fragments.contains(fragment_id)) + .map(|(fragment_id, rows)| (*fragment_id, rows.clone())) + .collect(), + } + } +} + /// The single owning value of the freshness sidecar. /// /// `SignatureMap` remains the public facade for callers that only need input @@ -107,6 +158,13 @@ pub type RowStateMap = BTreeMap; struct FreshnessState { signatures: SignatureMap, row_state: RowStateMap, + /// Physical offsets with an exact current-generation outcome. + failure_coverage: FailureRows, + /// The failed subset of `failure_coverage`. + failed_rows: FailureRows, + /// Whether the decoded source used the v3 sidecar format that carries + /// failure evidence. Older formats leave failure rows unclassified. + failure_evidence_recorded: bool, basis: String, // A fresh identity for each begin, even when the basis and dirty rows repeat. intent_id: Uuid, @@ -115,6 +173,8 @@ struct FreshnessState { impl FreshnessState { fn normalize(mut self) -> Result { self.row_state.retain(|_, rows| !rows.is_explicitly_empty()); + self.failure_coverage.retain(|_, rows| !rows.is_empty()); + self.failed_rows.retain(|_, rows| !rows.is_empty()); if self .row_state .keys() @@ -124,6 +184,26 @@ impl FreshnessState { "row state names a fragment without a signature".to_string(), )); } + if self + .failure_coverage + .keys() + .chain(self.failed_rows.keys()) + .any(|fragment_id| !self.signatures.contains_key(fragment_id)) + { + return Err(invalid( + "failure evidence names a fragment without a signature".to_string(), + )); + } + if self.failed_rows.iter().any(|(fragment_id, failed)| { + !self + .failure_coverage + .get(fragment_id) + .is_some_and(|covered| failed.is_subset(covered)) + }) { + return Err(invalid( + "failed rows are not covered by failure evidence".to_string(), + )); + } if self .signatures .values() @@ -138,6 +218,38 @@ impl FreshnessState { } Ok(self) } + + fn invalidate_failure_evidence(&mut self, fragments: impl IntoIterator) { + for fragment_id in fragments { + self.failure_coverage.remove(&fragment_id); + self.failed_rows.remove(&fragment_id); + } + } + + fn invalidate_failure_rows(&mut self, rows: &BTreeMap) { + for (fragment_id, rows) in rows { + if let Some(covered) = self.failure_coverage.get_mut(fragment_id) { + *covered -= rows; + } + if self + .failure_coverage + .get(fragment_id) + .is_some_and(RoaringBitmap::is_empty) + { + self.failure_coverage.remove(fragment_id); + } + if let Some(failed) = self.failed_rows.get_mut(fragment_id) { + *failed -= rows; + } + if self + .failed_rows + .get(fragment_id) + .is_some_and(RoaringBitmap::is_empty) + { + self.failed_rows.remove(fragment_id); + } + } + } } /// Opaque accepted-basis evidence returned by [`begin_row_repair`] and required by @@ -398,7 +510,8 @@ const SIDECAR_DIR: &str = "_computed"; const SIDECAR_REF: &str = "sidecar:"; const SIDECAR_MAGIC: &[u8; 4] = b"CSIG"; const SIDECAR_FORMAT_V1: u8 = 1; -const SIDECAR_FORMAT: u8 = 2; +const SIDECAR_FORMAT_V2: u8 = 2; +const SIDECAR_FORMAT: u8 = 3; /// How long an unreferenced sidecar is presumed to be a stamp in flight: /// lance's own threshold for unverified files, independent of how much /// version history a cleanup keeps. @@ -446,9 +559,85 @@ fn encode_legacy_sidecar(map: &SignatureMap) -> Result> { Ok(bytes) } +#[cfg(test)] +fn encode_v2_sidecar(state: &FreshnessState) -> Result> { + let state = state.clone().normalize()?; + let basis_len = u16::try_from(state.basis.len()) + .map_err(|_| invalid("freshness basis exceeds u16 bytes".to_string()))?; + let fragment_count = u32::try_from(state.signatures.len()) + .map_err(|_| invalid("too many fragments for a freshness sidecar".to_string()))?; + let mut bytes = Vec::new(); + bytes.extend_from_slice(SIDECAR_MAGIC); + bytes.push(SIDECAR_FORMAT_V2); + bytes.extend_from_slice(state.intent_id.as_bytes()); + bytes.extend_from_slice(&basis_len.to_le_bytes()); + bytes.extend_from_slice(state.basis.as_bytes()); + bytes.extend_from_slice(&fragment_count.to_le_bytes()); + for (fragment_id, signature) in &state.signatures { + let hash = u64::from_str_radix(signature, 16).map_err(|_| { + invalid(format!( + "signature '{signature}' is not a 64-bit hex digest" + )) + })?; + let rows = state + .row_state + .get(fragment_id) + .cloned() + .unwrap_or_else(|| DirtyRows::Rows(RoaringBitmap::new())); + let (kind, bitmap) = match rows { + DirtyRows::Rows(bitmap) => (0u8, bitmap), + DirtyRows::AllExcept(clean) => (1u8, clean), + }; + bytes.extend_from_slice(&fragment_id.to_le_bytes()); + bytes.extend_from_slice(&hash.to_le_bytes()); + bytes.push(kind); + encode_bitmap(&mut bytes, Some(&bitmap))?; + } + Ok(bytes) +} + +fn encode_bitmap(bytes: &mut Vec, bitmap: Option<&RoaringBitmap>) -> Result<()> { + let Some(bitmap) = bitmap.filter(|bitmap| !bitmap.is_empty()) else { + bytes.extend_from_slice(&0u32.to_le_bytes()); + return Ok(()); + }; + let mut encoded = Vec::with_capacity(bitmap.serialized_size()); + bitmap + .serialize_into(&mut encoded) + .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; + let bitmap_len = u32::try_from(encoded.len()) + .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; + bytes.extend_from_slice(&bitmap_len.to_le_bytes()); + bytes.extend_from_slice(&encoded); + Ok(()) +} + +fn decode_bitmap( + cursor: &mut Cursor<&[u8]>, + malformed: &impl Fn() -> Error, +) -> Result> { + let mut bitmap_len = [0u8; 4]; + cursor + .read_exact(&mut bitmap_len) + .map_err(|_| malformed())?; + let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; + if bitmap_len == 0 { + return Ok(None); + } + let mut encoded = vec![0u8; bitmap_len]; + cursor.read_exact(&mut encoded).map_err(|_| malformed())?; + let mut bitmap_reader = Cursor::new(encoded.as_slice()); + let bitmap = RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; + if bitmap_reader.position() != bitmap_len as u64 { + return Err(malformed()); + } + Ok(Some(bitmap)) +} + /// `CSIG`, format byte, 16-byte intent UUID, basis, entry count, then for each fragment its id, -/// 8-byte signature, dirty-row mode and serialized bitmap. All integers are -/// little-endian. Format 1 remains readable as clean row state. +/// 8-byte signature, dirty-row mode and serialized bitmap. Format 3 appends +/// failure-coverage and failed-row bitmaps. All integers are little-endian. +/// Format 1 remains readable as clean row state. fn encode_sidecar(state: &FreshnessState) -> Result> { let state = state.clone().normalize()?; let basis_len = u16::try_from(state.basis.len()) @@ -477,17 +666,12 @@ fn encode_sidecar(state: &FreshnessState) -> Result> { DirtyRows::Rows(bitmap) => (0u8, bitmap), DirtyRows::AllExcept(clean) => (1u8, clean), }; - let mut encoded = Vec::with_capacity(bitmap.serialized_size()); - bitmap - .serialize_into(&mut encoded) - .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; - let bitmap_len = u32::try_from(encoded.len()) - .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; bytes.extend_from_slice(&fragment_id.to_le_bytes()); bytes.extend_from_slice(&hash.to_le_bytes()); bytes.push(kind); - bytes.extend_from_slice(&bitmap_len.to_le_bytes()); - bytes.extend_from_slice(&encoded); + encode_bitmap(&mut bytes, Some(&bitmap))?; + encode_bitmap(&mut bytes, state.failure_coverage.get(fragment_id))?; + encode_bitmap(&mut bytes, state.failed_rows.get(fragment_id))?; } Ok(bytes) } @@ -526,7 +710,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { cursor.read_exact(&mut magic).map_err(|_| malformed())?; let mut format = [0u8; 1]; cursor.read_exact(&mut format).map_err(|_| malformed())?; - if &magic != SIDECAR_MAGIC || format[0] != SIDECAR_FORMAT { + if &magic != SIDECAR_MAGIC || !matches!(format[0], SIDECAR_FORMAT_V2 | SIDECAR_FORMAT) { return Err(malformed()); } let mut intent_id = [0u8; 16]; @@ -542,6 +726,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { let mut state = FreshnessState { basis, intent_id: Uuid::from_bytes(intent_id), + failure_evidence_recorded: format[0] == SIDECAR_FORMAT, ..Default::default() }; for _ in 0..count { @@ -554,19 +739,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { cursor.read_exact(&mut signature).map_err(|_| malformed())?; let mut kind = [0u8; 1]; cursor.read_exact(&mut kind).map_err(|_| malformed())?; - let mut bitmap_len = [0u8; 4]; - cursor - .read_exact(&mut bitmap_len) - .map_err(|_| malformed())?; - let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; - let mut encoded = vec![0u8; bitmap_len]; - cursor.read_exact(&mut encoded).map_err(|_| malformed())?; - let mut bitmap_reader = Cursor::new(encoded.as_slice()); - let bitmap = - RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; - if bitmap_reader.position() != bitmap_len as u64 { - return Err(malformed()); - } + let bitmap = decode_bitmap(&mut cursor, &malformed)?.unwrap_or_default(); let dirty = match kind[0] { 0 => DirtyRows::Rows(bitmap), 1 => DirtyRows::AllExcept(bitmap), @@ -582,6 +755,14 @@ fn decode_sidecar(bytes: &[u8]) -> Result { if !dirty.is_explicitly_empty() { state.row_state.insert(fragment_id, dirty); } + if format[0] == SIDECAR_FORMAT { + if let Some(covered) = decode_bitmap(&mut cursor, &malformed)? { + state.failure_coverage.insert(fragment_id, covered); + } + if let Some(failed) = decode_bitmap(&mut cursor, &malformed)? { + state.failed_rows.insert(fragment_id, failed); + } + } } if cursor.position() != bytes.len() as u64 { return Err(malformed()); @@ -763,12 +944,15 @@ enum StoredFreshnessState { Unreadable, } -async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { +async fn load_freshness_state( + dataset: &Dataset, + column: &str, +) -> Result)>> { let Some(encoded) = field_meta(dataset, column, SOURCE_SIGNATURE_META_KEY) else { - return StoredFreshnessState::Absent; + return Ok(None); }; // Inline JSON is the declaration's empty seed and the pre-sidecar form. - let (read, digest) = match encoded.strip_prefix(SIDECAR_REF) { + let read = match encoded.strip_prefix(SIDECAR_REF) { Some(digest) => ( read_sidecar(dataset, digest).await, Some(digest.to_string()), @@ -783,8 +967,14 @@ async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshn None, ), }; - match read { - Ok(state) => StoredFreshnessState::Present { state, digest }, + let (state, digest) = read; + Ok(Some((state?, digest))) +} + +async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { + match load_freshness_state(dataset, column).await { + Ok(Some((state, digest))) => StoredFreshnessState::Present { state, digest }, + Ok(None) => StoredFreshnessState::Absent, Err(error) => { log::warn!( "computed column '{column}' freshness state is unreadable ({error}); every fragment will be recomputed" @@ -853,6 +1043,38 @@ impl StalenessPlan { } } +/// Strict, internally consistent evidence for a Function-column status read. +/// +/// Unlike [`staleness_against`], this value never converts an unreadable +/// sidecar into a conservative recompute plan. Failure coverage may be +/// partial: the caller combines it with live-row freshness and value evidence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StrictFreshness { + /// No freshness certificate is recorded on this dataset version. + /// + /// This does not prove that no refresh was ever attempted; older failed + /// attempts may be untracked. Assignment and value evidence still decide + /// stale versus never computed. + Absent, + /// The sidecar predates failure evidence. Its staleness plan is still + /// usable; row classification may use freshness, values, and assignment + /// evidence outside this sidecar. + Uncertified { staleness: StalenessPlan }, + /// Exact staleness and current-generation failed rows. + Certified { + staleness: StalenessPlan, + failures: FailureEvidence, + }, +} + +fn incomplete_certificate(column: &str, reason: impl fmt::Display) -> Error { + Error::Runtime { + message: format!( + "computed column '{column}' has no complete freshness certificate: {reason}" + ), + } +} + /// A version of the log since the stamp that bears on carrying freshness /// forward: an append, whose fragments hold no computed value yet, or a /// compaction's rewrite groups, consumed and produced fragment ids. @@ -1158,6 +1380,16 @@ pub async fn staleness_against( } StoredFreshnessState::Present { state: stored, .. } => stored, }; + staleness_from_state(dataset, column, definition_version, inputs, stored).await +} + +async fn staleness_from_state( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + stored: FreshnessState, +) -> Result { let stored_version = field_meta(dataset, column, DEFINITION_VERSION_META_KEY); if stored_version.is_some_and(|version| version != definition_version) { return Ok(StalenessPlan { @@ -1221,6 +1453,71 @@ pub async fn staleness_against( }) } +/// Read exact status evidence without the planner's conservative fallback. +/// +/// A missing metadata key returns [`StrictFreshness::Absent`]. A referenced +/// sidecar that cannot be read or decoded propagates the existing error. The +/// returned plan is certified when the sidecar records a definition and can be +/// decoded. Failure coverage is returned only for live fragments whose stored +/// input signature still matches; stale evidence is omitted. The status +/// provider remains responsible for classifying uncovered live rows as fresh, +/// stale, or never computed, and for reporting an error only when a row is +/// genuinely ambiguous. +pub async fn strict_freshness_against( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, +) -> Result { + let Some((stored, _)) = load_freshness_state(dataset, column).await? else { + return Ok(StrictFreshness::Absent); + }; + let Some(stored_definition) = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) else { + return Err(incomplete_certificate( + column, + "the recorded definition is missing", + )); + }; + let staleness = + staleness_from_state(dataset, column, definition_version, inputs, stored.clone()).await?; + if !stored.failure_evidence_recorded { + return Ok(StrictFreshness::Uncertified { staleness }); + } + if stored_definition != definition_version { + return Ok(StrictFreshness::Certified { + staleness, + failures: FailureEvidence::default(), + }); + } + let mut failures = FailureEvidence::default(); + for fragment in dataset.get_fragments() { + let fragment_id = fragment.id() as u32; + let current = signature_of(dataset, fragment_id, inputs)?.ok_or_else(|| { + incomplete_certificate(column, format!("fragment {fragment_id} is not live")) + })?; + if stored.signatures.get(&fragment_id) != Some(¤t) { + // The old generation's failure evidence no longer describes this + // fragment. Its live rows are stale or never computed, not + // ambiguously failed. + continue; + } + if let Some(covered) = stored.failure_coverage.get(&fragment_id) + && !covered.is_empty() + { + failures.known_rows.insert(fragment_id, covered.clone()); + } + if let Some(failed) = stored.failed_rows.get(&fragment_id) + && !failed.is_empty() + { + failures.failed_rows.insert(fragment_id, failed.clone()); + } + } + Ok(StrictFreshness::Certified { + staleness, + failures, + }) +} + /// What [`record_freshness`] wrote: the table version the stamp landed at, /// if it wrote one, and the entries recorded and dropped for having moved. #[derive(Debug, Default, PartialEq, Eq)] @@ -1251,6 +1548,55 @@ pub async fn record_freshness( definition_version: &str, inputs: &InputFields, computed: SignatureMap, +) -> Result { + record_freshness_impl( + latest, + pinned, + column, + definition_version, + inputs, + computed, + None, + ) + .await +} + +/// Record signatures and an explicit current-generation failure outcome in one +/// immutable sidecar transition. +/// +/// `failures.known_rows` must include only physical offsets whose final +/// outcome is known. `failures.failed_rows` is the failed subset. Rows omitted +/// from coverage remain unknown to failure classification; freshness, values, +/// and assignment evidence may still classify them. +pub async fn record_freshness_with_failures( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, + failures: &FailureEvidence, +) -> Result { + record_freshness_impl( + latest, + pinned, + column, + definition_version, + inputs, + computed, + Some(failures), + ) + .await +} + +async fn record_freshness_impl( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, + failures: Option<&FailureEvidence>, ) -> Result { let absent = matches!( stored_signatures(latest, column).await, @@ -1270,7 +1616,7 @@ pub async fn record_freshness( } } entries.extend(computed); - if entries.is_empty() && !absent { + if entries.is_empty() && !absent && failures.is_none_or(FailureEvidence::is_empty) { return Ok(FreshnessRecord::default()); } let fragments: Vec = entries.keys().copied().collect(); @@ -1280,7 +1626,19 @@ pub async fn record_freshness( .filter(|(fragment_id, signature)| current.get(fragment_id) == Some(signature)) .collect(); let recorded = verified.len(); - let version = write_signatures(latest, column, definition_version, verified).await?; + let verified_fragments: HashSet = verified.keys().copied().collect(); + let scoped_failures = failures + .map(|failures| failures.for_fragments(&verified_fragments)) + .filter(|failures| !failures.is_empty()); + let version = write_signatures_impl( + latest, + column, + definition_version, + Some(inputs), + verified, + scoped_failures.as_ref(), + ) + .await?; Ok(FreshnessRecord { version: Some(version), recorded, @@ -1582,6 +1940,25 @@ pub async fn write_signatures( definition_version: &str, entries: SignatureMap, ) -> Result { + write_signatures_impl(dataset, column, definition_version, None, entries, None).await +} + +async fn write_signatures_impl( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: Option<&InputFields>, + entries: SignatureMap, + failures: Option<&FailureEvidence>, +) -> Result { + if let Some(failures) = failures { + failures.validate()?; + if inputs.is_none() { + return Err(invalid( + "failure evidence requires input fields for signature validation".to_string(), + )); + } + } let definition_changed = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) .is_some_and(|version| version != definition_version); let live: HashSet = dataset @@ -1619,17 +1996,40 @@ pub async fn write_signatures( } // A signature entry written through this API means the fragment was // recomputed in full. Whole callers keep their old semantics while - // clearing any partial retry state left by a previous publication. + // clearing any partial retry state left by a previous publication. The + // old failure outcome is also unknown unless the failure-aware wrapper + // supplies it below. for fragment_id in &recomputed { state.row_state.remove(fragment_id); } - state.signatures.extend(entries); + state.invalidate_failure_evidence(recomputed.iter().copied()); + state.signatures.extend( + entries + .iter() + .map(|(fragment_id, signature)| (*fragment_id, signature.clone())), + ); state .signatures .retain(|fragment_id, _| live.contains(fragment_id)); state .row_state .retain(|fragment_id, _| live.contains(fragment_id)); + state + .failure_coverage + .retain(|fragment_id, _| live.contains(fragment_id)); + state + .failed_rows + .retain(|fragment_id, _| live.contains(fragment_id)); + if let Some(failures) = failures { + apply_failure_evidence( + dataset, + inputs.expect("failure evidence requires input fields"), + &entries, + &mut state, + failures, + ) + .await?; + } if state.row_state.is_empty() || state_unreadable || signatures_changed { state.basis.clear(); } @@ -1645,6 +2045,70 @@ struct FreshnessWrite { intent_digest: Option, } +async fn apply_failure_evidence( + dataset: &Dataset, + inputs: &InputFields, + accepted: &SignatureMap, + state: &mut FreshnessState, + update: &FailureEvidence, +) -> Result<()> { + update.validate()?; + let physical_rows: BTreeMap = { + let mut rows = BTreeMap::new(); + for fragment in dataset.get_fragments() { + rows.insert(fragment.id() as u32, fragment.physical_rows().await? as u64); + } + rows + }; + let mut applied = HashSet::new(); + for (fragment_id, covered) in &update.known_rows { + let Some(rows) = physical_rows.get(fragment_id) else { + continue; + }; + let Some(current) = signature_of(dataset, *fragment_id, inputs)? else { + continue; + }; + // Evidence belongs to the attempt that produced this accepted + // signature. A concurrent attempt may have stamped a newer signature + // into `state`; that does not make this attempt's rows valid for it. + if accepted.get(fragment_id) != Some(¤t) { + continue; + } + if state.signatures.get(fragment_id) != Some(¤t) { + continue; + } + if covered + .max() + .is_some_and(|offset| u64::from(offset) >= *rows) + { + return Err(invalid(format!( + "failure evidence for fragment {fragment_id} exceeds its {rows} physical rows" + ))); + } + if let Some(failed) = state.failed_rows.get_mut(fragment_id) { + *failed -= covered; + } + let coverage = state.failure_coverage.entry(*fragment_id).or_default(); + *coverage |= covered; + applied.insert(*fragment_id); + } + for (fragment_id, failed) in &update.failed_rows { + if !applied.contains(fragment_id) { + continue; + } + if !update.known_rows.contains_key(fragment_id) { + return Err(invalid(format!( + "failed rows for fragment {fragment_id} have no coverage update" + ))); + } + let current = state.failed_rows.entry(*fragment_id).or_default(); + *current |= failed; + } + state.failed_rows.retain(|_, rows| !rows.is_empty()); + state.failure_coverage.retain(|_, rows| !rows.is_empty()); + Ok(()) +} + async fn write_freshness_state( dataset: &mut Dataset, column: &str, @@ -1656,6 +2120,8 @@ async fn write_freshness_state( let state = state.normalize()?; let inline_empty = state.signatures.is_empty() && state.row_state.is_empty() + && state.failure_coverage.is_empty() + && state.failed_rows.is_empty() && state.basis.is_empty() && !retain_empty_sidecar; // The sidecar is durable before the metadata commit references it. @@ -1817,6 +2283,8 @@ pub async fn begin_row_repair( freshness.signatures = signatures_for(dataset, &live.iter().copied().collect::>(), inputs)?; freshness.row_state.clear(); + freshness.failure_coverage.clear(); + freshness.failed_rows.clear(); freshness.basis.clear(); } if state_unreadable || definition_changed { @@ -1826,6 +2294,8 @@ pub async fn begin_row_repair( .iter() .map(|id| (*id, DirtyRows::AllExcept(RoaringBitmap::new()))) .collect(); + freshness.failure_coverage.clear(); + freshness.failed_rows.clear(); } for (fragment_id, repair) in repairs { @@ -1842,6 +2312,9 @@ pub async fn begin_row_repair( let preserve = !state_unreadable && !definition_changed && freshness.signatures.get(fragment_id) == Some(¤t); + if !preserve { + freshness.invalidate_failure_evidence([*fragment_id]); + } let dirty = if preserve { freshness .row_state @@ -1865,6 +2338,12 @@ pub async fn begin_row_repair( freshness .row_state .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .failure_coverage + .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .failed_rows + .retain(|fragment_id, _| live.contains(fragment_id)); freshness.basis = basis.clone(); freshness.intent_id = Uuid::new_v4(); @@ -1958,6 +2437,66 @@ pub async fn finish_row_repair( filled_rows: &BTreeMap, skipped_rows: &BTreeMap, verified_version: Option, +) -> Result { + finish_row_repair_impl( + dataset, + column, + definition_version, + inputs, + token, + filled_rows, + skipped_rows, + None, + verified_version, + ) + .await +} + +/// Finalize a row repair together with the exact failure evidence observed for +/// those rows. +/// +/// `failures.known_rows` must be a subset of the rows assigned either a +/// value or an explicit skipped outcome. This permits a deferral to become +/// known non-failed without turning it into a failure. `failed_rows` must be a +/// subset of `known_rows`. The same token, input-signature and version +/// fences as [`finish_row_repair`] apply. +#[allow(clippy::too_many_arguments)] +pub async fn finish_row_repair_with_failures( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + failures: &FailureEvidence, + verified_version: Option, +) -> Result { + finish_row_repair_impl( + dataset, + column, + definition_version, + inputs, + token, + filled_rows, + skipped_rows, + Some(failures), + verified_version, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn finish_row_repair_impl( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + failures: Option<&FailureEvidence>, + verified_version: Option, ) -> Result { if !is_sha256_hex(&token.intent_digest) { return Err(invalid("row repair token is malformed".to_string())); @@ -1971,6 +2510,36 @@ pub async fn finish_row_repair( "row repair result names a fragment outside its token".to_string(), )); } + if let Some(failures) = failures { + failures.validate()?; + for (fragment_id, covered) in &failures.known_rows { + let selected = token.selected_rows.get(fragment_id).ok_or_else(|| { + invalid(format!( + "failure evidence names fragment {fragment_id} outside its token" + )) + })?; + let mut known = filled_rows.get(fragment_id).cloned().unwrap_or_default(); + if let Some(skipped) = skipped_rows.get(fragment_id) { + known |= skipped; + } + if !covered.is_subset(selected) || !covered.is_subset(&known) { + return Err(invalid(format!( + "failure evidence for fragment {fragment_id} covers rows without a final outcome" + ))); + } + } + for (fragment_id, failed) in &failures.failed_rows { + if !failures.known_rows.contains_key(fragment_id) + || skipped_rows + .get(fragment_id) + .is_none_or(|skipped| !failed.is_subset(skipped)) + { + return Err(invalid(format!( + "failed rows for fragment {fragment_id} must be an explicit skipped subset" + ))); + } + } + } dataset.checkout_latest().await?; if verified_version.is_some_and(|version| dataset.version().version != version) { return Err(invalid( @@ -2015,14 +2584,32 @@ pub async fn finish_row_repair( ))); } } - let before = state.row_state.clone(); + let before = state.clone(); + state.invalidate_failure_rows(&token.selected_rows); apply_row_repair( &mut state.row_state, &token.selected_rows, filled_rows, skipped_rows, )?; - if state.row_state == before { + if let Some(failures) = failures { + let accepted = token + .selected_rows + .keys() + .map(|fragment_id| { + state + .signatures + .get(fragment_id) + .cloned() + .map(|signature| (*fragment_id, signature)) + }) + .collect::>() + .ok_or_else(|| { + invalid("row repair failure evidence lost an accepted signature".to_string()) + })?; + apply_failure_evidence(dataset, inputs, &accepted, &mut state, failures).await?; + } + if state == before { return Ok(dataset.version().version); } if current_digest != token.intent_digest.as_str() { @@ -2868,6 +3455,41 @@ mod tests { .unwrap(); } + async fn stamp_v2( + dataset: &mut Dataset, + column: &str, + definition: &str, + entries: SignatureMap, + ) { + let reference = write_sidecar_bytes( + dataset, + encode_v2_sidecar(&FreshnessState { + signatures: entries, + ..Default::default() + }) + .unwrap(), + ) + .await + .unwrap(); + let describes = dataset.version().version.to_string(); + dataset + .update_field_metadata() + .update( + column, + [ + (SOURCE_SIGNATURE_META_KEY.to_string(), reference), + ( + DEFINITION_VERSION_META_KEY.to_string(), + definition.to_string(), + ), + (RECORDED_AT_VERSION_META_KEY.to_string(), describes), + ], + ) + .unwrap() + .await + .unwrap(); + } + fn fragment_signature(dataset: &Dataset, fragment_id: u32) -> String { signature_of(dataset, fragment_id, &inputs(dataset)) .unwrap() @@ -2894,6 +3516,15 @@ mod tests { (3, DirtyRows::Rows(RoaringBitmap::from_iter([1, 4, 9]))), (7, DirtyRows::AllExcept(RoaringBitmap::from_iter([0, 2]))), ]), + failure_coverage: FailureRows::from([ + (3, RoaringBitmap::from_iter([1, 2, 4, 9])), + (7, RoaringBitmap::from_iter([0, 1, 2, 3])), + ]), + failed_rows: FailureRows::from([ + (3, RoaringBitmap::from_iter([1])), + (7, RoaringBitmap::from_iter([1, 3])), + ]), + failure_evidence_recorded: true, }; let encoded = encode_sidecar(&state).unwrap(); assert_eq!(encoded[4], SIDECAR_FORMAT); @@ -2913,9 +3544,283 @@ mod tests { let state = decode_sidecar(&encode_legacy_sidecar(&signatures).unwrap()).unwrap(); assert_eq!(state.signatures, signatures); assert!(state.row_state.is_empty()); + assert!(state.failure_coverage.is_empty()); + assert!(state.failed_rows.is_empty()); + assert!(!state.failure_evidence_recorded); assert!(state.basis.is_empty()); } + #[test] + fn v2_sidecar_decodes_with_unknown_failure_evidence() { + let state = FreshnessState { + signatures: SignatureMap::from([(1, "0000000000000001".to_string())]), + row_state: RowStateMap::from([(1, DirtyRows::Rows(RoaringBitmap::from_iter([2, 3])))]), + basis: "legacy-intent".to_string(), + intent_id: Uuid::from_u128(1), + ..Default::default() + }; + let decoded = decode_sidecar(&encode_v2_sidecar(&state).unwrap()).unwrap(); + assert_eq!(decoded, state); + assert!(decoded.failure_coverage.is_empty()); + assert!(decoded.failed_rows.is_empty()); + assert!(!decoded.failure_evidence_recorded); + } + + #[tokio::test] + async fn a_first_partial_write_keeps_untouched_legacy_rows_unknown() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let entries = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + stamp_v2(&mut dataset, COLUMN, &definition, entries).await; + + let StrictFreshness::Uncertified { staleness } = + strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("the v2 sidecar should yield a readable uncertified plan"); + }; + assert_eq!(staleness, StalenessPlan::default()); + + let selected = RoaringBitmap::from_iter([1, 2]); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, selected.clone()))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "legacy-partial", + &repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, selected)]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + None, + ) + .await + .unwrap(); + + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("partial v3 evidence is still readable"); + }; + assert_eq!( + staleness.row_dirty.get(&0), + Some(&DirtyRows::Rows(RoaringBitmap::from_iter([1]))) + ); + assert_eq!( + failures.known_rows.get(&0), + Some(&RoaringBitmap::from_iter([1, 2])), + "only the rows this partial publication observed are covered" + ); + assert_eq!( + failures.failed_rows.get(&0), + Some(&RoaringBitmap::from_iter([1])) + ); + assert!( + !failures.known_rows.contains_key(&1), + "the untouched legacy fragment remains unknown" + ); + } + + #[tokio::test] + async fn a_successful_retry_clears_only_its_failed_rows() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let signatures = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + stamp_v2(&mut dataset, COLUMN, &definition, signatures).await; + + let first_selected = RoaringBitmap::from_iter([1, 2]); + let first_repairs = BTreeMap::from([(0, repair(&dataset, 0, first_selected.clone()))]); + let first = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "failed-wave", + &first_repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &first, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, first_selected)]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + None, + ) + .await + .unwrap(); + + let retry_selected = RoaringBitmap::from_iter([1]); + let retry_repairs = BTreeMap::from([(0, repair(&dataset, 0, retry_selected.clone()))]); + let retry = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "successful-retry", + &retry_repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &retry, + &BTreeMap::from([(0, retry_selected.clone())]), + &BTreeMap::new(), + &FailureEvidence { + known_rows: BTreeMap::from([(0, retry_selected)]), + failed_rows: BTreeMap::new(), + }, + None, + ) + .await + .unwrap(); + + let StrictFreshness::Certified { failures, .. } = + strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("status should remain readable"); + }; + assert!(!failures.failed_rows.contains_key(&0)); + assert_eq!( + failures.known_rows.get(&0), + Some(&RoaringBitmap::from_iter([1, 2])) + ); + } + + #[tokio::test] + async fn an_old_attempt_cannot_rewrite_a_newer_signature_evidence() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let old = dataset.clone(); + let old_inputs = ids.clone(); + let old_signature = signature_of(&old, 0, &old_inputs).unwrap().unwrap(); + + rewrite_value(&mut dataset, 0).await; + let new_signature = signature_of(&dataset, 0, &inputs(&dataset)) + .unwrap() + .unwrap(); + assert_ne!(old_signature, new_signature); + + let current_entries = signatures_for(&dataset, &[0, 1], &inputs(&dataset)).unwrap(); + write_signatures(&mut dataset, COLUMN, &definition, current_entries.clone()) + .await + .unwrap(); + let StoredFreshnessState::Present { + state: mut current_state, + .. + } = stored_freshness_state(&dataset, COLUMN).await + else { + panic!("new attempt state"); + }; + current_state + .failure_coverage + .insert(0, RoaringBitmap::from_iter([3, 4])); + current_state + .failed_rows + .insert(0, RoaringBitmap::from_iter([4])); + let write = write_freshness_state( + &mut dataset, + COLUMN, + &definition, + current_state.clone(), + false, + None, + ) + .await + .unwrap(); + assert!(write.version > 0); + let new_evidence = FailureEvidence { + known_rows: current_state.failure_coverage.clone(), + failed_rows: current_state.failed_rows.clone(), + }; + + let record = record_freshness_with_failures( + &mut dataset, + None, + COLUMN, + &definition, + &old_inputs, + SignatureMap::from([(0, old_signature)]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1, 2]))]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + ) + .await + .unwrap(); + assert_eq!((record.recorded, record.moved), (0, 1)); + + let StrictFreshness::Certified { failures, .. } = + strict_freshness_against(&dataset, COLUMN, &definition, &inputs(&dataset)) + .await + .unwrap() + else { + panic!("current signature evidence should remain readable"); + }; + assert_eq!(failures.known_rows, new_evidence.known_rows); + assert_eq!(failures.failed_rows, new_evidence.failed_rows); + assert_eq!( + failures.failed_rows.get(&0), + Some(&RoaringBitmap::from_iter([4])), + "old S1 failure must not replace the S2 failure" + ); + assert!(!failures.known_rows.contains_key(&1)); + } + + #[test] + fn failure_evidence_must_be_a_subset_of_coverage() { + let state = FreshnessState { + signatures: SignatureMap::from([(3, "0000000000000003".to_string())]), + failure_coverage: FailureRows::from([(3, RoaringBitmap::from_iter([1]))]), + failed_rows: FailureRows::from([(3, RoaringBitmap::from_iter([2]))]), + ..Default::default() + }; + let error = encode_sidecar(&state).unwrap_err(); + assert!( + error + .to_string() + .contains("failed rows are not covered by failure evidence"), + "{error}" + ); + } + #[tokio::test] async fn a_row_repair_clears_filled_rows_and_retains_skipped_rows() { let dir = tempfile::tempdir().unwrap(); diff --git a/rust/lancedb/src/table/function_column_status.rs b/rust/lancedb/src/table/function_column_status.rs new file mode 100644 index 000000000..729ea33ba --- /dev/null +++ b/rust/lancedb/src/table/function_column_status.rs @@ -0,0 +1,303 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Read-only status for Function-backed table columns. + +use serde::{Deserialize, Serialize}; + +use crate::function::FunctionVersionRef; +use crate::{Error, Result}; + +/// Stable HTTP error code for a status read waiting on its matching finalize. +pub const FINALIZATION_PENDING_ERROR_CODE: &str = "function_column_status_finalization_pending"; + +/// One exact immutable Function revision attached to a table output. +pub type FunctionColumnVersionStatus = FunctionVersionRef; + +/// Latest matching refresh Job projected for a Function output. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub automatic: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed_at_millis: Option, +} + +/// Automatic-refresh scheduling state that the server can prove. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionColumnAutoRefreshState { + Disabled, + Running, + UpToDate, + Ready, + WaitingInterval, + WaitingBackoff, + Blocked, + Unobservable, +} + +impl FunctionColumnAutoRefreshState { + pub const fn as_str(self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Running => "running", + Self::UpToDate => "up_to_date", + Self::Ready => "ready", + Self::WaitingInterval => "waiting_interval", + Self::WaitingBackoff => "waiting_backoff", + Self::Blocked => "blocked", + Self::Unobservable => "unobservable", + } + } +} + +/// Why an enabled automatic refresh is not currently schedulable. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionColumnAutoRefreshBlockedReason { + TableHasMemWal, + InputsNotSettled, + DependencyInFlight, + TableCapacity, + Cancelled, + PreparationBackoff, +} + +impl FunctionColumnAutoRefreshBlockedReason { + pub const fn as_str(self) -> &'static str { + match self { + Self::TableHasMemWal => "table_has_mem_wal", + Self::InputsNotSettled => "inputs_not_settled", + Self::DependencyInFlight => "dependency_in_flight", + Self::TableCapacity => "table_capacity", + Self::Cancelled => "cancelled", + Self::PreparationBackoff => "preparation_backoff", + } + } +} + +/// Automatic-refresh projection for a Function output. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub interval_seconds: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub active_job_id: Option, + pub state: FunctionColumnAutoRefreshState, + pub failure_streak: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effective_cooldown_millis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub blocked_reason: Option, + /// Null is intentional until the Lance Agent exposes its scheduler decision. + pub next_run_at_millis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_run_at_reason: Option, +} + +/// Exact status of one Function output at one table version. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: u64, + pub rows: u64, + pub fresh: u64, + pub stale: u64, + pub never_computed: u64, + pub failed: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_refresh_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +impl FunctionColumnStatus { + /// Whether this status is safe to expose as an exact four-way count. + pub fn validate(&self) -> Result<()> { + let classified = self + .fresh + .checked_add(self.stale) + .and_then(|count| count.checked_add(self.never_computed)) + .and_then(|count| count.checked_add(self.failed)); + if classified != Some(self.rows) { + return Err(Error::Runtime { + message: format!( + "Function column '{}' status counts do not partition {} rows", + self.column, self.rows + ), + }); + } + if self.auto_refresh.state == FunctionColumnAutoRefreshState::Blocked + && self.auto_refresh.blocked_reason.is_none() + { + return Err(Error::Runtime { + message: format!( + "Function column '{}' reported a blocked scheduler state without a reason", + self.column + ), + }); + } + if self.auto_refresh.state == FunctionColumnAutoRefreshState::Unobservable + && self.auto_refresh.next_run_at_millis.is_none() + && self + .auto_refresh + .next_run_at_reason + .as_deref() + .is_none_or(str::is_empty) + { + return Err(Error::Runtime { + message: format!( + "Function column '{}' omitted a reason for an unavailable next run", + self.column + ), + }); + } + Ok(()) + } +} + +/// Validate one GET response, whose objects must all describe one snapshot. +pub fn validate_statuses(statuses: &[FunctionColumnStatus]) -> Result<()> { + let mut table_versions = statuses.iter().map(|status| status.table_version); + let Some(first) = table_versions.next() else { + return Ok(()); + }; + if table_versions.any(|version| version != first) { + return Err(Error::Runtime { + message: "Function column statuses came from different table versions".to_string(), + }); + } + statuses.iter().try_for_each(FunctionColumnStatus::validate) +} + +/// Whether an error is the typed transient response used while the data +/// version's matching freshness finalization is still in progress. +pub fn is_finalization_pending(error: &Error) -> bool { + #[cfg(feature = "remote")] + { + error.status_code() == Some(reqwest::StatusCode::SERVICE_UNAVAILABLE) + && error + .remote_error_metadata() + .and_then(|metadata| metadata.error_code.as_deref()) + == Some(FINALIZATION_PENDING_ERROR_CODE) + } + #[cfg(not(feature = "remote"))] + { + let _ = error; + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn status(column: &str, table_version: u64) -> FunctionColumnStatus { + FunctionColumnStatus { + column: column.to_string(), + binding_id: "fb_01".to_string(), + function: FunctionVersionRef { + name: "embed".to_string(), + namespace_path: Vec::new(), + object_id: "embed".to_string(), + location: "objects/embed".to_string(), + version: "7".to_string(), + manifest_digest: "sha256:abc".to_string(), + }, + table_version, + rows: 10, + fresh: 6, + stale: 2, + never_computed: 1, + failed: 1, + last_refresh_job: None, + auto_refresh: FunctionColumnAutoRefreshStatus { + enabled: true, + interval_seconds: Some(60), + active_job_id: None, + state: FunctionColumnAutoRefreshState::Unobservable, + failure_streak: 0, + effective_cooldown_millis: None, + blocked_reason: None, + next_run_at_millis: None, + next_run_at_reason: Some( + "authoritative_scheduler_projection_unavailable".to_string(), + ), + }, + } + } + + #[test] + fn validates_a_single_version_and_four_way_partition() { + validate_statuses(&[status("a", 42), status("b", 42)]).unwrap(); + + let error = validate_statuses(&[status("a", 42), status("b", 43)]).unwrap_err(); + assert!(error.to_string().contains("different table versions")); + + let mut invalid = status("a", 42); + invalid.fresh += 1; + let error = validate_statuses(&[invalid]).unwrap_err(); + assert!(error.to_string().contains("do not partition 10 rows")); + } + + #[test] + fn wire_keeps_job_and_auto_refresh_metadata() { + let mut value = status("a", 42); + value.last_refresh_job = Some(FunctionColumnLastRefreshJob { + job_id: "job-7".to_string(), + state: "finished".to_string(), + automatic: Some(true), + completed_at_millis: Some(1_790_000_000_000), + }); + let encoded = serde_json::to_value(value).unwrap(); + assert_eq!(encoded["last_refresh_job"]["job_id"], "job-7"); + assert_eq!(encoded["auto_refresh"]["enabled"], true); + assert_eq!( + encoded["auto_refresh"]["next_run_at_reason"], + "authoritative_scheduler_projection_unavailable" + ); + } + + #[test] + fn up_to_date_wire_is_stable() { + assert_eq!( + serde_json::to_string(&FunctionColumnAutoRefreshState::UpToDate).unwrap(), + "\"up_to_date\"" + ); + } + + #[test] + fn blocked_auto_refresh_wire_keeps_its_reason() { + let mut value = status("a", 42); + value.auto_refresh.state = FunctionColumnAutoRefreshState::Blocked; + value.auto_refresh.failure_streak = 3; + value.auto_refresh.effective_cooldown_millis = Some(8000); + value.auto_refresh.blocked_reason = + Some(FunctionColumnAutoRefreshBlockedReason::PreparationBackoff); + value.auto_refresh.next_run_at_reason = None; + + let encoded = serde_json::to_value(&value).unwrap(); + assert_eq!(encoded["auto_refresh"]["state"], "blocked"); + assert_eq!( + encoded["auto_refresh"]["blocked_reason"], + "preparation_backoff" + ); + assert_eq!(encoded["auto_refresh"]["failure_streak"], 3); + assert_eq!(encoded["auto_refresh"]["effective_cooldown_millis"], 8000); + value.validate().unwrap(); + + value.auto_refresh.blocked_reason = None; + assert!( + value + .validate() + .unwrap_err() + .to_string() + .contains("blocked scheduler state without a reason") + ); + } +} From a356950bced171427b8eacbe5f30bcfd886be76e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 21:14:30 +0800 Subject: [PATCH 02/75] feat: expose queued Function refresh status (#4959) ## Problem The existing Function `column_status` surface cannot decode the Agent scheduler's `queued` state or the `failure_threshold_reached` and `binding_revision_missing` blocked reasons. It also preserves only the latest refresh job, so a later cancellation can hide an earlier actual failure. ## Change - Adds the `queued`, `failure_threshold_reached`, and `binding_revision_missing` wire states in Rust, Python, and Node. The wire change is additive, while Rust callers must update exhaustive enum matches and public struct literals. - Adds optional `last_failure_job` alongside `last_refresh_job`. The latest cancellation and the most recent actual failure retain separate meanings. - Reuses the canonical Rust `JobFailure` and existing Python/Node `JobFailureInfo` models for nested job failure details instead of introducing a parallel status error model. - Maps the existing public `sql_job_id` field through Node's `JobFailureInfo`. - Keeps `column_status`, `column_statuses`, and `wait_fresh` as the existing API surfaces. There is no new endpoint, row-error list, durable ledger, or unknown-enum fallback. - Documents `queued` versus `running` and the separate latest-attempt and latest-failure jobs in the existing hidden freshness release draft. The new status values are additive but cross-service: `queued`, the two new blocked reasons, and `last_failure_job` require matching Agent/QN and SDK deployments before clients can rely on them. This SDK follow-up does not change the normal `7cc3904a` dependency pin or claim whole ENT-3487 completion. ## Validation The tested private source is `b19c8adbdc936c5976def6c17be47f6d5e3faf3e`, based on product commit `c9bac25ecb8b73b1bd0256bbea65c2621bcf6a94`. The final product docs commit changes generated TypeDoc only. - Rust: 2 selected tests passed, 0 failed, exit 0. The same two Rust blobs are unchanged from their tested `788ef85b` source through `c9bac25e`. - Python: the PyO3 extension built successfully, and the selected native PyO3 SDK test against a mock HTTP REST transport passed 1/0, exit 0. The test requests pinned version 42. - Node: the addon and TypeScript builds passed, Biome passed, and the selected Jest transport test passed 1/0 with 57 filtered tests. Addon SHA-256: `c888e260b61d41e79689ed2f20dd0dc98586a2377ce34f21610b06111734d426`. - Python extension SHA-256: `36c961d8a0cbd2e102a7765f2e47efb4c5af6310baa6262c8e3120407463da2b`. - TypeDoc was generated from the native `native.d.ts` produced by that Node build. A second generation produced no remaining diff. The public diff contains only product, test, and generated API documentation changes. Native runner scripts and preserved compile-failure logs remain private validation evidence. Agent/QN production mapping, mixed-version rollout, and the remaining ENT-3487 server-side work are tracked separately. --- .../FunctionColumnAutoRefreshStatus.md | 5 +- .../FunctionColumnLastRefreshJob.md | 10 ++ .../src/js/interfaces/FunctionColumnStatus.md | 11 ++ docs/src/js/interfaces/JobFailureInfo.md | 10 ++ .../feature-engineering/refresh-column.mdx | 11 ++ nodejs/__test__/remote.test.ts | 49 ++++-- nodejs/lancedb/table.ts | 13 +- nodejs/src/job.rs | 22 ++- nodejs/src/table.rs | 25 ++- python/python/lancedb/_lancedb.pyi | 2 + python/python/tests/test_remote_db.py | 45 ++++-- python/src/job.rs | 22 ++- python/src/table.rs | 5 + rust/lancedb/src/error.rs | 26 +++- rust/lancedb/src/remote/table.rs | 147 +++++++++++++++++- .../src/table/function_column_status.rs | 46 +++++- 16 files changed, 394 insertions(+), 55 deletions(-) diff --git a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md index bc8f7daab..3a203026c 100644 --- a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md +++ b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md @@ -27,7 +27,9 @@ optional blockedReason: | "dependency_in_flight" | "table_capacity" | "cancelled" - | "preparation_backoff"; + | "preparation_backoff" + | "failure_threshold_reached" + | "binding_revision_missing"; ``` *** @@ -85,6 +87,7 @@ optional nextRunAtReason: string; ```ts state: | "running" + | "queued" | "disabled" | "ready" | "up_to_date" diff --git a/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md index 1d7d3b300..a7c1df2aa 100644 --- a/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md +++ b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md @@ -26,6 +26,16 @@ optional completedAtMillis: bigint; *** +### failure? + +```ts +optional failure: JobFailureInfo; +``` + +Structured failure details for a failed Job. + +*** + ### jobId ```ts diff --git a/docs/src/js/interfaces/FunctionColumnStatus.md b/docs/src/js/interfaces/FunctionColumnStatus.md index 755a8af81..0c299ee2b 100644 --- a/docs/src/js/interfaces/FunctionColumnStatus.md +++ b/docs/src/js/interfaces/FunctionColumnStatus.md @@ -58,6 +58,17 @@ function: FunctionColumnVersionStatus; *** +### lastFailureJob? + +```ts +optional lastFailureJob: FunctionColumnLastRefreshJob; +``` + +Newest failed refresh Job. This remains present when `lastRefreshJob` +is a later cancellation. + +*** + ### lastRefreshJob? ```ts diff --git a/docs/src/js/interfaces/JobFailureInfo.md b/docs/src/js/interfaces/JobFailureInfo.md index fe9ce04e3..cdea222c5 100644 --- a/docs/src/js/interfaces/JobFailureInfo.md +++ b/docs/src/js/interfaces/JobFailureInfo.md @@ -34,6 +34,16 @@ optional retryable: boolean; *** +### sqlJobId? + +```ts +optional sqlJobId: string; +``` + +Isolated SQL job that raised this failure, when supplied by the server. + +*** + ### traceback? ```ts diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index e1a9c43f3..ed4838497 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -197,6 +197,17 @@ println!("{}", final_status.failed); ``` +`auto_refresh.state` reports `queued` while the scheduler has accepted the +refresh but a worker has not started it; `running` means execution has started. +`last_refresh_job` describes the most recent attempt, including a cancellation +or a failure. If a later attempt was cancelled, `last_failure_job` retains the +most recent job that actually failed, so its nested `failure` continues to +explain the failed rows. + +These fields require a matching Agent, Query Node, and SDK deployment. An older +client cannot decode the `queued` state, and an older server can omit the new +optional failure fields. + The wait helpers do not submit or cancel a refresh. They retry only the typed finalization-pending response and propagate other errors. */} diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 6c160ed03..f87c70091 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -681,14 +681,33 @@ describe("remote connection", () => { "stale":2, "never_computed":0, "failed":0, + "last_refresh_job":{ + "job_id":"job-cancelled", + "state":"cancelled", + "automatic":true, + "completed_at_millis":1790000002000 + }, + "last_failure_job":{ + "job_id":"job-failed", + "state":"failed", + "automatic":true, + "completed_at_millis":1790000001000, + "failure":{ + "phase":"finalize", + "message":"worker timed out", + "traceback":"Traceback: timeout", + "retryable":true, + "sql_job_id":"sql-job-7" + } + }, "auto_refresh":{ "enabled":true, "interval_seconds":60, - "state":"blocked", - "failure_streak":3, - "effective_cooldown_millis":8000, - "blocked_reason":"preparation_backoff", - "next_run_at_millis":null + "active_job_id":"job-queued", + "state":"queued", + "failure_streak":1, + "next_run_at_millis":null, + "next_run_at_reason":"job_queued_not_started" } }]`, ); @@ -701,10 +720,22 @@ describe("remote connection", () => { await table.checkout(42); const status = await table.functionColumnStatus("embedding"); expect(status.tableVersion).toBe(42n); - expect(status.autoRefresh.state).toBe("blocked"); - expect(status.autoRefresh.failureStreak).toBe(3); - expect(status.autoRefresh.effectiveCooldownMillis).toBe(8000n); - expect(status.autoRefresh.blockedReason).toBe("preparation_backoff"); + expect(status.autoRefresh.state).toBe("queued"); + expect(status.autoRefresh.activeJobId).toBe("job-queued"); + expect(status.autoRefresh.failureStreak).toBe(1); + expect(status.autoRefresh.nextRunAtReason).toBe( + "job_queued_not_started", + ); + expect(status.lastRefreshJob?.state).toBe("cancelled"); + expect(status.lastRefreshJob?.failure).toBeUndefined(); + expect(status.lastFailureJob?.jobId).toBe("job-failed"); + expect(status.lastFailureJob?.failure).toEqual({ + phase: "finalize", + message: "worker timed out", + traceback: "Traceback: timeout", + retryable: true, + sqlJobId: "sql-job-7", + }); }, ); expect(queries).toEqual([{ column: "embedding", version: "42" }]); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 99eb0d1f9..703fc7926 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -35,6 +35,7 @@ import { FunctionErrorsOptions, IndexConfig, IndexStatistics, + JobFailureInfo, Branches as NativeBranches, OptimizeStats, RTEStats, @@ -274,6 +275,8 @@ export interface FunctionColumnLastRefreshJob { state: string; automatic?: boolean; completedAtMillis?: bigint; + /** Structured failure details for a failed Job. */ + failure?: JobFailureInfo; } /** Automatic-refresh projection for a Function output. */ @@ -284,6 +287,7 @@ export interface FunctionColumnAutoRefreshStatus { state: | "disabled" | "running" + | "queued" | "ready" | "up_to_date" | "waiting_interval" @@ -298,7 +302,9 @@ export interface FunctionColumnAutoRefreshStatus { | "dependency_in_flight" | "table_capacity" | "cancelled" - | "preparation_backoff"; + | "preparation_backoff" + | "failure_threshold_reached" + | "binding_revision_missing"; nextRunAtMillis: bigint | null; nextRunAtReason?: string; } @@ -315,6 +321,11 @@ export interface FunctionColumnStatus { neverComputed: bigint; failed: bigint; lastRefreshJob?: FunctionColumnLastRefreshJob; + /** + * Newest failed refresh Job. This remains present when `lastRefreshJob` + * is a later cancellation. + */ + lastFailureJob?: FunctionColumnLastRefreshJob; autoRefresh: FunctionColumnAutoRefreshStatus; } diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 485035d33..09b245f97 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -138,12 +138,7 @@ impl Job { /// Why the job failed, when it failed and the server reports a reason. #[napi(getter)] pub fn failure(&self) -> Option { - self.inner.failure().map(|failure| JobFailureInfo { - phase: failure.phase, - message: failure.message, - traceback: failure.traceback, - retryable: failure.retryable, - }) + self.inner.failure().map(Into::into) } /// This job's recorded lifecycle events, as an Arrow IPC stream buffer. @@ -216,10 +211,25 @@ impl From for JobInfo { /// The server's account of why a job failed. #[napi(object)] +#[derive(Clone, Debug)] pub struct JobFailureInfo { pub phase: Option, pub message: Option, /// User-code traceback, possibly truncated by the server. pub traceback: Option, pub retryable: Option, + /// Isolated SQL job that raised this failure, when supplied by the server. + pub sql_job_id: Option, +} + +impl From for JobFailureInfo { + fn from(failure: lancedb::error::JobFailure) -> Self { + Self { + phase: failure.phase, + message: failure.message, + traceback: failure.traceback, + retryable: failure.retryable, + sql_job_id: failure.sql_job_id, + } + } } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index f6d3e538e..62fe811ad 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -20,6 +20,7 @@ use napi_derive::napi; use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable}; use crate::error::NapiErrorExt; use crate::index::Index; +use crate::job::JobFailureInfo; use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; use crate::util::schema_to_buffer; @@ -1868,6 +1869,19 @@ pub struct FunctionColumnLastRefreshJob { pub state: String, pub automatic: Option, pub completed_at_millis: Option, + pub failure: Option, +} + +impl From for FunctionColumnLastRefreshJob { + fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self { + Self { + job_id: job.job_id, + state: job.state, + automatic: job.automatic, + completed_at_millis: job.completed_at_millis.map(BigInt::from), + failure: job.failure.map(Into::into), + } + } } /// Automatic-refresh projection for a Function output. @@ -1899,6 +1913,7 @@ pub struct FunctionColumnStatus { pub never_computed: BigInt, pub failed: BigInt, pub last_refresh_job: Option, + pub last_failure_job: Option, pub auto_refresh: FunctionColumnAutoRefreshStatus, } @@ -1921,14 +1936,8 @@ impl From for FunctionColumnStatus { stale: BigInt::from(status.stale), never_computed: BigInt::from(status.never_computed), failed: BigInt::from(status.failed), - last_refresh_job: status - .last_refresh_job - .map(|job| FunctionColumnLastRefreshJob { - job_id: job.job_id, - state: job.state, - automatic: job.automatic, - completed_at_millis: job.completed_at_millis.map(BigInt::from), - }), + last_refresh_job: status.last_refresh_job.map(Into::into), + last_failure_job: status.last_failure_job.map(Into::into), auto_refresh: FunctionColumnAutoRefreshStatus { enabled: status.auto_refresh.enabled, interval_seconds: status.auto_refresh.interval_seconds.map(BigInt::from), diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 07306c1d9..4c5f5758a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1108,6 +1108,7 @@ class FunctionColumnLastRefreshJob: state: str automatic: Optional[bool] completed_at_millis: Optional[int] + failure: Optional[JobFailureInfo] class FunctionColumnAutoRefreshStatus: enabled: bool @@ -1131,6 +1132,7 @@ class FunctionColumnStatus: never_computed: int failed: int last_refresh_job: Optional[FunctionColumnLastRefreshJob] + last_failure_job: Optional[FunctionColumnLastRefreshJob] auto_refresh: FunctionColumnAutoRefreshStatus class RefreshMaterializedViewResult: diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index fd933b43c..407596d26 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2306,15 +2306,33 @@ def test_remote_function_column_status_passes_pinned_version(): "stale": 2, "never_computed": 0, "failed": 0, + "last_refresh_job": { + "job_id": "job-cancelled", + "state": "cancelled", + "automatic": True, + "completed_at_millis": 1790000002000, + }, + "last_failure_job": { + "job_id": "job-failed", + "state": "failed", + "automatic": True, + "completed_at_millis": 1790000001000, + "failure": { + "phase": "finalize", + "message": "worker timed out", + "traceback": "Traceback: timeout", + "retryable": True, + "sql_job_id": "sql-job-7", + }, + }, "auto_refresh": { "enabled": True, "interval_seconds": 60, - "active_job_id": None, - "state": "blocked", - "failure_streak": 3, - "effective_cooldown_millis": 8000, - "blocked_reason": "preparation_backoff", + "active_job_id": "job-queued", + "state": "queued", + "failure_streak": 1, "next_run_at_millis": None, + "next_run_at_reason": "job_queued_not_started", }, } @@ -2350,10 +2368,19 @@ def test_remote_function_column_status_passes_pinned_version(): 0, 0, ) - assert result.auto_refresh.state == "blocked" - assert result.auto_refresh.failure_streak == 3 - assert result.auto_refresh.effective_cooldown_millis == 8000 - assert result.auto_refresh.blocked_reason == "preparation_backoff" + assert result.auto_refresh.state == "queued" + assert result.auto_refresh.active_job_id == "job-queued" + assert result.auto_refresh.failure_streak == 1 + assert result.auto_refresh.next_run_at_reason == "job_queued_not_started" + assert result.last_refresh_job.state == "cancelled" + assert result.last_refresh_job.failure is None + assert result.last_failure_job.job_id == "job-failed" + failure = result.last_failure_job.failure + assert failure.phase == "finalize" + assert failure.message == "worker timed out" + assert failure.traceback == "Traceback: timeout" + assert failure.retryable is True + assert failure.sql_job_id == "sql-job-7" def test_remote_wait_fresh_retries_only_typed_finalization_pending(): diff --git a/python/src/job.rs b/python/src/job.rs index 79a9cd524..f1fd85844 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -228,7 +228,7 @@ impl From for JobInfo { /// The server's account of why a job failed. #[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)] -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct JobFailureInfo { phase: Option, message: Option, @@ -238,6 +238,18 @@ pub struct JobFailureInfo { sql_job_id: Option, } +impl From for JobFailureInfo { + fn from(failure: lancedb::error::JobFailure) -> Self { + Self { + phase: failure.phase, + message: failure.message, + traceback: failure.traceback, + retryable: failure.retryable, + sql_job_id: failure.sql_job_id, + } + } +} + #[pymethods] impl JobFailureInfo { fn __repr__(&self) -> String { @@ -341,13 +353,7 @@ impl From for JobDescription { .filter(|result| !result.is_null()) .map(|result| result.to_string()), _progress_json: Some(progress_json), - failure: description.failure.map(|failure| JobFailureInfo { - phase: failure.phase, - message: failure.message, - traceback: failure.traceback, - retryable: failure.retryable, - sql_job_id: failure.sql_job_id, - }), + failure: description.failure.map(Into::into), } } } diff --git a/python/src/table.rs b/python/src/table.rs index cf627961c..c4211e44d 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -15,6 +15,7 @@ use crate::{ error::PythonErrorExt, expr::PyExpr, index::{CodeAnalyzerOptions, IndexConfig, extract_index_params}, + job::JobFailureInfo, query::{Query, TakeQuery}, table::scannable::PyScannable, }; @@ -925,6 +926,7 @@ pub struct FunctionColumnLastRefreshJob { pub state: String, pub automatic: Option, pub completed_at_millis: Option, + pub failure: Option, } impl From for FunctionColumnLastRefreshJob { @@ -934,6 +936,7 @@ impl From for FunctionColumnLastRe state: job.state, automatic: job.automatic, completed_at_millis: job.completed_at_millis, + failure: job.failure.map(Into::into), } } } @@ -985,6 +988,7 @@ pub struct FunctionColumnStatus { pub never_computed: u64, pub failed: u64, pub last_refresh_job: Option, + pub last_failure_job: Option, pub auto_refresh: FunctionColumnAutoRefreshStatus, } @@ -1017,6 +1021,7 @@ impl From for FunctionColumnStatus { never_computed: status.never_computed, failed: status.failed, last_refresh_job: status.last_refresh_job.map(Into::into), + last_failure_job: status.last_failure_job.map(Into::into), auto_refresh: status.auto_refresh.into(), } } diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 853ca831f..89ad7a229 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -253,24 +253,48 @@ impl snafu::AsErrorSource for InterruptionSource { /// A job run remotely carries whatever the server reported, which older servers /// do not report at all. Every field is absent rather than invented when the /// backend does not supply it. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] pub struct JobFailure { /// The stage the job was in, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub phase: Option, /// A human-readable reason, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, /// User-code traceback, possibly truncated by the server. + #[serde(default, skip_serializing_if = "Option::is_none")] pub traceback: Option, /// Whether a retry could clear the failure, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub retryable: Option, /// Isolated SQL job that raised this failure, when the server supplies /// one across the Flight SQL boundary. + #[serde(default, skip_serializing_if = "Option::is_none")] pub sql_job_id: Option, /// The underlying error from a job run in this process or a structured /// remote Flight SQL failure. + #[serde(skip)] pub source: Option>, } +impl PartialEq for JobFailure { + fn eq(&self, other: &Self) -> bool { + let source_matches = match (&self.source, &other.source) { + (None, None) => true, + (Some(left), Some(right)) => Arc::ptr_eq(left, right), + _ => false, + }; + self.phase == other.phase + && self.message == other.message + && self.traceback == other.traceback + && self.retryable == other.retryable + && self.sql_job_id == other.sql_job_id + && source_matches + } +} + +impl Eq for JobFailure {} + impl JobFailure { /// A failure whose only known detail is the error that caused it. pub(crate) fn from_source(source: Arc) -> Self { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 222ff527b..37890fd17 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11655,12 +11655,13 @@ mod tests { } #[tokio::test] - async fn test_function_column_status_decodes_blocked_scheduler_fields() { + async fn test_function_column_status_decodes_scheduler_lifecycle_and_failures() { let table = Table::new_with_handler("my_table", |_request| { http::Response::builder() .status(200) .body( - r#"[{ + r#"[ + { "column":"embedding", "binding_id":"fb_01", "function":{ @@ -11676,6 +11677,101 @@ mod tests { "stale":2, "never_computed":0, "failed":0, + "last_refresh_job":{ + "job_id":"job-cancelled", + "state":"cancelled", + "automatic":true, + "completed_at_millis":1790000002000 + }, + "last_failure_job":{ + "job_id":"job-failed", + "state":"failed", + "automatic":true, + "completed_at_millis":1790000001000, + "failure":{ + "phase":"finalize", + "message":"worker timed out", + "traceback":"Traceback: timeout", + "retryable":true, + "sql_job_id":"sql-job-7" + } + }, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "active_job_id":"job-queued", + "state":"queued", + "failure_streak":1, + "next_run_at_millis":null, + "next_run_at_reason":"job_queued_not_started" + } + }, + { + "column":"rerank", + "binding_id":"fb_02", + "function":{ + "name":"rerank", + "object_id":"rerank", + "location":"objects/rerank", + "version":"3", + "manifest_digest":"sha256:def" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":5, + "blocked_reason":"failure_threshold_reached", + "next_run_at_millis":null + } + }, + { + "column":"classify", + "binding_id":"fb_03", + "function":{ + "name":"classify", + "object_id":"classify", + "location":"objects/classify", + "version":"2", + "manifest_digest":"sha256:ghi" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":0, + "blocked_reason":"binding_revision_missing", + "next_run_at_millis":null + } + }, + { + "column":"summarize", + "binding_id":"fb_04", + "function":{ + "name":"summarize", + "object_id":"summarize", + "location":"objects/summarize", + "version":"4", + "manifest_digest":"sha256:jkl" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, "auto_refresh":{ "enabled":true, "interval_seconds":60, @@ -11690,15 +11786,52 @@ mod tests { .unwrap() }); - let status = table.function_column_status("embedding").await.unwrap(); + let statuses = table.function_column_statuses(None).await.unwrap(); + assert_eq!(statuses.len(), 4); + let status = &statuses[0]; assert_eq!( status.auto_refresh.state, - crate::table::FunctionColumnAutoRefreshState::Blocked + crate::table::FunctionColumnAutoRefreshState::Queued ); - assert_eq!(status.auto_refresh.failure_streak, 3); - assert_eq!(status.auto_refresh.effective_cooldown_millis, Some(8000)); assert_eq!( - status.auto_refresh.blocked_reason, + status.auto_refresh.active_job_id.as_deref(), + Some("job-queued") + ); + assert_eq!( + status.auto_refresh.next_run_at_reason.as_deref(), + Some("job_queued_not_started") + ); + assert_eq!( + status + .last_refresh_job + .as_ref() + .map(|job| job.state.as_str()), + Some("cancelled") + ); + let failure_job = status.last_failure_job.as_ref().unwrap(); + assert_eq!(failure_job.job_id, "job-failed"); + let failure = failure_job.failure.as_ref().unwrap(); + assert_eq!(failure.phase.as_deref(), Some("finalize")); + assert_eq!(failure.message.as_deref(), Some("worker timed out")); + assert_eq!(failure.retryable, Some(true)); + assert_eq!(failure.sql_job_id.as_deref(), Some("sql-job-7")); + + assert_eq!(statuses[1].auto_refresh.failure_streak, 5); + assert_eq!( + statuses[1].auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::FailureThresholdReached) + ); + assert_eq!( + statuses[2].auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::BindingRevisionMissing) + ); + assert_eq!(statuses[3].auto_refresh.failure_streak, 3); + assert_eq!( + statuses[3].auto_refresh.effective_cooldown_millis, + Some(8000) + ); + assert_eq!( + statuses[3].auto_refresh.blocked_reason, Some(crate::table::FunctionColumnAutoRefreshBlockedReason::PreparationBackoff) ); } diff --git a/rust/lancedb/src/table/function_column_status.rs b/rust/lancedb/src/table/function_column_status.rs index 729ea33ba..15703f4e9 100644 --- a/rust/lancedb/src/table/function_column_status.rs +++ b/rust/lancedb/src/table/function_column_status.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; +use crate::error::JobFailure; use crate::function::FunctionVersionRef; use crate::{Error, Result}; @@ -23,6 +24,9 @@ pub struct FunctionColumnLastRefreshJob { pub automatic: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub completed_at_millis: Option, + /// Why this Job failed, when the server retained a structured failure. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure: Option, } /// Automatic-refresh scheduling state that the server can prove. @@ -31,6 +35,7 @@ pub struct FunctionColumnLastRefreshJob { pub enum FunctionColumnAutoRefreshState { Disabled, Running, + Queued, UpToDate, Ready, WaitingInterval, @@ -44,6 +49,7 @@ impl FunctionColumnAutoRefreshState { match self { Self::Disabled => "disabled", Self::Running => "running", + Self::Queued => "queued", Self::UpToDate => "up_to_date", Self::Ready => "ready", Self::WaitingInterval => "waiting_interval", @@ -64,6 +70,8 @@ pub enum FunctionColumnAutoRefreshBlockedReason { TableCapacity, Cancelled, PreparationBackoff, + FailureThresholdReached, + BindingRevisionMissing, } impl FunctionColumnAutoRefreshBlockedReason { @@ -75,6 +83,8 @@ impl FunctionColumnAutoRefreshBlockedReason { Self::TableCapacity => "table_capacity", Self::Cancelled => "cancelled", Self::PreparationBackoff => "preparation_backoff", + Self::FailureThresholdReached => "failure_threshold_reached", + Self::BindingRevisionMissing => "binding_revision_missing", } } } @@ -113,6 +123,10 @@ pub struct FunctionColumnStatus { pub failed: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub last_refresh_job: Option, + /// Newest failed refresh Job. Unlike `last_refresh_job`, this remains + /// visible when the latest attempt was cancelled. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_failure_job: Option, pub auto_refresh: FunctionColumnAutoRefreshStatus, } @@ -216,6 +230,7 @@ mod tests { never_computed: 1, failed: 1, last_refresh_job: None, + last_failure_job: None, auto_refresh: FunctionColumnAutoRefreshStatus { enabled: true, interval_seconds: Some(60), @@ -253,6 +268,7 @@ mod tests { state: "finished".to_string(), automatic: Some(true), completed_at_millis: Some(1_790_000_000_000), + failure: None, }); let encoded = serde_json::to_value(value).unwrap(); assert_eq!(encoded["last_refresh_job"]["job_id"], "job-7"); @@ -264,11 +280,31 @@ mod tests { } #[test] - fn up_to_date_wire_is_stable() { - assert_eq!( - serde_json::to_string(&FunctionColumnAutoRefreshState::UpToDate).unwrap(), - "\"up_to_date\"" - ); + fn scheduler_wire_names_are_stable() { + for (state, expected) in [ + (FunctionColumnAutoRefreshState::Queued, "queued"), + (FunctionColumnAutoRefreshState::UpToDate, "up_to_date"), + ] { + assert_eq!( + serde_json::to_string(&state).unwrap(), + format!("\"{expected}\"") + ); + } + for (reason, expected) in [ + ( + FunctionColumnAutoRefreshBlockedReason::FailureThresholdReached, + "failure_threshold_reached", + ), + ( + FunctionColumnAutoRefreshBlockedReason::BindingRevisionMissing, + "binding_revision_missing", + ), + ] { + assert_eq!( + serde_json::to_string(&reason).unwrap(), + format!("\"{expected}\"") + ); + } } #[test] From c1fee360457c65e784fe0c7055f91e171a7b7da5 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Wed, 11 Nov 2026 23:26:52 +0800 Subject: [PATCH 03/75] chore(deps): upgrade Lance to v15.0.0-beta.17 (#4943) Update the Rust workspace, Java dependency, and Python test dependency to [Lance v15.0.0-beta.17](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.17). This includes the FRI cache and vector-index changes required by current Sophon and retains the RaBitQ prewarm fixes. Lockfiles use the published source and test wheels without unrelated registry version bumps. The dependency dry run also exposed CI resource limits. Use the existing larger x64 runner for GNU Node and compatibility-wheel builds; allow 60 minutes for Mac Python tests, 120 minutes for the compatibility wheel, and 150 minutes for the Mac release wheel. Disable the CLI toolchain action's automatic target cache so only the subsequent downloads-only cache runs. Release optimization, the compatibility wheel's manylinux container and x86-64-v2 baseline, and test coverage stay unchanged. Validation: - Three native SDK regressions pass: refined RQ queries after deferred compaction, deferred index remapping, and ANN approximation planning. - Pinned Rust 1.97.0: `cargo clippy --quiet --locked --features remote --tests --examples -- -D warnings` passes. - Locked offline Rust metadata, Python lock validation, Ruff lint/format, and diff checks pass. The Python lock contains six published beta.17 wheels. - Repository YAML, whitespace and typo checks pass for the workflow changes. Product-source checks are reused for the subsequent CI-only commits. - At head `07033dc6`, all 65 applicable pre-review CI checks pass, including the compatibility wheel, Mac CLI, GNU Node, Mac Python tests, release wheels, and Java checks. Six checks are skipped by tag/main-only conditions or draft-only app behavior; the automated review and security checks run after the Ready transition. The upstream Java publisher succeeded and its beta.17 Maven artifact is available. Six upstream Python wheel builds/uploads succeeded; its Windows ARM job was cancelled. These checks do not establish Sophon performance or aggregate-memory acceptance. --- .github/workflows/cli.yml | 2 + .github/workflows/npm-publish.yml | 3 +- .github/workflows/pypi-publish.yml | 10 +-- .github/workflows/python.yml | 3 +- Cargo.lock | 97 +++++++++++++++--------------- Cargo.toml | 30 ++++----- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 15 ++--- 9 files changed, 86 insertions(+), 78 deletions(-) diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml index 8d8763e1d..e96d5b095 100644 --- a/.github/workflows/cli.yml +++ b/.github/workflows/cli.yml @@ -23,6 +23,8 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1 with: components: clippy + # Use only the downloads-only cache configured below. + cache: false - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: # Restoring compiled targets can exhaust the hosted runner disk. diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index a8dd3993e..1b7d3dcbc 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -66,7 +66,8 @@ jobs: choco install --no-progress protoc rustup target add aarch64-pc-windows-msvc - target: x86_64-unknown-linux-gnu - host: ubuntu-latest + # Fat LTO reached 15.1 GiB before rustc was killed on the 15 GiB runner. + host: ubuntu-2404-8x-x64 features: fp16kernels # https://github.com/napi-rs/napi-rs/blob/main/debian.Dockerfile docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 5aea2ca30..8730e220d 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -36,8 +36,8 @@ concurrency: jobs: linux: name: Python ${{ matrix.config.package_name }} ${{ matrix.config.platform }} manylinux${{ matrix.config.manylinux }} - # The ARM64 release build can exceed an hour with fat LTO on a cold runner. - timeout-minutes: ${{ matrix.config.platform == 'aarch64' && 120 || 60 }} + # ARM64 and compatibility release builds can exceed an hour with cold fat LTO. + timeout-minutes: ${{ (matrix.config.platform == 'aarch64' || matrix.config.package_name == 'lancedb-compat') && 120 || 60 }} strategy: matrix: config: @@ -64,7 +64,8 @@ jobs: - platform: x86_64 manylinux: "2_28" extra_args: "" - runner: ubuntu-22.04 + # Keep fat LTO on the same larger runner as the standard x64 wheel. + runner: ubuntu-2404-8x-x64 package_name: "lancedb-compat" rustflags: "-Ctarget-cpu=x86-64-v2" runs-on: ${{ matrix.config.runner }} @@ -102,7 +103,8 @@ jobs: path: target/wheels/*.whl if-no-files-found: error mac: - timeout-minutes: 90 + # Cold fat LTO was still compiling when the 90-minute limit was reached. + timeout-minutes: 150 runs-on: ${{ matrix.config.runner }} strategy: matrix: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2080789d4..2fabb4a6a 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -179,7 +179,8 @@ jobs: strategy: matrix: features: ["default", "experimental-functions"] - timeout-minutes: 30 + # A cold native build plus experimental-functions tests can exceed 30 minutes. + timeout-minutes: 60 runs-on: macos-15 defaults: run: diff --git a/Cargo.lock b/Cargo.lock index 56642301c..3518272e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arc-swap", "arrow", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,7 +5342,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-buffer", @@ -5356,7 +5356,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-schema", @@ -5365,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrayref", "crunchy", @@ -5376,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-buffer", @@ -5415,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5447,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5473,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5491,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "proc-macro2", "quote", @@ -5501,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-arith", "arrow-array", @@ -5535,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,8 +5567,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-schema", @@ -5599,8 +5599,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arc-swap", "arrow", @@ -5667,12 +5667,13 @@ dependencies = [ "tokio", "tracing", "twox-hash", + "uuid", ] [[package]] name = "lance-index-core" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-schema", @@ -5695,8 +5696,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5741,8 +5742,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "byteorder", "ethnum", @@ -5759,8 +5760,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5775,8 +5776,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "async-trait", @@ -5790,8 +5791,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arc-swap", "arrow", @@ -5845,8 +5846,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-buffer", @@ -5860,8 +5861,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5902,8 +5903,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-schema", @@ -5916,8 +5917,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index e77e0ffd6..9fc33e6ab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 2f72f98a7..514be8540 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.16 + 15.0.0-beta.17 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 036acf075..5ba1d4bbf 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b16", + "pylance==15.0.0b17", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index a5ae1caf8..01693079f 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b16" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b17" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b16" +version = "15.0.0b17" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,11 +4312,12 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_uZ4Az/pylance-15.0.0b16-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c4ed0ab9213082d9d8cc93aa09351e84574c76ddefc422a2ad073115bd9a1b43" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1nenYa/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f28f7b757ade1e4b556e788bc77d4ffcc351a9c8c570b35f769c457e9cc13bf" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1cb3ns/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49f358f3ddf33d76567f56d0e4a66c218dc1a2d2f06d37d779e13c87b1c3d9a6" }, - { url = "https://pypi.fury.io/lance-format/-/ver_g7LAk/pylance-15.0.0b16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:288c1b41f5068990672c8c182b4b79d6389c1a907c59ef6047cbee494d1e34ec" }, - { url = "https://pypi.fury.io/lance-format/-/ver_12YRtQ/pylance-15.0.0b16-cp310-abi3-win_amd64.whl", hash = "sha256:fa69acdd0960280f6fe8a83ea992fc92e2ed5a0eeb5159b90493dfc76831f752" }, + { url = "https://pypi.fury.io/lance-format/-/ver_il4JF/pylance-15.0.0b17-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:ee3c3d2baf1f0d788d706638873317740178a81988b71ffda47a2e71d1e15ff3" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2hFd0a/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a5b576e35054d4866d823ebadc9d3c531165628feb29ca1528db15b9082675a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_29zVw5/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47c534032d2f251f396657e47efbc224ee2d1964495d7982a449e5e1cdcf3169" }, + { url = "https://pypi.fury.io/lance-format/-/ver_548nr/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:509db7d8be3eebb111b7d28aa486437424cb3663cfb7f502b71532fa37ba7155" }, + { url = "https://pypi.fury.io/lance-format/-/ver_gmpNu/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd2cc05c2d553d44c54570612e793136e3433fcba28e4d51a503cca8f45435ea" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Otspk/pylance-15.0.0b17-cp310-abi3-win_amd64.whl", hash = "sha256:510c419e21a4daa4c18db4cc5048bd7dfc706924b23e13136306935f2e3e0c25" }, ] [[package]] From e9774ed168d3e82a50ba8cee19f602ca2ac41cfa Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 07:34:54 -0800 Subject: [PATCH 04/75] feat(nodejs): expose Function refresh publication intervals (#4957) Expose `publicationIntervalRows` on TypeScript refresh options and forward it as `publication_interval_rows`. Accept positive safe integers and preserve whole-fragment publication when omitted. ```typescript const job = await table.refreshColumnAsync("embedding", { publicationIntervalRows: 10000, }); await job.wait(); ``` Document the threshold semantics and add coverage for serialization, omission, invalid values, safe-integer boundaries, and Embedded rejection. Closes ENT-3755. --- docs/src/js/classes/Table.md | 6 +++ .../src/js/interfaces/RefreshColumnOptions.md | 13 ++++++ .../feature-engineering/refresh-column.mdx | 15 ++++-- nodejs/__test__/remote.test.ts | 46 +++++++++++++++++++ nodejs/__test__/table.test.ts | 8 ++++ nodejs/lancedb/table.ts | 6 +++ nodejs/src/table.rs | 15 ++++-- 7 files changed, 103 insertions(+), 6 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index aba747a7c..431796843 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1197,6 +1197,11 @@ LanceDB Enterprise it is the server's backfill job. `resourceBudget` for registered Functions. All are LanceDB Enterprise only; a LanceDB Embedded refresh rejects every option other than `batchSize`, `gpuClass` and `gpuCount`. + `publicationIntervalRows` opts into publishing completed Function split + ranges once their accumulated unpublished rows reach the threshold. + It must be a positive safe integer and requires non-Blob Function outputs. + Omit it for whole-fragment publication. Publications can exceed the + threshold, and remaining rows publish at completion. #### Returns @@ -1212,6 +1217,7 @@ const job = await table.refreshColumnAsync("embedding", { memoryBytes: 16 * 1024 ** 3, }, maxConcurrency: 4, + publicationIntervalRows: 10000, errorPolicy: "skip", maxFailedFraction: 0.01, rowTimeoutSeconds: 30, diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 6cc8f7f8f..c534e0fac 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -117,6 +117,19 @@ Worker count for an expression column; Function columns reject it. *** +### publicationIntervalRows? + +```ts +optional publicationIntervalRows: number; +``` + +Row-count threshold for publishing completed Function split ranges. +Must be a positive safe integer. Omit for whole-fragment publication. +Actual publications can be larger; remaining rows publish at completion. +Requires LanceDB Enterprise with non-Blob Function outputs. + +*** + ### resourceBudget? ```ts diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index ed4838497..1b809b91d 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -414,8 +414,8 @@ and `gpuCount` in the `refreshColumnAsync` options. Completed Function outputs publish with their fragment by default. To opt into -a row-count publication threshold, set `publication_interval_rows` in Python or -`publication_interval_rows()` in Rust: +a row-count publication threshold, set `publication_interval_rows` in Python, +`publicationIntervalRows` in TypeScript, or `publication_interval_rows()` in Rust: ```python Python icon="python" @@ -426,6 +426,13 @@ job = table.refresh_column_async( job.wait() ``` +```typescript TypeScript icon="square-js" +const job = await table.refreshColumnAsync("embedding", { + publicationIntervalRows: 60, +}); +await job.wait(); +``` + ```rust Rust icon="rust" use lancedb::table::RefreshColumnOptions; @@ -443,7 +450,9 @@ individual publication can differ from this value depending on completed work and Function batching; this is not an exact-N contract. Omit it to keep whole-fragment publication. -The TypeScript SDK does not expose the publication threshold option yet. +In TypeScript, the threshold must be a positive safe integer, at most +`Number.MAX_SAFE_INTEGER`. This option requires a supporting LanceDB Enterprise +server and Function outputs without Blob types; Blob inputs are allowed. The job APIs also take the row filter and failure handling of the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index f87c70091..4ac08b4c4 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -776,6 +776,7 @@ describe("remote connection", () => { const job = await table.refreshColumnAsync("embedding", { where: "id % 2 = 0", batchSize: 16, + publicationIntervalRows: 60, maxConcurrency: 3, gpuClass: "a10g", gpuCount: 2, @@ -788,6 +789,18 @@ describe("remote connection", () => { }); expect(job.id).toBe("j-9"); await table.refreshColumnAsync("embedding"); + await table.refreshColumnAsync("embedding", { + publicationIntervalRows: undefined, + }); + for (const publicationIntervalRows of [ + 1, + 2 ** 32 + 1, + Number.MAX_SAFE_INTEGER, + ]) { + await table.refreshColumnAsync("embedding", { + publicationIntervalRows, + }); + } await table.refreshColumnAsync("embedding", { resourceBudget: { cpuMillis: 8_000, @@ -799,6 +812,14 @@ describe("remote connection", () => { maxConcurrency: true as unknown as number, }), ).rejects.toThrow(); + for (const publicationIntervalRows of [true, "60", 60n]) { + await expect( + table.refreshColumnAsync("embedding", { + publicationIntervalRows: + publicationIntervalRows as unknown as number, + }), + ).rejects.toThrow(); + } // Invalid options reject before any request is sent. for (const [options, message] of [ [{ maxFailedRows: -1 }, "maxFailedRows"], @@ -806,6 +827,22 @@ describe("remote connection", () => { [{ where: " " }, "where"], [{ maxFailedFraction: 2 }, "max_failed_fraction"], [{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"], + [{ publicationIntervalRows: 0 }, "publicationIntervalRows"], + [{ publicationIntervalRows: -1 }, "publicationIntervalRows"], + [{ publicationIntervalRows: 1.5 }, "publicationIntervalRows"], + [{ publicationIntervalRows: Number.NaN }, "publicationIntervalRows"], + [ + { publicationIntervalRows: Number.POSITIVE_INFINITY }, + "publicationIntervalRows", + ], + [ + { publicationIntervalRows: Number.NEGATIVE_INFINITY }, + "publicationIntervalRows", + ], + [ + { publicationIntervalRows: Number.MAX_SAFE_INTEGER + 1 }, + "publicationIntervalRows", + ], [{ maxConcurrency: 1.5 }, "maxConcurrency"], [{ maxConcurrency: 0 }, "maxConcurrency"], [{ maxConcurrency: -1 }, "maxConcurrency"], @@ -893,6 +930,7 @@ describe("remote connection", () => { expect(bodies).toEqual([ JSON.parse( `{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16, + "publication_interval_rows": 60, "max_concurrency": 3, "gpu_class": "a10g", "gpu_count": 2, "error_policy": "skip", "max_failed_fraction": 0.01, "max_failed_rows": 50, @@ -900,6 +938,14 @@ describe("remote connection", () => { "max_executor_processes_per_worker": 2}`, ), { column: "embedding" }, + { column: "embedding" }, + JSON.parse('{"column": "embedding", "publication_interval_rows": 1}'), + JSON.parse( + '{"column": "embedding", "publication_interval_rows": 4294967297}', + ), + JSON.parse( + '{"column": "embedding", "publication_interval_rows": 9007199254740991}', + ), JSON.parse( `{"column": "embedding", "resource_budget": { diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 80d8296e2..b803e9043 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5686,6 +5686,14 @@ describe("computed columns", () => { await expect( table.refreshColumnAsync("x", { errorPolicy: "skip" }), ).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh"); + for (const refresh of [ + () => table.refreshColumn("x", { publicationIntervalRows: 60 }), + () => table.refreshColumnAsync("x", { publicationIntervalRows: 60 }), + ]) { + await expect(refresh()).rejects.toThrow( + "publication_interval_rows requires a LanceDB Enterprise refresh", + ); + } await expect( table.refreshColumnAsync("x", { maxConcurrency: 4 }), ).rejects.toThrow("max_concurrency requires a LanceDB Enterprise refresh"); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 703fc7926..b38c2381c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -808,6 +808,11 @@ export abstract class Table { * `resourceBudget` for registered Functions. All are LanceDB Enterprise * only; a LanceDB Embedded refresh rejects every option other than * `batchSize`, `gpuClass` and `gpuCount`. + * `publicationIntervalRows` opts into publishing completed Function split + * ranges once their accumulated unpublished rows reach the threshold. + * It must be a positive safe integer and requires non-Blob Function outputs. + * Omit it for whole-fragment publication. Publications can exceed the + * threshold, and remaining rows publish at completion. * @example * ```ts * const job = await table.refreshColumnAsync("embedding", { @@ -817,6 +822,7 @@ export abstract class Table { * memoryBytes: 16 * 1024 ** 3, * }, * maxConcurrency: 4, + * publicationIntervalRows: 10000, * errorPolicy: "skip", * maxFailedFraction: 0.01, * rowTimeoutSeconds: 30, diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 62fe811ad..e3bd22c0b 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1649,7 +1649,7 @@ pub struct FunctionWorkerResourceBudget { pub gpu_count: Option, } -fn resource_budget_integer(value: f64, name: &str) -> napi::Result { +fn positive_safe_integer(value: f64, name: &str) -> napi::Result { const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; if !value.is_finite() || value.fract() != 0.0 || !(1.0..=MAX_SAFE_INTEGER).contains(&value) { return Err(napi::Error::from_reason(format!( @@ -1699,6 +1699,11 @@ pub struct RefreshColumnOptions { pub where_clause: Option, /// Maximum rows per Function call; must be greater than zero. pub batch_size: Option, + /// Row-count threshold for publishing completed Function split ranges. + /// Must be a positive safe integer. Omit for whole-fragment publication. + /// Actual publications can be larger; remaining rows publish at completion. + /// Requires LanceDB Enterprise with non-Blob Function outputs. + pub publication_interval_rows: Option, /// Override the registered Function's maximum concurrent user-code calls /// for this logical execution. pub max_concurrency: Option, @@ -1735,6 +1740,10 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { let mut options = Self::default(); options.where_clause = value.where_clause; options.batch_size = value.batch_size.map(|size| size as usize); + options.publication_interval_rows = value + .publication_interval_rows + .map(|rows| positive_safe_integer(rows, "publicationIntervalRows")) + .transpose()?; options.max_concurrency = positive_u32(value.max_concurrency, "maxConcurrency")?; options.gpu_class = value.gpu_class; options.resource_budget = value @@ -1742,8 +1751,8 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { .map(|budget| { Ok::<_, napi::Error>( LanceFunctionWorkerResourceBudget::new( - resource_budget_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?, - resource_budget_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?, + positive_safe_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?, + positive_safe_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?, ) .with_gpu_count(resource_budget_gpu_count(budget.gpu_count)?), ) From ea1cf17f895a6b5046963c0b8a7524ace3d7bea9 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 07:35:43 -0800 Subject: [PATCH 05/75] feat(python): export recorded Function job timelines (#4946) Function jobs can now export their recorded execution timeline with `job.export_timeline(path)` or `await job.export_timeline(path)`. The SDK fetches a fresh Chrome Trace Event recording that opens in Perfetto, including worker split spans and timestamped job phases. Batch counts and latency statistics remain details rather than invented batch intervals. ```python job = db.open_job(job_id) job.export_timeline("refresh.trace.json") async_job = await async_db.open_job(job_id) await async_job.export_timeline("refresh.trace.json") ``` The export does not wait for completion or cancel the job. Running jobs return partial recordings. Local operations and SQL query handles remain unsupported, and servers must support the timeline endpoint. The destination is touched only after a successful fetch; network and filesystem errors propagate. Rust freshness wrappers forward the operation without changing the submitting table's read baseline. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/job.py | 43 ++++++++++++++++++++++++ python/python/tests/test_job.py | 52 ++++++++++++++++++++++++++++++ python/src/job.rs | 7 ++++ rust/lancedb/src/job.rs | 27 ++++++++++++++++ rust/lancedb/src/remote/db.rs | 43 ++++++++++++++++++++++++ rust/lancedb/src/remote/job.rs | 26 +++++++++++++++ rust/lancedb/src/remote/table.rs | 11 +++++++ 8 files changed, 210 insertions(+) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4c5f5758a..4029525e9 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -412,6 +412,7 @@ class Job: ) -> Optional[str]: ... async def cancel(self) -> None: ... async def refresh(self) -> None: ... + async def timeline(self) -> str: ... async def events( self, *, diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 86a1295cc..094a7b8d5 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -7,6 +7,8 @@ import asyncio import reprlib import time from datetime import timedelta +from os import PathLike +from pathlib import Path from typing import Any, Callable, Generic, Optional, TypeVar, cast import pyarrow as pa @@ -422,6 +424,31 @@ class AsyncJob(Generic[T]): description = self._inner._description if self._inner is not None else None return getattr(description, name) if description is not None else None + async def export_timeline(self, path: str | PathLike[str]) -> None: + """Write a fresh recorded Function job timeline as Chrome trace JSON. + + Open the file in Perfetto or Chrome tracing. The recording contains + retained split spans grouped by worker and timestamped job phases. + Batch counts and latency statistics are included as details; individual + batch timestamps are not recorded. Running jobs export a partial snapshot + without waiting or cancelling. Download again to include later work. + + Requires a server-side Function job and a server supporting timeline + export. Unsupported operations raise ``NotImplementedError`` or a server + error. The destination is overwritten only after the trace is fetched. + Filesystem errors propagate to the caller. + + Examples + -------- + >>> await job.export_timeline("refresh.trace.json") # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job timeline export requires a server-side Function job" + ) + trace = await self._inner.timeline() + await asyncio.to_thread(Path(path).write_text, trace, encoding="utf-8") + async def events( self, *, @@ -621,6 +648,22 @@ class Job(Generic[T]): def _field(self, name: str) -> Optional[Any]: return getattr(self._inner, name) if self._inner is not None else None + def export_timeline(self, path: str | PathLike[str]) -> None: + """Write Chrome trace JSON for this Function job. + + See :meth:`AsyncJob.export_timeline`. Open the file in Perfetto or + Chrome tracing. + + Examples + -------- + >>> job.export_timeline("refresh.trace.json") # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job timeline export requires a server-side Function job" + ) + return LOOP.run(self._inner.export_timeline(path)) + def events( self, *, diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 07b8a8c5e..690f6414b 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import asyncio +import json import time from datetime import timedelta from types import SimpleNamespace @@ -751,3 +752,54 @@ async def test_query_wait_timeout_requires_keeping_original_handle(): assert "continues on the server" in message assert "keep this handle to continue waiting" in message assert "db.open_job" not in message + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path): + trace = { + "traceEvents": [{"ph": "X", "ts": 0, "dur": 1000}], + "metadata": {"partial": True}, + } + inner = SimpleNamespace( + timeline=AsyncMock(return_value=json.dumps(trace)), + wait=AsyncMock(), + cancel=AsyncMock(), + ) + job = AsyncJob(inner) + path = tmp_path / "job.trace.json" + if sync: + await asyncio.to_thread(Job(job).export_timeline, str(path)) + else: + await job.export_timeline(path) + assert json.loads(path.read_text()) == trace + inner.timeline.assert_awaited_once_with() + inner.wait.assert_not_awaited() + inner.cancel.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_export_timeline_failure_preserves_existing_file(tmp_path): + path = tmp_path / "job.trace.json" + path.write_text("previous recording") + job = AsyncJob( + SimpleNamespace( + timeline=AsyncMock(side_effect=RuntimeError("unsupported server")) + ) + ) + with pytest.raises(RuntimeError, match="unsupported server"): + await job.export_timeline(path) + assert path.read_text() == "previous recording" + with pytest.raises(NotImplementedError, match="server-side Function job"): + await AsyncJob(None).export_timeline(path) + with pytest.raises(NotImplementedError, match="server-side Function job"): + Job(None).export_timeline(path) + + +@pytest.mark.asyncio +async def test_export_timeline_reports_filesystem_errors(tmp_path): + job = AsyncJob( + SimpleNamespace(timeline=AsyncMock(return_value='{"traceEvents":[]}')) + ) + with pytest.raises(FileNotFoundError): + await job.export_timeline(tmp_path / "missing" / "trace.json") diff --git a/python/src/job.rs b/python/src/job.rs index f1fd85844..0d411072f 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -152,6 +152,13 @@ impl Job { self.inner.description().map(JobDescription::from) } + pub fn timeline(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(inner.timeline().await.infer_error()?.to_string()) + }) + } + #[pyo3(signature = (*, limit=None, filter=None))] pub fn events( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 8644c6a48..d178542b7 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -85,6 +85,11 @@ pub(crate) trait JobHandle: Send + Sync { async fn describe(&self) -> Result { job_detail_not_supported("describing a job") } + /// Chrome Trace Event JSON for a server-side Function job. + async fn timeline(&self) -> Result { + job_detail_not_supported("job timeline export") + } + /// The job's recorded lifecycle events. async fn events(&self, _request: JobEventsRequest) -> Result> { job_detail_not_supported("job event history") @@ -468,6 +473,28 @@ where } } + /// Fetch a recorded Function job timeline as Chrome Trace Event JSON. + /// + /// The snapshot opens in Perfetto or Chrome tracing. It contains retained + /// split and positioned phase spans; batch statistics remain arguments, + /// because individual batch timestamps are not recorded. Running jobs return + /// a partial recording without waiting for completion. Requires server support; + /// in-process operations and SQL query handles do not support this operation. + /// + /// ```no_run + /// # async fn export(job: &lancedb::job::Job) -> Result<(), Box> { + /// let trace = job.timeline().await?; + /// std::fs::write("job.trace.json", trace.to_string())?; + /// # Ok(()) + /// # } + /// ``` + pub async fn timeline(&self) -> Result { + match &self.inner { + JobInner::Handle { handle, .. } => handle.timeline().await, + JobInner::Completed(_) => job_detail_not_supported("job timeline export"), + } + } + /// Waits until the operation reaches a terminal state. /// /// Returns the endpoint's typed result. Unit-result jobs return `()`. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a4952593b..a9d55b511 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -4261,6 +4261,49 @@ mod tests { ); } + #[tokio::test] + async fn test_job_timeline_fetches_recorded_trace_without_waiting() { + let conn = Connection::new_with_handler(|request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "job-1"); + let body = match request.url().path() { + "/v1/jobs/describe" => { + r#"{"job_id":"job-1","job_type":"function_refresh","job_state":"IN_PROGRESS","creation_ms":1}"# + } + "/v1/jobs/timeline" => { + r#"{"traceEvents":[{"ph":"X","pid":1,"tid":1,"ts":0,"dur":1000,"name":"Split 1"}],"metadata":{"partial":true}}"# + } + path => panic!("Unexpected request: {path}"), + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + let trace = job.timeline().await.unwrap(); + assert_eq!(trace["traceEvents"][0]["dur"], 1000); + assert_eq!(trace["metadata"]["partial"], true); + } + + #[tokio::test] + async fn test_job_timeline_rejects_an_unrelated_json_response() { + let conn = Connection::new_with_handler(|request| { + let body = if request.url().path() == "/v1/jobs/describe" { + r#"{"job_id":"job-1","job_type":"function_refresh","job_state":"SUCCEEDED","creation_ms":1}"# + } else { + r#"{"message":"not a trace"}"# + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + assert!( + job.timeline() + .await + .unwrap_err() + .to_string() + .contains("not Chrome Trace Event JSON") + ); + } + #[tokio::test] async fn test_job_events_scope_to_that_job() { let schema = Arc::new(Schema::new(vec![Field::new( diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 0c652a3ae..d27c9c666 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -235,6 +235,32 @@ impl JobHandle for RemoteJob { Ok(self.fetch_description().await?.1.into_description()) } + async fn timeline(&self) -> Result { + let request = self + .client + .post("/v1/jobs/timeline") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let trace: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse job timeline: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if !trace + .get("traceEvents") + .is_some_and(serde_json::Value::is_array) + { + return Err(Error::Http { + source: "server response is not Chrome Trace Event JSON; job timeline export requires server support".into(), + request_id, status_code: None, + }); + } + Ok(trace) + } + async fn events(&self, request: JobEventsRequest) -> Result> { let mut body = serde_json::json!({ "job_id": self.job_id }); if let Some(limit) = request.limit { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 37890fd17..3859cb830 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -289,6 +289,10 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::describe(&self.inner).await } + async fn timeline(&self) -> Result { + crate::job::JobHandle::timeline(&self.inner).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -370,6 +374,10 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::describe(&self.inner).await } + async fn timeline(&self) -> Result { + crate::job::JobHandle::timeline(&self.inner).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -12133,6 +12141,8 @@ mod tests { .body(events.clone()) .unwrap() } + "/v1/jobs/timeline" => http::Response::builder().status(200) + .body(br#"{"traceEvents":[],"metadata":{"partial":true}}"#.to_vec()).unwrap(), other => panic!("unexpected path {other}"), } }); @@ -12149,6 +12159,7 @@ mod tests { .await .unwrap(); assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(job.timeline().await.unwrap()["metadata"]["partial"], true); } /// A newly submitted refresh returns a freshness-wrapped handle. Waiting From 08d3f448af3548e66f1d17d09e1b95f19e80798e Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 11 Nov 2026 15:38:06 +0000 Subject: [PATCH 06/75] =?UTF-8?q?Bump=20version:=200.42.0-beta.10=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.11?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 992d126d0..076443831 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.10" +current_version = "0.42.0-beta.11" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 3518272e0..ee2a3d919 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5931,7 +5931,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" dependencies = [ "ahash", "anyhow", @@ -6042,7 +6042,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" dependencies = [ "anyhow", "arrow-array", @@ -6085,7 +6085,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" dependencies = [ "arrow-array", "arrow-buffer", @@ -6110,7 +6110,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 3d3a3f8e1..c06b4f230 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.10 + 0.42.0-beta.11 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 758e41acd..903be2b77 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.10 + 0.42.0-beta.11 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 514be8540..610c095b9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.10 + 0.42.0-beta.11 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 47fc92237..91d808647 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 3761d6f4f..1a9011b34 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 5b7a167d0..00b2918d6 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index e902929bf..f94f27216 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index a54f47de3..e0eefa2e9 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index cc1894e70..f0891fbed 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index d5e0309d0..04b65ba86 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 5e9698e7f..e5e0effab 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 5579e1c55..a03e1a794 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 102b0f67b..07ca7de02 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 783216243..cbb0142e1 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 051db741a..cde8b295a 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" edition = "2021" license.workspace = true repository.workspace = true From 9a9b681aaf26dcb32af45fc77d79cdbd49f46c6a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 12 Nov 2026 00:49:00 +0800 Subject: [PATCH 07/75] docs(python): clarify refresh result row counts (#4963) ## Summary `RefreshColumnResult` exposed the canonical refresh counters without documenting their unit. This change describes them as logical rows planned for one refresh: `rows_assigned` counts successful rows written, `rows_failed` counts rows whose computation failed, and `rows_remaining` counts planned rows neither assigned nor terminally skipped. Rows already covered by `rows_failed` are not counted again as remaining. Retry attempts and user-code calls do not change that logical-row scope. The change also documents the source and published versions and the deprecated `rows_filled` alias. The existing skip-policy example is now explicit: a refresh over 2,001 logical rows with 1,891 assigned, 110 failed, and 0 remaining uses 2,001 as the failure-rate denominator. ## Behavior Documentation only. No field names, Python or native behavior, REST wire format, dependencies, or pins change. ## Validation - `git diff --check` - `uvx ruff format --check` - `uvx ruff check` - Imported this Python source with a compatible prebuilt ABI3 extension and asserted the public class and property documentation, the affected source version, and the native extension identity. --- python/python/lancedb/functions.py | 32 +++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 6d0c2ff52..737abc44e 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -873,17 +873,47 @@ class RefreshColumnResult(_RemoteValue): LanceDB Embedded jobs produce this value in process. LanceDB Enterprise decodes the same value from the durable server-job terminal payload. + + Row counters describe logical rows planned for this refresh, not user-code + calls or retry attempts. ``rows_assigned`` counts rows successfully written + with an output value, ``rows_failed`` counts rows whose computation failed, + and ``rows_remaining`` counts planned rows neither assigned nor terminally + skipped. Rows already counted in ``rows_failed`` are covered and are not + counted again in ``rows_remaining``. + + For example, a refresh over 2,001 logical rows that assigns 1,891 values and + fails 110 rows reports ``rows_assigned=1,891``, ``rows_failed=110``, and + ``rows_remaining=0``. Its failure-rate denominator is those 2,001 logical + rows, not the number of execution attempts. """ rows_assigned: _UInt64 + """Number of logical rows successfully assigned an output value by this + refresh. Each row counts once, regardless of retry attempts, and failed rows + are not included.""" + rows_failed: _UInt64 + """Number of logical rows whose computation failed. Rows deferred because + an input was not ready are not failures.""" + rows_remaining: _UInt64 + """Number of planned logical rows neither assigned nor terminally skipped. + Rows already counted in ``rows_failed`` are covered and are not counted + again.""" + source_version: _UInt64 + """Exact table version the refresh read.""" + published_version: Optional[_UInt64] = None + """Table version made visible by the refresh, when one was published.""" @property def rows_filled(self) -> int: - """Deprecated compatibility alias for :attr:`rows_assigned`.""" + """Deprecated compatibility alias for :attr:`rows_assigned`. + + The value is the same successful logical-row count; it does not count + execution attempts. + """ return self.rows_assigned @property From 28bbc81c3e0488c9eca9dab738f6db713f24d12c Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 11 Nov 2026 12:06:00 -0800 Subject: [PATCH 08/75] fix(remote): explain unsupported optimize syntax (#4944) This PR addresses [OSS-2913](https://linear.app/lancedb/issue/OSS-2913) ([#4845](https://github.com/lancedb/lancedb/issues/4845)) and [ENT-2909](https://linear.app/lancedb/issue/ENT-2909): `table.optimize()` on an Enterprise table exposes SQL parser errors when the deployment does not support its generated SQL. The SDK generates the statement itself, but previously propagated unsupported grammar as a generic SQL failure. Parser errors and unknown-option errors reported as `InvalidArgument` now become `NotSupported` (`NotImplementedError` in Python), retaining the original diagnostic and request ID. --- docs/web/maintenance/compaction.mdx | 4 +- rust/lancedb/src/remote/sql_test.rs | 123 ++++++++++++++++ rust/lancedb/src/remote/table.rs | 16 ++- rust/lancedb/src/remote/table/optimize.rs | 162 ++++++++++++++++++++++ 4 files changed, 296 insertions(+), 9 deletions(-) diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 9c8765293..e7b79f768 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -13,8 +13,8 @@ import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompac Every write commits a new table version, and versions accumulate: small files from frequent appends, superseded files from updates and deletes, and rows added since an index was built. In the embedded library, `optimize()` addresses all -three; a deployment handles them in the background and does not support -`optimize()`. +three. Enterprise handles maintenance in the background and also supports +on-demand compaction through `optimize()` on compatible servers. Run optimization as regular table maintenance, particularly after many small writes or a large ingest. diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index efc2ba6a4..cfaf2a625 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -95,6 +95,7 @@ struct TestSqlService { exchanges: ReceivedExchanges, result_overrides: Arc>>, materialized_view_job_handle_supported: bool, + optimize_error: Option, /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, @@ -269,6 +270,7 @@ impl Default for TestSqlService { exchanges: Arc::new(std::sync::Mutex::new(Vec::new())), result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())), materialized_view_job_handle_supported: false, + optimize_error: None, exchange_drops: Arc::new(AtomicUsize::new(0)), result, large_result, @@ -439,6 +441,11 @@ impl FlightService for TestSqlService { .and_then(|command| command.unpack::().ok().flatten()); if let Some(command) = &initial { self.statements.lock().unwrap().push(command.query.clone()); + if command.query.starts_with("OPTIMIZE ") + && let Some(error) = &self.optimize_error + { + return Err(error.clone()); + } if command.query == "SELECT rejected" { return Err(Status::invalid_argument("invalid statement")); } @@ -3932,3 +3939,119 @@ async fn remote_compact_preserves_omissions_and_explicit_default_values() { shutdown.send(()).unwrap(); } } + +#[tokio::test] +async fn remote_optimize_parser_errors_are_clear_without_resubmission() { + use crate::table::optimize::CompactionOverrides; + for (code, message, unsupported) in [ + ( + tonic::Code::InvalidArgument, + "ParserError(\"Expected: end of statement, found: REWRITE at Line: 1\")", + true, + ), + ( + tonic::Code::InvalidArgument, + "ParserError: Expected: TABLE, found: events", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown OPTIMIZE option 'io_buffer_size'", + true, + ), + ( + tonic::Code::InvalidArgument, + "ParserError: future grammar diagnostic", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown OPTIMIZE option 'future_option'", + true, + ), + ( + tonic::Code::PermissionDenied, + "ParserError: future grammar diagnostic", + false, + ), + (tonic::Code::PermissionDenied, "permission denied", false), + (tonic::Code::NotFound, "table not found", false), + (tonic::Code::Unavailable, "transport error", false), + ( + tonic::Code::InvalidArgument, + "invalid table configuration", + false, + ), + ] { + let status = Status::new(code, message); + let service = TestSqlService { + adaptive: true, + optimize_error: Some(status), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = + client_with_handler(|_| -> http::Response { panic!("no REST fallback") }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ); + let error = table + .compact(CompactionOverrides::default()) + .await + .unwrap_err(); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error:?}" + ); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("request_id")); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_optimize_branch_options_are_not_dropped() { + let service = TestSqlService { + adaptive: true, + optimize_error: Some(Status::invalid_argument( + "ParserError: Expected: ), found: , at Line: 1", + )), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|_| -> http::Response { panic!("no REST fallback") }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ) + .with_branch(Some("exp".into())); + let error = table + .compact(crate::table::optimize::CompactionOverrides { + io_buffer_size: Some(0), + ..Default::default() + }) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("compatible release")); + assert_eq!( + *statements.lock().unwrap(), + ["OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'exp', io_buffer_size = 0)"] + ); + shutdown.send(()).unwrap(); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3859cb830..48e5652ae 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3717,14 +3717,14 @@ impl BaseTable for RemoteTable { /// `OptimizeAction::All`, `::Prune`, and `::Index` remain unsupported /// remotely: there is no SQL statement yet for version pruning or index /// optimization. A branch-scoped table handle submits a - /// `WITH (branch = '')` clause; the statement does not itself - /// validate the branch exists, so a nonexistent branch surfaces as an - /// async job failure rather than an error from this call. Per-job + /// `WITH (branch = '')` clause; the server resolves and validates + /// the selected target. Per-job /// `target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and /// `batch_size` are forwarded in the SQL `WITH` clause. Other non-default /// options are rejected before submission. Servers must support these - /// SQL options; an older server's error is returned without retrying - /// with the settings removed. + /// SQL options. Parser errors and unknown optimize option errors become + /// `NotSupported` with the server diagnostic after one SQL submission. + /// No settings are removed and the operation is never resubmitted. async fn optimize(&self, action: OptimizeAction) -> Result { self.check_mutable().await?; let OptimizeAction::Compact { @@ -3782,9 +3782,11 @@ impl BaseTable for RemoteTable { // value is built afterward. sql_client .submit_as_job(statement, self.namespace.clone(), || async { Ok(()) }) - .await? + .await + .map_err(optimize::map_optimize_error)? .wait() - .await?; + .await + .map_err(optimize::map_optimize_error)?; Ok(OptimizeStats { compaction: Some(lance::dataset::optimize::CompactionMetrics::default()), prune: None, diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 2a42dd3ab..6f4b7f7e8 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -35,10 +35,172 @@ pub(super) fn compaction_sql_options( Ok(result) } +const UNSUPPORTED_OPTIMIZE: &str = "Compaction on an Enterprise table requires support for OPTIMIZE REWRITE DATA. Upgrade LanceDB Enterprise to a compatible release."; +const UNSUPPORTED_OPTIONS: &str = "The requested compaction options are not supported by this version of LanceDB Enterprise. Upgrade to a compatible release; requested options will not be removed or retried."; + +/// The client generates the whole statement, so parser errors indicate a +/// client/server syntax mismatch. Match option errors without enumerating names. +fn unsupported_optimize_message(message: &str) -> Option<&'static str> { + let message = message.to_ascii_lowercase(); + if message.contains("parsererror") { + Some(UNSUPPORTED_OPTIMIZE) + } else if message.contains("unknown optimize option") { + Some(UNSUPPORTED_OPTIONS) + } else { + None + } +} + +/// Apply compatibility handling only to this constructed operation. +/// Preserve every unrelated SQL/authentication/transport error unchanged. +pub(super) fn map_optimize_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<(&Error, &'static str)> { + match error { + Error::Sql { + message, grpc_code, .. + } if *grpc_code == tonic::Code::InvalidArgument as i32 => { + unsupported_optimize_message(message).map(|reason| (error, reason)) + } + Error::JobFailed { failure, .. } => failure + .source + .as_deref() + .and_then(|source| unsupported(source)), + _ => None, + } + } + if let Some((source, reason)) = unsupported(&error) { + let diagnostic = match &error { + Error::Sql { .. } => error.to_string(), + // JobFailure's Display omits its source, including the SQL request ID. + _ => format!("{error}; {source}"), + }; + Error::NotSupported { + message: format!("{reason} Server diagnostic: {diagnostic}"), + } + } else { + error + } +} + #[cfg(test)] mod tests { use super::*; + use crate::error::JobFailure; use crate::table::{CompactionOptions, CompactionOverrides}; + use std::sync::Arc; + + fn sql_error(code: tonic::Code, message: &str) -> Error { + Error::Sql { + message: message.into(), + request_id: "optimize-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + } + } + + #[test] + fn direct_optimize_error_prints_its_diagnostic_once() { + let diagnostic = "ParserError: Expected: end of statement, found: REWRITE"; + let Error::NotSupported { message } = + map_optimize_error(sql_error(tonic::Code::InvalidArgument, diagnostic)) + else { + panic!("known optimize syntax must be unsupported"); + }; + assert_eq!(message.matches(diagnostic).count(), 1); + assert_eq!(message.matches("request_id=optimize-request").count(), 1); + } + + #[test] + fn wrapped_optimize_error_keeps_job_context_and_sql_diagnostic() { + let diagnostic = "ParserError: Expected: end of statement, found: REWRITE"; + let error = Error::JobFailed { + job_id: Some("optimize-job".into()), + failure: Box::new(JobFailure { + phase: Some("planning".into()), + message: Some("SQL planning failed".into()), + source: Some(Arc::new(sql_error( + tonic::Code::InvalidArgument, + diagnostic, + ))), + ..Default::default() + }), + }; + let Error::NotSupported { message } = map_optimize_error(error) else { + panic!("wrapped unsupported optimize SQL must be translated"); + }; + assert!(message.contains(UNSUPPORTED_OPTIMIZE)); + assert!(message.contains("optimize-job")); + assert!(message.contains("SQL planning failed (in planning)")); + assert_eq!(message.matches(diagnostic).count(), 1); + assert_eq!(message.matches("request_id=optimize-request").count(), 1); + } + + #[test] + fn unrelated_wrapped_sql_errors_pass_through_unchanged() { + let unsupported = "ParserError: Expected: end of statement, found: REWRITE"; + for (code, diagnostic) in [ + (tonic::Code::PermissionDenied, unsupported), + (tonic::Code::Unavailable, unsupported), + (tonic::Code::InvalidArgument, "invalid table configuration"), + ] { + let source = Arc::new(sql_error(code, diagnostic)); + let error = Error::JobFailed { + job_id: Some("optimize-job".into()), + failure: Box::new(JobFailure { + phase: Some("planning".into()), + message: Some("SQL planning failed".into()), + sql_job_id: Some("sql-job".into()), + retryable: Some(false), + source: Some(source.clone()), + ..Default::default() + }), + }; + let Error::JobFailed { job_id, failure } = map_optimize_error(error) else { + panic!("{code:?}: unrelated SQL failure must keep its classification"); + }; + assert_eq!(job_id.as_deref(), Some("optimize-job")); + assert_eq!(failure.phase.as_deref(), Some("planning")); + assert_eq!(failure.message.as_deref(), Some("SQL planning failed")); + assert_eq!(failure.sql_job_id.as_deref(), Some("sql-job")); + assert_eq!(failure.retryable, Some(false)); + assert!(Arc::ptr_eq(failure.source.as_ref().unwrap(), &source)); + } + } + + #[test] + fn generated_optimize_syntax_errors_indicate_incompatible_servers() { + for diagnostic in [ + "ParserError: Expected: end of statement, found: REWRITE", + "ParserError: Expected: identifier", + "SQL error: ParserError: future grammar diagnostic", + "parsererror: lowercase diagnostic", + ] { + assert_eq!( + unsupported_optimize_message(diagnostic), + Some(UNSUPPORTED_OPTIMIZE) + ); + } + for diagnostic in [ + "Unknown OPTIMIZE option 'io_buffer_size'", + "Error during planning: Unknown OPTIMIZE option 'future_option'", + ] { + assert_eq!( + unsupported_optimize_message(diagnostic), + Some(UNSUPPORTED_OPTIONS) + ); + } + for diagnostic in [ + "permission denied", + "table not found", + "connection reset", + "invalid table configuration", + ] { + assert!( + unsupported_optimize_message(diagnostic).is_none(), + "{diagnostic}" + ); + } + } #[test] fn omissions_and_explicit_default_target_are_distinct() { From 42f11d13a2755e44b63876b5a5edd93901291150 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Wed, 11 Nov 2026 12:50:07 -0800 Subject: [PATCH 09/75] docs: clarify Python job states and waiting behavior (#4954) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We weren’t explicit about the job states returned by the Python SDK. This documents those values and clarifies the difference between checking the current status and waiting for completion. --- docs/web/basics/jobs.mdx | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 5336d1dfd..47285f5d0 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -42,9 +42,21 @@ print(job.status()) result. If it failed or was cancelled, inspect the failure details and any results it committed before stopping. -In Python, `job.status()` reports the current state and `job.wait()` waits for -completion, raising if the job fails or is cancelled. Both `Job.wait()` and -`AsyncJob.wait()` retry transient connection and read errors with capped +In Python, `job.status()` returns the current state: + +| State | Meaning | +| --- | --- | +| `running` | The operation is in progress. | +| `finished` | The operation completed successfully. | +| `failed` | The operation failed. | +| `cancelled` | The operation was cancelled. | + +`job.status()` checks the current state without waiting for completion. +It returns `failed` or `cancelled` for unsuccessful jobs. + +Use `job.wait()` to wait for completion and raise if the job fails or is +cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection +and read errors with capped exponential backoff within the caller's timeout. Without a timeout, retries continue indefinitely. From ee231aad066289febc88bc4088b9c6f93b1e4d49 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 22:56:36 -0800 Subject: [PATCH 10/75] fix(python): validate function package requirements before registration (#4971) Function dependency typos currently reach the environment build before failing. Validate pip requirements with `packaging.requirements.Requirement` and conda requirements with Rattler's MatchSpec parser when constructing a function definition, before source packaging or registration. Errors identify the original entry and its index. ```python @lancedb.function(pip=["numpy", "torch>=2.0,,<3"]) def score(value: float) -> float: return value # ValueError: invalid pip[1] requirement 'torch>=2.0,,<3': ... ``` Preserves pip extras, markers, named references, bare archive/git URLs, and conda channel/build specifications. The existing native extension exposes the conda parser, so no additional Python package is required. Adds regression coverage for invalid and supported forms, including the deprecated `udf` alias. --- Cargo.lock | 288 +++++++++++++++++- python/Cargo.toml | 1 + python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/functions.py | 33 +- .../tests/test_function_requirements.py | 125 ++++++++ python/src/lib.rs | 1 + python/src/util.rs | 8 + 7 files changed, 450 insertions(+), 7 deletions(-) create mode 100644 python/python/tests/test_function_requirements.py diff --git a/Cargo.lock b/Cargo.lock index ee2a3d919..f38252fc5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1422,6 +1422,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "blake3" version = "1.8.5" @@ -2734,7 +2743,7 @@ dependencies = [ "arrow", "arrow-buffer", "base64 0.23.1", - "blake2", + "blake2 0.10.6", "blake3", "chrono", "chrono-tz 0.10.4", @@ -3197,6 +3206,15 @@ dependencies = [ "dirs-sys 0.5.0", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys 0.5.0", +] + [[package]] name = "dirs-sys" version = "0.4.1" @@ -3442,6 +3460,17 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + [[package]] name = "errno" version = "0.3.14" @@ -3572,6 +3601,19 @@ dependencies = [ "subtle", ] +[[package]] +name = "file_url" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec49f140842acf886ff3e4fd47600ffdbb5f1b1ba70f6775880e688837a0b174" +dependencies = [ + "itertools 0.15.0", + "percent-encoding", + "thiserror 2.0.18", + "typed-path", + "url", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -3616,6 +3658,15 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + [[package]] name = "float8" version = "0.7.0" @@ -3747,6 +3798,15 @@ version = "1.20260804.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82eb03a32a1d50555353c85a7b9d3279a6f1e91af9890b789acdf544ed57c8d7" +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", +] + [[package]] name = "fs4" version = "0.13.1" @@ -4323,6 +4383,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "halfbrown" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09" +dependencies = [ + "hashbrown 0.16.1", + "serde", +] + [[package]] name = "hash32" version = "0.3.1" @@ -4428,7 +4498,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" dependencies = [ - "dirs", + "dirs 6.0.0", "futures", "http", "indicatif", @@ -5624,7 +5694,7 @@ dependencies = [ "datafusion-functions-nested", "datafusion-physical-expr", "datafusion-physical-plan", - "dirs", + "dirs 6.0.0", "fst", "futures", "half", @@ -6132,6 +6202,7 @@ dependencies = [ "pyo3", "pyo3-async-runtimes", "pyo3-build-config", + "rattler_conda_types", "reqwest 0.13.5", "serde", "serde_json", @@ -6140,6 +6211,29 @@ dependencies = [ "uuid", ] +[[package]] +name = "lazy-regex" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a2cce8a22920a29fdcc8c9170aa5d29edd9fbcf8bea856e24c2cb1c2419f67" +dependencies = [ + "lazy-regex-proc_macros", + "once_cell", + "regex", +] + +[[package]] +name = "lazy-regex-proc_macros" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f1e4b1f1d8c71edb4ff2b2150ec4606445fd2ddf67ddc097655daf59286baa6" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "syn 3.0.3", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -6903,6 +6997,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "nom-language" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29" +dependencies = [ + "nom 8.0.0", +] + [[package]] name = "now" version = "0.1.3" @@ -8587,6 +8690,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" +[[package]] +name = "purl" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60ebe4262ae91ddd28c8721111a0a6e9e58860e211fc92116c4bb85c98fd96ad" +dependencies = [ + "hex", + "percent-encoding", + "serde", + "thiserror 2.0.18", +] + [[package]] name = "pyo3" version = "0.29.3" @@ -8973,6 +9088,99 @@ dependencies = [ "rustversion", ] +[[package]] +name = "rattler_conda_types" +version = "0.58.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fda631350e17df9bc789082d6b6c0fbde38e65cba580593ee3317fb6730644f2" +dependencies = [ + "ahash", + "core-foundation 0.10.1", + "dirs 7.0.0", + "fancy-regex 0.19.2", + "file_url", + "fs-err", + "glob", + "hex", + "indexmap 2.14.0", + "itertools 0.15.0", + "jiff", + "lazy-regex", + "memmap2 0.9.10", + "nom 8.0.0", + "nom-language", + "purl", + "rattler_conda_version", + "rattler_digest", + "rattler_macros", + "rattler_redaction", + "regex", + "serde", + "serde-untagged", + "serde_json", + "serde_repr", + "serde_with", + "serde_yaml", + "simd-json", + "smallvec", + "strum", + "tempfile", + "thiserror 2.0.18", + "tracing", + "typed-path", + "url", +] + +[[package]] +name = "rattler_conda_version" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee922b54cd30c198e93c542096a0d671cefba1a97600768b2ec4af3c11c44f55" +dependencies = [ + "itertools 0.15.0", + "nom 8.0.0", + "serde", + "smallvec", + "thiserror 2.0.18", +] + +[[package]] +name = "rattler_digest" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bda554663860e074665f838a4d9a89fbf671f576eaf288d29525114b345adc9" +dependencies = [ + "blake2 0.11.0", + "digest 0.11.3", + "hex", + "md-5", + "serde", + "serde-untagged", + "serde_bytes", + "serde_with", + "sha2 0.11.0", + "url", +] + +[[package]] +name = "rattler_macros" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a42690ed14c8b9d610aafc0f2eb715b85c05f3d3a2a307896e4f8d820aaa284f" +dependencies = [ + "quote", + "syn 3.0.3", +] + +[[package]] +name = "rattler_redaction" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b5ee47d0375643b037205a4fe238b90c518ca3fc83c7c240d82c49ba87d61c" +dependencies = [ + "url", +] + [[package]] name = "raw-cpuid" version = "11.6.0" @@ -9926,6 +10134,28 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -10056,6 +10286,19 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.0", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serde_yaml_ng" version = "0.10.0" @@ -10170,7 +10413,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8" dependencies = [ "bstr", - "dirs", + "dirs 6.0.0", "os_str_bytes", ] @@ -10235,6 +10478,20 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd-json" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebe141eb4a23ecc4d5de93fa5b139ac65dc07c38037a2fe9a8fb7c9d36bd832" +dependencies = [ + "halfbrown", + "ref-cast", + "serde", + "serde_json", + "simdutf8", + "value-trait", +] + [[package]] name = "simd_cesu8" version = "1.1.1" @@ -10274,6 +10531,9 @@ name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] [[package]] name = "smartstring" @@ -11403,6 +11663,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.0" @@ -11583,6 +11849,18 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "value-trait" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b" +dependencies = [ + "float-cmp", + "halfbrown", + "itoa", + "ryu", +] + [[package]] name = "vcpkg" version = "0.2.15" @@ -12561,7 +12839,7 @@ dependencies = [ "colored", "const-str", "ctor", - "dirs", + "dirs 6.0.0", "futures", "git-version", "humantime", diff --git a/python/Cargo.toml b/python/Cargo.toml index 07ca7de02..7c11d5fdf 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -37,6 +37,7 @@ pyo3-async-runtimes = { version = "0.29", features = [ "tokio-runtime", ] } reqwest.workspace = true +rattler_conda_types = { version = "0.58.3", default-features = false } pin-project.workspace = true futures.workspace = true serde.workspace = true diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4029525e9..521cc46bb 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1310,3 +1310,4 @@ class AuthzObject: def __repr__(self) -> str: ... def validate_function_retry_policy(json: str) -> None: ... +def _validate_conda_requirement(requirement: str) -> None: ... diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 737abc44e..4bf028306 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -44,6 +44,7 @@ from typing import ( ) import pyarrow as pa +from packaging.requirements import Requirement from pydantic import ( AfterValidator, BaseModel, @@ -57,6 +58,7 @@ from pydantic import ( from .schema import blob as _blob_field from .schema import is_blob_v2_field as _is_blob_v2_field from ._blob_reader import BlobReader +from ._lancedb import _validate_conda_requirement from .secrets import EnvVarSecret _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) @@ -1701,6 +1703,29 @@ def _packaged_by_source(value: Any) -> bool: return True +def _validate_package_requirements(kind: str, packages: Sequence[str]) -> None: + for index, package in enumerate(packages): + field = f"{kind}[{index}]" + if not isinstance(package, str): + raise TypeError(f"{field} must be a string, got {package!r}") + if not package or package != package.strip(): + raise ValueError( + f"{field} requirement {package!r} must be non-empty and trimmed" + ) + try: + if kind == "conda": + _validate_conda_requirement(package) + else: + candidate = package + if re.match(r"^[A-Za-z][A-Za-z0-9+.-]*://", package): + candidate = f"dependency @ {package}" + Requirement(candidate) + except ValueError as error: + raise ValueError( + f"invalid {field} requirement {package!r}: {error}" + ) from error + + def _requirement_name(requirement: str) -> str: requirement = requirement.rpartition("::")[2] match = _REQUIREMENT_NAME.match(requirement.strip()) @@ -2242,6 +2267,7 @@ class FunctionDefinition: raise ValueError("a Function environment is pip or conda, not both") if conda_channels and not conda: raise ValueError("conda_channels requires conda packages") + _validate_package_requirements("conda" if conda else "pip", conda or pip) gpu_marker = _normalize_gpu_marker(gpu) if gpu_class is not None: _validate_gpu_class_name(gpu_class) @@ -2595,9 +2621,12 @@ def function( 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. + Pip requirements for the remote environment. Syntax is validated at + decoration time, including extras and environment markers. Named direct + references and bare package or git URLs are supported. conda : sequence of str, optional - Conda packages for the remote environment, instead of ``pip``. + Conda packages for the remote environment, instead of ``pip``. MatchSpec + syntax is validated at decoration time, including channels and builds. conda_channels : sequence of str, optional Conda channels in priority order; requires ``conda``. apt : sequence of str, optional diff --git a/python/python/tests/test_function_requirements.py b/python/python/tests/test_function_requirements.py new file mode 100644 index 000000000..6f94d1313 --- /dev/null +++ b/python/python/tests/test_function_requirements.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +from lancedb import function, udf +from lancedb.functions import FunctionDefinition + + +def identity(value: int) -> int: + return value + + +@pytest.mark.parametrize( + "package", + [ + "torch>=2.0,,<3", + "torch>=", + "torch=>2.0", + "torch[", + "torch; python_version >=", + "", + " torch", + "torch ", + ], +) +def test_invalid_pip_requirement_fails_before_packaging(package, monkeypatch): + def unexpected_packaging(*args, **kwargs): + pytest.fail("invalid requirements must fail before packaging the function") + + monkeypatch.setattr("lancedb.functions._infer_signature", unexpected_packaging) + with pytest.raises(ValueError) as error: + function(pip=["numpy", package])(identity) + assert "pip[1]" in str(error.value) + assert repr(package) in str(error.value) + + +@pytest.mark.parametrize( + "package", + [ + "numpy>=1,,<3", + "numpy>=", + "numpy[version=]", + "numpy[unknown_field=value]", + "", + " numpy", + "numpy ", + ], +) +def test_invalid_conda_requirement_names_entry(package): + with pytest.raises(ValueError) as error: + function(conda=["scipy", package])(identity) + assert "conda[1]" in str(error.value) + assert repr(package) in str(error.value) + + +@pytest.mark.parametrize("kind", ["pip", "conda"]) +@pytest.mark.parametrize("package", [None, 42, ["numpy"]]) +def test_requirement_must_be_a_string(kind, package): + with pytest.raises(TypeError, match=rf"{kind}\[1\] must be a string"): + function(**{kind: ["numpy", package]})(identity) + + +@pytest.mark.parametrize( + "package", + [ + "numpy", + "torch>=2.0,<3", + 'requests[security,socks]>=2; python_version >= "3.10"', + "numpy (>=1.26, <3)", + "six @ https://example.com/six-1.16.0.tar.gz", + "six @ git+https://github.com/benjaminp/six.git@main", + "https://example.com/six-1.16.0.tar.gz", + "git+https://github.com/benjaminp/six.git@main", + "git+ssh://git@github.com/benjaminp/six.git@main", + ], +) +def test_supported_pip_requirements_are_preserved(package): + definition = function(pip=[package])(identity) + assert definition.registration_request.runtime.environment.packages == (package,) + + +@pytest.mark.parametrize( + "package", + [ + "numpy", + "numpy=1.26", + "numpy>=1.26,<3", + "numpy=1.26=py310_0", + "numpy 1.26 py310_0", + "conda-forge::numpy>=1.26", + "conda-forge/linux-64::numpy>=1.26", + "numpy[version='>=1.26,<3',build='py310*']", + ], +) +def test_supported_conda_requirements_are_preserved(package): + definition = function(conda=[package])(identity) + assert definition.registration_request.runtime.environment.packages == (package,) + + +def test_requirements_still_sort_and_deduplicate(): + definition = function(pip=["torch>=2", "numpy", "torch>=2"])(identity) + assert definition.registration_request.runtime.environment.packages == ( + "numpy", + "torch>=2", + ) + + +def test_deprecated_udf_alias_validates_requirements(): + with pytest.warns(DeprecationWarning, match="use lancedb.function"): + with pytest.raises(ValueError, match=r"pip\[0\]"): + udf(pip=["torch>=2.0,,<3"])(identity) + + +def test_direct_function_definition_validates_requirements(): + with pytest.raises(ValueError, match=r"pip\[0\]"): + FunctionDefinition( + identity, + name=None, + input_schema=None, + output_schema=None, + pip=("torch>=2.0,,<3",), + env={}, + python_version=None, + ) diff --git a/python/src/lib.rs b/python/src/lib.rs index f78c4e7bb..b0698d5e0 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -150,6 +150,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(table::tokenize, m)?)?; m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?; m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?; + m.add_function(wrap_pyfunction!(util::validate_conda_requirement, m)?)?; m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?; m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?; m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?; diff --git a/python/src/util.rs b/python/src/util.rs index a956066f1..44efa165a 100644 --- a/python/src/util.rs +++ b/python/src/util.rs @@ -9,6 +9,7 @@ use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, pyfunction, }; +use rattler_conda_types::{MatchSpec, ParseStrictness}; /// A wrapper around a rust builder /// @@ -61,6 +62,13 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> { .map_err(|e| PyValueError::new_err(e.to_string())) } +#[pyfunction(name = "_validate_conda_requirement")] +pub fn validate_conda_requirement(requirement: &str) -> PyResult<()> { + MatchSpec::from_str(requirement, ParseStrictness::Lenient) + .map(|_| ()) + .map_err(|error| PyValueError::new_err(error.to_string())) +} + /// Parse field references with the same identifier syntax as Lance writes. #[pyfunction(name = "_parse_field_path")] pub fn parse_field_path(path: &str) -> PyResult> { From e622254108f15e159627d8a1d8e42e983e45cd81 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 23:32:19 -0800 Subject: [PATCH 11/75] fix(python): use direct lookups for table existence checks (#4974) Table existence checks should not depend on listing every table or searching only the first 100 names. Use a direct lookup for `name in db` and implement `table_exists(table_id)` on synchronous local connections, matching the remote and asynchronous APIs. Native namespace connections use their initialized Rust connection for existence checks; custom namespace clients retain their existing callback. Missing tables return `False`; other lookup errors propagate. ```python if "events" in db: db.drop_table("events") exists = db.table_exists(["analytics", "events"]) all_names = list(db.list_tables()) ``` Clarify that `.tables` contains one page and update deprecation guidance with safe replacements. Add regression coverage for lookups beyond the first page, nested namespaces, native and custom namespace clients, missing tables, permission errors, and lookups that do not list tables. Include an unpublished draft for the table-management guide until the new SDK support ships. --- docs/src/python/python.md | 17 +++++++ docs/web/management/table.mdx | 23 ++++++++- python/python/lancedb/db.py | 56 +++++++++++++++++---- python/python/lancedb/listing.py | 8 +++ python/python/lancedb/namespace.py | 30 ++++++++--- python/python/lancedb/remote/db.py | 13 +++-- python/python/tests/test_db.py | 46 +++++++++++++---- python/python/tests/test_namespace.py | 41 +++++++++++++++ python/python/tests/test_remote_db.py | 26 ++++++++++ python/python/tests/test_sync_api_parity.py | 25 ++++++--- 10 files changed, 246 insertions(+), 39 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index eccaae6ce..8de5b5517 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -42,6 +42,18 @@ table names. `db.list_tables().tables` is a list of the first page; `limit` controls its page size and `page_token` resumes at a saved token. The same patterns apply to `list_namespaces()`. Other resource listings use `page_limit`. +For existence checks, use `db.table_exists(["events"])` or `"events" in db`. +These look up the table directly and work even when the database has more than +100 tables. For a table in a namespace, include the namespace segments: + +```python +exists = db.table_exists(["analytics", "events"]) +``` + +When migrating from `name in db.table_names()`, use `name in db` or +`db.table_exists([name])`. Checking `name in db.list_tables().tables` only +searches the first page and can miss an existing table. + Resource listings (`list_storage_integrations`, `list_secrets`, `list_views`, `list_jobs`, `list_functions`, and `list_materialized_views`) return lazy iterators. Use `list(db.list_views())` to collect synchronous results, or `[name async for name in db.list_views()]` with @@ -1055,6 +1067,11 @@ the page list does not consume the iterator. `page.page_token` is the token for the next request; drain cached results before using it to resume in a new listing. The same behavior applies to namespaces. +Use `await db.table_exists(["events"])` to check for a table in the root +namespace, or `await db.table_exists(["analytics", "events"])` for a table in +a namespace. Checking membership in an awaited listing's `.tables` attribute +only searches one page. + ::: lancedb.listing.AsyncTableListing ::: lancedb.listing.AsyncNamespaceListing diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 2a05b4a0f..23fdbdb4a 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -201,7 +201,7 @@ setting. See [Limits](/basics/limits#schema). ```python Python icon="python" tbl = db.open_table("documents") -db.table_names() +names = list(db.list_tables()) ``` ```typescript TypeScript icon="square-js" @@ -230,6 +230,27 @@ listing. A missing table raises `ValueError` on a local directory and A listing returns one page of names at a time, so check every page. TypeScript has no `tableExists`. +{/* +Draft for the table-existence lookup release (#4974). Once released, replace +the two table-existence paragraphs above with this guidance: + +For Python local, remote, and namespace connections, use +`db.table_exists(["documents"])` or `"documents" in db` to check whether a root +table exists. For an async connection, use +`await db.table_exists(["documents"])`. Include namespace segments before the +table name, for example `["analytics", "documents"]`. These checks return +`False` when the table is missing and propagate other errors, including +permission errors. They look up the table directly, regardless of the number +of tables in the database. + +When migrating from `name in db.table_names()`, use `name in db` or +`db.table_exists([name])`. To collect every table name, use +`list(db.list_tables())`, or `[name async for name in db.list_tables()]` on an +async connection. The `.tables` attribute holds only one page (100 names by +default), so membership checks against it can miss existing tables. TypeScript +has no `tableExists`. +*/} + ## Rename and clone tables {#rename-clone} diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 73c8305ff..84ebb41a1 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -322,6 +322,9 @@ class DBConnection(EnforceOverrides): def table_exists(self, table_id: List[str]) -> bool: """Check if a table exists. + Use this method instead of checking membership in + ``list_tables().tables``, which contains only one page of table names. + Parameters ---------- table_id: List[str] @@ -331,12 +334,20 @@ class DBConnection(EnforceOverrides): Returns ------- bool - True if the table exists, False otherwise. + True if the table exists, False if it is not found. + Other errors, including permission errors, are propagated. Raises ------ NotImplementedError - If the connection type does not support namespace operations. + If the connection type does not support table existence checks. + + Examples + -------- + >>> def check_table(conn): + ... root_exists = conn.table_exists(["events"]) + ... nested_exists = conn.table_exists(["analytics", "events"]) + ... return root_exists, nested_exists """ raise NotImplementedError( "Namespace operations are not supported for this connection type" @@ -348,7 +359,11 @@ class DBConnection(EnforceOverrides): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + ``list_tables().tables`` contains only the first page (100 names by + default). Use ``list(list_tables())`` to collect all names, or + ``table_exists([name])`` to check whether a particular table exists. Parameters ---------- @@ -934,7 +949,7 @@ class DBConnection(EnforceOverrides): def __contains__(self, name: str) -> bool: """Return whether the root namespace contains the named table.""" - return name in self._all_table_names() + return self.table_exists([name]) def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. @@ -1849,6 +1864,10 @@ class LanceDBConnection(DBConnection): ) -> DescribeNamespaceResponse: return LOOP.run(self._conn.describe_namespace(namespace_path=namespace_path)) + @override + def table_exists(self, table_id: List[str]) -> bool: + return LOOP.run(self._conn.table_exists(table_id)) + @override def list_tables( self, @@ -1856,7 +1875,11 @@ class LanceDBConnection(DBConnection): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -1894,7 +1917,9 @@ class LanceDBConnection(DBConnection): """Get the names of all tables in the database. The names are sorted. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -1914,7 +1939,8 @@ class LanceDBConnection(DBConnection): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -2878,6 +2904,9 @@ class AsyncConnection(object): async def table_exists(self, table_id: List[str]) -> bool: """Check if a table exists. + Use this method instead of checking membership in an awaited listing's + ``tables`` attribute, which contains only one page of table names. + Parameters ---------- table_id: List[str] @@ -2903,7 +2932,11 @@ class AsyncConnection(object): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> AsyncTableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -2942,7 +2975,9 @@ class AsyncConnection(object): """List all tables in this database, in sorted order .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -2966,7 +3001,8 @@ class AsyncConnection(object): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 8abc9d85b..59aba1431 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -175,6 +175,9 @@ class _AsyncPagedNameListing(AsyncIterator[str]): class AsyncTableListing(_AsyncPagedNameListing): """Awaitable table iterator; awaiting loads one page. + Iteration fetches all pages. The ``tables`` attribute contains only the + current page, so use ``await db.table_exists([name])`` for existence checks. + For example:: page = await db.list_tables(limit=20) @@ -229,6 +232,10 @@ class _PagedNameListing(Iterator[str]): class TableListing(_PagedNameListing): """Table iterator retaining the current page as a list. + Iteration fetches all pages. The ``tables`` attribute contains only the + current page, so use ``db.table_exists([name])`` or ``name in db`` for + existence checks. Use ``list(db.list_tables())`` to collect all names. + For example:: page = db.list_tables(limit=20) @@ -239,6 +246,7 @@ class TableListing(_PagedNameListing): @property def tables(self) -> list[str]: + """A copy of the table names in the most recently fetched page.""" return self._inner.tables diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 3356b363c..aa9025641 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -579,12 +579,15 @@ class LanceNamespaceDBConnection(DBConnection): If limit is None, return all table names; zero returns an empty list. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. """ import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -1015,6 +1018,8 @@ class LanceNamespaceDBConnection(DBConnection): bool True if the table exists, False otherwise. """ + if self._route_pushdown_to_rust: + return LOOP.run(self._inner.table_exists(table_id)) request = TableExistsRequest(id=table_id) try: self._namespace_client.table_exists(request) @@ -1030,7 +1035,11 @@ class LanceNamespaceDBConnection(DBConnection): limit: Optional[int] = None, ) -> TableListing: """ - List all tables in this database with pagination support. + Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -1227,12 +1236,15 @@ class AsyncLanceNamespaceDBConnection: If limit is None, return all table names; zero returns an empty list. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. """ import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -1614,6 +1626,8 @@ class AsyncLanceNamespaceDBConnection: bool True if the table exists, False otherwise. """ + if self._route_pushdown_to_rust: + return await self._inner.table_exists(table_id) request = TableExistsRequest(id=table_id) try: self._namespace_client.table_exists(request) @@ -1628,7 +1642,11 @@ class AsyncLanceNamespaceDBConnection: limit: Optional[int] = None, ) -> AsyncTableListing: """ - List all tables in this database with pagination support. + Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ebceba16b..21ad37b36 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -430,7 +430,11 @@ class RemoteDBConnection(DBConnection): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List a page of tables in this database. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -468,7 +472,9 @@ class RemoteDBConnection(DBConnection): """List the names of all tables in the database. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -488,7 +494,8 @@ class RemoteDBConnection(DBConnection): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 64bf928c0..80a98bc18 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -282,9 +282,7 @@ async def test_table_listing_defaults_and_zero_limit(tmp_path): assert empty.page_token is None -def test_db_contains_stops_after_matching_table_page( - tmp_db: lancedb.DBConnection, monkeypatch -): +def test_db_len_includes_all_table_pages(tmp_db: lancedb.DBConnection, monkeypatch): calls = [] pages = { None: SimpleNamespace(tables=["table_0", "table_1"], page_token="next"), @@ -297,18 +295,44 @@ def test_db_contains_stops_after_matching_table_page( monkeypatch.setattr(tmp_db, "list_tables", list_tables) - assert "table_1" in tmp_db - assert calls == [None] - - calls.clear() - assert "table_2" in tmp_db - assert calls == [None, "next"] - - calls.clear() assert len(tmp_db) == 3 assert calls == [None, "next"] +@pytest.mark.asyncio +@pytest.mark.parametrize("namespace_path", [[], ["analytics", "nested"]]) +async def test_local_table_exists_without_listing( + tmp_path, monkeypatch, namespace_path +): + db = lancedb.connect(tmp_path) + for depth in range(1, len(namespace_path) + 1): + db.create_namespace(namespace_path[:depth]) + db.create_table("events", data=[{"id": 1}], namespace_path=namespace_path) + if not namespace_path: + for idx in range(100): + (tmp_path / f"a{idx:03}.lance").mkdir() + assert "events" not in db.list_tables().tables + adb = await lancedb.connect_async(tmp_path) + + def fail_listing(*args, **kwargs): + raise AssertionError("Existence checks must not list tables") + + monkeypatch.setattr(db, "list_tables", fail_listing) + monkeypatch.setattr(adb, "list_tables", fail_listing) + table_id = namespace_path + ["events"] + assert db.table_exists(table_id) is True + assert await adb.table_exists(table_id) is True + assert db.table_exists(namespace_path + ["missing"]) is False + assert await adb.table_exists(namespace_path + ["missing"]) is False + assert ("events" in db) is (not namespace_path) + assert "missing" not in db + assert table_id == namespace_path + ["events"] + + db.drop_table("events", namespace_path=namespace_path) + assert db.table_exists(table_id) is False + assert await adb.table_exists(table_id) is False + + @pytest.mark.asyncio async def test_table_names_async(tmp_path): db = lancedb.connect(tmp_path) diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 5eb9c02bd..9bce1059d 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -34,6 +34,27 @@ PUSHDOWN_DATA = pa.table( ) +@pytest.mark.asyncio +@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]]) +async def test_custom_namespace_table_exists_uses_namespace_api(table_id): + class ExistenceNamespace(LanceNamespace): + def namespace_id(self): + return "existence-test" + + def table_exists(self, request): + if request.id == ["missing"]: + raise TableNotFoundError("Table not found") + + def describe_table(self, request): + raise AssertionError("Custom existence checks must not open tables") + + namespace = ExistenceNamespace() + db = LanceNamespaceDBConnection(namespace) + adb = lancedb.AsyncLanceNamespaceDBConnection(namespace) + assert db.table_exists(table_id) is (table_id != ["missing"]) + assert await adb.table_exists(table_id) is (table_id != ["missing"]) + + class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) @@ -411,8 +432,16 @@ class TestNamespaceConnection: assert "test_ns" in db.list_namespaces().namespaces schema = pa.schema([pa.field("id", pa.int64())]) + db.create_table("root_table", schema=schema) + assert db.table_exists(["root_table"]) is True + assert "root_table" in db + assert db.table_exists(["missing"]) is False + assert "missing" not in db table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"]) assert table.namespace == ["test_ns"] + assert db.table_exists(["test_ns", "test_table"]) is True + assert db.table_exists(["test_ns", "missing"]) is False + assert "test_table" not in db assert "test_table" in db.table_names(namespace_path=["test_ns"]) assert "test_table" in db.list_tables(namespace_path=["test_ns"]).tables @@ -420,7 +449,10 @@ class TestNamespaceConnection: assert opened.namespace == ["test_ns"] db.drop_table("test_table", namespace_path=["test_ns"]) + assert db.table_exists(["test_ns", "test_table"]) is False assert db.list_tables(namespace_path=["test_ns"]).tables == [] + db.drop_table("root_table") + assert "root_table" not in db db.drop_namespace(["test_ns"]) assert "test_ns" not in db.list_namespaces().namespaces @@ -942,12 +974,18 @@ class TestAsyncNamespaceConnection: assert "test_ns" in (await db.list_namespaces()).namespaces schema = pa.schema([pa.field("id", pa.int64())]) + await db.create_table("root_table", schema=schema) + assert await db.table_exists(["root_table"]) is True + assert await db.table_exists(["missing"]) is False table = await db.create_table( "test_table", schema=schema, namespace_path=["test_ns"] ) assert table._namespace_path == ["test_ns"] assert table._namespace_client is None assert table._route_pushdown_to_rust is True + assert await db.table_exists(["test_ns", "test_table"]) is True + assert await db.table_exists(["test_ns", "missing"]) is False + assert await db.table_exists(["test_table"]) is False assert "test_table" in await db.table_names(namespace_path=["test_ns"]) assert "test_table" in (await db.list_tables(namespace_path=["test_ns"])).tables @@ -955,7 +993,10 @@ class TestAsyncNamespaceConnection: assert opened._namespace_path == ["test_ns"] await db.drop_table("test_table", namespace_path=["test_ns"]) + assert await db.table_exists(["test_ns", "test_table"]) is False assert (await db.list_tables(namespace_path=["test_ns"])).tables == [] + await db.drop_table("root_table") + assert await db.table_exists(["root_table"]) is False await db.drop_namespace(["test_ns"]) assert "test_ns" not in (await db.list_namespaces()).namespaces diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 407596d26..952437051 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -22,6 +22,7 @@ import time from urllib.parse import parse_qs, urlparse from unittest.mock import MagicMock, patch import uuid +import warnings from packaging.version import Version from lance_namespace.errors import TableNotFoundError @@ -461,6 +462,31 @@ def test_remote_table_exists_rechecks_cached_table(): assert requests == ["/v1/table/ns$table/describe/"] * 2 +@pytest.mark.parametrize("status", [200, 404, 403]) +def test_remote_membership_uses_direct_lookup(status): + requests = [] + + def handler(request): + requests.append(request.path) + assert request.command == "POST" + assert request.path == "/v1/table/t129/describe/" + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}" if status == 200 else b"lookup failed") + + with mock_lancedb_connection(handler) as db: + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + if status in (200, 404): + assert ("t129" in db) is (status == 200) + else: + with pytest.raises(HttpError) as exc_info: + "t129" in db + assert exc_info.value.status_code == status + assert requests == ["/v1/table/t129/describe/"] + + def paginated_table_listing_handler(request): url = urlparse(request.path) assert url.path in { diff --git a/python/python/tests/test_sync_api_parity.py b/python/python/tests/test_sync_api_parity.py index a12efd0c9..230fb45c6 100644 --- a/python/python/tests/test_sync_api_parity.py +++ b/python/python/tests/test_sync_api_parity.py @@ -58,8 +58,8 @@ def test_legacy_table_replace_field_metadata(legacy_table): ] -def respond(request, body): - request.send_response(200) +def respond(request, body, status=200): + request.send_response(status) request.send_header("Content-Type", "application/json") request.end_headers() request.wfile.write(json.dumps(body).encode()) @@ -78,12 +78,20 @@ def test_remote_unsupported_properties(attribute): @pytest.mark.parametrize("tables", [[], ["first", "last"]]) -def test_remote_len_and_contains_follow_pages(tables): +def test_remote_len_paginates_and_contains_looks_up_table(tables): requests = [] def handler(request): requests.append(request.path) - query = parse_qs(urlparse(request.path).query) + url = urlparse(request.path) + if request.command == "POST": + name = url.path.split("/")[3] + assert url.path == f"/v1/table/{name}/describe/" + respond(request, {}, status=200 if name in tables else 404) + return + assert request.command == "GET" + assert url.path == "/v1/namespace/$/table/list" + query = parse_qs(url.query) if tables and "page_token" not in query: respond(request, {"tables": [tables[0]], "page_token": "opaque-next"}) else: @@ -93,11 +101,12 @@ def test_remote_len_and_contains_follow_pages(tables): with mock_lancedb_connection(handler) as db: assert len(db) == len(tables) - assert ("last" in db) == bool(tables) - assert "missing" not in db + assert len(requests) == (2 if tables else 1) requests.clear() - assert ("first" in db) == bool(tables) - assert len(requests) == 1 + for name in ("last", "missing", "first"): + assert (name in db) is (name in tables) + assert requests == [f"/v1/table/{name}/describe/"] + requests.clear() @pytest.mark.parametrize("namespace", [[], ["parent", "child"]]) From 1dee9b006caf2d02de96daf3db3c3bf37c56633b Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 23:32:57 -0800 Subject: [PATCH 12/75] fix(python): reject unsupported Function callables early (#4972) Reject synchronous and asynchronous generator Functions, including class `__call__` methods, during decoration so invalid outputs never reach remote execution. Give actionable errors for lambdas and decorated wrappers such as `functools.lru_cache`. Defaulted callable inputs remain unsupported; the error now names the parameter and explains how to use class initialization fields. ```python @function def double(value: float) -> float: yield value * 2 # TypeError: generator Functions are not supported; return a value instead of # yielding, or return a list for multiple values ``` The deprecated `@udf` alias shares the validation. Adds regression coverage for both decorators, class methods, explicit schemas, and the supported list-return alternative. Fixes https://linear.app/lancedb/issue/ENT-3539 --- python/python/lancedb/functions.py | 39 ++++++- .../python/tests/test_function_packaging.py | 104 +++++++++++++++++- 2 files changed, 138 insertions(+), 5 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 4bf028306..74cc2adf4 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1298,6 +1298,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: raise TypeError(f"unsupported Function annotation: {annotation!r}") +def _validate_callable(function: Any) -> None: + if hasattr(function, "__wrapped__"): + raise TypeError( + "decorated wrappers are not supported; put caching inside the function " + "body or use a class Function with a cache in __init__" + ) + if inspect.isgeneratorfunction(function) or inspect.isasyncgenfunction(function): + raise TypeError( + "generator Functions are not supported; return a value instead of " + "yielding, or return a list for multiple values" + ) + if inspect.isfunction(function) and function.__name__ == "": + raise TypeError("lambda Functions are not supported; use a named def instead") + + def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Parameter, ...]: parameters = tuple(inspect.signature(function).parameters.values()) for parameter in parameters: @@ -1308,7 +1323,11 @@ def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Paramete ): raise TypeError("Function callables require named, non-variadic parameters") if parameter.default is not inspect.Parameter.empty: - raise TypeError("Function callable defaults are not supported") + raise TypeError( + f"Function callable defaults are not supported: {parameter.name!r}; " + "move configuration parameters to a class Function's __init__ " + "and pass them as binding-time initialization values" + ) return parameters @@ -2201,6 +2220,7 @@ def _class_member(cls: type, name: str) -> Any: def _class_call(cls: type) -> Callable[..., Any]: call = _class_member(cls, "__call__") + _validate_callable(call) if not inspect.isfunction(call) or inspect.iscoroutinefunction(call): raise TypeError("a class Function must define a synchronous __call__ method") close = _class_member(cls, "close") @@ -2257,12 +2277,10 @@ class FunctionDefinition: if not is_class and ( not inspect.isfunction(function) or inspect.iscoroutinefunction(function) ): + _validate_callable(function) raise TypeError( "@function requires a synchronous Python function or a class" ) - function_name = name or function.__name__ - if not _FUNCTION_NAME.fullmatch(function_name): - raise ValueError(f"invalid Function name: {function_name!r}") if pip and conda: raise ValueError("a Function environment is pip or conda, not both") if conda_channels and not conda: @@ -2324,6 +2342,11 @@ class FunctionDefinition: "model Functions reserve environment variables " f"{reserved!r}; the worker sets them for the private snapshot" ) + if not is_class: + _validate_callable(function) + function_name = name or function.__name__ + if not _FUNCTION_NAME.fullmatch(function_name): + raise ValueError(f"invalid Function name: {function_name!r}") if is_class: if "<" in function.__qualname__ or "." in function.__qualname__: raise ValueError( @@ -2555,6 +2578,14 @@ def function( reuses them. An instance serves many batches of one binding, so state is shared across them, but not across instances or workers. + Functions and ``__call__`` methods must return a value. Generators, + including async generators, are not supported; return a list to produce + multiple values for a list output. Lambdas and decorated wrappers such as + ``functools.lru_cache`` are not supported. Use a named ``def`` and keep + caches inside the body or in a class instance initialized by ``__init__``. + Callable input parameters cannot have defaults; move configurable values + to class initialization fields instead. + **Initialization.** The annotated parameters of a class's ``__init__`` are the Function's initialization fields. Their values belong to each binding, not to the Function: ``function(text=col("body"), model="small")`` diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 83dfdaeb3..440adc4da 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,7 +20,7 @@ import pyarrow as pa import pytest from lancedb import col -from lancedb.functions import FunctionDefinition, FunctionVersion, function +from lancedb.functions import FunctionDefinition, FunctionVersion, function, udf FIXTURES = ( Path(__file__).parents[3] @@ -127,6 +127,108 @@ def test_function_without_initialization_keeps_its_wire_form(): assert request["artifact"]["kind"] == "python_callable" +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +@pytest.mark.parametrize("decorator", [function, udf]) +@pytest.mark.parametrize("explicit_schemas", [False, True]) +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize( + ("declaration", "statement"), + [ + ("def", "yield value"), + ("def", "yield from [value]"), + ("async def", "yield value"), + ], +) +def test_generator_functions_are_rejected_at_decoration( + helper_package, decorator, explicit_schemas, class_function, declaration, statement +): + signature = ( + "__call__(self, value: int)" if class_function else "generates(value: int)" + ) + source = f"{declaration} {signature} -> int:\n {statement}\n" + if class_function: + source = "class generates:\n" + textwrap.indent(source, " ") + module = helper_package("fx_generator", {"__init__.py": source}) + options = ( + { + "input_schema": pa.schema([pa.field("value", pa.int64(), nullable=False)]), + "output_schema": pa.int64(), + } + if explicit_schemas + else {} + ) + with pytest.raises(TypeError) as error: + decorator(**options)(module.generates) + message = str(error.value) + assert "generator Functions are not supported" in message + assert "return a value" in message + assert "return a list" in message + + +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +@pytest.mark.parametrize("decorator", [function, udf]) +@pytest.mark.parametrize("explicit_name", [False, True]) +def test_lambda_functions_explain_the_named_alternative(decorator, explicit_name): + options = {"name": "double"} if explicit_name else {} + with pytest.raises(TypeError, match="lambda.*use a named def"): + decorator(**options)(lambda value: value * 2) + + +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize("cache_decorator", ["lru_cache", "cache"]) +def test_cached_functions_explain_where_to_keep_caches( + helper_package, class_function, cache_decorator +): + signature = "__call__(self, value: int)" if class_function else "cached(value: int)" + source = ( + f"@functools.{cache_decorator}\ndef {signature} -> int:\n return value * 2\n" + ) + if class_function: + source = "class cached:\n" + textwrap.indent(source, " ") + module = helper_package("fx_cached", {"__init__.py": "import functools\n" + source}) + with pytest.raises(TypeError) as error: + function(module.cached) + message = str(error.value) + assert "decorated wrappers are not supported" in message + assert "inside the function body" in message + assert "class Function with a cache in __init__" in message + + +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize("keyword_only", [False, True]) +def test_callable_defaults_explain_class_initialization( + helper_package, class_function, keyword_only +): + parameters = "value: float, " + ("*, " if keyword_only else "") + parameters += "threshold: float = 0.5" + signature = ( + f"__call__(self, {parameters})" + if class_function + else f"thresholded({parameters})" + ) + source = f"def {signature} -> bool:\n return value >= threshold\n" + if class_function: + source = "class thresholded:\n" + textwrap.indent(source, " ") + module = helper_package("fx_defaults", {"__init__.py": source}) + with pytest.raises(TypeError) as error: + function(module.thresholded) + message = str(error.value) + assert "defaults are not supported: 'threshold'" in message + assert "class Function's __init__" in message + assert "binding-time initialization values" in message + + +def test_function_can_return_a_list_from_a_generator_expression(): + @function + def many(value: int) -> list[int]: + return list(item * 2 for item in range(value)) + + namespace = {} + exec(compile(artifact(many), "user_function.py", "exec"), namespace) + assert namespace["many"](3) == [0, 2, 4] + assert many.registration_request.signature.output.arrow_type == "list" + + @pytest.mark.parametrize("kind", ["function", "class"]) @pytest.mark.parametrize( ("global_value", "value_type"), From 5a38066234552fc1bd9826d12d71fc88fd64be93 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 12 Nov 2026 16:09:13 +0800 Subject: [PATCH 13/75] chore(deps): upgrade Lance to v15.0.0-beta.18 (#4965) Upgrade the Rust Lance dependency, Java lance-core, and Python test dependency from beta.17 to the officially published [v15.0.0-beta.18](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.18) (`079fd77683a7acf056b0912f6ecda938e39ee120`). This provides a compatible SDK for the newer Lance source already adopted downstream. Rust registry versions and checksums are unchanged; the Python lock uses the six published beta.18 wheels. ### Compatibility The adopted release includes [Lance #10863](https://github.com/lance-format/lance/pull/10863): `FilteredReadOptionsProto.has_fragment_ids` distinguishes an explicit empty fragment selection. Older executors ignore this field, so upgrade executors before relying on the corrected empty-selection behavior. Rust callers constructing this generated struct need the new field. [Lance #10112](https://github.com/lance-format/lance/pull/10112) also replaces the internal `hamming_distance_batch` API with `hamming_distance_batch_into`. The Linux Python matrix timeout is raised from 30 to 60 minutes: the Python 3.13 cold native build and both test passes completed, but the job hit its limit during cleanup. Build profiles, test commands, and coverage are unchanged. ### Validation - Three native FRI/ANN regressions passed: deferred-compaction refined RQ, deferred index remapping, and approximate-query builder. - `cargo clippy --quiet --locked --features remote --tests --examples -- -D warnings` passed with pinned Rust 1.97.0. - Locked metadata, formatting, Python Makefile-scope Ruff checks, and `uv lock --check --offline` passed. - YAML, whitespace, end-of-file, and typo checks passed for the timeout-only workflow change. ### Publication and CI Java beta.18 is now published. After [Lance #10968](https://github.com/lance-format/lance/pull/10968) merged, the [normal publication workflow](https://github.com/lance-format/lance/actions/runs/43146352505) built all three JNI targets and published successfully; the Maven jar is available. The upstream Python publication run was cancelled after its Windows ARM job hit the one-hour timeout; six other wheels were published and are the actual artifacts recorded in this lock. Cross-platform SDK CI is still required. No performance claim is made by this dependency update. --- .github/workflows/python.yml | 3 +- Cargo.lock | 96 ++++++++++++++++++------------------ Cargo.toml | 30 +++++------ java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 16 +++--- 6 files changed, 75 insertions(+), 74 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2fabb4a6a..e208ac7cd 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -130,7 +130,8 @@ jobs: run: pytest --doctest-modules python/lancedb linux: name: "Linux: python-3.${{ matrix.python-minor-version }}" - timeout-minutes: 30 + # A cold native build plus both test passes can exhaust 30 minutes. + timeout-minutes: 60 strategy: matrix: python-minor-version: ["10", "13"] diff --git a/Cargo.lock b/Cargo.lock index f38252fc5..4e6d2665a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3825,8 +3825,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5313,8 +5313,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5389,8 +5389,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5412,7 +5412,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5426,7 +5426,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5435,8 +5435,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrayref", "crunchy", @@ -5446,8 +5446,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5485,8 +5485,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5517,8 +5517,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5543,8 +5543,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5561,8 +5561,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "proc-macro2", "quote", @@ -5571,8 +5571,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-arith", "arrow-array", @@ -5605,8 +5605,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-arith", "arrow-array", @@ -5637,8 +5637,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5669,8 +5669,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5742,8 +5742,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5766,8 +5766,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5812,8 +5812,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "byteorder", "ethnum", @@ -5830,8 +5830,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5846,8 +5846,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "async-trait", @@ -5861,8 +5861,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5931,8 +5931,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5973,8 +5973,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5987,8 +5987,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 9fc33e6ab..c45eef6da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 610c095b9..9356288dc 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.17 + 15.0.0-beta.18 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 5ba1d4bbf..6940dce4f 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b17", + "pylance==15.0.0b18", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 01693079f..369d558d2 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b17" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b18" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b17" +version = "15.0.0b18" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,12 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_il4JF/pylance-15.0.0b17-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:ee3c3d2baf1f0d788d706638873317740178a81988b71ffda47a2e71d1e15ff3" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2hFd0a/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a5b576e35054d4866d823ebadc9d3c531165628feb29ca1528db15b9082675a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_29zVw5/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47c534032d2f251f396657e47efbc224ee2d1964495d7982a449e5e1cdcf3169" }, - { url = "https://pypi.fury.io/lance-format/-/ver_548nr/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:509db7d8be3eebb111b7d28aa486437424cb3663cfb7f502b71532fa37ba7155" }, - { url = "https://pypi.fury.io/lance-format/-/ver_gmpNu/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd2cc05c2d553d44c54570612e793136e3433fcba28e4d51a503cca8f45435ea" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Otspk/pylance-15.0.0b17-cp310-abi3-win_amd64.whl", hash = "sha256:510c419e21a4daa4c18db4cc5048bd7dfc706924b23e13136306935f2e3e0c25" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Rs8tZ/pylance-15.0.0b18-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:255e782b016555c3f8072bb3d2a33dfdb3cb67b5ccf10a6a999fd007c58b16ab" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1D7wV0/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11adaf98d8e2960bb25d30315720cb93a2ac291d3fec29cd9726e1085cd9e40f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pK9DO/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aea39d714821d561b655f2d046129700a5ff95c3352813edd6af15ec6d9d29e2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_28PrEd/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c19b3293be41ae4a87a67123e8d7233b0c5508aa39012c26525ab9d19884386d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_kV8Di/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7a48686ab4777b58fe9f0e17a68048b779c071879d48035afb3e79b81b9d47a1" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1pAhhP/pylance-15.0.0b18-cp310-abi3-win_amd64.whl", hash = "sha256:dc32e4731b78c8325d1bd0f0e23f13f7dab7ed1f0fcda47d52661d44c8bfc83a" }, ] [[package]] From 01e9ea44aa0609630cec2f3f728198a36374befd Mon Sep 17 00:00:00 2001 From: Lance Release Date: Thu, 12 Nov 2026 08:12:34 +0000 Subject: [PATCH 14/75] =?UTF-8?q?Bump=20version:=200.42.0-beta.11=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.12?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 076443831..e4989d1eb 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.11" +current_version = "0.42.0-beta.12" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 4e6d2665a..efe0338cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6001,7 +6001,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "ahash", "anyhow", @@ -6112,7 +6112,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "anyhow", "arrow-array", @@ -6155,7 +6155,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "arrow-array", "arrow-buffer", @@ -6180,7 +6180,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index c06b4f230..ca77b251c 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.11 + 0.42.0-beta.12 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 903be2b77..792b434a1 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.11 + 0.42.0-beta.12 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9356288dc..df709fb4f 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.11 + 0.42.0-beta.12 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 91d808647..22cfe6ecc 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 1a9011b34..283a32fdc 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 00b2918d6..5fd392245 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index f94f27216..ec5103284 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index e0eefa2e9..1d45a2ed2 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index f0891fbed..d17a3b4e7 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 04b65ba86..a7c4a74b6 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e5e0effab..0e3a4a626 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index a03e1a794..b0d99fb60 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 7c11d5fdf..5a2923216 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index cbb0142e1..737c385c1 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index cde8b295a..b22a3b8d8 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" edition = "2021" license.workspace = true repository.workspace = true From 478d1d9b0103971dbd31be655bfb7e5073995bd5 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 00:30:19 -0800 Subject: [PATCH 15/75] fix: expose comparable Function runtime identity (#4975) Expose `FunctionVersion.runtime_digest` through Rust and Python, and add `PythonRuntimeSpec.digest` so clients can compare declared environment inputs before registering a Function. Dependency pins, environment variables, Python version, and GPU settings affect this digest; package ordering does not. Clarify that matching `source_digest` alone is insufficient for reuse. Older servers/images leave `runtime_digest` unset, which cannot establish a match. Both digests and the other registration inputs must match before reusing a version. ```python request = definition.registration_request same_source = version.source_digest == request.artifact.digest same_runtime = version.runtime_digest == request.runtime.digest ``` Add shared runtime digest fixtures and coverage for environment-only changes and catalog decoding. Local builds and tests were skipped as requested. --- python/python/lancedb/functions.py | 39 +++ .../tests/test_first_class_function_slice1.py | 34 ++- .../tests/test_first_class_function_slice2.py | 28 ++ python/python/tests/test_remote_db.py | 3 + rust/lancedb/src/function.rs | 39 ++- .../v1/runtime_identity.json | 269 ++++++++++++++++++ 6 files changed, 410 insertions(+), 2 deletions(-) create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 74cc2adf4..a5c741cd8 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -495,6 +495,35 @@ class PythonRuntimeSpec(_RemoteValue): object.__setattr__(self, "gpu_class", None) return self + @property + def digest(self) -> str: + """SHA-256 identity of the declared runtime, before building an image. + + Covers Python version, environment sources, environment variables, and + GPU settings. Package and system-package order is ignored; conda channel + order is preserved. Compare with ``runtime_digest`` on + [FunctionVersion][lancedb.functions.FunctionVersion]. + This identifies build inputs, not the resolved contents of unpinned + dependencies or the deployment's default base image. + """ + if self.kind not in {"python", "python_v2"}: + raise ValueError(f"cannot digest unknown runtime kind {self.kind!r}") + value = self._known_dict() + if not value.get("env"): + value.pop("env", None) + environment = value["environment"] + for field in ("packages", "system_packages"): + if field in environment: + environment[field] = sorted(environment[field]) + encoded = json.dumps( + value, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + return f"sha256:{hashlib.sha256(encoded).hexdigest()}" + class FunctionImage(_RemoteValue): """A complete OCI Function image identified by its exact manifest digest.""" @@ -536,8 +565,17 @@ class FunctionVersion(_RemoteValue): of the built ``image``. Compare it with ``definition.registration_request.artifact.digest`` to check whether a local [FunctionDefinition][lancedb.functions.FunctionDefinition] has the same source. + It does not cover dependencies, environment variables, Python version, or + GPU settings. Equal source digests alone do not mean a version can be reused. It is ``None`` when the server does not provide a source digest. + ``runtime_digest`` identifies the declared environment inputs. Compare it + with ``definition.registration_request.runtime.digest`` to check whether + the local runtime matches. It is ``None`` for images built before runtime + identity was exposed. A missing digest cannot establish a match. Reusing a + version also requires matching the source and all other registration inputs, + including signature, Secret bindings, models, and execution controls. + ``gpu_class`` is the operator-defined GPU pool fixed into this Function version, or ``None`` when registration used the deployment default. @@ -554,6 +592,7 @@ class FunctionVersion(_RemoteValue): version: _ObjectVersion image: FunctionImage source_digest: Optional[str] = None + runtime_digest: Optional[str] = None signature: FunctionSignature secret_bindings: tuple[SecretBinding, ...] = () created_at_millis: int diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index f8e225183..867672fe9 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -34,7 +34,7 @@ FIXTURES = ( def fixture(name: str) -> str: - return (FIXTURES / name).read_text() + return (FIXTURES / name).read_text(encoding="utf-8") def job_result(name: str) -> dict: @@ -148,6 +148,38 @@ def test_function_version_identity_is_immutable_and_exact(): FunctionVersion(**{**value, "version": invalid}) +@pytest.mark.parametrize( + "case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"] +) +def test_runtime_digests_match_server_golden_values(case): + runtime = PythonRuntimeSpec.from_json(json.dumps(case["runtime"])) + assert runtime.digest == case["digest"] + assert ( + PythonRuntimeSpec.from_json(runtime.to_canonical_json()).digest + == runtime.digest + ) + + +def test_unknown_runtime_digest_fails_closed(): + runtime = PythonRuntimeSpec.from_json('{"kind":"python_v3","future":"value"}') + with pytest.raises(ValueError, match="cannot digest unknown runtime kind"): + runtime.digest + + +@pytest.mark.parametrize("runtime_digest", [None, "sha256:runtime-inputs"]) +def test_function_version_preserves_runtime_digest(runtime_digest): + value = job_result("remote_function_job.json") + legacy = FunctionVersion.from_json(json.dumps(value)) + assert legacy.runtime_digest is None + assert "runtime_digest" not in json.loads(legacy.to_canonical_json()) + value["runtime_digest"] = runtime_digest + version = FunctionVersion.from_json(json.dumps(value)) + assert version.runtime_digest == runtime_digest + assert FunctionVersion.from_json(version.to_canonical_json()) == version + with pytest.raises((TypeError, ValueError)): + version.runtime_digest = "sha256:changed" + + @pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"]) def test_function_version_preserves_source_digest(source_digest): value = job_result("remote_function_job.json") diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 2cc731892..d99a7aa21 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1891,6 +1891,29 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): return value +def test_default_function_runtime_matches_server_identity(): + definition = function(python_version="3.12")(analyze_caption.__wrapped__) + runtime = definition.registration_request.runtime + assert runtime.env == {} + cases = json.loads((FIXTURES / "runtime_identity.json").read_text(encoding="utf-8")) + expected = next( + case["digest"] for case in cases if case["name"] == "empty-environment" + ) + assert runtime.digest == expected + + +def test_environment_changes_do_not_change_source_identity(): + definition = function( + pip=["openai==3.46.0"], + env={"MODE": "test"}, + python_version="3.12", + )(analyze_caption.__wrapped__) + previous = analyze_caption.registration_request + changed = definition.registration_request + assert previous.artifact.digest == changed.artifact.digest + assert previous.runtime.digest != changed.runtime.digest + + def test_local_function_catalog_operations_are_not_supported(tmp_path): db = lancedb.connect(tmp_path) message = "Function catalog operations are not supported by this database" @@ -1950,6 +1973,7 @@ async def test_async_catalog_path_preserves_execution_controls(): (FIXTURES / "remote_function_version.canonical.json").read_text() ) definition.update( + runtime_digest=normalize_score.registration_request.runtime.digest, batch_size=12, row_timeout_seconds=8.0, result_stability="input_and_context", @@ -1977,6 +2001,7 @@ def test_sync_catalog_path_preserves_execution_controls(): (FIXTURES / "remote_function_version.canonical.json").read_text() ) definition.update( + runtime_digest=normalize_score.registration_request.runtime.digest, batch_size=12, row_timeout_seconds=8.0, result_stability="input_and_context", @@ -2090,6 +2115,9 @@ def _mock_remote_function_catalog(): )["image"], "signature": body["signature"], "source_digest": body["artifact"]["digest"], + "runtime_digest": PythonRuntimeSpec.from_json( + json.dumps(body["runtime"]) + ).digest, "secret_bindings": body.get("secret_bindings", []), "created_at_millis": 1787270400000, # 2026-08-21T00:00:00Z } diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 952437051..b0098aca3 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -6304,6 +6304,8 @@ def test_remote_function_registration_transports_max_concurrency(): def registered(value: float) -> float: return value + definition["runtime_digest"] = registered.registration_request.runtime.digest + class RegistrationServer(flight.FlightServerBase): def __init__(self): super().__init__("grpc://127.0.0.1:0") @@ -6322,6 +6324,7 @@ def test_remote_function_registration_transports_max_concurrency(): assert len(server.tickets) == 1 assert b'"max_concurrency":4' in server.tickets[0] assert version.max_concurrency == 4 + assert version.runtime_digest == registered.registration_request.runtime.digest @pytest.mark.asyncio diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 3566fc938..e3d47948e 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -594,6 +594,8 @@ pub struct FunctionVersion { image: FunctionImage, #[serde(default, skip_serializing_if = "Option::is_none")] source_digest: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime_digest: Option, signature: FunctionSignature, #[serde(default, skip_serializing_if = "Vec::is_empty")] secret_bindings: Vec, @@ -665,7 +667,9 @@ impl FunctionVersion { /// Digest of the registered source artifact, when provided by the server. /// /// Compare this with [`FunctionArtifactRequest::digest`] to identify matching - /// source, independently of the built image's manifest digest. + /// source, independently of the built image's manifest digest. It excludes + /// dependencies, environment variables, Python version, and GPU settings; + /// matching source alone does not establish that a version can be reused. /// /// ``` /// use lancedb::function::{FunctionArtifactRequest, FunctionVersion}; @@ -678,6 +682,15 @@ impl FunctionVersion { self.source_digest.as_deref() } + /// Digest of canonical runtime inputs, when provided by the server. + /// + /// Includes Python version, environment sources, variables, and GPU settings. + /// A missing digest cannot establish that a local runtime matches. Reusing a + /// version also requires matching its source and other registration inputs. + pub fn runtime_digest(&self) -> Option<&str> { + self.runtime_digest.as_deref() + } + /// Operator-defined GPU class declared at registration. pub fn gpu_class(&self) -> Option<&str> { self.gpu_class.as_deref() @@ -1329,6 +1342,30 @@ mod conda_environment_tests { mod tests { use super::*; + #[test] + fn function_version_preserves_runtime_digest() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + let legacy = FunctionVersion::from_json(VERSION).unwrap(); + assert_eq!(legacy.runtime_digest(), None); + assert_eq!(legacy.to_canonical_json().unwrap(), VERSION.trim_end()); + for digest in [Value::Null, serde_json::json!("sha256:runtime-inputs")] { + document["runtime_digest"] = digest.clone(); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime_digest(), digest.as_str()); + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + if digest.is_null() { + assert!(encoded_value.get("runtime_digest").is_none()); + } else { + assert_eq!(encoded_value["runtime_digest"], digest); + } + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + } + } + #[test] fn function_version_preserves_source_digest() { const VERSION: &str = include_str!( diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json new file mode 100644 index 000000000..7bf0c375c --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json @@ -0,0 +1,269 @@ +[ + { + "name": "pip", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "reordered-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "numpy==2.2.0", + "openai==3.40.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "changed-pin", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.46.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:43da49cfcf8ecd47becb5be20b9eff06c5267f9244c18e751b230c624f5ad12a" + }, + { + "name": "changed-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "prod", + "LABEL": "你好" + } + }, + "digest": "sha256:9b305e9188f4ddda5a0b72d2235c2c46ba50de9bf82c699f5060b02e4aa0820d" + }, + { + "name": "changed-python", + "runtime": { + "kind": "python", + "python_version": "3.11", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:8fa58561581414b02d0619e466e3720828d1820d8211b0e73c90ec4b0d3ecd0c" + }, + { + "name": "gpu", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true + }, + "digest": "sha256:3ea9354ff101038937b1f5a3b6639c4cc6dcb88ee975dcb8e1a5dee2500c283c" + }, + { + "name": "gpu-class", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true, + "gpu_class": "a100" + }, + "digest": "sha256:253f0641ef029aed8337bbcb210f7769147d671747406f7ce4fa5dc40d5c5efc" + }, + { + "name": "conda", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "conda-forge", + "defaults" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:9246f88a6b1daceb3090c51930650ea967947142cdc70737c847a6bf72c85d30" + }, + { + "name": "reordered-channels", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "defaults", + "conda-forge" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:12ef13a6f5b8730a719288ab2406e7f6c13634b14dbef2390f0bbe62f847e18d" + }, + { + "name": "system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "zlib1g", + "ffmpeg" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "reordered-system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "ffmpeg", + "zlib1g" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "empty-environment", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + } + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-fields", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [], + "channels": [], + "modules": [], + "system_packages": [] + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + } +] From 7b2dfb9e361bddfbf4b3e16f2d950f377d5b5e33 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 01:19:05 -0800 Subject: [PATCH 16/75] fix(python): align catalog and database connection inputs (#4983) Align Python catalog connection inputs with database connections, warn when region is ignored, and preserve remote storage settings in opened databases. --- docs/web/basics/catalog.mdx | 18 +++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/catalog.py | 154 ++++++++++++++++++++++-- python/python/lancedb/remote/db.py | 3 +- python/python/tests/test_catalog.py | 176 +++++++++++++++++++++++++++- python/python/type_tests/connect.py | 20 +++- python/src/catalog.rs | 8 +- rust/lancedb/src/catalog.rs | 12 ++ rust/lancedb/src/remote/catalog.rs | 10 ++ rust/lancedb/src/remote/db.rs | 2 +- 10 files changed, 389 insertions(+), 15 deletions(-) diff --git a/docs/web/basics/catalog.mdx b/docs/web/basics/catalog.mdx index 1e95aeca4..519d86067 100644 --- a/docs/web/basics/catalog.mdx +++ b/docs/web/basics/catalog.mdx @@ -158,6 +158,24 @@ list, create and drop databases across the whole deployment. Its `connect_database(name)` and `create_database(name)` then return the same kind of database connection `lancedb.connect()` does. +In Python, `connect_catalog` and `connect_catalog_async` accept the same +connection settings as their database counterparts. Use `host_override` to +share settings that include a `db://` URI; the catalog connection targets +the root of that deployment and ignores the database name. An explicitly +supplied `region` is ignored with a warning, since the HTTP(S) endpoint +selects the deployment. Embedded-only session and namespace settings are +unsupported. + +```python +settings = { + "uri": "db://analytics", + "api_key": "secret", + "host_override": "https://my-server.example", +} +db = lancedb.connect(**settings) +catalog = lancedb.connect_catalog(**settings) +``` + This connection is for database administration, not table or query work: list, create and drop databases through it, then switch to a **database** connection for everything else -- tables, queries, and SQL all run within a diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 521cc46bb..11798a520 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1227,6 +1227,7 @@ async def connect_catalog( sql_host_override: Optional[str] = None, read_consistency_interval: Optional[float] = None, oauth_config: Optional[Any] = None, + storage_options: Optional[dict[str, str]] = None, ) -> Catalog: ... class NameListing: diff --git a/python/python/lancedb/catalog.py b/python/python/lancedb/catalog.py index 338be98b8..5b3b0509c 100644 --- a/python/python/lancedb/catalog.py +++ b/python/python/lancedb/catalog.py @@ -3,13 +3,17 @@ """Remote catalogs manage databases.""" -from functools import cached_property +import os +import warnings +from concurrent.futures import ThreadPoolExecutor from datetime import timedelta +from functools import cached_property from typing import Any, AsyncIterator, Iterator, Optional, Union from . import _lancedb from .background_loop import LOOP from .authz import AsyncAuthorization, Authorization +from .common import URI, sanitize_uri from .db import AsyncConnection, DBConnection from .remote import ClientConfig, OAuthConfig from .remote.db import RemoteDBConnection @@ -163,12 +167,14 @@ class Catalog: client_config=None, sql_host_override: Optional[str] = None, oauth_config: Optional[OAuthConfig] = None, + storage_options: Optional[dict[str, str]] = None, ): self._inner = inner self._api_key = api_key self._client_config = client_config self._sql_host_override = sql_host_override self._oauth_config = oauth_config + self._storage_options = storage_options @cached_property def authz(self) -> Authorization: @@ -198,6 +204,7 @@ class Catalog: self._client_config, self._oauth_config, self._sql_host_override, + self._storage_options, ) def list_databases( @@ -227,28 +234,71 @@ class Catalog: async def connect_catalog_async( - endpoint: str, + uri: Optional[URI] = None, *, api_key: Optional[str] = None, - client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + region: Optional[str] = None, + host_override: Optional[str] = None, sql_host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, + client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + storage_options: Optional[dict[str, str]] = None, + session: Optional[_lancedb.Session] = None, + manifest_enabled: bool = False, + namespace_client_properties: Optional[dict[str, str]] = None, oauth_config: Optional[OAuthConfig] = None, ) -> AsyncCatalog: - """Connect to an HTTP(S) server's root catalog. + """Connect to a server's root catalog using database connection settings. + + ``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise + ``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with + [connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's + database is ignored and requests target the root catalog. + + ``region`` is ignored with a warning when supplied. Catalog connections use + the explicit endpoint rather than a region-derived Cloud (legacy) endpoint. + ``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable. + Embedded-only ``session``, ``manifest_enabled`` and + ``namespace_client_properties`` are not supported. Root requests omit database-selection headers. API key, client configuration, - OAuth, and table read consistency settings are inherited by opened databases. + OAuth, storage options, and table read consistency settings are inherited by + opened databases. Database names containing slashes remain single logical names. Set ``sql_host_override`` to the SQL service endpoint to execute SQL through returned connections when the catalog endpoint uses HTTPS. """ + if region is not None: + warnings.warn( + "region is ignored by connect_catalog_async; the catalog endpoint " + "is selected by host_override or uri.", + UserWarning, + stacklevel=2, + ) + for name, value in ( + ("session", session), + ("manifest_enabled", manifest_enabled or None), + ("namespace_client_properties", namespace_client_properties), + ): + if value is not None: + raise NotImplementedError( + f"{name} is not supported for catalog connections" + ) + endpoint = host_override if host_override is not None else uri + if endpoint is None: + raise ValueError("uri or host_override is required for catalog connections") if isinstance(client_config, dict): client_config = ClientConfig(**client_config) if client_config is None: client_config = ClientConfig() + if ( + api_key is None + and oauth_config is None + and client_config.header_provider is None + ): + api_key = os.environ.get("LANCEDB_API_KEY") inner = await _lancedb.connect_catalog( - endpoint, + sanitize_uri(endpoint), api_key=api_key, client_config=client_config, sql_host_override=sql_host_override, @@ -258,32 +308,115 @@ async def connect_catalog_async( else None ), oauth_config=oauth_config, + storage_options=storage_options, ) return AsyncCatalog(inner) def connect_catalog( - endpoint: str, + uri: Optional[URI] = None, *, api_key: Optional[str] = None, - client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + region: Optional[str] = None, + host_override: Optional[str] = None, sql_host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, + request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None, + client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + storage_options: Optional[dict[str, str]] = None, + session: Optional[_lancedb.Session] = None, + manifest_enabled: bool = False, + namespace_client_impl: Optional[str] = None, + namespace_client_properties: Optional[dict[str, str]] = None, + namespace_client_pushdown_operations: Optional[list[str]] = None, oauth_config: Optional[OAuthConfig] = None, + **kwargs: Any, ) -> Catalog: - """Connect synchronously to an HTTP(S) server's root catalog. + """Connect synchronously to a root catalog using database connection settings. See [connect_catalog_async][lancedb.connect_catalog_async] for options. + The inputs match [connect][lancedb.connect]; ``region`` is ignored with a + warning when supplied. Namespace client options and embedded session settings + are not supported. ``request_thread_pool`` is deprecated and unused, as in + ``connect``. Local filesystem and object-store catalogs are not supported. + + Examples + -------- + ```python + settings = {"api_key": "secret", "host_override": "https://my-server.example"} + catalog = lancedb.connect_catalog("db://analytics", **settings) + db = lancedb.connect("db://analytics", **settings) + ``` """ + unknown_kwargs = { + key: value + for key, value in kwargs.items() + if key not in ("connection_timeout", "read_timeout") + } + if unknown_kwargs: + raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}") + for name, value in ( + ("namespace_client_impl", namespace_client_impl), + ("namespace_client_pushdown_operations", namespace_client_pushdown_operations), + ): + if value is not None: + raise NotImplementedError( + f"{name} is not supported for catalog connections" + ) + if region is not None: + warnings.warn( + "region is ignored by connect_catalog; the catalog endpoint " + "is selected by host_override or uri.", + UserWarning, + stacklevel=2, + ) + if request_thread_pool is not None: + warnings.warn( + "request_thread_pool is no longer used and will be removed in " + "a future release.", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(client_config, dict): + client_config = ClientConfig(**client_config) + if client_config is None: + client_config = ClientConfig() + for name, field in ( + ("connection_timeout", "connect_timeout"), + ("read_timeout", "read_timeout"), + ): + if kwargs.get(name) is not None: + warnings.warn( + f"{name} is deprecated and will be removed in a future release. " + f"Please use client_config.timeout_config.{field} instead.", + DeprecationWarning, + stacklevel=2, + ) + setattr( + client_config.timeout_config, + field, + timedelta(seconds=kwargs[name]), + ) + if ( + api_key is None + and oauth_config is None + and client_config.header_provider is None + ): + api_key = os.environ.get("LANCEDB_API_KEY") return Catalog( LOOP.run( connect_catalog_async( - endpoint, + uri, api_key=api_key, + host_override=host_override, client_config=client_config, sql_host_override=sql_host_override, read_consistency_interval=read_consistency_interval, + storage_options=storage_options, + session=session, + manifest_enabled=manifest_enabled, + namespace_client_properties=namespace_client_properties, oauth_config=oauth_config, ) ), @@ -291,4 +424,5 @@ def connect_catalog( client_config=client_config, sql_host_override=sql_host_override, oauth_config=oauth_config, + storage_options=storage_options, ) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 21ad37b36..4219ca40b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -214,6 +214,7 @@ class RemoteDBConnection(DBConnection): client_config, oauth_config, sql_host_override, + storage_options, ): config = ( ClientConfig(**client_config) @@ -233,7 +234,7 @@ class RemoteDBConnection(DBConnection): result.region = "us-east-1" result.host_override = endpoint result.sql_host_override = sql_host_override - result.storage_options = None + result.storage_options = storage_options result.client_config = replace(config, extra_headers=headers) result._catalog_oauth = oauth_config is not None result._conn = inner diff --git a/python/python/tests/test_catalog.py b/python/python/tests/test_catalog.py index 95b03c6e7..edac21bc1 100644 --- a/python/python/tests/test_catalog.py +++ b/python/python/tests/test_catalog.py @@ -2,7 +2,9 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from datetime import timedelta import json +import warnings import pytest @@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): endpoint, api_key="secret", sql_host_override="invalid://localhost", + storage_options={"azure_storage_account_name": "catalog-account"}, client_config={ "extra_headers": { "X-LanceDB-Database": "wrong", @@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): assert db.table_names() == [] restored = lancedb.deserialize_conn(db.serialize()) assert restored.sql_host_override == "invalid://localhost" + assert restored.storage_options == {"azure_storage_account_name": "catalog-account"} for connection in (db, restored): with pytest.raises(ValueError, match="sql_host_override must use"): connection.execute_query_async("SELECT 1") @@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): ) assert "x-lancedb-database-prefix" not in headers assert headers["x-api-key"] == "secret" + assert headers["x-azure-storage-account-name"] == "catalog-account" @pytest.mark.asyncio @@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server): ] ) catalog = await lancedb.connect_catalog_async( - endpoint, sql_host_override="invalid://localhost" + endpoint, + sql_host_override="invalid://localhost", + storage_options={"account_name": "async-account"}, ) assert isinstance(catalog, lancedb.AsyncCatalog) db = await catalog.connect_database("analytics") @@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server): await catalog.drop_database("full") await catalog.drop_database("missing", ignore_missing=True) assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"} + for _, headers, _ in requests: + headers = {key.lower(): value for key, value in headers.items()} + assert headers["x-azure-storage-account-name"] == "async-account" @pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"]) @@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint): lancedb.connect_catalog(endpoint) +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"]) +@pytest.mark.asyncio +async def test_catalog_accepts_database_connection_settings( + catalog_server, asynchronous, region +): + endpoint, requests, responses = catalog_server + responses.extend([(200, {"namespaces": []}), (200, {"tables": []})]) + settings = { + "uri": "db://analytics", + "api_key": "shared-secret", + "region": region, + "host_override": endpoint, + "sql_host_override": "invalid://localhost", + "read_consistency_interval": timedelta(seconds=5), + "client_config": {"extra_headers": {"x-shared-setting": "shared"}}, + "storage_options": {"azure_storage_account_name": "shared-account"}, + "session": None, + "manifest_enabled": False, + "namespace_client_properties": None, + } + if not asynchronous: + settings.update( + request_thread_pool=None, + namespace_client_impl=None, + namespace_client_pushdown_operations=None, + ) + with pytest.warns( + UserWarning, match="region is ignored by connect_catalog" + ) as caught: + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert len(caught) == 1 + assert catalog.uri == endpoint + assert ( + [name async for name in catalog.list_databases()] + if asynchronous + else list(catalog.list_databases()) + ) == [] + db = ( + await lancedb.connect_async(**settings) + if asynchronous + else lancedb.connect(**settings) + ) + assert (await db.table_names() if asynchronous else db.table_names()) == [] + root_headers = {key.lower(): value for key, value in requests[0][1].items()} + db_headers = {key.lower(): value for key, value in requests[1][1].items()} + for headers in (root_headers, db_headers): + assert headers["x-api-key"] == "shared-secret" + assert headers["x-shared-setting"] == "shared" + assert headers["x-azure-storage-account-name"] == "shared-account" + assert "x-lancedb-database" not in root_headers + assert db_headers["x-lancedb-database"] == "analytics" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("host_only", [False, True]) +@pytest.mark.asyncio +async def test_catalog_default_region_is_silent_and_api_key_uses_environment( + catalog_server, monkeypatch, asynchronous, host_only +): + endpoint, requests, responses = catalog_server + monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret") + responses.extend([(200, {}), (200, {"tables": []})]) + settings = {"host_override": endpoint} if host_only else {"uri": endpoint} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert caught == [] + assert catalog.uri == endpoint + db = ( + await catalog.connect_database("analytics") + if asynchronous + else catalog.connect_database("analytics") + ) + if not asynchronous: + db = lancedb.deserialize_conn(db.serialize()) + assert (await db.table_names() if asynchronous else db.table_names()) == [] + for _, headers, _ in requests: + headers = {key.lower(): value for key, value in headers.items()} + assert headers["x-api-key"] == "environment-secret" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.asyncio +async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous): + endpoint, _, _ = catalog_server + settings = {"uri": "https://unused.example", "host_override": endpoint} + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert catalog.uri == endpoint + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "options, message", + [ + ({}, "uri or host_override is required"), + ({"session": object()}, "session"), + ({"manifest_enabled": True}, "manifest_enabled"), + ({"namespace_client_properties": {}}, "namespace_client_properties"), + ], +) +@pytest.mark.asyncio +async def test_catalog_rejects_unsupported_connection_settings( + catalog_server, asynchronous, options, message +): + _, requests, _ = catalog_server + error = NotImplementedError if options else ValueError + with pytest.raises(error, match=message): + if asynchronous: + await lancedb.connect_catalog_async(**options) + else: + lancedb.connect_catalog(**options) + assert requests == [] + + +@pytest.mark.parametrize( + "options, error, message", + [ + ( + {"namespace_client_impl": "dir"}, + NotImplementedError, + "namespace_client_impl", + ), + ( + {"namespace_client_pushdown_operations": []}, + NotImplementedError, + "namespace_client_pushdown_operations", + ), + ({"unknown_option": True}, ValueError, "Unknown keyword arguments"), + ], +) +def test_catalog_rejects_unsupported_sync_settings(options, error, message): + with pytest.raises(error, match=message): + lancedb.connect_catalog(**options) + + +def test_catalog_accepts_deprecated_sync_settings(catalog_server): + endpoint, _, responses = catalog_server + responses.append((200, {})) + with pytest.warns(DeprecationWarning) as caught: + catalog = lancedb.connect_catalog( + endpoint, + request_thread_pool=2, + connection_timeout=5, + read_timeout=10, + ) + assert len(caught) == 3 + db = catalog.connect_database("analytics") + assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5) + assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10) + + @pytest.mark.parametrize("asynchronous", [False, True]) @pytest.mark.asyncio @pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)]) diff --git a/python/python/type_tests/connect.py b/python/python/type_tests/connect.py index eb2cba37c..6da32d2ec 100644 --- a/python/python/type_tests/connect.py +++ b/python/python/type_tests/connect.py @@ -4,12 +4,30 @@ from typing import assert_type import lancedb -from lancedb import AsyncConnection, DBConnection +from lancedb import AsyncCatalog, AsyncConnection, Catalog, DBConnection def check_connect_type() -> None: assert_type(lancedb.connect("memory://"), DBConnection) + assert_type( + lancedb.connect_catalog( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + Catalog, + ) async def check_connect_async_type() -> None: assert_type(await lancedb.connect_async("memory://"), AsyncConnection) + assert_type( + await lancedb.connect_catalog_async( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + AsyncCatalog, + ) diff --git a/python/src/catalog.rs b/python/src/catalog.rs index fb2e7e8a0..456d62a3c 100644 --- a/python/src/catalog.rs +++ b/python/src/catalog.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -127,7 +128,8 @@ impl DatabaseNames { } #[pyfunction] -#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None))] +#[allow(clippy::too_many_arguments)] +#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None, storage_options=None))] pub fn connect_catalog( py: Python<'_>, endpoint: String, @@ -136,6 +138,7 @@ pub fn connect_catalog( sql_host_override: Option, read_consistency_interval: Option, oauth_config: Option, + storage_options: Option>, ) -> PyResult> { let interval = read_consistency_interval .map(Duration::try_from_secs_f64) @@ -151,6 +154,9 @@ pub fn connect_catalog( if let Some(config) = client_config { builder = builder.client_config(config.into()); } + if let Some(options) = storage_options { + builder = builder.storage_options(options); + } if let Some(endpoint) = sql_host_override { builder = builder.sql_host_override(endpoint); } diff --git a/rust/lancedb/src/catalog.rs b/rust/lancedb/src/catalog.rs index df80b6de6..dcea8fd90 100644 --- a/rust/lancedb/src/catalog.rs +++ b/rust/lancedb/src/catalog.rs @@ -349,6 +349,18 @@ impl ConnectCatalogBuilder { self.options.client_config = config; self } + /// Set storage options inherited by the catalog's remote database connections. + pub fn storage_options( + mut self, + options: impl IntoIterator, impl Into)>, + ) -> Self { + self.options.storage_options.extend( + options + .into_iter() + .map(|(key, value)| (key.into(), value.into())), + ); + self + } /// Set the SQL service endpoint inherited by database connections. /// /// Required to execute SQL when the catalog endpoint uses HTTPS. The SQL diff --git a/rust/lancedb/src/remote/catalog.rs b/rust/lancedb/src/remote/catalog.rs index 95facd04b..c620cf272 100644 --- a/rust/lancedb/src/remote/catalog.rs +++ b/rust/lancedb/src/remote/catalog.rs @@ -30,6 +30,8 @@ pub struct RemoteCatalogOptions { pub api_key: Option, /// Shared transport and authentication settings. pub client_config: ClientConfig, + /// Storage options supported by remote database connections. + pub storage_options: HashMap, /// SQL service endpoint used by returned database connections. /// Required for SQL when the catalog endpoint uses HTTPS. pub sql_host_override: Option, @@ -391,6 +393,10 @@ mod tests { .await; let mut options = RemoteCatalogOptions { api_key: Some("test-key".into()), + storage_options: HashMap::from([( + "azure_storage_account_name".into(), + "catalog-account".into(), + )]), ..Default::default() }; options.client_config.extra_headers = HashMap::from([ @@ -460,6 +466,10 @@ mod tests { ); assert!(!request.headers.contains_key("x-lancedb-database-prefix")); assert_eq!(request.headers["authorization"], "Bearer refreshed"); + assert_eq!( + request.headers["x-azure-storage-account-name"], + "catalog-account" + ); } assert_eq!( requests[0].line, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a9d55b511..549baf345 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -385,7 +385,7 @@ impl RemoteDatabase { sql: options.sql_host_override.clone(), }, config, - RemoteOptions::default(), + StorageOptions(options.storage_options.clone()).into(), options.read_consistency_interval, super::client::ParsedDbUrl { db_name: name.unwrap_or("").to_string(), From ced4799ad51f7ee4dd4bdff40c061ef59d8bb014 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 01:21:58 -0800 Subject: [PATCH 17/75] fix(python): preserve typed results for reopened refresh jobs (#4981) Restore typed results for reopened Function and SQL-expression refresh jobs while preserving their handles and cached descriptions. Fixes https://linear.app/lancedb/issue/ENT-3441. --- python/python/lancedb/db.py | 10 +- python/python/lancedb/job.py | 7 ++ python/python/tests/test_remote_db.py | 138 ++++++++++++++++++++++++++ python/src/connection.rs | 11 +- rust/lancedb/src/job.rs | 51 ++++++++++ rust/lancedb/src/remote/job.rs | 23 +++++ 6 files changed, 236 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 84ebb41a1..e2138520a 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -67,7 +67,7 @@ from .graph import ( PropertyGraph, _definition_json, ) -from .job import AsyncJob, Job, _typed_job +from .job import AsyncJob, Job, _opened_job, _typed_job from .storage_integration import SecretReference, StorageIntegrationInfo from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery @@ -1450,6 +1450,12 @@ class DBConnection(EnforceOverrides): specification, result, failure and event history, so there is no separate connection-level call for any of them. + For a column refresh, ``wait()`` returns a + [RefreshColumnResult][lancedb.functions.RefreshColumnResult], including + when the refresh was started through SQL. Other job types return + ``None`` from ``wait()``; their persisted result is available through + ``job.result`` after ``job.refresh()``. + Raises `JobNotFoundError` when the server has no such job, the way `open_table` does for a missing table. """ @@ -3626,7 +3632,7 @@ class AsyncConnection(object): """Open a server-side job by id. See [DBConnection.open_job][lancedb.db.DBConnection.open_job]. """ - return AsyncJob(await self._inner.open_job(job_id)) + return _opened_job(await self._inner.open_job(job_id)) async def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 094a7b8d5..bf9605567 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -17,6 +17,7 @@ from lancedb.background_loop import LOOP from . import _lancedb from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url +from .functions import RefreshColumnResult from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -692,3 +693,9 @@ def _typed_job( ) -> AsyncJob[T]: """Bind an internal JSON-producing job to its public result model.""" return AsyncJob(inner, result_decoder) + + +def _opened_job(inner: "_lancedb.Job") -> AsyncJob: + if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"): + return _typed_job(inner, RefreshColumnResult.from_json) + return AsyncJob(inner) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b0098aca3..8fde1209c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2557,6 +2557,144 @@ async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync): assert exc.value.__cause__.is_transport_error is True +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize( + "job_type", ["function_refresh", "computed_refresh", "refresh_column"] +) +@pytest.mark.parametrize("running", [False, True]) +@pytest.mark.parametrize("rows_failed", [0, 8]) +async def test_reopened_refresh_job_wait_returns_typed_result( + sync, job_type, running, rows_failed +): + terminal_result = { + "rows_assigned": 400 - rows_failed, + "rows_failed": rows_failed, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + "summary": {"future_field": True}, + } + polls = 0 + + def handler(request): + nonlocal polls + assert request.path == "/v1/jobs/describe" + payload = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert payload == {"job_id": "refresh-1"} + polls += 1 + in_progress = running and polls <= 2 + response = { + "job_id": "refresh-1", + "job_type": job_type, + "job_state": "IN_PROGRESS" if in_progress else "DONE", + "creation_ms": 1000, + "spec": {"column": "derived"}, + } + if not in_progress: + response["result"] = terminal_result + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + observed = [] + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + assert job.id == "refresh-1" + assert job.spec == {"column": "derived"} + result = job.wait(timeout=timedelta(seconds=5), progress=observed.append) + assert job.wait() == result + job.refresh() + assert job.result == terminal_result + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + assert job.id == "refresh-1" + assert job.spec == {"column": "derived"} + result = await job.wait( + timeout=timedelta(seconds=5), progress=observed.append + ) + assert await job.wait() == result + await job.refresh() + assert job.result == terminal_result + + assert isinstance(result, lancedb.RefreshColumnResult) + assert result == lancedb.RefreshColumnResult.model_validate(terminal_result) + assert result.rows_failed == rows_failed + assert observed[-1]["state"] == "finished" + if running: + assert observed[0]["state"] == "running" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("terminal_result", [None, {}]) +async def test_reopened_refresh_job_rejects_missing_or_invalid_result( + sync, terminal_result +): + def handler(request): + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + with pytest.raises(HttpError, match="typed job"): + job.wait() + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + with pytest.raises(HttpError, match="typed job"): + await job.wait() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_reopened_unit_job_ignores_additive_result_payload(sync): + terminal_result = {"future_field": True} + + def handler(request): + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "index-1", + "job_type": "create_index", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("index-1") + assert job.wait() is None + assert job.result == terminal_result + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("index-1") + assert await job.wait() is None + assert job.result == terminal_result + + @pytest.mark.parametrize("payload", [b"{", b"{}"]) def test_remote_job_wait_does_not_retry_malformed_description(payload): polls = 0 diff --git a/python/src/connection.rs b/python/src/connection.rs index 0be933cf2..69cf54c99 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -24,7 +24,7 @@ use lancedb::{ connection::NamespaceClientPushdownOperation, database::namespace::LanceNamespaceDatabase, database::{CreateTableMode, Database, ReadConsistency}, - function::GpuClass as LanceGpuClass, + function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, }; use pyo3::{ @@ -854,7 +854,14 @@ impl Connection { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let job = inner.open_job(&job_id).await.infer_error()?; - Ok(crate::job::Job::new(job)) + match job.job_type().as_deref() { + Some("function_refresh" | "computed_refresh" | "refresh_column") => { + Ok(crate::job::Job::new_typed( + job.into_typed::().infer_error()?, + )) + } + _ => Ok(crate::job::Job::new(job)), + } }) } diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index d178542b7..092ece8b5 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -277,6 +277,42 @@ impl Job<()> { } job } + + /// Decode this job's terminal payload as `T` when waiting. + /// + /// Use this after [`crate::Connection::open_job`] when the job's result + /// type is known. The job identity and cached description are preserved. + /// Missing or incompatible payloads are reported by [`Job::wait`]. + /// A job that completed before its handle was created has only a unit + /// result; converting it fails immediately if `T` cannot decode JSON null. + /// + /// ```no_run + /// # async fn reopen( + /// # db: &lancedb::Connection, id: &str, + /// # ) -> lancedb::Result { + /// let job = db.open_job(id).await? + /// .into_typed::()?; + /// job.wait().await + /// # } + /// ``` + pub fn into_typed(self) -> Result> + where + T: Clone + DeserializeOwned + Send + Sync + 'static, + { + let inner = match self.inner { + JobInner::Handle { handle, .. } => JobInner::Handle { + handle, + decode: Arc::new(TerminalResult::decode::), + }, + JobInner::Completed(()) => { + JobInner::Completed(TerminalResult::local(Value::Null).decode::()?) + } + }; + Ok(Job { + inner, + cache: self.cache, + }) + } } impl Job @@ -750,6 +786,21 @@ mod tests { )); } + #[tokio::test] + async fn completed_unit_job_can_be_retyped_as_unit() { + let job = Job::new_done().into_typed::<()>().unwrap(); + job.wait().await.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + } + + #[test] + fn completed_unit_job_rejects_an_incompatible_result_type() { + assert!(matches!( + Job::new_done().into_typed::(), + Err(Error::Runtime { .. }) + )); + } + #[tokio::test] async fn mapped_spawned_job_reuses_outcome() { let job = Job::spawned(tokio::spawn(async { Ok(41_u64) })).map(|value| value + 1); diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index d27c9c666..5a0afa7e8 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -403,6 +403,29 @@ mod tests { ); } + #[tokio::test] + async fn reopened_job_preserves_its_description_and_decodes_the_terminal_result() { + let description: DescribeJobResponse = serde_json::from_str(REFRESH_JOB).unwrap(); + let job = Job::opened( + Box::new(FixtureRemoteJob(REFRESH_JOB)), + description.into_description(), + ); + let raw_result = job.result(); + let job = job.into_typed::().unwrap(); + + assert_eq!(job.job_type().as_deref(), Some("refresh_function_columns")); + assert_eq!(job.state().as_deref(), Some("finished")); + assert_eq!(job.creation_ms(), Some(1787270400001)); + assert_eq!(job.result(), raw_result); + assert_eq!(job.wait().await.unwrap().rows_assigned, 999_998_800); + assert_eq!(job.wait().await.unwrap().published_version, Some(919)); + + let missing = Job::new(Box::new(FixtureRemoteJob(MISSING_RESULT_JOB))) + .into_typed::() + .unwrap(); + assert!(missing.wait().await.is_err()); + } + /// Five in-progress polls then done: 0.2 + 0.4 + 0.8 + 1 + 1 s of waiting. /// Under the old 5 s cap the same job would have waited 10 s. #[tokio::test(start_paused = true)] From 9e03bf97d400572e38d265f5c59acd990c4d818a Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 08:03:11 -0800 Subject: [PATCH 18/75] feat(python): support exist_ok when creating secrets (#4978) Add `exist_ok=False` to synchronous and asynchronous Python `create_secret`. Passing `True` uses `CREATE SECRET IF NOT EXISTS`, preserving an existing credential. The default continues to fail on an existing name; rotation stays explicit through `alter_secret`. ```python db.create_secret("api-key", value, exist_ok=True) await async_db.create_secret("api-key", value, exist_ok=True) ``` The Rust API gains an awaitable builder with `.exist_ok(true)` while existing `create_secret(...).await` calls keep working. Includes Python SQL round-trip coverage and Rust coverage for direct and deferred SQL responses. --- python/python/lancedb/_lancedb.pyi | 7 ++- python/python/lancedb/db.py | 48 ++++++++++++--- python/python/lancedb/remote/db.py | 13 ++++- python/python/tests/test_sql.py | 50 ++++++++++++++++ python/src/connection.rs | 4 +- rust/lancedb/src/connection.rs | 29 +++++++--- rust/lancedb/src/connection/create_secret.rs | 61 ++++++++++++++++++++ rust/lancedb/src/database.rs | 5 +- rust/lancedb/src/remote/db.rs | 12 +++- rust/lancedb/src/remote/sql.rs | 1 + rust/lancedb/src/remote/sql/secret.rs | 29 +++++++--- rust/lancedb/src/remote/sql_test.rs | 48 +++++++++++++-- 12 files changed, 269 insertions(+), 38 deletions(-) create mode 100644 rust/lancedb/src/connection/create_secret.rs diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 11798a520..a64014cb7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -228,7 +228,12 @@ class Connection(object): self, name: str, namespace_path: Optional[List[str]] = None ) -> None: ... async def create_secret( - self, name: str, value: str, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> None: ... async def alter_secret( self, name: str, value: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index e2138520a..59fa5b4c6 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1158,14 +1158,24 @@ class DBConnection(EnforceOverrides): ) def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: """Create a named Secret in this database. - Fails if the name is taken, so a create never silently becomes a - rotation. Nothing reads the value back: it is bound to a Function by + Fails if the name is taken unless ``exist_ok=True``, which leaves the + existing value unchanged. Use :meth:`alter_secret` to rotate a Secret. + Nothing reads the value back: it is bound to a Function by name and resolved by the service when that Function runs. Local connections raise ``NotImplementedError``. + + Examples + -------- + >>> db.create_secret("api-key", "credential", exist_ok=True) # doctest: +SKIP """ raise NotImplementedError( _append_doc_url( @@ -2492,9 +2502,18 @@ class LanceDBConnection(DBConnection): @override def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: - LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path)) + LOOP.run( + self._conn.create_secret( + name, value, exist_ok=exist_ok, namespace_path=namespace_path + ) + ) @override def alter_secret( @@ -3949,17 +3968,30 @@ class AsyncConnection(object): ) async def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: """Create a named Secret in this database. - Fails if the name is taken, so a create never silently becomes a - rotation. Nothing reads the value back. + Fails if the name is taken unless ``exist_ok=True``, which leaves the + existing value unchanged. Use :meth:`alter_secret` to rotate a Secret. + Nothing reads the value back. + + Examples + -------- + >>> await db.create_secret( # doctest: +SKIP + ... "api-key", "credential", exist_ok=True + ... ) """ await self._inner.create_secret( validate_secret_name(name), value, list(validate_namespace_path(namespace_path)), + exist_ok=exist_ok, ) async def alter_secret( diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 4219ca40b..a06af5d62 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1129,9 +1129,18 @@ class RemoteDBConnection(DBConnection): @override def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: - LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path)) + LOOP.run( + self._conn.create_secret( + name, value, exist_ok=exist_ok, namespace_path=namespace_path + ) + ) @override def alter_secret( diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index b4c555635..a479fa5d1 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -293,6 +293,56 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent(): assert echoed.column("k").to_pylist() == [10] +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "status"), + [ + (None, "created"), + (False, "created"), + (True, "created"), + (True, "already_exists"), + ], +) +async def test_create_secret_exist_ok_reaches_sql(asynchronous, exist_ok, status): + flight = pytest.importorskip("pyarrow.flight") + + class SecretServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.writes = [] + + def do_exchange(self, context, descriptor, reader, writer): + self.writes.append((descriptor.command, reader.read_all())) + result = pa.table({"status": [status]}) + writer.begin(result.schema) + writer.write_table(result) + writer.close() + + with SecretServer() as server: + options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {"namespace_path": ["team", "production"]} + if exist_ok is not None: + kwargs["exist_ok"] = exist_ok + if asynchronous: + db = await lancedb.connect_async("db://analytics", **options) + await db.create_secret("api-key", "credential's value", **kwargs) + else: + db = lancedb.connect("db://analytics", **options) + db.create_secret("api-key", "credential's value", **kwargs) + ((command, parameters),) = server.writes + + prefix = "CREATE SECRET IF NOT EXISTS" if exist_ok else "CREATE SECRET" + sql = f'{prefix} "api-key" TYPE = GENERIC_STRING SECRET_STRING = $1' + assert sql.encode() in command + assert b"credential's value" not in command + assert parameters.column(0).to_pylist() == ["credential's value"] + + @pytest.mark.parametrize("job_id", [None, "sql-job-1"]) def test_sql_input_error_metadata_crosses_native_boundary(job_id): flight = pytest.importorskip("pyarrow.flight") diff --git a/python/src/connection.rs b/python/src/connection.rs index 69cf54c99..1a99c1372 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1036,18 +1036,20 @@ impl Connection { }) } - #[pyo3(signature = (name, value, namespace_path=None))] + #[pyo3(signature = (name, value, namespace_path=None, *, exist_ok=false))] pub fn create_secret( self_: PyRef<'_, Self>, name: String, value: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner .create_secret(name, value, &namespace_path) + .exist_ok(exist_ok) .await .infer_error() }) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index a360818b5..fa35dc459 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -51,8 +51,11 @@ pub use lance_file::version::LanceFileVersion; use lance_io::object_store::StorageOptions; use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; +mod create_secret; mod create_table; +pub use create_secret::CreateSecretBuilder; + pub(crate) fn merge_storage_options( store_params: &mut ObjectStoreParams, pairs: impl IntoIterator, @@ -853,20 +856,30 @@ impl Connection { /// Create a named Secret in this database. /// - /// Fails if the name is taken, so a create can never silently become a - /// rotation. There is no API that reads a stored credential back; the only + /// Fails if the name is taken unless [`CreateSecretBuilder::exist_ok`] is true, + /// in which case the existing value is left unchanged. There is no API that + /// reads a stored credential back; the only /// consumer is a Function that binds the Secret by name. LanceDB Embedded databases /// return [`Error::NotSupported`]. - pub async fn create_secret( + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// connection.create_secret("api-key", "credential", &[]).exist_ok(true).await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_secret( &self, name: impl AsRef, value: impl AsRef, namespace_path: &[String], - ) -> Result<()> { - validate_secret_reference(name.as_ref(), namespace_path)?; - self.internal - .create_secret(name.as_ref(), value.as_ref(), namespace_path) - .await + ) -> CreateSecretBuilder { + CreateSecretBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + value.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// Replace the credential behind an existing Secret. diff --git a/rust/lancedb/src/connection/create_secret.rs b/rust/lancedb/src/connection/create_secret.rs new file mode 100644 index 000000000..265b97571 --- /dev/null +++ b/rust/lancedb/src/connection/create_secret.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_secret_reference; + +/// Configure creation of a named Secret with [`super::Connection::create_secret`]. +#[must_use] +pub struct CreateSecretBuilder { + database: Arc, + name: String, + value: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateSecretBuilder { + pub(super) fn new( + database: Arc, + name: String, + value: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + value, + namespace_path, + exist_ok: false, + } + } + + /// Succeed without changing the stored value when the Secret already exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the Secret, preserving any existing value when `exist_ok` is true. + pub async fn execute(self) -> Result<()> { + validate_secret_reference(&self.name, &self.namespace_path)?; + self.database + .create_secret(&self.name, &self.value, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateSecretBuilder { + type Output = Result<()>; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index bcdfd94b8..7b4859faa 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -635,13 +635,14 @@ pub trait Database: secret_catalog_not_supported() } - /// Create a named Secret in this database. Fails if the name is taken, so - /// a create can never silently become a rotation. + /// Create a named Secret in this database. If the name is taken, fail unless + /// `exist_ok` is true, in which case the stored value is left unchanged. async fn create_secret( &self, _name: &str, _value: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result<()> { secret_catalog_not_supported() } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 549baf345..31808f244 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -44,8 +44,8 @@ use super::client::{ ClientConfig, HeaderProvider, HttpSend, ID_DELIMITER, RequestResultExt, RestfulLanceDbClient, Sender, }; -use super::sql::SqlClient; use super::sql::materialized_view::quote_identifier; +use super::sql::{SecretWriteOperation, SqlClient}; use super::storage_integration as integration_sql; use super::table::RemoteTable; use super::util::parse_server_version; @@ -1044,11 +1044,17 @@ impl Database for RemoteDatabase { name: &str, value: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result<()> { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .write_secret(name, value, namespace_path, true) + .write_secret( + name, + value, + namespace_path, + SecretWriteOperation::Create { exist_ok }, + ) .await .map_err(direct_catalog_resource_error) } @@ -1056,7 +1062,7 @@ impl Database for RemoteDatabase { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .write_secret(name, value, namespace_path, false) + .write_secret(name, value, namespace_path, SecretWriteOperation::Alter) .await .map_err(direct_catalog_resource_error) } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 0b87ff5a5..949b078e3 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -40,6 +40,7 @@ mod function; pub(super) mod materialized_view; mod objects; mod secret; +pub(super) use secret::SecretWriteOperation; mod stream; mod view; diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index bdb70ef6f..6ddc78645 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -13,6 +13,12 @@ use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::TryStreamExt; use std::sync::Arc; + +pub(in crate::remote) enum SecretWriteOperation { + Create { exist_ok: bool }, + Alter, +} + fn secret_info(batches: Vec) -> Result { if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { return Err(Error::Runtime { @@ -47,10 +53,21 @@ impl SqlClient { name: &str, value: &str, namespace: &[String], - create: bool, + operation: SecretWriteOperation, ) -> Result<()> { validate_secret_name(name)?; validate_namespace(namespace)?; + let (prefix, assignment) = match operation { + SecretWriteOperation::Create { exist_ok } => ( + if exist_ok { + "CREATE SECRET IF NOT EXISTS" + } else { + "CREATE SECRET" + }, + "TYPE = GENERIC_STRING ", + ), + SecretWriteOperation::Alter => ("ALTER SECRET", "SET "), + }; let parameters = RecordBatch::try_from_iter(vec![( "", Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, @@ -61,14 +78,10 @@ impl SqlClient { self.object_job( ExecuteQueryRequest { query: format!( - "{} SECRET {} {}SECRET_STRING = $1", - if create { "CREATE" } else { "ALTER" }, + "{} {} {}SECRET_STRING = $1", + prefix, quote_identifier(name), - if create { - "TYPE = GENERIC_STRING " - } else { - "SET " - } + assignment ), default_namespace_path: namespace.to_vec(), parameters: Some(parameters), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index cfaf2a625..471966731 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3214,29 +3214,55 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { }; let exchanges = service.exchanges.clone(); let statements = service.statements.clone(); + let headers = service.headers.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|request| -> http::Response { panic!("unexpected REST request: {}", request.url().path()); }) .with_sql_client(client); - db.create_secret("api-key", "credential's value", &["team".into()]) + let connection = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + connection + .create_secret("api-key", "credential's value", &["team".into()]) .await .unwrap(); - db.alter_secret("api-key", "rotated-value", &["team".into()]) + connection + .create_secret("api-key", "ignored-value", &["team".into()]) + .exist_ok(true) + .await + .unwrap(); + connection + .alter_secret("api-key", "rotated-value", &["team".into()]) + .await + .unwrap(); + connection + .drop_secret("api-key", &["team".into()]) .await .unwrap(); - db.drop_secret("api-key", &["team".into()]).await.unwrap(); assert_eq!( statements.lock().unwrap().as_slice(), ["DROP SECRET IF EXISTS \"api-key\""] ); let seen = exchanges.lock().unwrap(); - assert_eq!(seen.len(), 2); + assert_eq!(seen.len(), 3); assert_eq!( seen[0].0, "CREATE SECRET \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" ); - assert_eq!(seen[1].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert_eq!( + seen[1].0, + "CREATE SECRET IF NOT EXISTS \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" + ); + assert_eq!(seen[2].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); assert_eq!( seen[0] .1 @@ -3259,6 +3285,18 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { .downcast_ref::() .unwrap() .value(0), + "ignored-value" + ); + assert_eq!( + seen[2] + .1 + .as_ref() + .unwrap() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), "rotated-value" ); shutdown.send(()).unwrap(); From a2a0d7f6322d64195243ff606de7924bcb08708b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:20:53 +0800 Subject: [PATCH 19/75] fix(ci): restore the unlocked Rust build cache once (#4997) `build-no-lock` restores Rust build outputs twice: toolchain setup enables its own cache by default before Cargo.lock removal, then the workflow restores an explicit cache afterward. Both restore into the same Cargo and target paths; the implicit action also allows PR cache saves. Disable only toolchain setup's implicit cache. The explicit restore remains after lock removal and retains its main-only save condition. This configuration is inherited unchanged by #4996. Its [failed job](https://github.com/lancedb/lancedb/actions/runs/43229196192/job/131220088196) reported runner ENOSPC while the second cache action was active, before dependency installation or Cargo. Earlier hosted logs confirm two restores into overlapping paths, but the failed job's full logs are unavailable, so the exact disk peak and ENOSPC cause remain unproven. A bounded probe using the resolved composite-action definitions verifies two restores before this change versus one afterward, preserves ordering and main-only saves, and confirms all other workflow configuration is unchanged. The [hosted run](https://github.com/lancedb/lancedb/actions/runs/43230840086/job/131225407007) confirms one successful 1.62 GB cache restore after lock removal and no PR cache save. It reached Cargo and linking without ENOSPC, but hit the inherited 30-minute deadline with the unchanged one-job driver. Free disk was 85 GiB before the build and 79 GiB at cancellation; these endpoint observations do not establish peak disk use or a general ENOSPC guarantee. The complementary two-job repair in #4996 now includes this prerequisite for combined hosted acceptance; this PR remains limited to cache ownership. --- .github/workflows/rust.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 9d28ac5e4..6d2bbf78d 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -154,6 +154,8 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: "stable" + # The explicit cache below runs after lock removal and only saves on main. + cache: false # Remove cargo.lock to force a fresh build - name: Remove Cargo.lock run: rm -f Cargo.lock From ec5e2cd621b605a5e362d81f7a13a449018b14e4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:21:31 +0800 Subject: [PATCH 20/75] ci: use two Cargo jobs for unlocked builds (#4996) Fresh unlocked workspace builds can exhaust the 30-minute CI job while Cargo is restricted to one compiler/linker task. Allow two concurrent tasks while retaining fresh dependency resolution, all workspace features and targets, the existing profile and timeout, and immediate cleanup of completed test executables. The single-cache prerequisite #4997 is included by a normal merge; merge it first under normal review gates. The final combined candidate passed hosted build-no-lock on head `8a3cda494f79a414101db392986cd18a64e5d80d` (tested merge `8d56029`, run [43236975778](https://github.com/lancedb/lancedb/actions/runs/43236975778/job/131247077833)). The build step took 18m42s and the full job 19m58s, within the unchanged 30-minute budget. Exactly one 1,624,797,998-byte cache restore completed; free disk samples before and after the build were 85 GiB and 79 GiB. These are endpoint samples, not peak RAM/disk measurements or a controlled speedup comparison. This job compiles and links targets but does not execute their tests. Temporary diagnostics are removed. The three existing driver tests pass, and the combined workflow and driver match their independently reviewed parents. --- ci/build_no_lock.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ci/build_no_lock.py b/ci/build_no_lock.py index 6ec156432..17d9ad333 100644 --- a/ci/build_no_lock.py +++ b/ci/build_no_lock.py @@ -54,6 +54,7 @@ def main() -> int: ["cargo", "metadata", "--format-version=1", "--no-deps", "--all-features"], stdout=subprocess.PIPE, text=True, + check=False, ) if metadata.returncode: return metadata.returncode @@ -68,7 +69,7 @@ def main() -> int: "--tests", # Bound simultaneous compiler/linker temporary outputs as well as retained files. "--jobs", - "1", + "2", "--message-format=json,json-diagnostic-rendered-ansi", ] cleanup_failed = False From b5623f88819120982731195b37f19b340eed1c02 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:22:21 +0800 Subject: [PATCH 21/75] ci: separate macOS Rust test phases (#4995) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit macOS doctests and library/integration tests currently share a 60-minute job budget. In #4967, compilation and doctests left only 3–4 minutes for an integration group that takes 6–7 minutes on the base revision, so the job was cancelled before it could finish. Run doctests and library/integration tests in separate matrix jobs on both macOS 15 and 26, each retaining the existing 60-minute limit. Preserve the library/integration check names, feature selection, locked dependencies and all existing coverage. This adds runner/build cost but removes the cumulative deadline coupling without reducing coverage. YAML parsing, shell syntax and matrix coverage checks pass. Hosted macOS execution and subsequent beta19 integration still need verification; this does not address the separate unlocked-build timeout. --- .github/workflows/rust.yml | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 6d2bbf78d..a5e5c9c30 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -297,10 +297,12 @@ jobs: run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests macos: + name: ${{ matrix.phase == 'tests' && format('macos ({0})', matrix.mac-runner) || format('macos-doc ({0})', matrix.mac-runner) }} timeout-minutes: 60 strategy: matrix: mac-runner: ["macos-15", "macos-26"] + phase: [tests, doc] runs-on: "${{ matrix.mac-runner }}" defaults: run: @@ -322,16 +324,17 @@ jobs: - name: Install dependencies run: brew install protobuf - name: Run tests + env: + CARGO_TEST_TARGETS: ${{ matrix.phase == 'doc' && '--doc' || '--lib --tests' }} run: | # Don't run the s3 integration tests since docker isn't available # on this image. ALL_FEATURES=`cargo metadata --format-version=1 --no-deps \ | jq -r '.packages[] | .features | keys | .[]' \ | grep -v s3-test | sort | uniq | paste -s -d "," -` - # Run doctests before test binaries fill the runner disk. Examples are - # already built by the Linux job, so avoid retaining them here. - cargo test --profile ci --features $ALL_FEATURES --locked --doc - cargo test --profile ci --features $ALL_FEATURES --locked --lib --tests + # Separate jobs give each phase its own time and disk budget. Examples + # are already built by the Linux job, so avoid retaining them here. + cargo test --profile ci --features $ALL_FEATURES --locked $CARGO_TEST_TARGETS windows: strategy: From b4d1c55f6228e9cf0a389fef07351aacfba09c01 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:22:35 +0800 Subject: [PATCH 22/75] test: isolate DynamoDB integration test databases (#4998) The concurrent-append and drop-all DynamoDB tests shared a database prefix. A timeout in the first could leave its table visible to the second. Give each test its own prefix while retaining five independent concurrent appends, the six-row assertion, and all drop/recreate checks. The final two-prefix diff passed both tests in hosted LocalStack across Node 22, 24, 26, and Node 24 experimental, without timing instrumentation ([run 43245851764](https://github.com/lancedb/lancedb/actions/runs/43245851764), head `5896c419`). Concurrency and the 5000 ms budget are unchanged. This fixes cascading fixture contamination; the original timeout remains unexplained, and these passing runs do not prove its root cause was fixed. --- nodejs/__test__/s3_integration.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nodejs/__test__/s3_integration.test.ts b/nodejs/__test__/s3_integration.test.ts index e4bc46806..35ce478a8 100644 --- a/nodejs/__test__/s3_integration.test.ts +++ b/nodejs/__test__/s3_integration.test.ts @@ -282,7 +282,7 @@ maybeDescribe("DynamoDB Lock", () => { }); it("can be used to configure a DynamoDB table for commit log", async () => { - const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`; + const uri = `s3+ddb://${bucket.name}/concurrent-appends?ddbTableName=${commitTable.name}`; const db = await connect(uri, { storageOptions: CONFIG, readConsistencyInterval: 0, @@ -307,7 +307,7 @@ maybeDescribe("DynamoDB Lock", () => { }); it("clears dynamodb state after dropping all tables", async () => { - const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`; + const uri = `s3+ddb://${bucket.name}/drop-all-tables?ddbTableName=${commitTable.name}`; const db = await connect(uri, { storageOptions: CONFIG, readConsistencyInterval: 0, From e61e21035c1f6f9b357510df5e88d0fa4c1be3f8 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 09:01:39 -0800 Subject: [PATCH 23/75] fix(python): explain Function namespace import restrictions (#4982) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plain `import ctypes.util` in a Function currently reports “dynamic namespace access” without explaining the module restriction or a way forward. Give blocked module imports a distinct error that names the modules, explains the reconstructed namespace constraint, and recommends an importable helper supplied through `code=`, `pip=`, or `conda=`. Dynamic namespace operations also get an actionable explanation. Document the full restrictions and the helper alternative in the decorator and Python Functions reference. Add regression coverage for direct imports, `from` imports, global module aliases, class Functions, the deprecated `@udf` alias, and helpers imported normally or shipped with `code=`. Existing import restrictions remain in place. For example, move `ctypes.util.find_library` into `native_diagnostics/__init__.py`, then use: ```python import native_diagnostics from lancedb import function @function(code=[native_diagnostics]) def probe_library(name: str) -> str: return native_diagnostics.find_library(name) ``` Fixes ENT-3408. --- docs/src/python/python.md | 45 +++++++ python/python/lancedb/functions.py | 63 ++++++--- .../tests/test_first_class_function_slice2.py | 7 +- .../python/tests/test_function_packaging.py | 120 ++++++++++++++++++ 4 files changed, 214 insertions(+), 21 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 8de5b5517..35f50c5a8 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -447,6 +447,51 @@ assert scaler(3.0) == 6.0 scaler.close() ``` +### Function packaging restrictions + +The decorator snapshots the Function's source and referenced globals into a new +module. It conservatively rejects imports of `sys`, `builtins`, `importlib`, +`inspect`, `gc`, `ctypes`, and `types`, including submodules such as `ctypes.util` +and `importlib.metadata`. This applies to imports inside function or class bodies +and references to module-level aliases. Even ordinary uses such as `sys.version` +and `ctypes.util.find_library` are blocked: these modules can reach names outside +the reconstructed Function namespace. References to `globals`, `locals`, `vars`, +`eval`, `exec`, `compile`, and `__import__` are rejected as dynamic namespace access. +These restrictions also apply to the deprecated `@udf` alias. + +For legitimate uses, move the code into an importable helper module and ship it +with `code=`, or install its package with `pip=` or `conda=`. Imported helpers keep +their own namespace; the packager does not scan their bodies. Helpers defined in +`__main__` are copied by source and have the same restrictions as the Function. + +For example, put this helper in `native_diagnostics/__init__.py`: + +```python +import ctypes.util + + +def find_library(name: str) -> str: + return ctypes.util.find_library(name) or "" +``` + +Then import the helper and include its source in the Function's artifact: + +```python +import native_diagnostics +from lancedb import function + + +@function(code=[native_diagnostics]) +def probe_library(name: str) -> str: + return native_diagnostics.find_library(name) +``` + +Captured literal globals support `None`, booleans, integers, strings, bytes, +finite floats, and tuples of these values. Construct other objects, including +PyArrow types and schemas, inside the Function or helper module instead. Values +used only in the decorator's `input_schema` or `output_schema` are not captured +globals and can be defined outside the Function. + Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or with `bytes` to materialize its contents before the Function runs. Reader inputs infer the Blob V2 type without an explicit input schema. Readers are diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index a5c741cd8..19d4171fb 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1570,10 +1570,23 @@ _NAMESPACE_MODULES = frozenset( ) -def _namespace_acquisition( - definition: ast.FunctionDef, references: set[str] -) -> list[str]: - found = set(references & _DYNAMIC_NAMESPACE_ACCESS) +_NAMESPACE_HELPER_HINT = ( + "Move this code into an importable helper module supplied with code=, pip=, " + "or conda=, then import and call the helper from the Function." +) + + +def _namespace_import_error(modules: Sequence[str]) -> ValueError: + return ValueError( + f"@function cannot package imports from namespace-access modules: {modules!r}. " + f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) " + "are blocked because they can access names outside the packaged " + "Function's reconstructed module namespace. " + _NAMESPACE_HELPER_HINT + ) + + +def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]: + found: set[str] = set() for node in ast.walk(definition): if isinstance(node, ast.Import): found.update( @@ -1883,11 +1896,17 @@ class _SourcePackager: ) source = ast.unparse(definition) references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n") - dynamic = _namespace_acquisition(definition, references) + dynamic = sorted(references & _DYNAMIC_NAMESPACE_ACCESS) if dynamic: raise ValueError( - f"@function cannot package dynamic namespace access: {dynamic!r}" + f"@function cannot package dynamic namespace access: {dynamic!r}. " + "These operations can access names outside the packaged " + "Function's reconstructed module namespace. Reference dependencies " + "explicitly. " + _NAMESPACE_HELPER_HINT ) + namespace_imports = _namespace_imports(definition) + if namespace_imports: + raise _namespace_import_error(namespace_imports) self._warn_unshipped_direct_imports(definition) self._packaged.add(id(target)) self._claim(target.__name__, ("definition", id(target))) @@ -1982,10 +2001,7 @@ class _SourcePackager: return f"from lance_blob import BlobReader as {name}" if isinstance(value, types.ModuleType): if value.__name__.split(".")[0] in _NAMESPACE_MODULES: - raise ValueError( - "@function cannot package dynamic namespace access: " - f"{value.__name__!r}" - ) + raise _namespace_import_error([value.__name__]) try: imported = importlib.import_module(value.__name__) except ImportError: @@ -2663,13 +2679,28 @@ def function( Other global values, including Arrow types and schemas, lists, dictionaries, sets, and NumPy arrays, cannot be captured as literals. Define them inside the function or class body instead. - Closures, lambdas, nested definitions, mutable module-level - objects, code that reaches the module namespace another way - (``globals()``/``eval``, ``sys.modules``, ``builtins``), and a + Closures, lambdas, nested definitions, mutable module-level objects, and a non-standard ``__builtins__`` are rejected where they can be seen and - otherwise unsupported. Changing any packaged source, including a module in - ``code``, produces a new Function version; the environment built from - ``pip`` or ``conda`` is reused. + otherwise unsupported. + + **Namespace restrictions.** The packaged source cannot import ``sys``, + ``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``, + including submodules such as ``ctypes.util`` and ``importlib.metadata``. + Referencing a module-level alias for one of these modules is also rejected. + References to ``globals``, ``locals``, ``vars``, ``eval``, ``exec``, + ``compile``, or ``__import__`` are rejected as dynamic namespace access. + These restrictions are conservative: even ordinary uses such as + ``ctypes.util.find_library`` or ``sys.version`` are blocked because these + modules can reach names outside the reconstructed Function namespace. + Move such code into an importable helper module supplied with ``code=``, + ``pip=``, or ``conda=``, then import and call the helper from the Function. + Helpers imported normally keep their own module namespace; these checks do + not scan their bodies. A helper defined in ``__main__`` is packaged by source + and is subject to the same checks. + + Changing any packaged source, including a module in ``code``, produces a + new Function version; the environment built from ``pip`` or ``conda`` is + reused. Parameters ---------- diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index d99a7aa21..97c0a5f3c 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -888,7 +888,7 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path): spec = importlib.util.spec_from_file_location("aliasing_udfs", module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) - with pytest.raises(ValueError, match="dynamic namespace access"): + with pytest.raises(ValueError, match="imports from namespace-access modules"): function(module.score) @@ -899,7 +899,6 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path): "eval('THRESHOLD')", "(lambda g: g()['THRESHOLD'])(globals)", "__import__('sys').modules[__name__].THRESHOLD", - "sys.modules[__name__].THRESHOLD", ], ) def test_function_rejects_dynamic_namespace_access(access): @@ -911,9 +910,7 @@ def test_function_rejects_dynamic_namespace_access(access): ) with pytest.raises(ValueError, match="dynamic namespace access"): _package_from_text( - "def score(value: int) -> int:\n" - " import sys\n" - f" return value + {access}\n" + f"def score(value: int) -> int:\n return value + {access}\n" ) diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 440adc4da..2e285aa33 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -466,6 +466,126 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): return value * factor +@pytest.mark.parametrize( + "module_name", + [ + "sys", + "builtins", + "importlib", + "inspect", + "gc", + "ctypes", + "types", + "ctypes.util", + "importlib.metadata", + ], +) +@pytest.mark.parametrize("import_style", ["import", "from", "global"]) +@pytest.mark.parametrize("class_function", [False, True]) +def test_namespace_module_errors_explain_the_rule_and_remedy( + helper_package, module_name, import_style, class_function +): + statement = f"import {module_name} as namespace_module" + body = f"{statement}\nreturn value\n" + preamble = "" + if import_style == "from": + body = f"from {module_name} import __name__\nreturn value\n" + elif import_style == "global": + preamble = statement + "\n" + body = "return str(namespace_module)\n" + if class_function: + definition = "class blocked:\n def __call__(self, value: str) -> str:\n" + source = preamble + definition + textwrap.indent(body, " ") + else: + definition = "def blocked(value: str) -> str:\n" + source = preamble + definition + textwrap.indent(body, " ") + module = helper_package("fx_namespace_import", {"__init__.py": source}) + + with pytest.raises(ValueError) as error: + function(module.blocked) + message = str(error.value) + assert "imports from namespace-access modules" in message + assert repr(module_name) in message + assert "builtins, ctypes, gc, importlib, inspect, sys, types" in message + assert "including submodules" in message + assert "reconstructed module namespace" in message + assert "importable helper module" in message + assert "code=, pip=, or conda=" in message + assert "dynamic namespace access" not in message + + +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +def test_udf_namespace_import_error_explains_the_helper_alternative(): + with pytest.raises(ValueError, match="ctypes.util.*importable helper module"): + + @udf + def probe(value: str) -> str: + import ctypes.util + + return str(ctypes.util.find_library(value)) + + +@pytest.mark.parametrize( + "operation", ["globals", "locals", "vars", "eval", "exec", "compile", "__import__"] +) +def test_dynamic_namespace_errors_name_the_operation_and_remedy( + helper_package, operation +): + module = helper_package( + "fx_namespace_operation", + { + "__init__.py": ( + f"def blocked(value: str) -> str:\n return str({operation})\n" + ) + }, + ) + with pytest.raises(ValueError) as error: + function(module.blocked) + message = str(error.value) + assert f"dynamic namespace access: ['{operation}']" in message + assert "Reference dependencies explicitly" in message + assert "importable helper module" in message + + +@pytest.mark.parametrize("ship_source", [False, True]) +def test_namespace_access_in_importable_helpers_keeps_its_module_namespace( + helper_package, ship_source +): + helpers = helper_package( + "fx_namespace_helper", + { + "__init__.py": """ + import ctypes.util + + def module_name(): + return ctypes.util.__name__ + """, + }, + ) + entry = helper_package( + "fx_namespace_entry", + { + "__init__.py": """ + from fx_namespace_helper import module_name + + def probe(value: str) -> str: + return module_name() + value + """, + }, + ) + options = {"code": [helpers]} if ship_source else {"pip": ["fx-namespace-helper"]} + definition = function(**options)(entry.probe) + if ship_source: + files = bundle_files(definition) + assert "import ctypes.util" in files["fx_namespace_helper/__init__.py"] + source = files["user_function.py"] + else: + source = artifact(definition).decode() + namespace = {} + exec(compile(source, "user_function.py", "exec"), namespace) + assert namespace["probe"]("!") == "ctypes.util!" + + def test_binding_passes_initialization_as_constants(): version = FunctionVersion.from_json( json.dumps( From 8939ef1f016b78e26dd41a77886edd6b83710e7a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:04:32 +0800 Subject: [PATCH 24/75] feat(python): warn on scalar GPU Functions (#4966) GPU Functions that use a scalar callable currently invoke the callable once per row. The SDK documents Arrow-vectorized callables, but silently accepts a scalar GPU callable, which makes it easy to assume that the runtime will batch model work automatically. Warn during Function construction when a GPU callable does not use the documented vectorized form. A callable is recognized as vectorized when every input is annotated as `pyarrow.Array`, or when a single input is annotated as `pyarrow.RecordBatch`. The warning explains the resulting per-row invocation and shows how to opt into batch execution. CPU Functions and the vectorized GPU forms do not emit it. The warning is advisory and does not change registration serialization, the artifact, the runtime adapter, or execution behavior. It is one part of the ENT-3522 documentation-and-warning alternative; it does not claim that a single A10G meets the original batch throughput requirement. Validation on the designated EC2 host reused the compatible existing native extension from `ent3563-sdk-freshness-9336cfb`; this does not claim a new native package or GPU performance run. The final head has a clean source tree and ran: ```bash PYTHONPATH="$sdk/python/python" /home/ec2-user/.venvs/ent3563-0a839fa/bin/python -m pytest -q python/python/tests/test_first_class_function_slice2.py -k 'gpu_marker_uses_gpu_runtime or gpu_scalar_warning_names_the_vectorized_alternative' /home/ec2-user/.venvs/ent3563-0a839fa/bin/ruff format --check python/python/lancedb/functions.py python/python/tests/test_first_class_function_slice2.py /home/ec2-user/.venvs/ent3563-0a839fa/bin/ruff check python/python/lancedb/functions.py python/python/tests/test_first_class_function_slice2.py ``` The actual result was `2 passed, 123 deselected`; both Ruff commands passed. The original 2,000-row single-A10G throughput requirement remains a separate ENT-3522 acceptance gate. --- python/python/lancedb/functions.py | 27 +++++++- .../tests/test_first_class_function_slice2.py | 63 ++++++++++++++++++- 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 19d4171fb..92be658a8 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1529,6 +1529,17 @@ def _infer_signature( return FunctionSignature(inputs=tuple(inputs), output=output) +def _is_vectorized_callable(function: Callable[..., Any], *, method: bool) -> bool: + parameters = _callable_parameters(function) + if method: + parameters = parameters[1:] + annotations = get_type_hints(function, include_extras=True) + annotated = tuple(annotations.get(parameter.name) for parameter in parameters) + return (len(annotated) == 1 and annotated[0] is pa.RecordBatch) or ( + bool(annotated) and all(annotation is pa.Array for annotation in annotated) + ) + + # Both spellings strip from packaged source; `udf` is the deprecated alias. _DECORATOR_NAMES = frozenset({"function", "udf"}) @@ -2302,7 +2313,9 @@ class FunctionDefinition: once per row. A callable whose parameters are all annotated as ``pyarrow.Array`` receives whole Arrow arrays and returns a ``pyarrow.Array`` instead. This authoring choice is independent of the - internal artifact adapter in the registration request. + internal artifact adapter in the registration request. GPU Functions should + use the Arrow form when the model supports batches: a scalar GPU callable is + invoked once per row and leaves the model's own batching unavailable. """ def __init__( @@ -2424,6 +2437,18 @@ class FunctionDefinition: signature = signature._copy(update={"initialization": initialization}) else: signature = _infer_signature(function, input_schema, output_schema) + if gpu_marker is not None: + call = _class_call(function) if is_class else function + if not _is_vectorized_callable(call, method=is_class): + warnings.warn( + f"GPU Function {function_name!r} uses a scalar callable, so each " + "row invokes it separately and its model batch is not inferred. " + "For GPU throughput, annotate every input as pyarrow.Array or " + "take one pyarrow.RecordBatch, provide input_schema and " + "output_schema, and batch inside that callable.", + UserWarning, + stacklevel=3, + ) code_files, code_modules = _code_files(code) entry_source = _SourcePackager( code_modules, frozenset(_requirement_name(package) for package in packages) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 97c0a5f3c..a3a9e3e20 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -18,6 +18,7 @@ import subprocess import sys import typing import urllib.parse +import warnings from typing import Optional import pyarrow as pa @@ -658,9 +659,11 @@ def test_function_image_requires_digest_reference(image): def test_function_gpu_marker_uses_gpu_runtime(): - @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") - def double_on_gpu(value: int) -> int: - return value * 2 + with pytest.warns(UserWarning, match="uses a scalar callable"): + + @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") + def double_on_gpu(value: int) -> int: + return value * 2 request = json.loads(double_on_gpu.registration_request.to_canonical_json()) assert request["runtime"]["kind"] == "python_v2" @@ -710,6 +713,60 @@ def test_function_gpu_marker_uses_gpu_runtime(): ) +class _GpuScalarFunction: + def __call__(self, value: str) -> int: + return len(value) + + +class _GpuArrayFunction: + def __call__(self, value: pa.Array) -> pa.Array: + return value + + +def test_gpu_scalar_warning_names_the_vectorized_alternative(): + with pytest.warns(UserWarning, match="model batch is not inferred"): + + @function(gpu=True) + def scalar_embedding(value: str) -> list[int]: + return [len(value)] + + input_schema = pa.schema([pa.field("value", pa.string(), nullable=False)]) + with pytest.warns(UserWarning, match="uses a scalar callable"): + class_scalar = function(_GpuScalarFunction, gpu=True) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + + @function( + gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64()) + ) + def array_embedding(value: pa.Array) -> pa.Array: + return value + + @function( + gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64()) + ) + def record_batch_embedding(value: pa.RecordBatch) -> pa.Array: + return value.column(0) + + @function + def cpu_scalar(value: str) -> int: + return len(value) + + class_embedding = function( + _GpuArrayFunction, + gpu=True, + input_schema=input_schema, + output_schema=pa.list_(pa.int64()), + ) + + assert not caught + assert array_embedding.registration_request.batch_size is None + assert record_batch_embedding.registration_request.batch_size is None + assert cpu_scalar.registration_request.batch_size is None + assert class_scalar.registration_request.batch_size is None + assert class_embedding.registration_request.batch_size is None + + def test_unknown_runtime_discards_payload_before_known_field_validation(): for payload in [ { From 10f89b3c32577bf054774b5c74346ba24ee79576 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:09 +0800 Subject: [PATCH 25/75] perf: reduce Blob read buffering and expose read window controls (#4979) Remote Blob reads retain and concatenate intermediate IPC buffers across batches and HTTP requests, increasing peak memory. Decode fragmented IPC bodies using their declared length, assemble Blob values once across batches/requests, and collect large-object Range responses into known-size buffers. Impossible IPC/Range allocations return errors instead of panicking. Closing a remote Blob file releases cached bytes immediately, including while a cross-window read is waiting for the network. Rust and Python expose configurable Blob read buffers. Python sync/async `fetch_blob_files` and `open_blob_file(s)` accept `buffer_size`; the default is 512 KiB and zero disables prefetch. Explicit ranges bypass prefetch. New PE batch-endpoint adoption is separate. Malformed-length and retained-cache regressions fail on the previous implementation and pass after the correction. Real HTTP tests cover buffer propagation, close during blocked input, batch/request aggregation, and large-object fallback. The final extension was rebuilt before Python validation. Non-Blob Arrow arrays may still require alignment copies; a contiguous multi-batch result still requires its final allocation. ## Benchmark Peak client RSS increment in KiB, using `python/benchmarks/bench_fetch_blobs_rss.py`, independent clients and real loopback HTTP. Both extensions were rebuilt from clean, unchanged source with the same toolchain/configuration; loaded artifact hashes were checked. Baseline `42f11d13a2755e44b63876b5a5edd93901291150`, after `0a8a76de5286949d80368f95a5c529adf422c187`. | Equivalent fetch workload | Payload | Before | After | | --- | ---: | ---: | ---: | | Single response, one batch | 48 MiB | 63,812 | 63,896 | | Multiple responses, one batch per response | 144 MiB | 423,104 | 195,628 | | Single response, 12 rows per batch | 48 MiB | 130,520 | 71,348 | | Multiple responses, 12 rows per batch | 144 MiB | 363,144 | 172,748 | | One oversized row, Range fallback | 70 MiB | 182,816 | 85,548 | These are one observation per workload and build, not a statistical distribution or memory upper bound. The single-batch workload shows no improvement. Cloud/Sophon deployment, credentialed S3 and long-running stress have not been exercised. --- docs/src/python/python.md | 9 + python/benchmarks/bench_fetch_blobs_rss.py | 183 ++++++++ python/python/lancedb/_blob.py | 19 + python/python/lancedb/_lancedb.pyi | 7 +- python/python/lancedb/remote/table.py | 13 +- python/python/lancedb/table.py | 56 ++- python/python/tests/test_blob_buffering.py | 236 ++++++++++ python/src/table.rs | 27 +- rust/lancedb/src/blob.rs | 24 + rust/lancedb/src/remote/table/blobs.rs | 424 +++++++++++++++--- .../src/remote/table/blobs/aggregate.rs | 121 +++++ rust/lancedb/src/remote/table/ipc_stream.rs | 123 ++++- .../src/remote/table/ipc_stream/framing.rs | 172 +++++++ 13 files changed, 1326 insertions(+), 88 deletions(-) create mode 100644 python/benchmarks/bench_fetch_blobs_rss.py create mode 100644 python/python/tests/test_blob_buffering.py create mode 100644 rust/lancedb/src/remote/table/blobs/aggregate.rs create mode 100644 rust/lancedb/src/remote/table/ipc_stream/framing.rs diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 35f50c5a8..0e7164c1a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -793,6 +793,15 @@ with `search().with_row_id(True).to_arrow()` and pass the result to the fetch AP One missing or deleted row ID rejects the entire blob-read batch; the APIs do not return partial results. +Local and remote `BlobFile` handles prefetch 512 KiB for sequential reads by +default. Pass `buffer_size=0` to `fetch_blob_files`, `open_blob_file`, or +`open_blob_files` for sparse reads, or choose another window size in bytes. +Call `file.set_buffer_size(size)` to change it without moving the cursor; +changing the size discards unused prefetched bytes. Explicit `read_range` and +`read_ranges` calls always read exactly the requested intervals and leave the +cursor unchanged. Remote prefetch consumes the HTTP response completely before +returning, so idle handles do not hold request concurrency slots or connections. + To construct inline Blob V2 arrays for ingestion in record batches, use [blob_array][lancedb.schema.blob_array]. It accepts bytes and `None`, preserving the distinction between an empty blob (`b""`) and a null blob: diff --git a/python/benchmarks/bench_fetch_blobs_rss.py b/python/benchmarks/bench_fetch_blobs_rss.py new file mode 100644 index 000000000..8281490f0 --- /dev/null +++ b/python/benchmarks/bench_fetch_blobs_rss.py @@ -0,0 +1,183 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Measure fetch_blobs RSS in a fresh client process against real HTTP. + +Run with the uv environment's Python. The server lives in a separate process so +payload generation and Arrow serialization are excluded from the client's RSS. +Each row contains 1 MiB; requests over the server's 64 MiB limit are split by the +SDK. Example: python benchmarks/bench_fetch_blobs_rss.py --rows 48 144 +""" + +import argparse +import json +import resource +import subprocess +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +def serve(batch_rows, row_mib): + import pyarrow as pa + + payload = b"x" * (row_mib << 20) + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def respond(self, status, data, content_type="application/json"): + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.send_header("phalanx-version", "0.5.0") + self.send_header("x-lancedb-version", "1") + self.end_headers() + for offset in range(0, len(data), 8192): + self.wfile.write(data[offset : offset + 8192]) + + def do_POST(self): + length = int(self.headers.get("Content-Length", 0)) + request_body = self.rfile.read(length) + if self.path.endswith("/describe/"): + self.do_GET() + return + body = json.loads(request_body) + count = len(body["row_ids"]) + if count * row_mib > 64: + self.respond( + 400, + b"fetch_blobs accepts at most 67108864 total blob bytes", + ) + return + schema = pa.schema([pa.field("image", pa.large_binary())]) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, schema) as writer: + for start in range(0, count, batch_rows): + array = pa.array( + [payload] * min(batch_rows, count - start), + type=pa.large_binary(), + ) + writer.write_batch(pa.record_batch([array], schema=schema)) + self.respond(200, sink.getvalue(), "application/vnd.apache.arrow.stream") + + def do_GET(self): + if "/blob/image/" in self.path: + start, end = map(int, self.headers["Range"][6:].split("-")) + body = memoryview(payload)[start : end + 1] + self.send_response(206) + self.send_header("Content-Length", str(len(body))) + self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}") + self.send_header("x-lancedb-version", "1") + self.end_headers() + for offset in range(0, len(body), 8192): + self.wfile.write(body[offset : offset + 8192]) + return + self.respond( + 200, + json.dumps( + { + "table": "test", + "version": 1, + "schema": {"fields": []}, + } + ).encode(), + ) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + print(server.server_port, flush=True) + server.serve_forever() + + +def client(port, rows, row_mib): + import lancedb + + db = lancedb.connect( + "db://rss-test", api_key="test", host_override=f"http://127.0.0.1:{port}" + ) + table = db.open_table("test") + # Reset the Linux high-water mark after imports and connection setup. + with open("/proc/self/clear_refs", "w") as reset: + reset.write("5") + + def memory_kib(field): + with open("/proc/self/status") as status: + return next( + int(line.split()[1]) for line in status if line.startswith(field + ":") + ) + + before = memory_kib("VmRSS") + values = table.fetch_blobs("image", list(range(rows))) + peak = memory_kib("VmHWM") + assert len(values) == rows + assert values.buffers()[2].size == rows * (row_mib << 20) + # Inspect slices without copying the result to Python bytes. + for i in (0, rows - 1): + assert values.slice(i, 1).buffers()[2][i * (row_mib << 20)] == ord("x") + print( + json.dumps( + { + "rows": rows, + "payload_mib": rows * row_mib, + "baseline_rss_kib": before, + "peak_rss_kib": peak, + "peak_delta_kib": peak - before, + "peak_delta_per_payload": (peak - before) / (rows * row_mib * 1024), + "rusage_maxrss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--rows", nargs="+", type=int, default=[48, 144]) + parser.add_argument("--batch-rows", type=int, default=48) + parser.add_argument("--row-mib", type=int, default=1) + parser.add_argument("--serve", action="store_true") + parser.add_argument("--client", type=int) + args = parser.parse_args() + if args.serve: + serve(args.batch_rows, args.row_mib) + elif args.client is not None: + client(args.client, args.rows[0], args.row_mib) + else: + server = subprocess.Popen( + [ + sys.executable, + __file__, + "--serve", + "--batch-rows", + str(args.batch_rows), + "--row-mib", + str(args.row_mib), + ], + stdout=subprocess.PIPE, + text=True, + ) + try: + port = server.stdout.readline().strip() + for rows in args.rows: + subprocess.run( + [ + sys.executable, + __file__, + "--client", + port, + "--rows", + str(rows), + "--row-mib", + str(args.row_mib), + ], + check=True, + ) + finally: + server.terminate() + server.wait() + + +if __name__ == "__main__": + main() diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 2c545a17e..fc1925ca6 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -35,6 +35,15 @@ FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray] FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]] +def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]: + if size is None: + return None + size = operator.index(size) + if size < 0: + raise ValueError("buffer_size must be non-negative") + return size + + def _normalize_blob_descriptor(value): if isinstance(value, pa.Scalar): value = value.as_py() @@ -58,6 +67,16 @@ class BlobFile(io.RawIOBase): def __init__(self, inner) -> None: self._inner = inner + def set_buffer_size(self, size: int) -> None: + """Set sequential read-ahead bytes (default 512 KiB); 0 disables it. + + Changing the size discards unused prefetched bytes without moving the + cursor. Explicit ``read_range`` and ``read_ranges`` bypass read-ahead. + """ + if self.closed: + raise ValueError("set_buffer_size of closed file") + self._inner.set_buffer_size(_validate_blob_buffer_size(size)) + async def aread(self) -> bytes: if self.closed: raise ValueError("read of closed file") diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a64014cb7..4f1da9ba7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -397,6 +397,7 @@ class BlobFile: def seek(self, position: int) -> None: ... def tell(self) -> int: ... def size(self) -> int: ... + def set_buffer_size(self, size: int) -> None: ... def read_range(self, offset: int, length: int) -> bytes: ... def read_ranges(self, ranges: list[tuple[int, int]]) -> list[bytes]: ... def read_up_to(self, length: int) -> bytes: ... @@ -755,9 +756,11 @@ class Table: requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: ... async def fetch_blob_files( - self, column: str, row_ids: list[int] + self, column: str, row_ids: list[int], buffer_size: Optional[int] = None ) -> list[Optional[BlobFile]]: ... - async def open_blob_file(self, descriptor: str) -> BlobFile: ... + async def open_blob_file( + self, descriptor: str, buffer_size: Optional[int] = None + ) -> BlobFile: ... def vector_search(self) -> VectorQuery: ... class Tags: diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 3f6bff45e..21749a0a7 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1420,13 +1420,20 @@ class RemoteTable(Table): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": - return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + return LOOP.run( + self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size) + ) def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: - return LOOP.run(self._table.open_blob_file(descriptor)) + return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size)) def head(self, n=5) -> pa.Table: """ diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 762f826c2..424b4b64c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -40,6 +40,7 @@ from ._blob import ( BlobFile, _normalize_blob_descriptor, _normalize_blob_row_ids, + _validate_blob_buffer_size, _wrap_blob_files, strip_auto_row_ids, validate_blob_mode, @@ -2664,6 +2665,8 @@ class Table(ABC): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": """Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles. @@ -2673,6 +2676,8 @@ class Table(ABC): ``pyarrow.Table`` carrying row identity via ``_rowid`` or a ``_lance_row_id`` field on the blob descriptor. Null blob values return ``None``. LanceDB Enterprise requires server version 0.5.0 or newer. + ``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB). + Set it to 0 for sparse reads. Explicit range reads bypass this buffer. ``_rowid`` values stay valid after compaction when the table has stable row ids. @@ -2682,7 +2687,10 @@ class Table(ABC): @abstractmethod def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: """Open a seekable file from a SQL ``blob_descriptor`` result. @@ -2691,6 +2699,7 @@ class Table(ABC): not change this table's checkout. Null descriptors return ``None``. Payload bytes load only when the returned handle is read. An external blob with an unspecified size may require a metadata request on opening. + ``buffer_size`` controls sequential read-ahead (default 512 KiB; 0 disables). ```python rows = db.execute_query( @@ -2701,7 +2710,9 @@ class Table(ABC): ``` """ - def open_blob_files(self, descriptors: Iterable) -> Iterator[Optional[BlobFile]]: + def open_blob_files( + self, descriptors: Iterable, *, buffer_size: Optional[int] = None + ) -> Iterator[Optional[BlobFile]]: """Iterate over lazy files from descriptor dictionaries or Arrow scalars. Accepts an Arrow array/chunked array or any iterable. Opens each handle @@ -2716,7 +2727,10 @@ class Table(ABC): ``` """ for descriptor in descriptors: - yield self.open_blob_file(descriptor) + if buffer_size is None: + yield self.open_blob_file(descriptor) + else: + yield self.open_blob_file(descriptor, buffer_size=buffer_size) @abstractmethod def _execute_query( @@ -3998,13 +4012,20 @@ class LanceTable(Table): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": - return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + return LOOP.run( + self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size) + ) def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: - return LOOP.run(self._table.open_blob_file(descriptor)) + return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size)) @property def tags(self) -> Tags: @@ -8620,26 +8641,39 @@ class AsyncTable: self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": + """Open handles with configurable read-ahead. + + See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files]. + """ + buffer_size = _validate_blob_buffer_size(buffer_size) handles = await self._inner.fetch_blob_files( - column, _normalize_blob_row_ids(row_ids, column) + column, _normalize_blob_row_ids(row_ids, column), buffer_size ) return _wrap_blob_files(handles) async def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: """Open a snapshot-bound descriptor as a seekable file. See [Table.open_blob_file][lancedb.table.Table.open_blob_file]. """ + buffer_size = _validate_blob_buffer_size(buffer_size) descriptor = _normalize_blob_descriptor(descriptor) if descriptor is None: return None - return BlobFile(await self._inner.open_blob_file(json.dumps(descriptor))) + return BlobFile( + await self._inner.open_blob_file(json.dumps(descriptor), buffer_size) + ) async def open_blob_files( - self, descriptors: Iterable + self, descriptors: Iterable, *, buffer_size: Optional[int] = None ) -> AsyncIterator[Optional[BlobFile]]: """Asynchronously iterate over files in descriptor order, preserving nulls. @@ -8654,7 +8688,7 @@ class AsyncTable: ``` """ for descriptor in descriptors: - yield await self.open_blob_file(descriptor) + yield await self.open_blob_file(descriptor, buffer_size=buffer_size) @property def tags(self) -> AsyncTags: diff --git a/python/python/tests/test_blob_buffering.py b/python/python/tests/test_blob_buffering.py new file mode 100644 index 000000000..09fbfb862 --- /dev/null +++ b/python/python/tests/test_blob_buffering.py @@ -0,0 +1,236 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +import threading +from contextlib import contextmanager +from urllib.parse import urlparse + +import pyarrow as pa +import pytest + +import lancedb +from test_remote_db import ( + BLOB_DESCRIBE_RESPONSE, + blob_descriptor_take_table, + mock_lancedb_connection, +) + + +@contextmanager +def remote_buffer_table(*, http_requests=None, truncate_first=False): + payload = bytes(range(256)) * 4096 + requests = [] + + def handler(request): + path = urlparse(request.path).path + if http_requests is not None: + http_requests.append(path) + if path.endswith("/describe/"): + body = json.dumps(BLOB_DESCRIBE_RESPONSE).encode() + content_type = "application/json" + elif path.endswith("/query/"): + data = json.loads( + request.rfile.read(int(request.headers["Content-Length"])) + ) + assert data["columns"] == ["image"] + table = blob_descriptor_take_table().slice(0, 1) + images = table["image"].combine_chunks() + images = pa.StructArray.from_arrays( + [ + images.field("kind"), + images.field("position"), + pa.array([len(payload)], pa.uint64()), + images.field("blob_id"), + images.field("blob_uri"), + ], + fields=list(images.type), + ) + table = table.set_column(0, table.schema.field(0), images) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, table.schema) as writer: + writer.write_table(table) + body = sink.getvalue().to_pybytes() + content_type = "application/vnd.apache.arrow.stream" + else: + assert path == "/v1/table/test/blob/image/10/bytes" + assert "version=1" in request.path + start, end = map(int, request.headers["Range"][6:].split("-")) + requests.append((start, end + 1)) + body = payload[start : end + 1] + if truncate_first and len(requests) == 1: + body = body[:5] + request.send_response(206) + request.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}") + request.send_header("Content-Length", str(len(body))) + request.end_headers() + request.wfile.write(body) + return + request.send_response(200) + request.send_header("Content-Type", content_type) + request.send_header("Content-Length", str(len(body))) + request.send_header("phalanx-version", "0.5.0") + request.send_header("x-lancedb-version", "1") + request.end_headers() + request.wfile.write(body) + + with mock_lancedb_connection(handler, blob_request_concurrency=1) as db: + yield db.open_table("test"), payload, requests + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("buffer_size", [None, 0, 8, 512 * 1024]) +async def test_remote_read_ahead_over_http(use_async, buffer_size): + with remote_buffer_table() as (table, payload, requests): + if use_async: + files = await table._table.fetch_blob_files( + "image", [10], buffer_size=buffer_size + ) + else: + files = table.fetch_blob_files("image", [10], buffer_size=buffer_size) + file = files[0] + assert requests == [] + assert file.read(2) == payload[:2] + window = 512 * 1024 if buffer_size is None else max(buffer_size, 2) + assert requests == [(0, window)] + assert file.read(2) == payload[2:4] + assert len(requests) == (2 if buffer_size == 0 else 1) + file.seek(1) + assert file.read(1) == payload[1:2] + assert len(requests) == (3 if buffer_size == 0 else 1) + before = len(requests) + assert file.read_range(0, 1) == payload[:1] + assert len(requests) == before + 1 + assert requests[-1] == (0, 1) + assert file.tell() == 2 + file.set_buffer_size(0) + assert file.read(1) == payload[2:3] + assert requests[-1] == (2, 3) + file.set_buffer_size(16) + assert file.read(1) == payload[3:4] + assert requests[-1] == (3, 19) + file.seek(len(payload) - 1) + assert file.read(4) == payload[-1:] + assert requests[-1] == (len(payload) - 1, len(payload)) + before = len(requests) + assert file.read(1) == b"" + assert len(requests) == before + file.close() + with pytest.raises(ValueError, match="closed"): + file.set_buffer_size(0) + + +def test_short_prefetch_over_http_preserves_cursor(): + with remote_buffer_table(truncate_first=True) as (table, payload, requests): + file = table.fetch_blob_files("image", [10], buffer_size=8)[0] + with pytest.raises(RuntimeError, match="returned 5 bytes, expected 8"): + file.read(6) + assert file.tell() == 0 + assert file.read(3) == payload[:3] + assert file.tell() == 3 + assert requests == [(0, 8), (0, 8)] + file.close() + + +def test_idle_prefetch_releases_http_concurrency_slot(): + with remote_buffer_table() as (table, payload, requests): + first, second = table.fetch_blob_files("image", [10, 10]) + assert first.read(1) == payload[:1] + results = [] + errors = [] + + def read_other(): + try: + results.append(second.read(1)) + except Exception as error: + errors.append(error) + + reader = threading.Thread(target=read_other, daemon=True) + reader.start() + reader.join(timeout=2) + completed_while_first_idle = not reader.is_alive() + first.close() + reader.join(timeout=2) + second.close() + assert completed_while_first_idle, ( + "idle prefetch retained the HTTP request slot" + ) + assert not errors + assert results == [payload[:1]] + assert requests == [(0, 512 * 1024), (0, 512 * 1024)] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_local_buffer_configuration_through_python(tmp_path, use_async): + db = lancedb.connect(tmp_path) + table = db.create_table( + "blobs", [{"image": b"0123456789"}], schema=pa.schema([lancedb.blob("image")]) + ) + row_ids = table.search().with_row_id(True).to_arrow()["_rowid"] + if use_async: + files = await table._table.fetch_blob_files("image", row_ids, buffer_size=0) + else: + files = table.fetch_blob_files("image", row_ids, buffer_size=0) + file = files[0] + assert file.read(2) == b"01" + file.set_buffer_size(4) + assert file.read(2) == b"23" + file.seek(1) + assert file.read(3) == b"123" + assert file.read_range(8, 2) == b"89" + with pytest.raises(ValueError, match="non-negative"): + file.set_buffer_size(-1) + with pytest.raises(TypeError): + file.set_buffer_size(1.5) + file.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_open_descriptor_files_forward_buffer_size(use_async): + with remote_buffer_table() as (table, payload, requests): + descriptor = { + "kind": 1, + "position": 0, + "size": len(payload), + "blob_id": 0, + "blob_uri": "", + "source": { + "uri": "s3://bucket/test.lance", + "version": 1, + "committed_at_micros": 1, + "column": "image", + "row_reference": 10, + "row_is_address": False, + }, + } + if use_async: + files = [ + file + async for file in table._table.open_blob_files( + [None, descriptor], buffer_size=8 + ) + ] + else: + files = list(table.open_blob_files([None, descriptor], buffer_size=8)) + assert files[0] is None + assert files[1].read(1) == payload[:1] + assert requests == [(0, 8)] + files[1].close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_invalid_buffer_size_rejects_before_http(use_async): + http_requests = [] + with remote_buffer_table(http_requests=http_requests) as (table, _, requests): + http_requests.clear() + with pytest.raises(ValueError, match="non-negative"): + if use_async: + await table._table.fetch_blob_files("image", [10], buffer_size=-1) + else: + table.fetch_blob_files("image", [10], buffer_size=-1) + assert requests == [] + assert http_requests == [] diff --git a/python/src/table.rs b/python/src/table.rs index c4211e44d..62c2ee765 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1243,6 +1243,15 @@ impl PyBlobFile { .map_err(|e| blob_file_error("tell", e)) } + fn set_buffer_size(self_: PyRef<'_, Self>, size: usize) -> PyResult<()> { + self_.ensure_open()?; + let inner = self_.inner.clone(); + self_ + .py() + .detach(move || block_on(async move { inner.set_buffer_size(size).await })) + .map_err(|e| blob_file_error("set_buffer_size", e)) + } + fn size(self_: PyRef<'_, Self>) -> u64 { self_.inner.size() } @@ -2019,11 +2028,12 @@ impl Table { } /// Open lazy blob handles for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids))] + #[pyo3(signature = (column, row_ids, buffer_size=None))] pub fn fetch_blob_files( self_: PyRef<'_, Self>, column: String, row_ids: Vec, + buffer_size: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2031,6 +2041,13 @@ impl Table { .fetch_blob_files(column.as_str(), &row_ids) .await .infer_error()?; + if let Some(size) = buffer_size { + for file in handles.iter().flatten() { + file.set_buffer_size(size) + .await + .map_err(|e| blob_file_error("set_buffer_size", e))?; + } + } Ok(handles .into_iter() .map(|handle| { @@ -2043,16 +2060,22 @@ impl Table { }) } - #[pyo3(signature = (descriptor))] + #[pyo3(signature = (descriptor, buffer_size=None))] pub fn open_blob_file<'py>( self_: PyRef<'py, Self>, descriptor: &str, + buffer_size: Option, ) -> PyResult> { let descriptor: BlobDescriptor = serde_json::from_str(descriptor) .map_err(|error| PyValueError::new_err(format!("invalid blob descriptor: {error}")))?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let file = inner.open_blob_file(&descriptor).await.infer_error()?; + if let Some(size) = buffer_size { + file.set_buffer_size(size) + .await + .map_err(|e| blob_file_error("set_buffer_size", e))?; + } Ok(PyBlobFile { inner: Arc::new(file), closed: AtomicBool::new(false), diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index a8a816fdd..ead1f2410 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -204,6 +204,30 @@ impl BlobFile { lance::dataset::BlobFile::new_external(object_store, path, uri, position, size).into() } + /// Default sequential read-ahead window, in bytes. + pub const DEFAULT_READ_BUFFER_SIZE: usize = 512 * 1024; + + /// Set sequential read-ahead bytes. `0` disables read-ahead. + /// + /// Changing the size discards unused prefetched bytes without moving the + /// cursor. [`Self::read_range`] and [`Self::read_ranges`] bypass read-ahead. + /// The default is [`Self::DEFAULT_READ_BUFFER_SIZE`]. + /// + /// ``` + /// # async fn sparse_read(file: &lancedb::blob::BlobFile) -> lance_core::Result<()> { + /// file.set_buffer_size(0).await?; + /// let header = file.read_up_to(16).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn set_buffer_size(&self, size: usize) -> lance_core::Result<()> { + match &self.inner { + BlobFileInner::Native(file) => file.set_buffer_size(size).await, + #[cfg(feature = "remote")] + BlobFileInner::Remote(file) => file.set_buffer_size(size).await, + } + } + /// Close the handle. pub async fn close(&self) -> lance_core::Result<()> { match &self.inner { diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 65ab13935..345b731c5 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -3,6 +3,11 @@ //! Cloud blob column listing, whole-byte fetch, and seekable HTTP byte-range handles. +mod aggregate; + +use aggregate::BlobAccumulator; +use arrow_buffer::{Buffer, OffsetBuffer}; + use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; @@ -159,9 +164,25 @@ impl BlobRangeRequester for TableBlobRangeRequester { } } -#[derive(Debug, Default)] +#[derive(Debug)] struct RemoteBlobState { cursor: u64, + buffer_size: usize, +} + +impl Default for RemoteBlobState { + fn default() -> Self { + Self { + cursor: 0, + buffer_size: BlobFile::DEFAULT_READ_BUFFER_SIZE, + } + } +} + +#[derive(Debug, Default)] +struct RemoteBlobBuffer { + start: u64, + bytes: Bytes, } /// Seekable Cloud blob handle over HTTP Range. @@ -171,6 +192,9 @@ struct RemoteBlobState { pub struct RemoteBlobFile { requester: Arc, state: Mutex, + // Never held across I/O: close can release cached bytes even while a read + // holds the cursor lock. A reader may retain its own prefix until it ends. + buffer: std::sync::Mutex, closed: AtomicBool, size: u64, version: Option, @@ -181,6 +205,7 @@ impl RemoteBlobFile { Self { requester, state: Mutex::new(RemoteBlobState::default()), + buffer: std::sync::Mutex::new(RemoteBlobBuffer::default()), closed: AtomicBool::new(false), size, version, @@ -190,6 +215,18 @@ impl RemoteBlobFile { /// Close the handle without waiting for an in-flight read. pub(crate) async fn close(&self) -> lance_core::Result<()> { self.closed.store(true, Ordering::Release); + self.buffer.lock().unwrap().bytes = Bytes::new(); + Ok(()) + } + + pub(crate) async fn set_buffer_size(&self, size: usize) -> lance_core::Result<()> { + self.ensure_open()?; + let mut state = self.state.lock().await; + self.ensure_open()?; + if state.buffer_size != size { + state.buffer_size = size; + self.buffer.lock().unwrap().bytes = Bytes::new(); + } Ok(()) } @@ -228,7 +265,7 @@ impl RemoteBlobFile { let BlobRangeResponse { request_id, response, - _permit, + _permit: permit, } = self .requester .request_range(&range_header, RangeRequestMode::DataRead, self.version) @@ -236,19 +273,9 @@ impl RemoteBlobFile { .map_err(remote_blob_error)?; self.ensure_open()?; validate_partial_response(&response, range.clone(), self.size)?; - let bytes = response - .bytes() - .await - .err_to_http(request_id) - .map_err(remote_blob_error)?; + let bytes = read_blob_body(response, range.end - range.start, request_id).await?; + drop(permit); self.ensure_open()?; - if bytes.len() as u64 != range.end - range.start { - return Err(remote_blob_error(format!( - "byte range returned {} bytes, expected {}", - bytes.len(), - range.end - range.start - ))); - } Ok(bytes) } @@ -275,7 +302,16 @@ impl RemoteBlobFile { let remaining = usize::try_from(remaining).map_err(|_| { lance_core::Error::invalid_input("remaining blob length exceeds addressable memory") })?; - self.read_up_to_locked(&mut state, remaining).await + // Joining a small cached prefix to a large tail would copy the entire + // blob while both allocations are live. Match the native reader's + // bounded reuse rule for whole-blob reads. + let held_len = cached_prefix(&self.buffer.lock().unwrap(), state.cursor, remaining).len(); + if remaining > held_len.saturating_mul(2) { + self.buffer.lock().unwrap().bytes = Bytes::new(); + } + let bytes = self.read_up_to_locked(&mut state, remaining).await?; + self.buffer.lock().unwrap().bytes = Bytes::new(); + Ok(bytes) } pub(crate) async fn read_up_to(&self, len: usize) -> lance_core::Result { @@ -296,14 +332,51 @@ impl RemoteBlobFile { return Ok(Bytes::new()); } - // A partial read must release its HTTP response before returning. Keeping - // it open across calls would hold a connection slot indefinitely and - // prevent other handles from making progress. - let end = state.cursor + target_len as u64; - let bytes = self.read_range(state.cursor..end).await?; + let prefix = cached_prefix(&self.buffer.lock().unwrap(), state.cursor, target_len); + if prefix.len() == target_len { + state.cursor += target_len as u64; + return Ok(prefix); + } + let fetch_start = state.cursor + prefix.len() as u64; + let still_need = target_len - prefix.len(); + let fetch_len = if state.buffer_size == 0 { + still_need as u64 + } else { + (state.buffer_size.max(still_need) as u64).min(self.size - fetch_start) + }; + // Fully consume the response before retaining only its Bytes. read_range + // releases both the connection and the concurrency permit before return. + let data = self + .read_range(fetch_start..fetch_start + fetch_len) + .await?; self.ensure_open()?; - state.cursor = end; - Ok(bytes) + let tail = data.slice(..still_need); + let result = if prefix.is_empty() { + tail + } else { + let mut joined = Vec::new(); + joined.try_reserve_exact(target_len).map_err(|error| { + remote_blob_error(format!( + "cannot allocate blob read of {target_len} bytes: {error}" + )) + })?; + joined.extend_from_slice(&prefix); + joined.extend_from_slice(&tail); + Bytes::from(joined) + }; + { + let mut buffer = self.buffer.lock().unwrap(); + // Serialize publishing a new window with close clearing the cache. + self.ensure_open()?; + if state.buffer_size != 0 { + buffer.start = fetch_start; + buffer.bytes = data; + } else { + buffer.bytes = Bytes::new(); + } + } + state.cursor += target_len as u64; + Ok(result) } pub(crate) async fn seek(&self, new_cursor: u64) -> lance_core::Result<()> { @@ -326,6 +399,83 @@ impl RemoteBlobFile { } } +/// Collect a range without retaining a second payload's worth of network chunks. +async fn read_blob_body( + response: Response, + expected: u64, + request_id: String, +) -> lance_core::Result { + let expected = usize::try_from(expected).map_err(|_| { + lance_core::Error::invalid_input("blob range length exceeds addressable memory") + })?; + let length_error = |received| { + remote_blob_error(format!( + "byte range returned {received} bytes, expected {expected}" + )) + }; + let mut chunks = response.bytes_stream(); + let first = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + .ok_or_else(|| length_error(0))?; + if first.len() > expected { + return Err(length_error(first.len())); + } + if first.len() == expected { + while let Some(chunk) = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + { + if !chunk.is_empty() { + return Err(length_error(expected.saturating_add(chunk.len()))); + } + } + return Ok(first); + } + let mut bytes = Vec::new(); + bytes.try_reserve_exact(expected).map_err(|error| { + remote_blob_error(format!( + "cannot allocate blob range of {expected} bytes: {error}" + )) + })?; + bytes.extend_from_slice(&first); + drop(first); + while let Some(chunk) = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + { + let received = bytes.len().saturating_add(chunk.len()); + if received > expected { + return Err(length_error(received)); + } + bytes.extend_from_slice(&chunk); + } + if bytes.len() != expected { + return Err(length_error(bytes.len())); + } + Ok(Bytes::from(bytes)) +} + +fn cached_prefix(buffer: &RemoteBlobBuffer, cursor: u64, length: usize) -> Bytes { + let Some(offset) = cursor.checked_sub(buffer.start) else { + return Bytes::new(); + }; + let Ok(offset) = usize::try_from(offset) else { + return Bytes::new(); + }; + if offset >= buffer.bytes.len() { + return Bytes::new(); + } + let end = offset.saturating_add(length).min(buffer.bytes.len()); + buffer.bytes.slice(offset..end) +} + fn remote_blob_error(error: impl std::fmt::Display) -> lance_core::Error { lance_core::Error::io(format!("remote blob read failed: {error}")) } @@ -434,10 +584,13 @@ impl RemoteTable { read_snapshot.version = Some(self.describe_read_snapshot(read_snapshot).await?.version); } let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); - let mut chunks = Vec::new(); + let mut blobs = BlobAccumulator::new(row_ids.len()); while let Some(ids) = pending.pop() { - match self.fetch_blobs_chunk(column, ids, read_snapshot).await { - Ok(blobs) => chunks.push(blobs), + match self + .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) + .await + { + Ok(()) => {} Err(error) if is_fetch_blobs_byte_limit_error(&error) => { // A single-request call may turn into several requests after a // byte-cap error. No bytes from the failed request were used. @@ -455,7 +608,15 @@ impl RemoteTable { Some(file) => Some(file.read().await?), None => None, }; - chunks.push(LargeBinaryArray::from(vec![blob.as_deref()])); + let blob = match blob { + Some(bytes) => LargeBinaryArray::new( + OffsetBuffer::new(vec![0, bytes.len() as i64].into()), + Buffer::from(bytes), + None, + ), + None => LargeBinaryArray::new_null(1), + }; + blobs.append(&blob)?; } else { let mid = ids.len() / 2; pending.push(&ids[mid..]); @@ -466,15 +627,7 @@ impl RemoteTable { } } - if chunks.len() == 1 { - return Ok(chunks.pop().unwrap()); - } - let chunk_refs: Vec<&dyn Array> = chunks.iter().map(|chunk| chunk as &dyn Array).collect(); - Ok(arrow::compute::concat(&chunk_refs)? - .as_any() - .downcast_ref::() - .expect("concatenating LargeBinary arrays returns LargeBinary") - .clone()) + Ok(blobs.finish()) } async fn fetch_blobs_chunk( @@ -482,7 +635,8 @@ impl RemoteTable { column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, - ) -> Result { + blobs: &mut BlobAccumulator, + ) -> Result<()> { let mut body = serde_json::json!({ "version": read_snapshot.version, "column": column, @@ -502,7 +656,7 @@ impl RemoteTable { Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), }; - let mut blob_chunks: Vec> = Vec::new(); + let mut rows = 0; while let Some(batch) = stream.try_next().await? { let blob_column = batch.column_by_name(column).ok_or_else(|| Error::Http { source: format!("fetch_blobs response is missing the '{column}' column").into(), @@ -525,28 +679,19 @@ impl RemoteTable { status_code: None, }); } - blob_chunks.push(arrow::compute::cast(blob_column, &DataType::LargeBinary)?); - } - let blobs = if blob_chunks.is_empty() { - LargeBinaryArray::from(Vec::>::new()) - } else { - let blob_chunk_refs: Vec<&dyn Array> = blob_chunks.iter().map(AsRef::as_ref).collect(); - arrow::compute::concat(&blob_chunk_refs)? + let array = arrow::compute::cast(blob_column, &DataType::LargeBinary)?; + let array = array .as_any() .downcast_ref::() - .ok_or_else(|| Error::Http { - source: "fetch_blobs could not read the concatenated response as LargeBinary" - .into(), - request_id: request_id.clone(), - status_code: None, - })? - .clone() - }; - if blobs.len() != row_ids.len() { + .expect("casting to LargeBinary returns LargeBinary"); + rows += array.len(); + blobs.append(array)?; + } + if rows != row_ids.len() { return Err(Error::Http { source: format!( "fetch_blobs returned {} rows for {} row ids", - blobs.len(), + rows, row_ids.len() ) .into(), @@ -554,7 +699,7 @@ impl RemoteTable { status_code: None, }); } - Ok(blobs) + Ok(()) } /// Materialize ranges through version-pinned handles, preserving nulls and order. @@ -1893,9 +2038,8 @@ mod tests { [ ("bytes=0-0".to_string(), None), ("bytes=5-8".to_string(), Some("5".to_string())), - ("bytes=0-3".to_string(), Some("5".to_string())), ( - format!("bytes=10-{}", PAYLOAD.len() - 1), + format!("bytes=0-{}", PAYLOAD.len() - 1), Some("5".to_string()) ), ] @@ -1943,7 +2087,7 @@ mod tests { } #[tokio::test] - async fn remote_blob_file_releases_response_after_each_partial_read() { + async fn remote_blob_file_reuses_prefetched_bytes_across_reads_and_seeks() { let requests = Arc::new(StdMutex::new(Vec::new())); let table = mock_remote_blob_table(requests.clone()); let file = table @@ -1961,7 +2105,41 @@ mod tests { assert_eq!(file.tell().await.unwrap(), 24); assert_eq!( requests.lock().unwrap().as_slice(), - ["bytes=0-0", "bytes=0-3", "bytes=4-6", "bytes=20-23"] + ["bytes=0-0", &format!("bytes=0-{}", PAYLOAD.len() - 1)] + ); + } + + #[tokio::test] + async fn remote_buffer_boundaries_and_disabled_read_ahead() { + let requests = Arc::new(StdMutex::new(Vec::new())); + let table = mock_remote_blob_table(requests.clone()); + let file = table + .probe_files("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + file.set_buffer_size(4).await.unwrap(); + assert_eq!(file.read_up_to(3).await.unwrap(), &PAYLOAD[..3]); + assert_eq!(file.read_up_to(3).await.unwrap(), &PAYLOAD[3..6]); + file.seek(5).await.unwrap(); + assert_eq!(file.read_up_to(2).await.unwrap(), &PAYLOAD[5..7]); + assert_eq!(file.read_range(5..6).await.unwrap(), &PAYLOAD[5..6]); + assert_eq!(file.tell().await.unwrap(), 7); + file.set_buffer_size(0).await.unwrap(); + assert_eq!(file.read_up_to(1).await.unwrap(), &PAYLOAD[7..8]); + assert_eq!(file.read_up_to(1).await.unwrap(), &PAYLOAD[8..9]); + assert_eq!( + requests.lock().unwrap().as_slice(), + [ + "bytes=0-0", + "bytes=0-3", + "bytes=4-7", + "bytes=5-5", + "bytes=7-7", + "bytes=8-8" + ] ); } @@ -2198,6 +2376,7 @@ mod tests { .flatten() .unwrap(); + file.set_buffer_size(0).await.unwrap(); let error = file.read_up_to(10).await.unwrap_err(); assert!( error.to_string().contains("returned 5 bytes, expected 10"), @@ -2324,6 +2503,7 @@ mod tests { file.read_up_to(1).await.unwrap_err(), file.seek(0).await.unwrap_err(), file.tell().await.unwrap_err(), + file.set_buffer_size(0).await.unwrap_err(), ] { assert!(error.to_string().contains("already closed"), "got: {error}"); } @@ -2530,10 +2710,114 @@ mod tests { assert!(error.to_string().contains("206"), "got: {error}"); } + #[tokio::test] + async fn impossible_range_capacity_returns_an_error() { + let size = isize::MAX as u64 + 1; + let table = RemoteTable::new_mock( + "videos".to_string(), + move |request| { + let range = request + .headers() + .get(header::RANGE) + .unwrap() + .to_str() + .unwrap(); + let end = if range == "bytes=0-0" { 0 } else { size - 1 }; + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, format!("bytes 0-{end}/{size}")) + .header(VERSION_HEADER, "5") + .body(vec![1]) + .unwrap() + }, + Some(Version::new(0, 5, 0)), + ); + let file = table + .probe_files("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + let error = file.read().await.unwrap_err(); + assert!( + error.to_string().contains("cannot allocate blob range"), + "{error}" + ); + assert_eq!(file.tell().await.unwrap(), 0); + } + + #[derive(Debug)] + struct TrackedRangeBody { + bytes: Vec, + dropped: Arc, + } + + impl AsRef<[u8]> for TrackedRangeBody { + fn as_ref(&self) -> &[u8] { + &self.bytes + } + } + + impl Drop for TrackedRangeBody { + fn drop(&mut self) { + self.dropped.store(true, Ordering::Release); + } + } + + #[tokio::test] + async fn close_releases_existing_cache_after_in_flight_read_ends() { + for cancel in [false, true] { + let release = Arc::new(tokio::sync::Barrier::new(2)); + let started = Arc::new(tokio::sync::Notify::new()); + let dropped = Arc::new(AtomicBool::new(false)); + let file = Arc::new(RemoteBlobFile::new( + Arc::new(BlockingRangeRequester { + release: release.clone(), + started: started.clone(), + block_start: 4, + tracked: Some(dropped.clone()), + }), + PAYLOAD.len() as u64, + Some(5), + )); + file.set_buffer_size(4).await.unwrap(); + assert_eq!(file.read_up_to(1).await.unwrap().as_ref(), &PAYLOAD[..1]); + file.seek(3).await.unwrap(); + assert!( + !dropped.load(Ordering::Acquire), + "warm cache was not retained" + ); + let reader = { + let file = file.clone(); + tokio::spawn(async move { file.read_up_to(2).await }) + }; + started.notified().await; + tokio::time::timeout(Duration::from_millis(50), file.close()) + .await + .expect("close waited for I/O") + .unwrap(); + if cancel { + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + } else { + release.wait().await; + let error = reader.await.unwrap().unwrap_err(); + assert!(error.to_string().contains("already closed"), "{error}"); + } + assert!( + dropped.load(Ordering::Acquire), + "closed handle retained its old window (cancel={cancel})" + ); + } + } + #[derive(Debug)] struct BlockingRangeRequester { release: Arc, started: Arc, + block_start: usize, + tracked: Option>, } #[async_trait::async_trait] @@ -2544,17 +2828,31 @@ mod tests { _mode: RangeRequestMode, _version: Option, ) -> Result { - if range_header == "bytes=0-3" { + let (start, end) = range_header + .strip_prefix("bytes=") + .unwrap() + .split_once('-') + .unwrap(); + let start: usize = start.parse().unwrap(); + let end: usize = end.parse().unwrap(); + if start == self.block_start { self.started.notify_one(); self.release.wait().await; } + let bytes = match &self.tracked { + Some(dropped) if start == 0 => Bytes::from_owner(TrackedRangeBody { + bytes: PAYLOAD[start..=end].to_vec(), + dropped: dropped.clone(), + }), + _ => Bytes::copy_from_slice(&PAYLOAD[start..=end]), + }; let response = http::Response::builder() .status(StatusCode::PARTIAL_CONTENT) .header( header::CONTENT_RANGE, - format!("bytes 0-{}/{}", PAYLOAD.len() - 1, PAYLOAD.len()), + format!("bytes {start}-{end}/{}", PAYLOAD.len()), ) - .body(PAYLOAD.to_vec()) + .body(bytes) .unwrap(); Ok(("hung".to_string(), Response::from(response)).into()) } @@ -2567,6 +2865,8 @@ mod tests { let requester: Arc = Arc::new(BlockingRangeRequester { release: release.clone(), started: started.clone(), + block_start: 0, + tracked: None, }); let file = Arc::new(RemoteBlobFile::new( requester, diff --git a/rust/lancedb/src/remote/table/blobs/aggregate.rs b/rust/lancedb/src/remote/table/blobs/aggregate.rs new file mode 100644 index 000000000..e8e794fa0 --- /dev/null +++ b/rust/lancedb/src/remote/table/blobs/aggregate.rs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Flatten response batches once, releasing each source buffer as it is copied. + +use std::collections::VecDeque; + +use arrow_array::{Array, LargeBinaryArray}; +use arrow_buffer::{Buffer, MutableBuffer, NullBufferBuilder, OffsetBuffer}; +use arrow_schema::ArrowError; + +pub(super) struct BlobAccumulator { + offsets: Vec, + nulls: NullBufferBuilder, + values: VecDeque, + bytes: i64, +} + +impl BlobAccumulator { + pub(super) fn new(rows: usize) -> Self { + let mut offsets = Vec::with_capacity(rows + 1); + offsets.push(0); + Self { + offsets, + nulls: NullBufferBuilder::new(rows), + values: VecDeque::new(), + bytes: 0, + } + } + + pub(super) fn append(&mut self, array: &LargeBinaryArray) -> Result<(), ArrowError> { + let offsets = array.value_offsets(); + let start = offsets[0]; + let length = offsets[array.len()] - start; + let total = self.bytes.checked_add(length).ok_or_else(|| { + ArrowError::ComputeError("fetch_blobs result exceeds i64 byte offsets".into()) + })?; + self.offsets.extend( + offsets[1..] + .iter() + .map(|offset| self.bytes + (*offset - start)), + ); + if let Some(nulls) = array.nulls() { + self.nulls.append_buffer(nulls); + } else { + self.nulls.append_n_non_nulls(array.len()); + } + if length != 0 { + self.values.push_back( + array + .values() + .slice_with_length(start as usize, length as usize), + ); + } + self.bytes = total; + Ok(()) + } + + pub(super) fn finish(mut self) -> LargeBinaryArray { + let values = match self.values.len() { + 0 => Buffer::default(), + 1 => self.values.pop_front().unwrap(), + _ => { + let mut values = MutableBuffer::new(self.bytes as usize); + // Do not retain all decoded batches alongside the final allocation. + // Drop each source allocation immediately after copying its bytes. + while let Some(chunk) = self.values.pop_front() { + values.extend_from_slice(&chunk); + } + values.into() + } + }; + LargeBinaryArray::new( + OffsetBuffer::new(self.offsets.into()), + values, + self.nulls.finish(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_buffer_is_not_copied() { + let array = LargeBinaryArray::from(vec![Some(b"alpha".as_slice()), None, Some(b"")]); + let mut result = BlobAccumulator::new(3); + result.append(&array).unwrap(); + let output = result.finish(); + assert_eq!(output.values().as_ptr(), array.values().as_ptr()); + assert_eq!(output, array); + } + + #[test] + fn slices_batches_nulls_and_empty_values_keep_order() { + let array = LargeBinaryArray::from(vec![ + Some(b"unused".as_slice()), + Some(b"alpha"), + None, + Some(b""), + Some(b"beta"), + ]); + let mut result = BlobAccumulator::new(6); + result.append(&array.slice(1, 3)).unwrap(); + result.append(&array.slice(4, 1)).unwrap(); + result.append(&array.slice(2, 2)).unwrap(); + assert_eq!( + result.finish(), + LargeBinaryArray::from(vec![ + Some(b"alpha".as_slice()), + None, + Some(b""), + Some(b"beta"), + None, + Some(b""), + ]) + ); + assert_eq!(BlobAccumulator::new(0).finish().len(), 0); + } +} diff --git a/rust/lancedb/src/remote/table/ipc_stream.rs b/rust/lancedb/src/remote/table/ipc_stream.rs index af31a9b28..08b3b1dea 100644 --- a/rust/lancedb/src/remote/table/ipc_stream.rs +++ b/rust/lancedb/src/remote/table/ipc_stream.rs @@ -3,6 +3,10 @@ //! Incremental decoding of response bodies that use Arrow IPC stream framing. +mod framing; + +use framing::{FramingError, IpcFraming}; + use arrow_array::RecordBatch; use arrow_buffer::Buffer; use arrow_ipc::reader::StreamDecoder; @@ -10,7 +14,6 @@ use bytes::Bytes; use datafusion_common::DataFusionError; use datafusion_physical_plan::SendableRecordBatchStream; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; -use futures::stream::BoxStream; use futures::{Stream, StreamExt, TryStreamExt}; use crate::error::{BoxError, Error, Result}; @@ -35,7 +38,7 @@ where E: Into + 'static, { let mut body = IpcStreamBody { - chunks: chunks.map_err(Into::into).boxed(), + framing: IpcFraming::new(chunks.map_err(Into::into).boxed()), chunk: Buffer::default(), decoder: StreamDecoder::new(), finished: false, @@ -62,7 +65,7 @@ where } struct IpcStreamBody { - chunks: BoxStream<'static, std::result::Result>, + framing: IpcFraming, /// The part of the current chunk that has not been decoded yet. chunk: Buffer, decoder: StreamDecoder, @@ -80,11 +83,12 @@ impl IpcStreamBody { async fn next_batch(&mut self) -> Result> { while !self.finished { if self.chunk.is_empty() { - match self.chunks.next().await { - Some(Ok(chunk)) => self.chunk = chunk.into(), - Some(Err(error)) => return Err(self.interrupted(error)), - None if read_end_of_stream(&mut self.decoder) => self.finished = true, - None => { + match self.framing.next_buffer().await { + Ok(Some(chunk)) => self.chunk = chunk, + Err(FramingError::Interrupted(error)) => return Err(self.interrupted(error)), + Err(FramingError::Arrow(error)) => return Err(error.into()), + Ok(None) if read_end_of_stream(&mut self.decoder) => self.finished = true, + Ok(None) => { return Err(self.interrupted( "the response ended before the Arrow end-of-stream marker".into(), )); @@ -208,6 +212,37 @@ mod tests { .collect() } + #[tokio::test] + async fn impossible_ipc_body_lengths_return_errors() { + let batches = batches(); + let messages = messages(&batches[0].schema(), &batches, IpcWriteOptions::default()); + for length in [-1, i64::MAX - 31, i64::MAX] { + let mut message = messages[1].clone(); + let metadata_len = u32::from_le_bytes(message[4..8].try_into().unwrap()) as usize; + let metadata = arrow_ipc::root_as_message(&message[8..8 + metadata_len]).unwrap(); + let field = metadata + ._tab + .vtable() + .get(arrow_ipc::Message::VT_BODYLENGTH); + assert_ne!(field, 0, "fixture must contain a body length field"); + let offset = 8 + metadata._tab.loc() + field as usize; + message[offset..offset + 8].copy_from_slice(&length.to_le_bytes()); + // A valid schema and message metadata followed by just one body byte. + message.truncate(8 + metadata_len + 1); + let (_, returned, error) = read(vec![ + Ok(Bytes::copy_from_slice(&messages[0])), + Ok(Bytes::from(message)), + ]) + .await; + assert!(returned.is_empty()); + let error = error.unwrap().to_string(); + assert!( + error.contains("body length") || error.contains("cannot allocate IPC message"), + "unexpected error for length {length}: {error}" + ); + } + } + /// The schema, the batches yielded, and the error that ended the stream. async fn read( chunks: Vec>, @@ -278,6 +313,78 @@ mod tests { assert_eq!(output, input); } + #[tokio::test] + async fn fragmented_body_keeps_only_its_declared_allocation() { + use arrow_array::LargeBinaryArray; + + let bytes = vec![42; 3 * 1024 * 1024 + 13]; + let array = LargeBinaryArray::from(vec![bytes.as_slice()]); + let batch = RecordBatch::try_from_iter([("blob", Arc::new(array) as ArrayRef)]).unwrap(); + let body = messages( + &batch.schema(), + std::slice::from_ref(&batch), + IpcWriteOptions::default(), + ) + .concat(); + let (_, output, error) = read(chunks(&body, 8191)).await; + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, [batch]); + let blobs = output[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!( + blobs.values().capacity() <= bytes.len() + 256, + "IPC body retained {} bytes for {} value bytes", + blobs.values().capacity(), + bytes.len() + ); + } + + #[rstest] + #[case(false)] + #[case(true)] + #[tokio::test] + async fn zero_body_batches_and_legacy_prefixes(#[case] legacy: bool) { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let input = [vec![], vec![1, 2], vec![]] + .into_iter() + .map(|values| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(values))]) + .unwrap() + }) + .collect::>(); + let options = IpcWriteOptions::try_new(8, legacy, arrow_ipc::MetadataVersion::V4).unwrap(); + let body = messages(&schema, &input, options).concat(); + let (_, output, error) = read(chunks(&body, 1)).await; + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, input); + } + + #[tokio::test] + async fn partial_next_prefix_still_delivers_a_zero_body_batch() { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let empty = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(Vec::::new()))], + ) + .unwrap(); + let nonempty = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1]))]) + .unwrap(); + let messages = messages( + &schema, + &[empty.clone(), nonempty], + IpcWriteOptions::default(), + ); + let cutoff = messages[..2].concat().len() + 1; + let body = messages.concat(); + let (_, output, error) = read(chunks(&body[..cutoff], 1)).await; + assert_eq!(output, [empty]); + assert_interrupted(error, 1, 0); + } + /// The server answers an empty result with the schema and the end-of-stream marker. #[tokio::test] async fn empty_result_keeps_its_schema() { diff --git a/rust/lancedb/src/remote/table/ipc_stream/framing.rs b/rust/lancedb/src/remote/table/ipc_stream/framing.rs new file mode 100644 index 000000000..da20c8e99 --- /dev/null +++ b/rust/lancedb/src/remote/table/ipc_stream/framing.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Frame IPC bodies before decoding, avoiding StreamDecoder's growing scratch buffer. + +use arrow_buffer::Buffer; +use arrow_schema::ArrowError; +use bytes::Bytes; +use futures::StreamExt; +use futures::stream::BoxStream; + +use crate::error::BoxError; + +pub(super) enum FramingError { + Interrupted(BoxError), + Arrow(ArrowError), +} + +#[derive(Clone, Copy)] +enum Frame { + Header { + bytes: [u8; 4], + read: usize, + continuation: bool, + }, + Metadata(usize), + Body(usize), + End, +} + +impl Default for Frame { + fn default() -> Self { + Self::Header { + bytes: [0; 4], + read: 0, + continuation: false, + } + } +} + +pub(super) struct IpcFraming { + chunks: BoxStream<'static, Result>, + chunk: Buffer, + frame: Frame, +} + +impl IpcFraming { + pub(super) fn new(chunks: BoxStream<'static, Result>) -> Self { + Self { + chunks, + chunk: Buffer::default(), + frame: Frame::default(), + } + } + + pub(super) async fn next_buffer(&mut self) -> Result, FramingError> { + let buffer = match self.frame { + Frame::Header { + mut bytes, + mut read, + continuation, + } => { + // Forward even a partial prefix immediately. StreamDecoder may + // need that byte to yield the preceding zero-body record batch. + self.fill_chunk().await?; + let take = self.chunk.len().min(4 - read); + let buffer = self.chunk.slice_with_length(0, take); + self.chunk.advance(take); + bytes[read..read + take].copy_from_slice(&buffer); + read += take; + self.frame = if read == 4 { + match u32::from_le_bytes(bytes) { + u32::MAX if !continuation => Frame::Header { + bytes: [0; 4], + read: 0, + continuation: true, + }, + 0 => Frame::End, + length => Frame::Metadata(length as usize), + } + } else { + Frame::Header { + bytes, + read, + continuation, + } + }; + buffer + } + Frame::Metadata(length) => { + let metadata = self.read_exact(length).await?; + let message = arrow_ipc::root_as_message(&metadata).map_err(|error| { + FramingError::Arrow(ArrowError::IpcError(format!( + "Invalid IPC message: {error}" + ))) + })?; + let length = usize::try_from(message.bodyLength()).map_err(|_| { + FramingError::Arrow(ArrowError::IpcError( + "IPC message body length is negative or exceeds addressable memory".into(), + )) + })?; + self.frame = if length == 0 { + Frame::default() + } else { + Frame::Body(length) + }; + metadata + } + Frame::Body(length) => { + let body = self.read_exact(length).await?; + self.frame = Frame::default(); + body + } + Frame::End => { + // Forward trailing bytes to the decoder so it rejects data after EOS. + if !self.chunk.is_empty() { + return Ok(Some(std::mem::take(&mut self.chunk))); + } + return self + .chunks + .next() + .await + .transpose() + .map(|chunk| chunk.map(Buffer::from)) + .map_err(FramingError::Interrupted); + } + }; + Ok(Some(buffer)) + } + + async fn read_exact(&mut self, length: usize) -> Result { + self.fill_chunk().await?; + if self.chunk.len() >= length { + let buffer = self.chunk.slice_with_length(0, length); + self.chunk.advance(length); + return Ok(buffer); + } + // The declared length is untrusted. Arrow's infallible aligned allocator + // can panic on its layout or abort on OOM; Vec exposes both as errors. + // StreamDecoder handles any array-specific alignment when decoding. + let mut buffer = Vec::new(); + buffer.try_reserve_exact(length).map_err(|error| { + FramingError::Arrow(ArrowError::IpcError(format!( + "cannot allocate IPC message of {length} bytes: {error}" + ))) + })?; + while buffer.len() < length { + self.fill_chunk().await?; + let take = self.chunk.len().min(length - buffer.len()); + buffer.extend_from_slice(&self.chunk[..take]); + self.chunk.advance(take); + } + Ok(Buffer::from_vec(buffer)) + } + + async fn fill_chunk(&mut self) -> Result<(), FramingError> { + while self.chunk.is_empty() { + self.chunk = self + .chunks + .next() + .await + .ok_or_else(|| { + FramingError::Interrupted( + "the response ended before the Arrow end-of-stream marker".into(), + ) + })? + .map_err(FramingError::Interrupted)? + .into(); + } + Ok(()) + } +} From 725eee8a47399ec634ad20b98e4968334d89b27d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:13 +0800 Subject: [PATCH 26/75] fix: prevent unsafe write retries and bound Blob uploads (#4977) Ambiguous gateway failures can occur after a write commits, so replaying the operation can append duplicate rows. Non-idempotent writes now retry only known precommit failures. Multipart retries reuse the same upload ID, part ID, and encoded bytes; ambiguous completion returns an unknown-outcome error without abort or replay. A definite 409/429 completion rejection triggers best-effort cleanup using the call's retry budget. Replayable parts and the shared byte-based partition target default to 64 MiB. Dictionary-bearing batches are compacted before size estimation and again when actual compressed IPC framing requires further splitting: keys are remapped without changing their types or schema, view backing buffers are collected, and ListView/LargeListView child ranges are compacted as an interval union so overlapping views retain sharing. Parts are prepared on demand; a single row and its schema can still exceed the target. Multipart progress starts at zero and counts each acknowledged IPC body once. Rust write builders and Python/TypeScript `add` expose per-call retry overrides. Atomic `create_table` pre-encodes to a temporary file and rejects compressed IPC over 256 MiB before sending any request; the schema-first import guidance now includes Python, TypeScript, and Rust examples. The shared partition target also affects local automatic partitioning. At `cb2a79473bd1b51b950c9fa3e9f247f929c8ac3b`, 70 targeted Rust cases pass on source verified against the committed four-file patch. With a 16 KiB target and 128 unique 1 KiB dictionary values, the original ordinary dictionary reproducer drops from 128 requests / 16,942,080 bytes to 16 / 143,488; ListView and LargeListView drop from 128 / 17,056,768 to 16 / 149,632. Encoded HTTP bodies are decoded to check values, nulls, slices, metadata, changing dictionaries, and overlapping views; additional cases cover framing-driven splitting, oversized rows, stable retry bytes/IDs, acknowledged progress, and atomic create. Real HTTP fault tests commit Blob payloads to a local Lance table and verify byte equality, no duplicate append, and zero abort/replay after ambiguous completion. The earlier 811 remote and 7 progress cases at `f36d217110a25f6b501c0255df9aaa60e3c8000a`, Linux Python remote database/options results (437 cases plus 8 fixture consumers), Node retry-binding evidence, and Rust/TypeScript documentation example checks remain historical validation. Python/Node extensions were not rebuilt for the dictionary follow-up; these results do not establish current binding integration or fresh cross-platform/minimum-dependency CI acceptance. A separate real Query Node lifecycle experiment used SDK `b8efe7d2d63647d4962789ca5fc042b59efe073d` and Sophon `58b7895c7c287810fff4e89f13226fc5fa60d9ef`. After the actual listener forced a connection closed, a surviving QN accepted a retry with identical upload ID, part ID, and IPC bytes. Ordinary insert and complete response-loss scenarios sent no replay or abort; fresh reads observed exactly one commit and exact Blob bytes in all three scenarios. This local experiment used a 1-second drain grace, two 32 KiB payloads, and one distinct staged part. It validates acknowledgement-loss recovery at those revisions, not concurrent overlapping attempts, large uploads, physical orphan cleanup, the later dictionary encoding change, or the original sixth-insert EOF. The part target is not a process memory limit: source/ancestor buffers and temporary compaction allocations may coexist. Struct/FixedSizeList parent nulls can retain hidden child keys; this is not complete logical-reachability GC for every Arrow combination, and retained hidden values may affect wire size. The current local Lance 15.0.0-beta.17 rejects ListView/LargeListView persistence; the tests establish remote client IPC encoding behavior, not native or Cloud persistence support. Live Cloud, full workspace/Clippy, the original ordinary-insert disconnect root cause, and Sophon's asynchronous transaction cleanup behavior are not established. Cancelling during staging retains the existing server-session cleanup limitation. Function reader delivery is separate. --- docs/src/js/interfaces/AddDataOptions.md | 12 + docs/web/ingestion/insert.mdx | 102 ++- nodejs/__test__/remote.test.ts | 59 ++ nodejs/lancedb/table.ts | 16 + nodejs/src/table.rs | 8 +- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/remote/table.py | 5 + python/python/lancedb/table.py | 17 + python/python/tests/test_remote_db.py | 302 ++++++- python/src/table.rs | 6 +- rust/lancedb/src/data/scannable.rs | 8 +- rust/lancedb/src/remote/client.rs | 65 +- rust/lancedb/src/remote/db.rs | 145 ++- rust/lancedb/src/remote/retry.rs | 35 +- rust/lancedb/src/remote/table.rs | 441 +++++++--- rust/lancedb/src/remote/table/insert.rs | 875 +++++++++++++++---- rust/lancedb/src/remote/table/write_tests.rs | 436 +++++++++ rust/lancedb/src/remote/util.rs | 283 +++++- rust/lancedb/src/table/add_data.rs | 12 + rust/lancedb/src/table/merge.rs | 10 + rust/lancedb/src/table/update.rs | 9 + rust/lancedb/src/table/write_progress.rs | 27 +- 22 files changed, 2484 insertions(+), 390 deletions(-) create mode 100644 rust/lancedb/src/remote/table/write_tests.rs diff --git a/docs/src/js/interfaces/AddDataOptions.md b/docs/src/js/interfaces/AddDataOptions.md index f1f57b98b..567269471 100644 --- a/docs/src/js/interfaces/AddDataOptions.md +++ b/docs/src/js/interfaces/AddDataOptions.md @@ -71,3 +71,15 @@ await table.add(data, { }, }); ``` + +*** + +### retries? + +```ts +optional retries: number; +``` + +Override the remote retry budget for this call (0 to 255). Zero disables +retries, including multipart parts. Ambiguous commits are never replayed. +Ignored by LanceDB Embedded. diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index befc1c37b..923a71b0e 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -150,6 +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. + 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 after a write fails or is cancelled. Input errors before writing starts may @@ -164,11 +168,29 @@ from a TypeScript callback are logged and do not abort the write. Wait for the write operation's result, then check the expected records. Progress callbacks describe activity; they do not establish that a write succeeded. If a request fails after the server may have committed it, blindly -repeating an append can duplicate rows. The client's automatic retries can do -the same: on an Enterprise table, the Python and TypeScript 0.40.0 clients resend an -append after a retryable status such as `504`, even when the server had already -committed it, and `add()` still returns success. Reconcile using your record -IDs, or choose an upsert policy designed for replay. +repeating an append can duplicate rows. Current clients do not automatically +replay non-idempotent writes after `500`, `502`, `503`, or `504`, or after a +response is lost. A plain `503` does not prove that a write was rejected before +commit. Connection failures before sending, `409` transaction conflicts, and +explicit `429` rate-limit rejections may be retried within `RetryConfig` limits. Idempotent multipart +parts have a separate retry policy described below. + +If multipart completion times out, loses its response, or receives a `5xx`, the +error reports **commit outcome unknown**. The client neither aborts the upload +nor resends completion or the input under +a new upload ID: aborting at this point could delete already committed data. +Check the table using your record IDs before retrying the operation. + +Configure connection-wide limits with `client_config.retry_config` in Python +(`lancedb.remote.RetryConfig`) or `clientConfig.retryConfig` in TypeScript. +Override the budget for one `add()` with Python `table.add(data, retries=0)` +or TypeScript `table.add(data, { retries: 0 })`. The value must be an integer +between 0 and 255. Rust write builders also provide a per-call override, for +example `table.add(data).retries(0).execute().await?`, +`table.update().retries(0)`, and `table.merge_insert(&["id"]).retries(0)`. +This disables transport retries for that operation, including multipart part +retries; it does not change local transaction conflict handling. Increasing a +retry budget never makes ambiguous commits safe to replay. ## Configure large uploads {#bulk-ingests-into-a-remote-table} @@ -176,26 +198,41 @@ IDs, or choose an upsert policy designed for replay. This section applies only to LanceDB Enterprise tables (`db://` connections). LanceDB Embedded writes are unaffected. -When you write to a LanceDB Enterprise table, the client sends the write as one HTTP `insert` request unless it splits the data into more than one partition, which it does for a large input it can measure or when you set [`write_parallelism`](#write-parallelism). A partitioned write goes up as a multipart write: the client cuts each partition into one or more `insert` parts and uploads them under a single upload id. Each part is streamed. Its size and duration still affect resource use and -timeouts: it has to finish within the client read timeout while the server writes it to object storage, so on very large ingests an oversized part can run past that timeout and surface as: +Large measured inputs, unknown-length streams, and explicit parallel uploads use +multipart writes when the server supports them. The client slices large batches +before IPC encoding and buffers each part for replay. A disconnected request, +read timeout, or configured retryable staging status retries exactly the same +upload ID, part ID, and IPC bytes. `RetryConfig.statuses` controls status retries; +an empty list disables them. The default includes `500`, `502`, `503`, and `504`. +The server replaces that part's staged transaction, so losing +its response does not append the rows twice. Exhausting the part retry budget +aborts the uncommitted session; it does not restart the entire upload. +A complete request rejected with a transaction conflict (`409`) or rate limit +(`429`) also triggers best-effort cleanup. Cleanup uses the call's retry budget; +its failure does not replace the original error. Ambiguous completion outcomes +never trigger cleanup or replay. -```text -lancedb.remote.errors.HttpError: operation timed out -``` +Part size still affects memory and HTTP timeouts. A single blob row cannot be +split across Arrow batches; a very large row may require a larger timeout and +more memory. No connection-pool or keepalive setting guarantees that a write +response will arrive. Two environment variables control how a multipart write's parts are cut. Both are picked up automatically by the Python and TypeScript clients, for clients that support these settings: | Variable | Default | What it controls | |----------|---------|------------------| -| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 8 GiB | Maximum size of a single insert part, in LZ4-compressed Arrow IPC bytes. Set to `0` to disable splitting and send one request per partition. | -| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Maximum wall-clock time, in whole seconds, that any one insert part may stay open. Set to `0` to disable the time-based cut. | +| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 64 MiB | Target LZ4-compressed IPC bytes per replayable part. A single indivisible row and its IPC schema may exceed the target. `0` disables byte-based cuts and can require buffering a whole partition. | +| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Time spent filling a replayable payload, in whole seconds. `0` disables time-based cuts. HTTP deadlines are configured separately in `timeout_config`. | -A part is cut after the input batch that reaches either limit, so cuts fall between batches. Lower the byte budget, with smaller input batches, when large ingests hit the read timeout; lower the duration when uploads are slow or throttled and the byte budget isn't the limiting factor. +A part is cut after an encoding slice reaches either limit. Input batches are +sliced to approximately 8 MiB before encoding, preserving row order. Peak +additional memory scales with active writers and the part budget. Lower +`write_parallelism` or the byte budget to reduce memory use. ```bash Bash icon="terminal" -export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=1073741824 # 1 GiB -export LANCE_CLIENT_MAX_REQUEST_DURATION=120 # 2 minutes +export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=33554432 # 32 MiB +export LANCE_CLIENT_MAX_REQUEST_DURATION=30 # payload preparation budget ``` @@ -203,6 +240,41 @@ Splitting into more parts does not change the final table. The server stages the the write. This upload protocol is separate from repeating an application-level `add()` after a timeout. +Remote `create_table(name, data)` remains one atomic request, including overwrite +and `exist_ok` modes. The client encodes into an automatically removed temporary +file before sending, rejects payloads larger than 256 MiB of compressed IPC, and +never silently creates an empty table as a fallback. Encoding and input failures +therefore issue no create request. Temporary disk usage is bounded by this budget; +individual oversized rows can still need substantial encoding memory. + +For larger imports, create the schema first and upload with progress reporting. +The empty table becomes visible immediately; `add()` commits its rows atomically. +The following examples use an existing connection `db`, an Arrow `schema`, and +input `data` matching that schema (an Arrow reader in Rust): + + +```python Python icon="python" +table = db.create_table("items", schema=schema) +table.add(data, progress=True) +``` + +```typescript TypeScript icon="square-js" +const table = await db.createEmptyTable("items", schema); +await table.add(data, { + progress: (p) => console.log(`Rows written: ${p.outputRows}`), +}); +``` + +```rust Rust icon="rust" +let table = db.create_empty_table("items", schema).execute().await?; +table + .add(data) + .progress(|p| println!("Rows written: {}", p.output_rows())) + .execute() + .await?; +``` + + ## Complete write workflow {#complete-example} diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 4ac08b4c4..a9989b84e 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -483,6 +483,65 @@ describe("remote connection", () => { expect(insertRequests).toBe(2); }); + it.each([ + { status: 429, retries: undefined, attempts: 2 }, + { status: 429, retries: 0, attempts: 1 }, + { status: 504, retries: undefined, attempts: 1 }, + { status: 504, retries: 0, attempts: 1 }, + ])("applies per-call add retries: %j", async (scenario) => { + let attempts = 0; + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + expect(req.url).toContain("/insert/"); + req.resume(); + req.on("end", () => { + attempts++; + res + .writeHead(attempts === 1 ? scenario.status : 200) + .end('{"version":2}'); + }); + }, + async (db) => { + const table = await db.openTable("items"); + const result = table.add([{ id: 1n }], { retries: scenario.retries }); + if (scenario.attempts === 2) { + await expect(result).resolves.toMatchObject({ version: 2 }); + } else { + await expect(result).rejects.toThrow(); + } + for (const retries of [-1, 256, 1.5]) { + await expect(table.add([{ id: 2n }], { retries })).rejects.toThrow( + "retries must be an integer between 0 and 255", + ); + } + }, + { + clientConfig: { + retryConfig: { + retries: 3, + statuses: [429, 504], + backoffFactor: 0, + backoffJitter: 0, + }, + }, + }, + ); + expect(attempts).toBe(scenario.attempts); + }); + it("should accept partial connection options", async () => { await connect("db://test", { apiKey: "fake", diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index b38c2381c..185088424 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -137,6 +137,13 @@ export interface AddDataOptions { * when the blob is read later. */ allowExternalBlobOutsideBases?: boolean; + + /** + * Override the remote retry budget for this call (0 to 255). Zero disables + * retries, including multipart parts. Ambiguous commits are never replayed. + * Ignored by LanceDB Embedded. + */ + retries?: number; } export interface UpdateOptions { @@ -1320,6 +1327,14 @@ export class LocalTable extends Table { } async add(data: Data, options?: Partial): Promise { + if ( + options?.retries !== undefined && + (!Number.isInteger(options.retries) || + options.retries < 0 || + options.retries > 255) + ) { + throw new Error("retries must be an integer between 0 and 255"); + } const mode = options?.mode ?? "append"; const schema = await this.schema(); @@ -1342,6 +1357,7 @@ export class LocalTable extends Table { mode, progress, options?.allowExternalBlobOutsideBases, + options?.retries, ); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index e3bd22c0b..7076bbec1 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -134,7 +134,7 @@ impl Table { #[napi( catch_unwind, - ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean" + ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean, retries?: number" )] pub async fn add( &self, @@ -142,6 +142,7 @@ impl Table { mode: String, progress_callback: Option, allow_external_blob_outside_bases: Option, + retries: Option, ) -> napi::Result { let batches = ipc_file_to_batches(buf.to_vec()) .map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?; @@ -157,6 +158,11 @@ impl Table { }) .collect::>>()?; let mut op = self.inner_ref()?.add(batches); + if let Some(retries) = retries { + let retries = u8::try_from(retries) + .map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?; + op = op.retries(retries); + } op = if mode == "append" { op.mode(AddDataMode::Append) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4f1da9ba7..15234532d 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -544,6 +544,7 @@ class Table: progress: Optional[Any] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: ... async def update( self, updates: Dict[str, str], where: Optional[str] diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 21749a0a7..6730e6694 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -719,6 +719,7 @@ class RemoteTable(Table): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. @@ -753,6 +754,9 @@ class RemoteTable(Table): using too much memory. allow_external_blob_outside_bases: bool, default False Not supported in LanceDB Enterprise. Setting this raises. + retries: int, optional + Override the retry budget for this call (0 to 255). Zero disables + retries, including multipart parts. Ambiguous commits are never replayed. Returns ------- @@ -770,6 +774,7 @@ class RemoteTable(Table): progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) ) finally: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 424b4b64c..3161eda30 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2256,6 +2256,7 @@ class Table(ABC): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. @@ -2316,6 +2317,10 @@ class Table(ABC): Store blob URIs that sit outside registered blob bases. The row keeps a reference, so the object has to stay readable. Local tables only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. Returns ------- @@ -4821,6 +4826,7 @@ class LanceTable(Table): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add data to the table. If vector columns are missing and the table @@ -4852,6 +4858,10 @@ class LanceTable(Table): allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. LanceDB Embedded only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. Returns ------- @@ -4869,6 +4879,7 @@ class LanceTable(Table): progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) ) finally: @@ -7080,6 +7091,7 @@ class AsyncTable: progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [AsyncTable][lancedb.table.AsyncTable]. @@ -7118,6 +7130,10 @@ class AsyncTable: allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. LanceDB Embedded only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. """ schema = await self.schema() @@ -7172,6 +7188,7 @@ class AsyncTable: progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) except RuntimeError as e: if "Cast error" in str(e): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 8fde1209c..448fd6c39 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -59,20 +59,124 @@ import pyarrow as pa from utils import start_server_thread -def make_mock_http_handler(handler): +def make_mock_http_handler(handler, *, buffer_body=True): class MockLanceDBHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): handler(self) def do_POST(self): - handler(self) + if not buffer_body: + handler(self) + return - def do_PUT(self): - handler(self) + # HTTP/1.0 closes after the response. Leaving a streamed upload unread + # can reset the connection while the client is still writing its body. + # Keep the original framing so handlers can inspect the actual request. + source = self.rfile + body = bytearray() + if self.headers.get("Transfer-Encoding") == "chunked": + while True: + line = source.readline() + assert line.endswith(b"\r\n") + body.extend(line) + size = int(line.split(b";")[0], 16) + if size == 0: + while True: + line = source.readline() + assert line.endswith(b"\r\n") + body.extend(line) + if line == b"\r\n": + break + break + chunk = source.read(size + 2) + assert len(chunk) == size + 2 and chunk[-2:] == b"\r\n" + body.extend(chunk) + else: + size = int(self.headers.get("Content-Length", 0)) + body.extend(source.read(size)) + assert len(body) == size + self.rfile = io.BytesIO(body) + try: + handler(self) + finally: + self.rfile.close() + self.rfile = source + + do_PUT = do_POST return MockLanceDBHandler +@pytest.mark.parametrize("chunked", [False, True]) +@pytest.mark.parametrize("read_body", [False, True]) +def test_mock_http_handler_waits_for_body(chunked, read_body): + body = ( + b"7;ext=value\r\npayload\r\n0\r\nX-Trailer: value\r\n\r\n" + if chunked + else b"payload" + ) + received = [] + + def handler(request): + if read_body: + assert (request.headers.get("Transfer-Encoding") == "chunked") == chunked + received.append(request.rfile.read(len(body))) + request.send_response(200) + request.end_headers() + + with http.server.HTTPServer( + ("127.0.0.1", 0), make_mock_http_handler(handler) + ) as server: + thread = start_server_thread(server) + try: + with socket.create_connection(server.server_address, timeout=2) as client: + framing = ( + "Transfer-Encoding: chunked" if chunked else "Content-Length: 7" + ) + client.sendall( + f"POST / HTTP/1.0\r\nHost: localhost\r\n{framing}\r\n\r\n".encode() + ) + client.settimeout(0.1) + with pytest.raises(TimeoutError): + client.recv(1024) + client.settimeout(2) + client.sendall(body) + assert client.recv(1024).startswith(b"HTTP/1.0 200") + finally: + server.shutdown() + thread.join() + assert received == ([body] if read_body else []) + + +@pytest.mark.parametrize("disconnect", [False, True]) +def test_mock_http_handler_allows_early_failure(disconnect): + def handler(request): + if disconnect: + request.connection.shutdown(socket.SHUT_RDWR) + request.close_connection = True + else: + request.send_response(413) + request.end_headers() + + with http.server.HTTPServer( + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=False) + ) as server: + thread = start_server_thread(server) + try: + with socket.create_connection(server.server_address, timeout=2) as client: + client.sendall( + b"POST / HTTP/1.0\r\nHost: localhost\r\nContent-Length: 7\r\n\r\n" + ) + response = client.recv(1024) + if disconnect: + assert response == b"" + else: + assert response.startswith(b"HTTP/1.0 413") + finally: + server.shutdown() + thread.join() + + @pytest.mark.parametrize("db_name", ["a" * 64, "invalid..database"]) def test_connect_rejects_invalid_cloud_dns_hostname(db_name): with pytest.raises(ValueError, match="DNS labels must contain 1 to 63 bytes"): @@ -80,9 +184,9 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name): @contextlib.contextmanager -def mock_lancedb_connection(handler, **client_config): +def mock_lancedb_connection(handler, *, buffer_body=True, **client_config): with http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body) ) as server: port = server.server_address[1] handle = start_server_thread(server) @@ -108,9 +212,9 @@ def mock_lancedb_connection(handler, **client_config): @contextlib.asynccontextmanager -async def mock_lancedb_connection_async(handler, **client_config): +async def mock_lancedb_connection_async(handler, *, buffer_body=True, **client_config): with http.server.HTTPServer( - ("127.0.0.1", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body) ) as server: port = server.server_address[1] handle = start_server_thread(server) @@ -135,6 +239,76 @@ async def mock_lancedb_connection_async(handler, **client_config): handle.join() +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.parametrize("retries", [None, 0]) +@pytest.mark.parametrize("status", [429, 504]) +@pytest.mark.asyncio +async def test_add_retry_override(sync_api, retries, status): + attempts = 0 + + def handler(request): + nonlocal attempts + if request.path.endswith("/describe/"): + payload = { + "version": 1, + "schema": { + "fields": [ + {"name": "id", "type": {"type": "int64"}, "nullable": True} + ] + }, + } + request.send_response(200) + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + return + assert request.path.endswith("/insert/") + body = bytearray() + if request.headers.get("Transfer-Encoding") == "chunked": + while True: + size = int(request.rfile.readline().strip(), 16) + if size == 0: + request.rfile.readline() + break + body.extend(request.rfile.read(size)) + request.rfile.read(2) + else: + body.extend( + request.rfile.read(int(request.headers.get("Content-Length", 0))) + ) + assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}] + attempts += 1 + request.send_response(status if attempts == 1 else 200) + request.end_headers() + request.wfile.write(b'{"version": 2}') + + config = { + "retry_config": { + "retries": 3, + "statuses": [429, 504], + "backoff_factor": 0, + "backoff_jitter": 0, + } + } + expected_success = status == 429 and retries is None + if sync_api: + with mock_lancedb_connection(handler, **config) as db: + table = db.open_table("test") + if expected_success: + assert table.add([{"id": 1}], retries=retries).version == 2 + else: + with pytest.raises((HttpError, RetryError)): + table.add([{"id": 1}], retries=retries) + else: + async with mock_lancedb_connection_async(handler, **config) as db: + table = await db.open_table("test") + if expected_success: + assert (await table.add([{"id": 1}], retries=retries)).version == 2 + else: + with pytest.raises((HttpError, RetryError)): + await table.add([{"id": 1}], retries=retries) + assert attempts == (2 if expected_success else 1) + + @pytest.fixture def missing_table_handler(cached, namespace_path): request_ids = [] @@ -1248,7 +1422,7 @@ async def test_create_table_timeout_is_actionable(timeout_config): request.close_connection = True async with mock_lancedb_connection_async( - handler, timeout_config=timeout_config + handler, buffer_body=False, timeout_config=timeout_config ) as db: batch = pa.record_batch({"id": [1, 2]}) reader = pa.RecordBatchReader.from_batches(batch.schema, [batch]) @@ -5076,10 +5250,14 @@ def test_remote_schema_restores_blob_extensions(use_async, with_pylance, nested) @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) -@pytest.mark.parametrize("mode", ["merge", "overwrite"]) +@pytest.mark.parametrize( + "mode,part_status", + [("merge", 200), ("overwrite", 200), ("overwrite", 503)], + ids=["merge", "overwrite", "overwrite-retry"], +) @pytest.mark.parametrize("target_with_ranges", [False, True]) async def test_remote_writes_normalize_blob_layouts( - use_async, mode, target_with_ranges + use_async, mode, part_status, target_with_ranges, mem_db ): description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE)) if target_with_ranges: @@ -5088,29 +5266,77 @@ async def test_remote_writes_normalize_blob_layouts( for name in ("position", "size") ) received = [] + paths = [] + staged = {} + part_attempts = [] + published = mem_db.create_table( + "published", + [{"id": 0, "image": b"before"}], + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), + ) def handler(request): - if request.path == "/v1/table/test/describe/": + path = urlparse(request.path).path + query = parse_qs(urlparse(request.path).query) + status = 200 + if path == "/v1/table/test/describe/": response = description else: - expected = "merge_insert" if mode == "merge" else "insert" - assert urlparse(request.path).path == f"/v1/table/test/{expected}/" - if request.headers.get("Transfer-Encoding") == "chunked": - body = bytearray() - while size := int(request.rfile.readline().split(b";")[0], 16): - body.extend(request.rfile.read(size)) - assert request.rfile.read(2) == b"\r\n" - assert request.rfile.read(2) == b"\r\n" + paths.append(path.removeprefix("/v1/table/test/")) + body = request.rfile.read() + if path == "/v1/table/test/multipart_write/create": + assert mode == "overwrite" + assert paths == ["multipart_write/create"] + assert not query and not body + response = {"upload_id": "blob-overwrite"} + elif path == "/v1/table/test/insert/": + assert mode == "overwrite" + assert query["mode"] == ["overwrite"] + assert query["upload_id"] == ["blob-overwrite"] + part_id = query["upload_part_id"][0] + assert str(uuid.UUID(part_id)) == part_id + part_attempts.append((part_id, body)) + assert published.version == 1 + assert published.search().select(["id"]).to_list() == [{"id": 0}] + if staged: + assert staged == {part_id: body} + else: + staged[part_id] = body + assert body[-8:] == b"\xff\xff\xff\xff\x00\x00\x00\x00" + received.append(pa.ipc.open_stream(body).read_all()) + status = part_status if len(part_attempts) == 1 else 200 + response = {} + elif path == "/v1/table/test/multipart_write/complete": + assert mode == "overwrite" + assert query == {"upload_id": ["blob-overwrite"]} and not body + expected_attempts = 2 if part_status == 503 else 1 + assert paths == ["multipart_write/create"] + [ + "insert/" + ] * expected_attempts + ["multipart_write/complete"] + assert len(staged) == len(received) == 1 + assert part_attempts == [part_attempts[0]] * expected_attempts + assert published.version == 1 + published.add(received[0], mode="overwrite") + response = {"version": published.version} else: - body = request.rfile.read(int(request.headers["Content-Length"])) - received.append(pa.ipc.open_stream(body).read_all()) - response = { - "version": 2, - "num_updated_rows": 0, - "num_inserted_rows": 2, - "num_deleted_rows": 0, - } - request.send_response(200) + assert mode == "merge" + assert path == "/v1/table/test/merge_insert/" + # merge_insert still streams a chunked body; preserve its framing. + if request.headers.get("Transfer-Encoding") == "chunked": + stream = io.BytesIO(body) + body = bytearray() + while size := int(stream.readline().split(b";")[0], 16): + body.extend(stream.read(size)) + assert stream.read(2) == b"\r\n" + assert stream.read(2) == b"\r\n" + received.append(pa.ipc.open_stream(body).read_all()) + response = { + "version": 2, + "num_updated_rows": 0, + "num_inserted_rows": 2, + "num_deleted_rows": 0, + } + request.send_response(status) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", "0.5.0") request.end_headers() @@ -5143,7 +5369,23 @@ async def test_remote_writes_normalize_blob_layouts( else: result = table.add(data, mode="overwrite") if use_async: - await result + result = await result + assert result.version == 2 + + if mode == "overwrite": + assert published.version == 2 + hits = published.search().select(["id"]).with_row_id(True).to_arrow() + by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + assert set(by_id) == {1, 2} + row_ids = [by_id[1], by_id[2]] + assert published.fetch_blobs("image", row_ids).to_pylist() == [b"payload", None] + payload, null = published.fetch_blob_files("image", row_ids) + assert null is None + with payload: + assert payload.read_range(1, 3) == b"ayl" + assert payload.read() == b"payload" + else: + assert paths == ["merge_insert/"] assert len(received) == 1 images = received[0]["image"].combine_chunks() diff --git a/python/src/table.rs b/python/src/table.rs index 62c2ee765..e76bae00a 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1471,7 +1471,7 @@ impl Table { }) } - #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false))] + #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))] pub fn add<'a>( self_: PyRef<'a, Self>, data: PyScannable, @@ -1479,6 +1479,7 @@ impl Table { progress: Option>, write_parallelism: Option, allow_external_blob_outside_bases: bool, + retries: Option, ) -> PyResult> { let mut op = self_ .inner_ref()? @@ -1491,6 +1492,9 @@ impl Table { } else { return Err(PyValueError::new_err(format!("Invalid mode: {}", mode))); } + if let Some(retries) = retries { + op = op.retries(retries); + } if let Some(write_parallelism) = write_parallelism { op = op.write_parallelism(write_parallelism); } diff --git a/rust/lancedb/src/data/scannable.rs b/rust/lancedb/src/data/scannable.rs index 0f810941a..cfad157b8 100644 --- a/rust/lancedb/src/data/scannable.rs +++ b/rust/lancedb/src/data/scannable.rs @@ -504,7 +504,7 @@ impl Scannable for PeekedScannable { /// when known; otherwise `sample_rows` row count is used as a lower bound /// estimate. /// -/// Targets roughly 1 million rows or 2 GB per partition, capped at +/// Targets roughly 1 million rows or 64 MiB per partition, capped at /// `max_partitions` (typically the number of available CPU cores). pub(crate) fn estimate_write_partitions( sample_bytes: usize, @@ -519,7 +519,7 @@ pub(crate) fn estimate_write_partitions( let total_rows = total_rows_hint.unwrap_or(sample_rows); let total_bytes = total_rows * bytes_per_row; let by_rows = total_rows.div_ceil(1_000_000); - let by_bytes = total_bytes.div_ceil(2 * 1024 * 1024 * 1024); + let by_bytes = total_bytes.div_ceil(64 * 1024 * 1024); by_rows.max(by_bytes).max(1).min(max_partitions) } @@ -813,8 +813,8 @@ mod tests { #[test] fn test_scales_by_byte_size() { - // 100k rows at 40KB/row = ~4GB total → ceil(4GB / 2GB) = 2 - let sample_bytes = 40_000 * 10; + // 100k rows at 1KB/row exceeds one 64 MiB partition. + let sample_bytes = 1_000 * 10; assert_eq!( estimate_write_partitions(sample_bytes, 10, Some(100_000), 8), 2 diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index e0722bfbc..b16d0091d 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -69,14 +69,9 @@ pub trait HeaderProvider: Send + Sync + std::fmt::Debug { async fn get_headers(&self) -> Result>; } -/// Default maximum bytes per insert request (8 GiB). -/// -/// Sized so a multipart part can hold at least one full Lance data file (the -/// default is 1M rows / 90 GB per file), which keeps fragments from being split -/// into undersized files across parts. The time-based cut -/// ([`DEFAULT_MAX_REQUEST_DURATION_DIVISOR`]) bounds request duration on slow -/// uploads, so a large byte budget does not risk the read timeout. -const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 8 * 1024 * 1024 * 1024; +/// Default target size for replayable multipart IPC payloads (64 MiB). +/// A single oversized row (including its schema) may exceed the target. +const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 64 * 1024 * 1024; /// The default max request duration is the read timeout divided by this, leaving /// headroom for the server to finalize and acknowledge a part before the read @@ -114,28 +109,22 @@ pub struct ClientConfig { /// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment /// variable that contains the user ID value. pub user_id: Option, - /// Maximum number of bytes to send in a single insert HTTP request. + /// Target compressed IPC bytes per multipart request. Defaults to 64 MiB. /// - /// During a multipart write, each partition's data is split into one or more - /// parts of at most this many (Arrow IPC, compressed) bytes, each uploaded as - /// a separate request under the shared upload id. This bounds how long any - /// one request stays open, so large bulk ingests do not exceed the client - /// read timeout while the server streams the part to object storage. - /// - /// The request body is still streamed (not buffered), so this does not - /// increase peak memory. Set to `Some(0)` to disable splitting (one request - /// per partition). You can also set the `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` - /// environment variable. Defaults to 8 GiB. + /// Parts are buffered for retries with the same upload and part IDs. Input + /// batches are sliced before encoding. A single row and its schema are + /// indivisible and may exceed the target. Peak additional memory is bounded + /// by the number of active writers times the part size (plus encoding buffers). + /// Set to `Some(0)` to disable byte-based cuts, or configure + /// `LANCE_CLIENT_MAX_BYTES_PER_REQUEST`. Disabling cuts can require buffering + /// an entire partition for replay. pub max_bytes_per_request: Option, - /// Maximum wall-clock time to spend uploading a single insert HTTP request. + /// Maximum time spent filling a replayable multipart payload. /// - /// Complements [`Self::max_bytes_per_request`]: during a multipart write a - /// part is cut when it reaches either the byte budget or this duration, - /// whichever comes first. The client read timeout also covers the - /// request-body upload, so a slow or throttled upload of a large part can - /// hit that timeout before the byte budget is reached; cutting by time keeps - /// each request short enough that it completes (and the server acknowledges - /// the part) within the read timeout. + /// A part is cut after encoding a batch slice when either its byte budget + /// or this duration is reached. This does not impose a network deadline; + /// `timeout_config` controls HTTP timeouts. Timed-out parts are retried using + /// their original payload and transaction ID. /// /// Set to `Some(Duration::ZERO)` to disable the time-based cut. You can also /// set the `LANCE_CLIENT_MAX_REQUEST_DURATION` environment variable (integer @@ -306,8 +295,9 @@ pub struct RetryConfig { /// You can also set the `LANCE_CLIENT_RETRY_STATUSES` environment variable /// to set this value. Use a comma-separated list of integer values. /// - /// Note that write operations will never be retried on 5xx errors as this may - /// result in duplicated writes. + /// Non-idempotent writes do not replay ambiguous 5xx responses. Multipart + /// parts can retry configured statuses because each replay replaces the same + /// staged transaction. Completion is never replayed. /// /// The default is 409, 429, 500, 502, 503, 504. pub statuses: Option>, @@ -888,6 +878,16 @@ impl RestfulLanceDbClient { Ok((request_id, response)) } + pub(crate) fn with_retries(&self, retries: Option) -> Self { + let mut client = self.clone(); + if let Some(retries) = retries { + client.retry_config.retries = retries; + client.retry_config.connect_retries = retries; + client.retry_config.read_retries = retries; + } + client + } + /// Send the request using retries configured in the RetryConfig. /// If retry_5xx is false, 5xx requests will not be retried regardless of the statuses configured /// in the RetryConfig. @@ -963,6 +963,13 @@ impl RestfulLanceDbClient { return Err(source); } retry_counter.increment_request_failures(source)?; + if status.is_server_error() { + log::warn!( + "Retrying request {} after gateway status {}", + request_id, + status + ); + } } Err(err) if err.is_connect() => { retry_counter.increment_connect_failures(err)?; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 31808f244..b562f41df 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -31,7 +31,7 @@ use crate::job::Job; use crate::listing::{ListingOptions, ListingPage}; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::job::{PauseJobResponse, RemoteJob, ResumeJobResponse, job_state_to_client}; -use crate::remote::util::stream_as_body; +use crate::remote::util::create_body; use crate::secrets::SecretInfo; use crate::table::BaseTable; use crate::utils::{ @@ -1497,7 +1497,7 @@ impl Database for RemoteDatabase { } } let data_schema = request.data.schema(); - let body = stream_as_body(request.data.scan_as_stream())?; + let body = create_body(request.data.scan_as_stream()).await?; let identifier = build_table_identifier(&request.name, &request.namespace_path)?; let req = self @@ -2623,6 +2623,147 @@ mod tests { assert_eq!(table.name(), "table1"); } + #[tokio::test] + async fn test_create_table_over_budget_never_reaches_server() { + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + let mut bytes = vec![0u8; 8 * 1024 * 1024]; + SmallRng::seed_from_u64(42).fill_bytes(&mut bytes); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(arrow_array::LargeBinaryArray::from(vec![Some( + bytes.as_slice(), + )]))], + ) + .unwrap(); + for overwrite in [false, true] { + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |_| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + http::Response::builder().status(200).body("").unwrap() + }); + let input: Box = + Box::new(arrow_array::RecordBatchIterator::new( + (0..34).map(|_| Ok(batch.clone())).collect::>(), + batch.schema(), + )); + let mut create = conn.create_table("table1", input); + if overwrite { + create = create.mode(CreateTableMode::Overwrite); + } + let error = create.execute().await.unwrap_err(); + let message = error.to_string(); + assert!(message.contains("single-request budget"), "{message}"); + assert!( + message.contains("schema=") && message.contains("progress=True"), + "{message}" + ); + // The same assertion covers a new half-table and damage to an + // existing table under overwrite: neither mode sends a request. + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 0); + } + } + + #[tokio::test] + async fn test_create_table_slices_large_batches_in_one_atomic_request() { + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |request| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let bytes = request.body().unwrap().as_bytes().unwrap(); + let batches = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None) + .unwrap() + .collect::, _>>() + .unwrap(); + assert!(batches.len() > 1); + assert_eq!( + batches.iter().map(|b| b.num_rows()).sum::(), + 4_000_000 + ); + http::Response::builder().status(200).body("").unwrap() + }); + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from_iter_values(0..4_000_000))], + ) + .unwrap(); + conn.create_table("table1", input).execute().await.unwrap(); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_create_table_compacts_dictionary_slices_in_one_atomic_request() { + use arrow_array::{Array, DictionaryArray, StringArray, cast::AsArray, types::Int32Type}; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + + let mut bytes = vec![0; 128 * 72 * 1024]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(72 * 1024) + .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let mut batches = Vec::new(); + for values in [strings.clone(), strings.iter().rev().cloned().collect()] { + let dict = DictionaryArray::::new( + Int32Array::from_iter_values(0..128), + Arc::new(StringArray::from(values)), + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "category", + dict.data_type().clone(), + false, + )])); + batches.push(RecordBatch::try_new(schema, vec![Arc::new(dict)]).unwrap()); + } + let schema = batches[0].schema(); + let expected = strings + .iter() + .chain(strings.iter().rev()) + .cloned() + .collect::>(); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let wire_schema = schema.clone(); + let conn = Connection::new_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/table/table1/create/"); + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let body = request.body().unwrap().as_bytes().unwrap(); + let reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), wire_schema); + let batches = reader.collect::, _>>().unwrap(); + assert!( + (2..=8).contains(&batches.len()), + "dictionary produced {} encoding slices", + batches.len() + ); + let actual = batches + .iter() + .flat_map(|batch| { + let values = arrow_cast::cast(batch.column(0), &DataType::Utf8).unwrap(); + values + .as_string::() + .iter() + .map(|s| s.unwrap().to_owned()) + .collect::>() + }) + .collect::>(); + assert_eq!(actual, expected); + assert!(body.len() < 2 * bytes.len() + 64 * 1024); + http::Response::builder().status(200).body("").unwrap() + }); + let input: Box = Box::new( + arrow_array::RecordBatchIterator::new(batches.into_iter().map(Ok), schema), + ); + conn.create_table("table1", input).execute().await.unwrap(); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + } + #[tokio::test] async fn test_create_table_already_exists() { let conn = Connection::new_with_handler(|_| { diff --git a/rust/lancedb/src/remote/retry.rs b/rust/lancedb/src/remote/retry.rs index 51c9b2126..c0ef2bd11 100644 --- a/rust/lancedb/src/remote/retry.rs +++ b/rust/lancedb/src/remote/retry.rs @@ -63,7 +63,7 @@ impl<'a> RetryCounter<'a> { /// Increment the appropriate failure counter based on the error type. /// /// For `Error::Http` whose source is a connect error, increments - /// `connect_failures`. For read errors (`is_body` or `is_decode`), + /// `connect_failures`. For read errors (`is_timeout`, `is_body` or `is_decode`), /// increments `read_failures`. For all other errors, increments /// `request_failures`. Calls `check_out_of_retries` to enforce global limits. pub fn increment_from_error(&mut self, source: crate::Error) -> crate::Result<()> { @@ -74,7 +74,7 @@ impl<'a> RetryCounter<'a> { if reqwest_err.is_some_and(|e| e.is_connect()) { self.connect_failures += 1; - } else if reqwest_err.is_some_and(|e| e.is_body() || e.is_decode()) { + } else if reqwest_err.is_some_and(|e| e.is_timeout() || e.is_body() || e.is_decode()) { self.read_failures += 1; } else { self.request_failures += 1; @@ -187,6 +187,37 @@ mod tests { )); } + #[tokio::test] + async fn test_increment_from_error_read_timeout() { + 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 socket, _) = listener.accept().await.unwrap(); + let _ = tokio::io::copy(&mut socket, &mut tokio::io::sink()).await; + }); + let err = reqwest::Client::builder() + .read_timeout(Duration::from_millis(100)) + .build() + .unwrap() + .get(format!("http://{address}/")) + .send() + .await + .unwrap_err(); + assert!(err.is_timeout() && !err.is_connect()); + let config = test_config(); + let mut counter = RetryCounter::new(&config, "part-1".into()); + counter + .increment_from_error(Error::Http { + request_id: "part-1".into(), + status_code: None, + source: Box::new(err), + }) + .unwrap(); + assert_eq!(counter.read_failures, 1); + assert_eq!(counter.request_failures, 0); + server.abort(); + } + #[test] fn test_increment_from_error_request() { let config = test_config(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 48e5652ae..cc495a83f 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5,6 +5,8 @@ pub mod blobs; pub mod insert; mod ipc_stream; mod optimize; +#[cfg(test)] +mod write_tests; use self::insert::{RemoteWriteExec, WriteOp}; use super::client::RequestResultExt; @@ -1420,13 +1422,18 @@ impl RemoteTable { Ok(bodies) } - async fn create_multipart_write(&self) -> Result { + async fn create_multipart_write(&self, retries: Option) -> Result { let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/multipart_write/create", self.identifier ))); - let (request_id, response) = self.send(request, true).await?; + let client = self.client.with_retries(retries); + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = client + .send_with_retry(freshness_request.apply(request), None, true) + .await?; let response = self.check_table_response(&request_id, response).await?; + freshness_request.observe_headers(&self.freshness, response.headers()); let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse multipart create response: {}", e).into(), @@ -1452,7 +1459,7 @@ impl RemoteTable { )) .query(&[("upload_id", upload_id)]), ); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self.send(request, false).await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { @@ -1468,7 +1475,7 @@ impl RemoteTable { Ok(AddResult { version }) } - async fn abort_multipart_write(&self, upload_id: &str) -> Result<()> { + async fn abort_multipart_write(&self, upload_id: &str, retries: Option) -> Result<()> { let request = self.apply_branch_query( self.client .post(&format!( @@ -1477,7 +1484,14 @@ impl RemoteTable { )) .query(&[("upload_id", upload_id)]), ); - let (request_id, response) = self.send(request, true).await?; + let freshness = self.snapshot_freshness_headers(); + let client = self.client.with_retries(retries); + let (request_id, response) = client + .send_with_retry(freshness.apply(request), None, true) + .await?; + if response.status().is_success() { + freshness.observe_headers(&self.freshness, response.headers()); + } self.check_table_response(&request_id, response).await?; Ok(()) } @@ -1975,43 +1989,96 @@ mod test_utils { } } +#[derive(Debug)] +struct UnknownWriteOutcome { + upload_id: String, + source: Error, +} + +impl std::fmt::Display for UnknownWriteOutcome { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Multipart write {} commit outcome unknown; no abort or replay was attempted. Check the table before retrying: {}", + self.upload_id, self.source + ) + } +} + +impl std::error::Error for UnknownWriteOutcome { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.source) + } +} + impl RemoteTable { fn is_retryable_write_error(&self, err: &Error) -> bool { + // Transaction conflicts and explicit rate limits reject the write. + // A gateway 5xx says nothing about whether its manifest was committed. + let safe_status = |status| { + matches!(status, StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + && self.client.retry_config.statuses.contains(&status) + }; match err { Error::Http { source, status_code, .. } => { - // Don't retry read errors (is_body/is_decode): the - // server may have committed the write already, and - // without an idempotency key we'd duplicate data. source .downcast_ref::() .is_some_and(|e| e.is_connect()) - || status_code.is_some_and(|s| self.client.retry_config.statuses.contains(&s)) - } - // send_with_retry exhausted its internal retries on a retryable - // status. The outer loop can still retry the whole operation with - // a fresh session. - Error::Retry { status_code, .. } => { - status_code.is_some_and(|s| self.client.retry_config.statuses.contains(&s)) + || status_code.is_some_and(safe_status) } + Error::Retry { status_code, .. } => status_code.is_some_and(safe_status), _ => false, } } + async fn send_write_request( + &self, + request: RequestBuilder, + freshness: FreshnessHeaders, + retries: Option, + ) -> Result<(String, Response)> { + let client = self.client.with_retries(retries); + let mut counter = crate::remote::retry::RetryCounter::new( + &client.retry_config, + uuid::Uuid::new_v4().to_string(), + ); + loop { + let req = request.try_clone().ok_or_else(|| Error::Runtime { + message: "Write request cannot be replayed".into(), + })?; + let result = async { + let (id, response) = client.send(freshness.apply(req)).await?; + let response = self.check_table_response(&id, response).await?; + freshness.observe_headers(&self.freshness, response.headers()); + Ok((id, response)) + } + .await; + match result { + Err(err) if self.is_retryable_write_error(&err) => { + counter.increment_from_error(err)?; + tokio::time::sleep(counter.next_sleep_time()).await; + } + result => return result, + } + } + } + async fn add_single_partition(&self, output: PreprocessingOutput) -> Result { use crate::remote::retry::RetryCounter; let _guard = output.tracker.as_ref().map(|t| t.track_task()); + let client = self.client.with_retries(output.retries); let freshness_request = self.snapshot_freshness_headers(); let mut insert: Arc = Arc::new( RemoteWriteExec::new( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client.clone(), output.plan, WriteOp::Insert { overwrite: output.overwrite, @@ -2026,7 +2093,7 @@ impl RemoteTable { ); let mut retry_counter = - RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); + RetryCounter::new(&client.retry_config, uuid::Uuid::new_v4().to_string()); loop { let stream = execute_plan(insert.clone(), Default::default())?; @@ -2062,61 +2129,82 @@ impl RemoteTable { output: PreprocessingOutput, num_partitions: usize, ) -> Result { - use crate::remote::retry::RetryCounter; - - let mut retry_counter = - RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); - - loop { - let freshness_request = self.snapshot_freshness_headers(); - let upload_id = self.create_multipart_write().await?; - - let result = self - .execute_multipart_inserts(&upload_id, &output, num_partitions) - .await; - - match result { - Ok(()) => match self.complete_multipart_write(&upload_id).await { - Ok(result) => { - if output.overwrite { - self.invalidate_schema_cache(); - } - self.track_write_version(freshness_request, result.version); - return Ok(result); + if let Some(tracker) = &output.tracker { + tracker.use_wire_bytes(); + } + let freshness_request = self.snapshot_freshness_headers(); + let upload_id = self.create_multipart_write(output.retries).await?; + if let Err(err) = self + .execute_multipart_inserts(&upload_id, &output, num_partitions) + .await + { + if let Err(abort_err) = self.abort_multipart_write(&upload_id, output.retries).await { + log::warn!( + "Failed to abort multipart write {}: {}", + upload_id, + abort_err + ); + } + return Err(err); + } + // A lost complete response can mean a successful commit. Neither repeat + // complete nor start a new upload session without a server commit token. + let result = match self.complete_multipart_write(&upload_id).await { + Ok(result) => result, + Err(err) => { + let (request_id, status_code) = match &err { + Error::Http { + request_id, + status_code, + .. } - Err(e) => { - if let Err(abort_err) = self.abort_multipart_write(&upload_id).await { - log::warn!( - "Failed to abort multipart write {}: {}", - upload_id, - abort_err - ); - } - if output.rescannable && self.is_retryable_write_error(&e) { - retry_counter.increment_from_error(e)?; - tokio::time::sleep(retry_counter.next_sleep_time()).await; - continue; - } - return Err(e); - } - }, - Err(e) => { - if let Err(abort_err) = self.abort_multipart_write(&upload_id).await { + | Error::Retry { + request_id, + status_code, + .. + } => (request_id.clone(), *status_code), + _ => return Err(err), + }; + // These responses positively reject the commit. Cleanup remains + // best effort and must not replace the original write error. + if matches!( + status_code, + Some(StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + ) { + if let Err(abort_err) = + self.abort_multipart_write(&upload_id, output.retries).await + { log::warn!( - "Failed to abort multipart write {}: {}", + "Failed to abort rejected multipart write {}: {}", upload_id, abort_err ); } - if output.rescannable && self.is_retryable_write_error(&e) { - retry_counter.increment_from_error(e)?; - tokio::time::sleep(retry_counter.next_sleep_time()).await; - continue; - } - return Err(e); + return Err(err); } + if status_code.is_some_and(|status| !status.is_server_error()) { + return Err(err); + } + log::warn!( + "Multipart write {} completion failed; commit outcome may be unknown: {}. Check the table before retrying.", + upload_id, + err + ); + return Err(Error::Http { + request_id, + status_code, + source: Box::new(UnknownWriteOutcome { + upload_id, + source: err, + }), + }); } + }; + if output.overwrite { + self.invalidate_schema_cache(); } + self.track_write_version(freshness_request, result.version); + Ok(result) } async fn execute_multipart_inserts( @@ -2125,10 +2213,7 @@ impl RemoteTable { output: &PreprocessingOutput, num_partitions: usize, ) -> Result<()> { - debug_assert!( - output.rescannable, - "multipart inserts require rescannable input for retry support" - ); + let client = self.client.with_retries(output.retries); let plan = Arc::new( datafusion_physical_plan::repartition::RepartitionExec::try_new( @@ -2141,7 +2226,7 @@ impl RemoteTable { RemoteWriteExec::new_multipart( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client, plan, output.overwrite, upload_id.to_string(), @@ -3000,6 +3085,7 @@ impl BaseTable for RemoteTable { crate::table::computed_columns::ensure_supported_function_metadata(table_schema.as_ref())?; let table_def = TableDefinition::try_from_rich_schema(table_schema.clone())?; + let mut use_multipart = false; let num_partitions = if self.server_version.support_multipart_write() { // Peek at the first batch to estimate write partitions (same as // NativeTable) and, regardless of `write_parallelism`, to detect a @@ -3012,20 +3098,29 @@ impl BaseTable for RemoteTable { // sends one schema-only request. let mut peeked = PeekedScannable::new(add.data); let n = match peeked.peek().await { - Some(first_batch) => match add.write_parallelism { - Some(parallelism) if parallelism > 1 => parallelism, - Some(_) => 1, - None => { - let max_partitions = - lance_core::utils::tokio::get_num_compute_intensive_cpus(); - estimate_write_partitions( - first_batch.get_array_memory_size(), - first_batch.num_rows(), - peeked.num_rows(), - max_partitions, - ) + Some(first_batch) => { + let estimated_bytes = peeked.num_rows().map(|rows| { + first_batch.get_array_memory_size().saturating_mul(rows) + / first_batch.num_rows().max(1) + }); + // Unknown-length streams also need bounded requests, even + // when they cannot be rescanned or only use one writer. + use_multipart = estimated_bytes.is_none_or(|bytes| bytes > 64 * 1024 * 1024); + match add.write_parallelism { + Some(parallelism) if parallelism > 1 => parallelism, + Some(_) => 1, + None => { + let max_partitions = + lance_core::utils::tokio::get_num_compute_intensive_cpus(); + estimate_write_partitions( + first_batch.get_array_memory_size(), + first_batch.num_rows(), + peeked.num_rows(), + max_partitions, + ) + } } - }, + } None => 1, }; add.data = Box::new(peeked); @@ -3041,7 +3136,7 @@ impl BaseTable for RemoteTable { } let _finish = FinishOnDrop(output.tracker.clone()); - if num_partitions > 1 { + if use_multipart || num_partitions > 1 { self.add_multipart(output, num_partitions).await } else { self.add_single_partition(output).await @@ -3278,7 +3373,7 @@ impl BaseTable for RemoteTable { let freshness_request = self.snapshot_freshness_headers(); let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) + .send_write_request(request, freshness_request, update.retries) .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3316,7 +3411,7 @@ impl BaseTable for RemoteTable { .json(&body); let freshness_request = self.snapshot_freshness_headers(); let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) + .send_write_request(request, freshness_request, None) .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3363,6 +3458,7 @@ impl BaseTable for RemoteTable { self.check_mutable().await?; let timeout = params.timeout; + let client = self.client.with_retries(params.retries); let query = MergeInsertRequest::try_from(params)?; // Drive merge_insert through the same RemoteWriteExec streaming path as @@ -3407,7 +3503,7 @@ impl BaseTable for RemoteTable { RemoteWriteExec::new( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client.clone(), input, WriteOp::MergeInsert { query, timeout }, None, @@ -3420,7 +3516,7 @@ impl BaseTable for RemoteTable { ); let mut retry_counter = crate::remote::retry::RetryCounter::new( - &self.client.retry_config, + &client.retry_config, uuid::Uuid::new_v4().to_string(), ); @@ -14748,41 +14844,116 @@ mod tests { } #[tokio::test] - async fn test_add_retries_on_retryable_status() { - // Verify that rescannable data retries on retryable status codes (e.g. 502) - // and eventually succeeds. - let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); - let describe_body = describe_response(&batch.schema()); - - let attempt = Arc::new(AtomicUsize::new(0)); - let attempt_clone = attempt.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_body.clone()) - .unwrap(), - "/v1/table/my_table/insert/" => { - let n = attempt_clone.fetch_add(1, Ordering::SeqCst); - if n < 2 { - http::Response::builder() - .status(502) - .body("bad gateway".to_string()) - .unwrap() - } else { - http::Response::builder() + async fn test_add_write_retry_policy_and_override() { + for status in [429, 500, 502, 503, 504] { + for retries in [None, Some(0)] { + let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let describe = describe_response(&batch.schema()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let table = Table::new_with_handler("my_table", move |req| { + if req.url().path().ends_with("describe/") { + return http::Response::builder() .status(200) - .body(r#"{"version": 3}"#.to_string()) - .unwrap() + .body(describe.clone()) + .unwrap(); } + let n = observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(if n == 0 { status } else { 200 }) + .body(r#"{"version":3}"#.to_string()) + .unwrap() + }); + let mut add = table.add(batch); + if let Some(retries) = retries { + add = add.retries(retries); } - path => panic!("Unexpected request path: {}", path), - }); + let result = add.execute().await; + let safe_retry = status == 429 && retries.is_none(); + assert_eq!( + result.is_ok(), + safe_retry, + "{status}, {retries:?}: {result:?}" + ); + assert_eq!( + attempts.load(Ordering::SeqCst), + if safe_retry { 2 } else { 1 } + ); + } + } + } - let result = table.add(batch).execute().await.unwrap(); - assert_eq!(result.version, 3); - assert_eq!(attempt.load(Ordering::SeqCst), 3); + #[tokio::test] + async fn test_mutations_do_not_replay_gateway_failures() { + for status in [500, 502, 503, 504] { + for op in ["update", "delete", "merge_insert"] { + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let describe = describe_response(&batch.schema()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let table = Table::new_with_handler("my_table", move |req| { + if req.url().path().ends_with("describe/") { + return http::Response::builder() + .status(200) + .body(describe.clone()) + .unwrap(); + } + assert!(req.url().path().contains(op)); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(status) + .body("gateway fault".to_string()) + .unwrap() + }); + let result = match op { + "update" => table + .update() + .column("id", "id + 1") + .execute() + .await + .map(|_| ()), + "delete" => table.delete("true").await.map(|_| ()), + _ => { + let reader = + RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let mut merge = table.merge_insert(&["id"]); + merge.when_not_matched_insert_all(); + merge.execute(Box::new(reader)).await.map(|_| ()) + } + }; + assert!(result.is_err(), "{op}, {status}"); + assert_eq!(attempts.load(Ordering::SeqCst), 1, "{op}, {status}"); + } + } + } + + #[test] + fn test_write_retry_policy_for_both_error_variants() { + let table = RemoteTable::new_mock_with_config( + "my_table".into(), + |_| http::Response::builder().body("").unwrap(), + ClientConfig { + retry_config: RetryConfig { + retries: Some(1), + statuses: Some(vec![429, 500, 502, 503, 504]), + ..Default::default() + }, + ..Default::default() + }, + ); + for status in [429, 500, 502, 503, 504] { + let err = Error::Http { + request_id: "test".into(), + status_code: Some(StatusCode::from_u16(status).unwrap()), + source: "gateway response".into(), + }; + assert_eq!(table.is_retryable_write_error(&err), status == 429); + let mut counter = + crate::remote::retry::RetryCounter::new(&table.client.retry_config, "test".into()); + let exhausted = counter.increment_request_failures(err).unwrap_err(); + assert!(matches!(exhausted, Error::Retry { .. })); + assert_eq!(table.is_retryable_write_error(&exhausted), status == 429); + } } #[tokio::test] @@ -14931,7 +15102,7 @@ mod tests { let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap(); let result = table - .add(vec![batch]) + .add(vec![batch.clone(), batch]) .write_parallelism(2) .execute() .await @@ -15335,7 +15506,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_write_abort_on_complete_failure() { + async fn test_multipart_write_does_not_abort_on_complete_failure() { let abort_count = Arc::new(AtomicUsize::new(0)); let abort_count_c = abort_count.clone(); @@ -15386,7 +15557,7 @@ mod tests { let result = table.add(vec![batch]).write_parallelism(2).execute().await; assert!(result.is_err()); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); } fn retry_config_no_backoff() -> ClientConfig { @@ -15405,9 +15576,9 @@ mod tests { #[tokio::test] async fn test_multipart_write_retry_on_partition_failure() { - // All inserts for the first upload session return 503 (retryable). - // After exhausting internal retries, the outer loop retries with a - // new session and succeeds. + // A staging failure is retried in the same upload session. + let insert_count = Arc::new(AtomicUsize::new(0)); + let insert_count_c = insert_count.clone(); let create_count = Arc::new(AtomicUsize::new(0)); let complete_count = Arc::new(AtomicUsize::new(0)); let abort_count = Arc::new(AtomicUsize::new(0)); @@ -15435,7 +15606,9 @@ mod tests { if path == "/v1/table/my_table/insert/" { // Fail all inserts for the first session - if query.contains("upload_id=upload-1") { + assert!(query.contains("upload_id=upload-1")); + assert!(query.contains("upload_part_id=")); + if insert_count_c.fetch_add(1, Ordering::SeqCst) == 0 { return http::Response::builder() .status(503) .body("Service Unavailable".to_string()) @@ -15477,14 +15650,16 @@ mod tests { .unwrap(); assert_eq!(result.version, 7); - assert_eq!(create_count.load(Ordering::SeqCst), 2); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert_eq!(create_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); assert_eq!(complete_count.load(Ordering::SeqCst), 1); } #[tokio::test] - async fn test_multipart_write_retry_on_complete_failure() { - // Complete returns 503 for the first session, succeeds for the second. + async fn test_multipart_complete_unknown_outcome_never_aborts_or_replays() { + // A gateway failure may hide a committed write. No abort or replay is safe. + let complete_count = Arc::new(AtomicUsize::new(0)); + let complete_count_c = complete_count.clone(); let create_count = Arc::new(AtomicUsize::new(0)); let abort_count = Arc::new(AtomicUsize::new(0)); @@ -15516,6 +15691,7 @@ mod tests { } if path == "/v1/table/my_table/multipart_write/complete" { + complete_count_c.fetch_add(1, Ordering::SeqCst); // Fail complete for first session if query.contains("upload_id=upload-1") { return http::Response::builder() @@ -15548,11 +15724,12 @@ mod tests { .write_parallelism(2) .execute() .await - .unwrap(); + .unwrap_err(); - assert_eq!(result.version, 9); - assert_eq!(create_count.load(Ordering::SeqCst), 2); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert!(result.to_string().contains("commit outcome unknown")); + assert_eq!(complete_count.load(Ordering::SeqCst), 1); + assert_eq!(create_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); } // ---- Read freshness header tests ------------------------------------ diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index ebae823e1..0de1c21cc 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -17,7 +17,7 @@ use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, }; -use futures::{SinkExt, StreamExt}; +use futures::StreamExt; use http::header::CONTENT_TYPE; use lance::io::exec::utils::InstrumentedRecordBatchStreamAdapter; @@ -268,6 +268,17 @@ impl RemoteWriteExec { error_tx: tokio::sync::oneshot::Sender, tracker: Option>, ) -> DataFusionResult { + let data: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new( + data.schema(), + data.flat_map(|batch| match batch { + Ok(batch) => futures::stream::iter( + crate::remote::util::split_batch(batch, crate::remote::util::IPC_BATCH_BYTES) + .map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }), + )); let options = arrow_ipc::writer::IpcWriteOptions::default() .try_with_compression(Some(CompressionType::LZ4_FRAME))?; let writer = arrow_ipc::writer::StreamWriter::try_new_with_options( @@ -347,55 +358,55 @@ impl PartRequestCtx<'_, S> { /// whenever the current one reaches `max_bytes` (Arrow IPC, compressed) or /// has been uploading for `max_duration`, whichever comes first. /// - /// Each part is a separate `/insert?upload_id=...&upload_part_id=...` request - /// whose body is still streamed through a bounded channel, so peak memory - /// stays at a couple of batches regardless of `max_bytes`. The server stages - /// every part under the shared `upload_id` and merges them atomically when - /// the caller completes the multipart write. An empty partition stages - /// nothing: the multipart write always has at least one non-empty partition - /// to commit. + /// Each part has a fixed IPC body and transaction ID. A retry replaces the + /// same staged transaction instead of adding another part. Only the final + /// complete request makes staged rows visible. Parts are prepared on demand; + /// the target does not bound memory retained by input or ancestor buffers. /// - /// The byte budget targets a good on-disk fragment size; the duration budget - /// bounds request time so a slow or throttled upload does not keep a request - /// open past the client read timeout (which also covers the request body). + /// The duration budget limits payload preparation time; HTTP timeouts are + /// handled by retrying the prepared payload. async fn send_multipart_chunked( &self, max_bytes: u64, max_duration: Option, - mut input: SendableRecordBatchStream, + input: SendableRecordBatchStream, tracker: Option>, ) -> DataFusionResult<()> { let schema = input.schema(); + let max_batch_bytes = (max_bytes as usize).clamp(1, crate::remote::util::IPC_BATCH_BYTES); + let stream = input.flat_map(move |batch| match batch { + Ok(batch) => futures::stream::iter( + crate::remote::util::split_batch(batch, max_batch_bytes) + .map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }); + let mut input: SendableRecordBatchStream = + Box::pin(RecordBatchStreamAdapter::new(schema.clone(), stream)); - // A part always starts from a batch we already hold: the first batch of - // the partition, or the look-ahead batch from the previous part. This - // keeps empty partitions from staging a part and stops a size cut that - // lands exactly on the end of input from emitting a trailing empty part. - let mut first = match input.next().await { - Some(batch) => batch?, - None => return Ok(()), - }; - + let mut pending = std::collections::VecDeque::new(); loop { - let input_ended = self + let first = match pending.pop_front() { + Some(batch) => batch, + None => match input.next().await { + Some(batch) => batch?, + None => break, + }, + }; + if self .send_one_part( - &schema, max_bytes, max_duration, first, &mut input, + &mut pending, &tracker, ) - .await?; - - if input_ended { + .await? + { break; } - - first = match input.next().await { - Some(batch) => batch?, - None => break, - }; } Ok(()) @@ -431,143 +442,137 @@ impl PartRequestCtx<'_, S> { &self, request: reqwest::RequestBuilder, freshness_request: Option, - ) -> DataFusionResult<()> { - let (request_id, response) = self - .client - .send(request) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; + ) -> crate::Result<()> { + let (request_id, response) = self.client.send(request).await?; let response = RemoteTable::::handle_table_not_found(self.table_name, response, &request_id) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let response = self - .client - .check_response(&request_id, response) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; + .await?; + let response = self.client.check_response(&request_id, response).await?; self.freshness .observe(freshness_request, response.headers()); - response.bytes().await.map_err(|e| { - DataFusionError::External(Box::new(Error::Http { - source: Box::new(e), - request_id: request_id.clone(), - status_code: None, - })) + response.bytes().await.map_err(|e| Error::Http { + source: Box::new(e), + request_id: request_id.clone(), + status_code: None, })?; Ok(()) } - /// Stream one part, starting from `first` and pulling from `input` until the - /// part reaches `max_bytes`, has been uploading for `max_duration`, or the - /// input ends. The body is streamed through a bounded channel concurrently - /// with the request, so peak memory stays at a couple of batches. Wire bytes - /// are recorded on `tracker` as each chunk is produced, so progress advances - /// smoothly rather than jumping once per completed part. Returns whether the - /// input was exhausted while filling this part. + /// Encode each part before sending so a lost staging response can be retried + /// with exactly the same transaction ID and bytes. async fn send_one_part( &self, - schema: &arrow_schema::SchemaRef, max_bytes: u64, max_duration: Option, first: RecordBatch, input: &mut SendableRecordBatchStream, + queued: &mut std::collections::VecDeque, tracker: &Option>, ) -> DataFusionResult { - let (mut chunk_tx, chunk_rx) = - futures::channel::mpsc::channel::, std::io::Error>>(2); - let body = reqwest::Body::wrap_stream(chunk_rx); - - let part_id = uuid::Uuid::new_v4().to_string(); - let (request, freshness_request) = self.build_part_request(&part_id, body); - - // Measured from just before the request is sent, matching the window the - // client read timeout applies to the upload. + let schema = input.schema(); + let options = arrow_ipc::writer::IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME))?; + let mut writer = arrow_ipc::writer::StreamWriter::try_new_with_options( + Vec::new(), + &schema, + options.clone(), + )?; let started = Instant::now(); - let tracker = tracker.clone(); - // Unlike `stream_as_http_body`, this producer also cuts the part at the - // byte/time budget and reports back whether the input ended, so it drives - // its own bounded mpsc channel joined with the request instead of reusing - // that helper. - let producer = async move { - let options = arrow_ipc::writer::IpcWriteOptions::default() - .try_with_compression(Some(CompressionType::LZ4_FRAME)) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let mut writer = - arrow_ipc::writer::StreamWriter::try_new_with_options(Vec::new(), schema, options) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - - let mut part_bytes: u64 = 0; - let mut input_ended = false; - let mut pending = Some(first); - loop { - let batch = match pending.take() { - Some(batch) => batch, - None => match input.next().await { - Some(Ok(batch)) => batch, - Some(Err(e)) => { - // Abort the body so the server does not treat the - // truncated stream as a successful write; the - // original error is surfaced to the caller. - let _ = chunk_tx - .send(Err(std::io::Error::other("input stream error"))) - .await; - return Err(e); - } - None => { - input_ended = true; - break; - } - }, - }; - writer - .write(&batch) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let chunk = std::mem::take(writer.get_mut()); - let chunk_len = chunk.len(); - part_bytes += chunk_len as u64; - if chunk_tx.send(Ok(chunk)).await.is_err() { - // The request finished or failed; stop producing. + let mut pending = Some(first); + let mut has_batch = false; + let mut input_ended = false; + loop { + let batch = match pending.take().or_else(|| queued.pop_front()) { + Some(batch) => batch, + None => match input.next().await { + Some(batch) => batch?, + None => { + input_ended = true; + break; + } + }, + }; + let before = writer.get_ref().len(); + writer.write(&batch)?; + // Reserve the EOS marker. A rejected batch starts a fresh stream, + // so its dictionary messages are encoded again with fresh state. + if (writer.get_ref().len() as u64).saturating_add(8) > max_bytes { + if has_batch { + writer.get_mut().truncate(before); + queued.push_front(batch); break; } - if let Some(ref t) = tracker { - t.record_bytes(chunk_len); - } - if part_bytes >= max_bytes - || max_duration.is_some_and(|limit| started.elapsed() >= limit) - { - break; + if batch.num_rows() > 1 { + let middle = batch.num_rows() / 2; + queued.push_front(crate::remote::util::compact_batch_dictionaries( + batch.slice(middle, batch.num_rows() - middle), + )?); + pending = Some(crate::remote::util::compact_batch_dictionaries( + batch.slice(0, middle), + )?); + writer = arrow_ipc::writer::StreamWriter::try_new_with_options( + Vec::new(), + &schema, + options.clone(), + )?; + continue; } + // A single row and its schema cannot be split further. } - - writer - .finish() - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let tail = std::mem::take(writer.get_mut()); - if !tail.is_empty() { - let tail_len = tail.len(); - if chunk_tx.send(Ok(tail)).await.is_ok() - && let Some(ref t) = tracker - { - t.record_bytes(tail_len); - } + has_batch = true; + if writer.get_ref().len() as u64 >= max_bytes + || max_duration.is_some_and(|limit| started.elapsed() >= limit) + { + break; } - Ok::(input_ended) - }; + } + writer.finish()?; + let body = bytes::Bytes::from(writer.into_inner()?); + let part_id = uuid::Uuid::new_v4().to_string(); + let mut retries = + crate::remote::retry::RetryCounter::new(&self.client.retry_config, part_id.clone()); + loop { + let (request, freshness) = self.build_part_request(&part_id, body.clone().into()); + match self.send_part_request(request, freshness).await { + Ok(()) => { + if let Some(tracker) = tracker { + tracker.record_bytes(body.len()); + } + return Ok(input_ended); + } + Err(err) if retryable_part_error(&err, &self.client.retry_config.statuses) => { + let cause = err.to_string(); + retries + .increment_from_error(err) + .map_err(|err| DataFusionError::External(Box::new(err)))?; + log::warn!( + "Retrying multipart upload {} part {} after {}; reusing the same payload", + self.upload_id, + part_id, + cause + ); + tokio::time::sleep(retries.next_sleep_time()).await; + } + Err(err) => return Err(DataFusionError::External(Box::new(err))), + } + } + } +} - let send = self.send_part_request(request, freshness_request); - - // `join!` rather than `tokio::spawn`: the producer borrows `input` (and - // `schema`), so it cannot satisfy the `'static` bound a spawned task - // needs. Running both futures on this task lets them make progress - // concurrently without that constraint. - let (producer_result, send_result) = futures::join!(producer, send); - // Prefer the producer error (e.g. NaN rejection) over any HTTP error it - // induced. - let input_ended = producer_result?; - send_result?; - - Ok(input_ended) +fn retryable_part_error(err: &Error, statuses: &[reqwest::StatusCode]) -> bool { + match err { + Error::Http { + status_code: Some(status), + .. + } => statuses.contains(status), + Error::Http { source, .. } => source.downcast_ref::().is_some_and(|err| { + err.is_connect() + || err.is_timeout() + || err.is_body() + || err.is_decode() + || err.is_request() + }), + _ => false, } } @@ -697,13 +702,10 @@ impl ExecutionPlan for RemoteWriteExec { let max_request_duration = self.max_request_duration; let stream = futures::stream::once(async move { - // Multipart writes with a byte budget split the partition into - // several bounded, still-streamed requests so no single request - // stays open long enough to hit the client read timeout. This path - // is insert-only (guarded above). - if let (Some(upload_id), Some(max_bytes)) = - (upload_id.as_deref(), max_bytes_per_request) - { + // Multipart payloads remain replayable even when byte-based cuts + // are disabled. Single-request writes never replay ambiguous errors. + if let Some(upload_id) = upload_id.as_deref() { + let max_bytes = max_bytes_per_request.unwrap_or(u64::MAX); let overwrite = matches!(op, WriteOp::Insert { overwrite: true }); let ctx = PartRequestCtx { client: &client, @@ -1220,7 +1222,7 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - // A 1-byte budget forces every batch into its own part. + // A 1-byte budget forces every row into its own part. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1237,7 +1239,102 @@ mod tests { let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); while stream.next().await.transpose().unwrap().is_some() {} - assert_eq!(insert_count.load(Ordering::SeqCst), 3); + assert_eq!(insert_count.load(Ordering::SeqCst), 6); + } + + #[tokio::test] + async fn test_multipart_respects_disabled_status_retries() { + use futures::StreamExt; + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let mut client = crate::remote::client::test_utils::client_with_handler(move |_| { + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(503) + .body("unavailable") + .unwrap() + }); + client.retry_config.statuses.clear(); + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let input = input_plan_from_batches(batch.schema(), vec![batch]).await; + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(64 * 1024 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + assert!(stream.next().await.unwrap().is_err()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_multipart_splits_one_batch_within_encoded_byte_budget() { + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + let mut bytes = vec![0; 128 * 1024]; + SmallRng::seed_from_u64(7).fill_bytes(&mut bytes); + let values = arrow_array::LargeBinaryArray::from_iter_values(bytes.chunks_exact(1024)); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + false, + )])); + let input = input_plan_from_batches( + schema.clone(), + vec![arrow_array::RecordBatch::try_new(schema, vec![Arc::new(values)]).unwrap()], + ) + .await; + let decoded = Arc::new(Mutex::new(Vec::new())); + let observed = decoded.clone(); + let requests = Arc::new(AtomicUsize::new(0)); + let count = requests.clone(); + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + assert!( + body.len() <= 16 * 1024, + "encoded part exceeded its budget: {}", + body.len() + ); + let reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + let mut decoded = observed.lock().unwrap(); + for batch in reader { + let batch = batch.unwrap(); + let values = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + for value in values.iter() { + decoded.extend_from_slice(value.unwrap()); + } + } + count.fetch_add(1, Ordering::SeqCst); + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert!(requests.load(Ordering::SeqCst) > 1); + assert_eq!(*decoded.lock().unwrap(), bytes); } #[tokio::test] @@ -1376,7 +1473,7 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - // A 1-byte budget forces every batch into its own part. + // A 1-byte budget forces every row into its own part. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1394,13 +1491,13 @@ mod tests { while stream.next().await.transpose().unwrap().is_some() {} let ids = part_ids.lock().unwrap().clone(); - assert_eq!(ids.len(), 3, "expected one part id per part: {ids:?}"); + assert_eq!(ids.len(), 6, "expected one part id per part: {ids:?}"); assert!( ids.iter().all(|id| !id.is_empty()), "part ids must be non-empty: {ids:?}" ); let unique: HashSet<&String> = ids.iter().collect(); - assert_eq!(unique.len(), 3, "part ids must be distinct: {ids:?}"); + assert_eq!(unique.len(), 6, "part ids must be distinct: {ids:?}"); } #[tokio::test] @@ -1446,8 +1543,8 @@ mod tests { while stream.next().await.transpose().unwrap().is_some() {} } - // 2 parts from partition 0 + 1 part from partition 1. - assert_eq!(insert_count.load(Ordering::SeqCst), 3); + // 4 single-row parts from partition 0 + 2 from partition 1. + assert_eq!(insert_count.load(Ordering::SeqCst), 6); } #[tokio::test] @@ -1551,7 +1648,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_records_progress_within_a_part() { + async fn test_multipart_records_acknowledged_bytes() { use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; use futures::StreamExt; @@ -1577,9 +1674,7 @@ mod tests { })); let tracker = Arc::new(WriteProgressTracker::new(callback, None)); - // A large byte budget keeps all three batches in one part; smooth - // progress therefore requires bytes to be reported per chunk rather than - // once when the part completes. + // Count encoded bytes once when the part is acknowledged. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1603,8 +1698,8 @@ mod tests { ); let observed = observed.lock().unwrap(); assert!( - observed.len() > 1, - "expected multiple incremental progress updates within the part: {observed:?}" + observed.len() == 1, + "expected one progress update per acknowledged part: {observed:?}" ); assert!( observed.windows(2).all(|w| w[1] >= w[0]), @@ -1615,4 +1710,454 @@ mod tests { "final progress should report bytes: {observed:?}" ); } + #[tokio::test] + async fn test_multipart_nested_dictionary_values_and_retries() { + use arrow_array::{ + Array, ArrayRef, BinaryArray, DictionaryArray, ListArray, RecordBatch, StructArray, + UInt8Array, types::UInt8Type, + }; + use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; + use arrow_cast::cast; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + use std::collections::HashMap; + + let mut bytes = vec![0; 128 * 1024]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let mut batches = Vec::new(); + for shift in [0, 1] { + let values = BinaryArray::from_iter( + std::iter::once(None).chain(bytes.chunks_exact(1024).skip(shift).map(Some)), + ); + let keys = UInt8Array::from(vec![ + Some(120), + Some(1), + None, + Some(1), + Some(2), + Some(0), + Some(3), + Some(4), + ]); + let dict = Arc::new(DictionaryArray::::new(keys, Arc::new(values))); + let field = Arc::new( + Field::new("category", dict.data_type().clone(), true) + .with_metadata(HashMap::from([("field-meta".into(), "retained".into())])), + ); + let entries = StructArray::new(vec![field].into(), vec![dict], None); + let list = ListArray::new( + Arc::new(Field::new_list_field(entries.data_type().clone(), false)), + OffsetBuffer::new(ScalarBuffer::from(vec![0, 1, 3, 5, 6, 6, 8])), + Arc::new(entries), + Some(NullBuffer::from(vec![true, true, true, true, false, true])), + ); + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![Field::new("categories", list.data_type().clone(), true)], + HashMap::from([("schema-meta".into(), "retained".into())]), + )); + // The discarded first row references a large, otherwise unused value. + batches.push( + RecordBatch::try_new(schema, vec![Arc::new(list)]) + .unwrap() + .slice(1, 5), + ); + } + let schema = batches[0].schema(); + let plain_type = DataType::List(Arc::new(Field::new_list_field( + DataType::Struct( + vec![ + Field::new("category", DataType::Binary, true) + .with_metadata(HashMap::from([("field-meta".into(), "retained".into())])), + ] + .into(), + ), + false, + ))); + let expected: Vec = batches + .iter() + .map(|b| cast(b.column(0), &plain_type).unwrap()) + .collect(); + let expected = + arrow_select::concat::concat(&expected.iter().map(|a| a.as_ref()).collect::>()) + .unwrap(); + let input = input_plan_from_batches(schema.clone(), batches).await; + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = requests.clone(); + let mut client = crate::remote::client::test_utils::client_with_handler(move |request| { + let query: HashMap<_, _> = request.url().query_pairs().into_owned().collect(); + assert_eq!(query["upload_id"], "upload-1"); + let body = request.body().unwrap().as_bytes().unwrap().to_vec(); + let mut requests = observed.lock().unwrap(); + requests.push((query["upload_part_id"].clone(), body)); + http::Response::builder() + .status(if requests.len() == 1 { 503 } else { 200 }) + .body("{}") + .unwrap() + }); + client.retry_config.backoff_factor = 0.0; + client.retry_config.backoff_jitter = 0.0; + use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; + let acknowledged = Arc::new(AtomicUsize::new(0)); + let acknowledged_c = acknowledged.clone(); + let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { + acknowledged_c.store(p.output_bytes(), Ordering::SeqCst); + })); + let tracker = Arc::new(WriteProgressTracker::new(callback, None)); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + Some(tracker), + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + let requests = requests.lock().unwrap(); + assert!(requests.len() >= 2); + assert_eq!( + requests[0], requests[1], + "retry must reuse part id and encoded bytes" + ); + let mut decoded = Vec::new(); + for (_, body) in &requests[1..] { + assert!(body.len() <= 16 * 1024, "part size: {}", body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + for batch in reader { + decoded.push(cast(batch.unwrap().column(0), &plain_type).unwrap()); + } + } + let actual = + arrow_select::concat::concat(&decoded.iter().map(|a| a.as_ref()).collect::>()) + .unwrap(); + assert_eq!(actual.as_ref(), expected.as_ref()); + let total: usize = requests[1..].iter().map(|(_, b)| b.len()).sum(); + assert_eq!(acknowledged.load(Ordering::SeqCst), total); + assert!( + total < 16 * 1024, + "unused dictionary values leaked: {total}" + ); + } + + #[rstest::rstest] + #[case(false, "linear", 1024)] + #[case(true, "linear", 1024)] + #[case(false, "linear", 1000)] + #[case(true, "linear", 1000)] + #[case(false, "nested", 1024)] + #[case(true, "nested", 1024)] + #[case(false, "sharing", 1024)] + #[case(true, "sharing", 1024)] + #[case(false, "empty", 1024)] + #[case(true, "empty", 1024)] + #[tokio::test] + async fn test_multipart_list_view_dictionary_ranges( + #[case] large: bool, + #[case] layout: &str, + #[case] value_bytes: usize, + ) { + if large { + check_list_view_dictionary_ranges::(layout, value_bytes).await; + } else { + check_list_view_dictionary_ranges::(layout, value_bytes).await; + } + } + + async fn check_list_view_dictionary_ranges( + layout: &str, + value_bytes: usize, + ) { + use arrow_array::{ + Array, ArrayRef, DictionaryArray, GenericListViewArray, Int32Array, ListArray, + RecordBatch, StringArray, StructArray, cast::AsArray, types::Int32Type, + }; + use arrow_buffer::{NullBuffer, OffsetBuffer}; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + use std::collections::HashMap; + + let mut bytes = vec![0; 128 * value_bytes]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(value_bytes) + .map(|c| c.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let mut expected = Vec::new(); + let mut batches = Vec::new(); + let nested = layout != "linear"; + for reverse in [false, true] + .into_iter() + .take(if layout == "nested" { 2 } else { 1 }) + { + let values: Vec<_> = if reverse { + strings.iter().rev().cloned().collect() + } else { + strings.clone() + }; + let keys: Vec = (0..128) + .map(|i| if layout == "sharing" { i % 2 } else { i }) + .collect(); + // A sliced child has its own nonzero physical offset. + let dict = DictionaryArray::::new( + Int32Array::from_iter_values(std::iter::once(127).chain(keys.iter().copied())), + Arc::new(StringArray::from(values.clone())), + ) + .slice(1, 128); + let mut offsets = Vec::new(); + let mut sizes = Vec::new(); + let mut valid = Vec::new(); + let start = usize::from(layout == "nested"); + for row in 0..128 + start { + let (offset, size, is_valid) = match layout { + "empty" if row % 2 == 0 => (80, 48, false), + "empty" => (128, 0, true), + "nested" if row % 17 == 0 => (80, 48, false), + "nested" if row % 13 == 0 => (128, 0, true), + "nested" => (4 + (row * 7) % 64, 3, true), + "sharing" => (4 + (row % 2) * 4, 64, true), + _ => (row, 1, true), + }; + offsets.push(O::from_usize(offset).unwrap()); + sizes.push(O::from_usize(size).unwrap()); + valid.push(is_valid); + if row >= start { + expected.push(is_valid.then(|| { + (offset..offset + size) + .map(|i| values[keys[i] as usize].clone()) + .collect::>() + })); + } + } + let item = Arc::new( + Field::new("category", dict.data_type().clone(), false) + .with_metadata(HashMap::from([("item-meta".into(), "retained".into())])), + ); + let views = GenericListViewArray::::new( + item, + offsets.into(), + sizes.into(), + Arc::new(dict), + Some(NullBuffer::from(valid)), + ); + let view_count = views.len(); + let column: ArrayRef = if nested { + let field = Arc::new(Field::new("views", views.data_type().clone(), true)); + let entries = StructArray::new(vec![field].into(), vec![Arc::new(views)], None); + Arc::new(ListArray::new( + Arc::new(Field::new_list_field(entries.data_type().clone(), false)), + OffsetBuffer::from_lengths(std::iter::repeat_n(1, view_count)), + Arc::new(entries), + None, + )) + } else { + Arc::new(views) + }; + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![Field::new("categories", column.data_type().clone(), true)], + HashMap::from([("schema-meta".into(), "retained".into())]), + )); + batches.push( + RecordBatch::try_new(schema, vec![column]) + .unwrap() + .slice(start, 128), + ); + } + let schema = batches[0].schema(); + let logical_bytes: usize = expected.iter().flatten().flatten().map(String::len).sum(); + let input = input_plan_from_batches(schema.clone(), batches).await; + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let decoded = Arc::new(Mutex::new(Vec::new())); + let decoded_c = decoded.clone(); + let sharing = layout == "sharing"; + let empty = layout == "empty"; + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + observed.lock().unwrap().push(body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + for batch in reader { + let batch = batch.unwrap(); + for row in 0..batch.num_rows() { + let column = if nested { + batch + .column(0) + .as_list::() + .value(row) + .as_struct() + .column(0) + .slice(0, 1) + } else { + batch.column(0).slice(row, 1) + }; + let views = column + .as_any() + .downcast_ref::>() + .unwrap(); + if empty { + assert_eq!(views.values().len(), 0, "null/empty views retain no child"); + } + if sharing { + assert_eq!( + views.values().len(), + 68, + "overlapping ranges must share their child" + ); + } + decoded_c.lock().unwrap().push(if views.is_null(0) { + None + } else { + let value = arrow_cast::cast(&views.value(0), &DataType::Utf8).unwrap(); + Some( + value + .as_string::() + .iter() + .map(|v| v.unwrap().to_owned()) + .collect::>(), + ) + }); + } + } + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert_eq!(*decoded.lock().unwrap(), expected); + let lengths = lengths.lock().unwrap(); + let total: usize = lengths.iter().sum(); + eprintln!( + "ListView IPC: large={}, layout={layout}, value_bytes={value_bytes}, parts={}, first={}, total={total}", + O::IS_LARGE, + lengths.len(), + lengths[0] + ); + // Every selected row in these cases fits the target, including IPC framing. + assert!( + lengths.iter().all(|n| *n <= 16 * 1024), + "oversized parts: {lengths:?}" + ); + assert!( + total <= (2 * logical_bytes).max(16 * 1024), + "dictionary upload amplified: {total}" + ); + if sharing { + assert_eq!(lengths.len(), 1); + } + } + + #[rstest::rstest] + #[case(1024, false)] + // Dictionary data fits the target; IPC framing forces the sender to split again. + #[case(1000, false)] + #[case(1024, true)] + #[case(20 * 1024, false)] + #[tokio::test] + async fn test_multipart_dictionary_payload_is_not_repeated_per_row( + #[case] value_bytes: usize, + #[case] use_views: bool, + ) { + use arrow_array::{ + Array, ArrayRef, DictionaryArray, Int32Array, RecordBatch, StringArray, + StringViewArray, types::Int32Type, + }; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + + let mut bytes = vec![0; 128 * value_bytes]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(value_bytes) + .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let values: ArrayRef = if use_views { + Arc::new(StringViewArray::from_iter_values(&strings)) + } else { + Arc::new(StringArray::from(strings.clone())) + }; + let array = + DictionaryArray::::try_new(Int32Array::from_iter_values(0..128), values) + .unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "category", + array.data_type().clone(), + false, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap(); + let input = input_plan_from_batches(schema.clone(), vec![batch]).await; + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let decoded = Arc::new(Mutex::new(Vec::new())); + let decoded_c = decoded.clone(); + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + observed.lock().unwrap().push(body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + let mut rows = 0; + for batch in reader { + let batch = batch.unwrap(); + rows += batch.num_rows(); + let values = arrow_cast::cast(batch.column(0), &DataType::Utf8).unwrap(); + let values = values.as_any().downcast_ref::().unwrap(); + decoded_c + .lock() + .unwrap() + .extend(values.iter().map(|v| v.unwrap().to_owned())); + } + assert!( + body.len() <= 16 * 1024 || rows == 1, + "oversized divisible part: {} bytes, {rows} rows", + body.len() + ); + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert_eq!(*decoded.lock().unwrap(), strings); + let lengths = lengths.lock().unwrap(); + let total: usize = lengths.iter().sum(); + eprintln!( + "dictionary IPC: value_bytes={value_bytes}, views={use_views}, parts={}, first={}, total={total}", + lengths.len(), + lengths[0] + ); + assert!( + total <= 2 * bytes.len(), + "dictionary upload amplified: parts={}, first={}, total={total}", + lengths.len(), + lengths[0] + ); + } } diff --git a/rust/lancedb/src/remote/table/write_tests.rs b/rust/lancedb/src/remote/table/write_tests.rs new file mode 100644 index 000000000..c97619af1 --- /dev/null +++ b/rust/lancedb/src/remote/table/write_tests.rs @@ -0,0 +1,436 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Real HTTP faults with a local Lance table behind the staging fixture. This +//! exercises SDK behavior; it does not model Sophon's asynchronous txn cleanup. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{LargeBinaryArray, RecordBatch}; +use arrow_ipc::reader::StreamReader; +use arrow_schema::{DataType, Field, Schema}; +use lance::arrow::json::JsonSchema; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use super::RemoteTable; +use crate::remote::client::{ClientConfig, RestfulLanceDbClient, RetryConfig, TimeoutConfig}; +use crate::remote::db::ServerVersion; +use crate::table::AddDataBuilder; + +#[derive(Clone, Copy, Debug)] +enum Fault { + Close, + Timeout, + Status(u16), +} + +#[derive(Default)] +struct State { + creates: usize, + completes: usize, + aborts: usize, + attempts: Vec<(String, Vec)>, + parts: HashMap>, +} + +async fn read_request(socket: &mut tokio::net::TcpStream) -> (String, Vec) { + let mut header = Vec::new(); + while !header.ends_with(b"\r\n\r\n") { + header.push(socket.read_u8().await.unwrap()); + assert!(header.len() < 64 * 1024); + } + let header = String::from_utf8(header).unwrap(); + let path = header.split_whitespace().nth(1).unwrap().to_owned(); + let length = header + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().unwrap()) + }) + .unwrap_or(0); + assert!( + !header + .to_ascii_lowercase() + .contains("transfer-encoding: chunked") + ); + let mut body = vec![0; length]; + socket.read_exact(&mut body).await.unwrap(); + (path, body) +} + +async fn respond(socket: &mut tokio::net::TcpStream, status: u16, body: &str) { + let response = format!( + "HTTP/1.1 {status} Result\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; +} + +#[tokio::test] +async fn multipart_http_faults_preserve_committed_blob_payloads() { + for complete_fault in [false, true] { + for fault in [ + Fault::Close, + Fault::Timeout, + Fault::Status(500), + Fault::Status(502), + Fault::Status(503), + Fault::Status(504), + ] { + let dir = tempfile::tempdir().unwrap(); + let db = crate::connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![crate::blob::blob("payload", true)])); + let stored = db + .create_empty_table("stored", schema.clone()) + .execute() + .await + .unwrap(); + let state = Arc::new(Mutex::new(State::default())); + let server_state = state.clone(); + let server_table = stored.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 tasks = tokio::task::JoinSet::new(); + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let state = server_state.clone(); + let table = server_table.clone(); + tasks.spawn(async move { + let (path, body) = read_request(&mut socket).await; + let mut apply_fault = false; + let response; + if path.contains("multipart_write/create") { + state.lock().unwrap().creates += 1; + response = r#"{"upload_id":"00000000-0000-0000-0000-000000000001"}"# + .to_string(); + } else if path.contains("/insert/") { + let url = url::Url::parse(&format!("http://localhost{path}")).unwrap(); + let params: HashMap<_, _> = url.query_pairs().into_owned().collect(); + assert_eq!(params["upload_id"], "00000000-0000-0000-0000-000000000001"); + let part = params["upload_part_id"].clone(); + let mut state = state.lock().unwrap(); + apply_fault = !complete_fault && state.attempts.is_empty(); + state.attempts.push((part.clone(), body.clone())); + // Match the verified server contract: replace the txn + // associated with this part ID before acknowledging it. + state.parts.insert(part, body); + response = "{}".into(); + } else if path.contains("multipart_write/complete") { + let parts = { + let mut state = state.lock().unwrap(); + state.completes += 1; + state.parts.values().cloned().collect::>() + }; + for body in parts { + let reader = + StreamReader::try_new(std::io::Cursor::new(body), None) + .unwrap(); + let batches = reader.collect::, _>>().unwrap(); + table.add(batches).execute().await.unwrap(); + } + apply_fault = complete_fault; + response = r#"{"version":2}"#.into(); + } else if path.contains("multipart_write/abort") { + state.lock().unwrap().aborts += 1; + panic!("abort must never follow a possibly committed complete"); + } else { + panic!("unexpected request {path}"); + } + if apply_fault { + match fault { + Fault::Close => return, + Fault::Timeout => { + tokio::time::sleep(Duration::from_secs(2)).await; + return; + } + Fault::Status(status) => { + respond( + &mut socket, + status, + "gateway fault after staging/commit", + ) + .await; + return; + } + } + } + respond(&mut socket, 200, &response).await; + }); + } + }); + let client = RestfulLanceDbClient::try_new( + &crate::remote::client::parse_db_url("db://test").unwrap(), + "us-east-1", + Some(format!("http://{address}")), + Default::default(), + ClientConfig { + timeout_config: TimeoutConfig { + read_timeout: Some(Duration::from_secs(1)), + ..Default::default() + }, + retry_config: RetryConfig { + retries: Some(3), + read_retries: Some(3), + connect_retries: Some(3), + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let remote = Arc::new(RemoteTable::new_with_sql_client( + client, + "test".into(), + "test".into(), + vec![], + "test".into(), + ServerVersion(semver::Version::new(0, 4, 0)), + None, + )); + remote.seed_schema(&serde_json::json!({"version": 1, "schema": JsonSchema::try_from(schema.as_ref()).unwrap()}).to_string()); + let payload_a = vec![17u8; 32 * 1024]; + let payload_b = vec![29u8; 32 * 1024]; + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(LargeBinaryArray::from(vec![ + Some(payload_a.as_slice()), + Some(payload_b.as_slice()), + ]))], + ) + .unwrap(); + let progress = Arc::new(Mutex::new(Vec::new())); + let seen = progress.clone(); + let result = AddDataBuilder::new(remote, Box::new(input), None) + .write_parallelism(2) + .progress(move |p| { + seen.lock() + .unwrap() + .push((p.output_rows(), p.output_bytes(), p.done())) + }) + .execute() + .await; + if complete_fault { + assert!( + result + .unwrap_err() + .to_string() + .contains("commit outcome unknown"), + "{fault:?}" + ); + } else { + result.unwrap(); + } + assert_eq!( + stored.count_rows(None).await.unwrap(), + 2, + "{fault:?}, complete={complete_fault}" + ); + let payloads = stored.fetch_blobs("payload", &[0, 1]).await.unwrap(); + assert_eq!(payloads.value(0), payload_a); + assert_eq!(payloads.value(1), payload_b); + let state = state.lock().unwrap(); + assert_eq!((state.creates, state.completes, state.aborts), (1, 1, 0)); + assert_eq!(state.parts.len(), 1); + assert_eq!(state.attempts.len(), if complete_fault { 1 } else { 2 }); + if !complete_fault { + assert_eq!(state.attempts[0], state.attempts[1]); + } + let progress = progress.lock().unwrap(); + let last = progress.last().unwrap(); + assert_eq!(last.0, 2); + assert!(last.1 > 0 && last.2); + assert_eq!( + progress.first().unwrap().1, + 0, + "scan is not an acknowledgement" + ); + assert!(progress.windows(2).all(|pair| pair[0].1 <= pair[1].1)); + assert_eq!(last.1, state.parts.values().map(Vec::len).sum::()); + server.abort(); + } + } +} + +#[tokio::test] +async fn multipart_retries_sixth_part_after_reused_connection_closes() { + use datafusion_execution::TaskContext; + use datafusion_physical_plan::ExecutionPlan; + use futures::TryStreamExt; + + 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 socket, _) = listener.accept().await.unwrap(); + for n in 0..6 { + let (path, body) = read_request(&mut socket).await; + attempts.push((path, body)); + if n == 5 { + break; + } + // Keep one connection pooled for the first five acknowledged parts. + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") + .await + .unwrap(); + } + // 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); + respond(&mut socket, 200, "{}").await; + attempts + }); + let client = RestfulLanceDbClient::try_new( + &crate::remote::client::parse_db_url("db://test").unwrap(), + "test-region", + Some(format!("http://{address}")), + Default::default(), + ClientConfig { + retry_config: RetryConfig { + retries: Some(3), + read_retries: Some(3), + connect_retries: Some(3), + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .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), + ); + let exec = super::insert::RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + plan, + false, + "upload-1".into(), + None, + None, + Some(1), + None, + ); + exec.execute(0, Arc::new(TaskContext::default())) + .unwrap() + .try_collect::>() + .await + .unwrap(); + let attempts = server.await.unwrap(); + assert_eq!(attempts.len(), 7); + assert_eq!( + attempts[5], attempts[6], + "retry must reuse both part ID and bytes" + ); + let unique: std::collections::HashSet<_> = attempts.iter().map(|(path, _)| path).collect(); + assert_eq!(unique.len(), 6, "the staged sixth txn must be replaced"); +} + +#[tokio::test] +async fn multipart_rejections_preserve_progress_and_cleanup_boundaries() { + // Stage rejection, definite complete rejection, and ambiguous successful responses. + for (stage_status, complete_status, complete_body, cleanup) in [ + (503, 200, "{}", true), + (200, 409, "transaction conflict", true), + (200, 429, "rate limited", true), + (200, 200, "{}", false), + (200, 200, "not json", false), + (200, 503, "gateway failure", false), + ] { + for abort_status in [200, 503] { + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = requests.clone(); + let progress = Arc::new(Mutex::new(Vec::new())); + let during_request = progress.clone(); + let remote = Arc::new(RemoteTable::new_mock( + "test".into(), + move |request| { + let path = request.url().path(); + observed.lock().unwrap().push(path.to_owned()); + let (status, body) = if path.ends_with("/create") { + (200, r#"{"upload_id":"rejected-upload"}"#) + } else if path.ends_with("/insert/") { + let progress = during_request.lock().unwrap(); + assert!(!progress.is_empty(), "must execute the scan tracker"); + assert!(progress.iter().all(|p: &(usize, usize, bool)| p.1 == 0)); + (stage_status, "{}") + } else if path.ends_with("/complete") { + (complete_status, complete_body) + } else if path.ends_with("/abort") { + (abort_status, "cleanup response") + } else { + panic!("unexpected request {path}") + }; + http::Response::builder() + .status(status) + .body(body.to_owned()) + .unwrap() + }, + Some(semver::Version::new(0, 4, 0)), + )); + let input = arrow_array::record_batch!(("id", Int32, [1, 2])).unwrap(); + remote.seed_schema(&serde_json::json!({"version": 1, "schema": JsonSchema::try_from(input.schema().as_ref()).unwrap()}).to_string()); + let seen = progress.clone(); + let error = AddDataBuilder::new(remote, Box::new(input), None) + .write_parallelism(2) + .retries(0) + .progress(move |p| { + seen.lock() + .unwrap() + .push((p.output_rows(), p.output_bytes(), p.done())) + }) + .execute() + .await + .unwrap_err(); + let requests = requests.lock().unwrap(); + let count = |suffix: &str| { + requests + .iter() + .filter(|path| path.ends_with(suffix)) + .count() + }; + assert_eq!(count("/create"), 1); + assert_eq!(count("/insert/"), 1); + assert_eq!(count("/complete"), usize::from(stage_status == 200)); + assert_eq!( + count("/abort"), + usize::from(cleanup), + "cleanup must honor retries=0: {error}" + ); + assert_eq!( + error.to_string().contains("commit outcome unknown"), + !cleanup, + "{error}" + ); + let progress = progress.lock().unwrap(); + let last = progress.last().unwrap(); + assert!(last.2); + assert_eq!(last.0, 2); + if stage_status != 200 { + assert!( + progress.iter().all(|p| p.1 == 0), + "unacknowledged bytes reported" + ); + } + } + } +} diff --git a/rust/lancedb/src/remote/util.rs b/rust/lancedb/src/remote/util.rs index 1c368e2f5..dcfaf9312 100644 --- a/rust/lancedb/src/remote/util.rs +++ b/rust/lancedb/src/remote/util.rs @@ -1,7 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use arrow_array::{ + Array, ArrayRef, GenericListViewArray, OffsetSizeTrait, RecordBatch, UInt64Array, + cast::AsArray, make_array, +}; +use arrow_buffer::ScalarBuffer; +use arrow_data::ArrayData; use arrow_ipc::CompressionType; +use arrow_schema::{ArrowError, DataType, Field}; +use arrow_select::{dictionary::garbage_collect_any_dictionary, take::take}; use futures::{Stream, StreamExt}; use reqwest::Response; @@ -9,6 +17,269 @@ use crate::{Result, arrow::SendableRecordBatchStream}; use super::db::ServerVersion; +fn has_dictionary(data: &ArrayData) -> bool { + matches!(data.data_type(), DataType::Dictionary(_, _)) + || data.child_data().iter().any(has_dictionary) +} + +fn has_list_view(data: &ArrayData) -> bool { + matches!( + data.data_type(), + DataType::ListView(_) | DataType::LargeListView(_) + ) || data.child_data().iter().any(has_list_view) +} + +// Arrow take on ordinary lists copies nested ListView ranges through +// MutableArrayData, losing sharing. Select child row IDs instead, then apply +// that selection recursively to the real children. +fn take_dictionary_rows( + array: &dyn Array, + indices: &UInt64Array, +) -> std::result::Result { + let data = array.to_data(); + if !has_list_view(&data) { + return take(array, indices, None); + } + let item = || std::sync::Arc::new(Field::new_list_field(DataType::UInt64, false)); + let proxy_type = match data.data_type() { + DataType::List(_) | DataType::Map(_, _) => DataType::List(item()), + DataType::LargeList(_) => DataType::LargeList(item()), + DataType::FixedSizeList(_, size) => DataType::FixedSizeList(item(), *size), + DataType::Struct(fields) => DataType::Struct( + fields + .iter() + .map(|f| f.as_ref().clone().with_data_type(DataType::UInt64)) + .collect(), + ), + // ListView take already preserves sharing; its actual child selection + // is performed by compact_list_view before dictionary collection. + _ => return take(array, indices, None), + }; + let children = data + .child_data() + .iter() + .map(|child| UInt64Array::from_iter_values(0..child.len() as u64).to_data()) + .collect(); + let proxy = make_array( + data.clone() + .into_builder() + .data_type(proxy_type) + .child_data(children) + .build()?, + ); + let selected = take(proxy.as_ref(), indices, None)?.to_data(); + let children = data + .child_data() + .iter() + .zip(selected.child_data()) + .map(|(child, ids)| { + let ids = UInt64Array::from(ids.clone()); + Ok(take_dictionary_rows(make_array(child.clone()).as_ref(), &ids)?.to_data()) + }) + .collect::, ArrowError>>()?; + Ok(make_array( + selected + .into_builder() + .data_type(data.data_type().clone()) + .child_data(children) + .build()?, + )) +} + +fn compact_list_view( + views: &GenericListViewArray, +) -> std::result::Result { + let mut ranges: Vec<_> = (0..views.len()) + .filter_map(|row| { + let start = views.value_offsets()[row].as_usize(); + let size = views.value_sizes()[row].as_usize(); + (views.is_valid(row) && size != 0).then(|| (start, start + size)) + }) + .collect(); + ranges.sort_unstable(); + let mut union: Vec<(usize, usize, usize)> = Vec::with_capacity(ranges.len()); + let mut len = 0; + for (start, end) in ranges { + if let Some(last) = union.last_mut().filter(|last| start <= last.1) { + let end = end.max(last.1); + len += end - last.1; + last.1 = end; + } else { + union.push((start, end, len)); + len += end - start; + } + } + let mut offsets = Vec::with_capacity(views.len()); + let mut sizes = Vec::with_capacity(views.len()); + for row in 0..views.len() { + let size = views.value_sizes()[row]; + if views.is_null(row) || size.as_usize() == 0 { + offsets.push(O::usize_as(0)); + sizes.push(O::usize_as(0)); + } else { + let start = views.value_offsets()[row].as_usize(); + let range = union[union.partition_point(|r| r.0 <= start) - 1]; + // Removing gaps cannot increase a valid original offset. + offsets.push(O::from_usize(range.2 + start - range.0).unwrap()); + sizes.push(size); + } + } + // Each child position is selected once, even for unsorted, overlapping views. + let indices = UInt64Array::from_iter_values( + union + .iter() + .flat_map(|&(start, end, _)| (start..end).map(|i| i as u64)), + ); + let child = take_dictionary_rows(views.values().as_ref(), &indices)?; + views + .to_data() + .into_builder() + .offset(0) + .buffers(vec![ + ScalarBuffer::from(offsets).into_inner(), + ScalarBuffer::from(sizes).into_inner(), + ]) + .child_data(vec![child.to_data()]) + .build() +} + +fn compact_dictionary_data(data: ArrayData) -> std::result::Result { + let data = match data.data_type() { + DataType::Dictionary(_, _) => { + let array = make_array(data); + garbage_collect_any_dictionary(array.as_any_dictionary())?.to_data() + } + DataType::ListView(_) => compact_list_view(make_array(data).as_list_view::())?, + DataType::LargeListView(_) => compact_list_view(make_array(data).as_list_view::())?, + // Selecting dictionary values retains view backing buffers, which IPC + // otherwise serializes in full even when most views are unreferenced. + DataType::Utf8View => make_array(data).as_string_view().gc().to_data(), + DataType::BinaryView => make_array(data).as_binary_view().gc().to_data(), + _ => data, + }; + let children = data + .child_data() + .iter() + .cloned() + .map(compact_dictionary_data) + .collect::, _>>()?; + data.into_builder().child_data(children).build() +} + +/// Compact dictionaries retained by row slices without changing the schema. +/// Row slices (and `take` alone) retain the original dictionary lookup tables. +/// Struct/fixed-size-list validity does not mask child slots, so values hidden +/// only by those ancestor nulls may remain referenced. +pub(super) fn compact_batch_dictionaries( + batch: RecordBatch, +) -> std::result::Result { + let columns = batch + .columns() + .iter() + .map(|array| { + let data = array.to_data(); + if !has_dictionary(&data) { + return Ok(array.clone()); + } + // Normalize container offsets and select their child rows before + // collecting dictionaries nested in lists/structs/maps. + let data = if matches!(data.data_type(), DataType::Dictionary(_, _)) { + data + } else { + let indices = UInt64Array::from_iter_values(0..array.len() as u64); + take_dictionary_rows(array.as_ref(), &indices)?.to_data() + }; + Ok(make_array(compact_dictionary_data(data)?)) + }) + .collect::, ArrowError>>()?; + RecordBatch::try_new_with_options( + batch.schema(), + columns, + &arrow_array::RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + ) +} + +/// Split batches before IPC encoding, preserving row order and allowing a single +/// oversized row. Compact each dictionary before measuring or splitting it so +/// descendants never repeatedly scan or encode the full source dictionary. +/// Yield slices on demand so compacted dictionary copies are not all retained. +pub(super) fn split_batch( + batch: RecordBatch, + max_bytes: usize, +) -> impl Iterator> { + let mut pending = vec![batch]; + std::iter::from_fn(move || { + while let Some(batch) = pending.pop() { + let batch = match compact_batch_dictionaries(batch) { + Ok(batch) => batch, + Err(err) => { + pending.clear(); + return Some(Err(err)); + } + }; + let size: usize = batch + .columns() + .iter() + .map(|array| { + array + .to_data() + .get_slice_memory_size() + .unwrap_or_else(|_| array.get_buffer_memory_size()) + }) + .sum(); + if size > max_bytes && batch.num_rows() > 1 { + let middle = batch.num_rows() / 2; + pending.push(batch.slice(middle, batch.num_rows() - middle)); + pending.push(batch.slice(0, middle)); + } else { + return Some(Ok(batch)); + } + } + None + }) +} + +pub(super) const IPC_BATCH_BYTES: usize = 8 * 1024 * 1024; +pub(super) const MAX_CREATE_BYTES: usize = 256 * 1024 * 1024; + +/// Validate the entire create payload before issuing its single atomic request. +/// A truncated IPC stream can be accepted as EOF by Arrow readers, so failing a +/// live request body after exceeding the budget cannot guarantee atomic failure. +/// Spooling bounds memory while ensuring an oversized input never reaches create. +pub(super) async fn create_body(data: SendableRecordBatchStream) -> Result { + use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; + let io_error = |err: std::io::Error| crate::Error::Other { + message: "Failed to prepare atomic remote create payload".into(), + source: Some(Box::new(err)), + }; + let file = tempfile::tempfile().map_err(io_error)?; + let mut file = tokio::fs::File::from_std(file); + let mut stream = Box::pin(stream_as_ipc(data)?); + let mut bytes = 0usize; + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + bytes = bytes.saturating_add(chunk.len()); + if bytes > MAX_CREATE_BYTES { + return Err(crate::Error::InvalidInput { + message: format!( + "Remote create_table exceeds the {MAX_CREATE_BYTES}-byte single-request budget. \ + Create the table with db.create_table(name, schema=...), then upload with \ + table.add(data, progress=True)." + ), + }); + } + file.write_all(&chunk).await.map_err(io_error)?; + } + file.rewind().await.map_err(io_error)?; + let stream = futures::stream::try_unfold(file, |mut file| async move { + let mut chunk = vec![0; 64 * 1024]; + let len = file.read(&mut chunk).await?; + chunk.truncate(len); + Ok::<_, std::io::Error>((len != 0).then_some((chunk, file))) + }); + Ok(reqwest::Body::wrap_stream(stream)) +} + pub fn stream_as_ipc( data: SendableRecordBatchStream, ) -> Result>> { @@ -18,6 +289,13 @@ pub fn stream_as_ipc( let buf = Vec::with_capacity(WRITE_BUF_SIZE); let writer = arrow_ipc::writer::StreamWriter::try_new_with_options(buf, &data.schema(), options)?; + let data = data.flat_map(|batch| match batch { + Ok(batch) => futures::stream::iter( + split_batch(batch, IPC_BATCH_BYTES).map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }); let stream = futures::stream::try_unfold( (data, writer, false), move |(mut data, mut writer, finished)| async move { @@ -42,11 +320,6 @@ pub fn stream_as_ipc( Ok(stream) } -pub fn stream_as_body(data: SendableRecordBatchStream) -> Result { - let stream = stream_as_ipc(data)?; - Ok(reqwest::Body::wrap_stream(stream)) -} - pub fn parse_server_version(req_id: &str, rsp: &Response) -> Result { let version = rsp .headers() diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index 8c5dc4b45..d6323449d 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -65,6 +65,7 @@ pub struct AddDataBuilder { pub(crate) progress_callback: Option, pub(crate) write_parallelism: Option, pub(crate) allow_external_blob_outside_bases: bool, + pub(crate) retries: Option, } impl std::fmt::Debug for AddDataBuilder { @@ -93,9 +94,18 @@ impl AddDataBuilder { progress_callback: None, write_parallelism: None, allow_external_blob_outside_bases: false, + retries: None, } } + /// Override the remote retry budget for this call. `0` disables retries, + /// including retries of idempotent multipart parts. Ambiguous commits are + /// never replayed, regardless of this setting. Ignored by embedded tables. + pub fn retries(mut self, retries: u8) -> Self { + self.retries = Some(retries); + self + } + pub fn mode(mut self, mode: AddDataMode) -> Self { self.mode = mode; self @@ -217,6 +227,7 @@ impl AddDataBuilder { mode: self.mode, tracker, allow_external_blob_outside_bases: self.allow_external_blob_outside_bases, + retries: self.retries, }) } } @@ -231,6 +242,7 @@ pub struct PreprocessingOutput { pub mode: AddDataMode, pub tracker: Option>, pub allow_external_blob_outside_bases: bool, + pub retries: Option, } /// Check that the input schema is valid for insert. diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 3f37c540d..fe131d907 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -75,6 +75,7 @@ pub struct MergeInsertBuilder { pub(crate) when_not_matched_by_source_delete: bool, pub(crate) when_not_matched_by_source_delete_filt: Option, pub(crate) timeout: Option, + pub(crate) retries: Option, pub(crate) use_index: bool, pub(crate) use_rte: Option, pub(crate) validate_single_shard: bool, @@ -91,12 +92,21 @@ impl MergeInsertBuilder { when_not_matched_by_source_delete: false, when_not_matched_by_source_delete_filt: None, timeout: None, + retries: None, use_index: true, use_rte: None, validate_single_shard: true, } } + /// Override the remote transport retry budget for this operation. `0` + /// disables retries. Ambiguous write results are never replayed. This is + /// independent of local transaction conflict retries. + pub fn retries(&mut self, retries: u8) -> &mut Self { + self.retries = Some(retries); + self + } + /// Rows that exist in both the source table (new data) and /// the target table (old data) will be updated, replacing /// the old row with the corresponding matching row. diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index d9828fff1..55980c5ff 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -26,6 +26,7 @@ pub struct UpdateBuilder { parent: Arc, pub(crate) filter: Option, pub(crate) columns: Vec<(String, String)>, + pub(crate) retries: Option, } impl UpdateBuilder { @@ -34,9 +35,17 @@ impl UpdateBuilder { parent, filter: None, columns: Vec::new(), + retries: None, } } + /// Override the remote retry budget for this call. `0` disables retries. + /// Ambiguous write results are never replayed. Ignored by embedded tables. + pub fn retries(mut self, retries: u8) -> Self { + self.retries = Some(retries); + self + } + /// Limits the update operation to rows matching the given filter /// /// If a row does not match the filter then it will be left unchanged. diff --git a/rust/lancedb/src/table/write_progress.rs b/rust/lancedb/src/table/write_progress.rs index 191c3284d..12e4dd62c 100644 --- a/rust/lancedb/src/table/write_progress.rs +++ b/rust/lancedb/src/table/write_progress.rs @@ -6,7 +6,7 @@ //! You can add a callback to process progress in [`crate::table::AddDataBuilder::progress`]. //! [`WriteProgress`] is the struct passed to the callback. -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -30,12 +30,19 @@ impl WriteProgress { self.elapsed } - /// Number of rows written so far. + /// Number of rows processed by the input scan. + /// + /// This does not indicate that the rows have been committed. pub fn output_rows(&self) -> usize { self.output_rows } - /// Number of bytes written so far. + /// Number of bytes processed by the writer. + /// + /// Remote multipart writes report acknowledged IPC part bytes, starting at + /// zero. Retransmitted parts are counted once. Other writers report their + /// encoded bytes when available, otherwise the scanned Arrow memory size. + /// This does not indicate that the write has been committed. pub fn output_bytes(&self) -> usize { self.output_bytes } @@ -94,6 +101,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, active_tasks: Arc, total_tasks: AtomicUsize, start: Instant, @@ -107,6 +116,7 @@ impl WriteProgressTracker { Self { rows_and_bytes: std::sync::Mutex::new((0, 0)), wire_bytes: AtomicUsize::new(0), + wire_bytes_enabled: AtomicBool::new(false), active_tasks: Arc::new(AtomicUsize::new(0)), total_tasks: AtomicUsize::new(1), start: Instant::now(), @@ -115,6 +125,11 @@ 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); + } + /// Set the total number of parallel write tasks (the write parallelism). pub fn set_total_tasks(&self, n: usize) { self.total_tasks.store(n, Ordering::Relaxed); @@ -179,7 +194,11 @@ 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 wire > 0 { wire } else { in_memory_bytes }; + let output_bytes = if self.wire_bytes_enabled.load(Ordering::Relaxed) || wire > 0 { + wire + } else { + in_memory_bytes + }; WriteProgress { elapsed: self.start.elapsed(), output_rows: rows, From da40aa6c44b0eaf5f2003e5837e1a4f5e7c3799b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:23 +0800 Subject: [PATCH 27/75] test: isolate SQL reader timeout from submission latency (#5000) The reader timeout regression can fail on a busy runner while submitting its real loopback Flight exchange, before it ever calls `reader()`. Freeze Tokio time and inhibit automatic clock advancement during submission, then let the existing 200ms result timeout fire. Preserve the exact result-stage error through both describe APIs and a second reader, and verify that the timeout closes the server response stream. With a diagnostic-only 300ms wall-clock delay in request-header preparation, main fails with `SQL query submission timed out`; the repaired fixture passes the same scenario through the real Flight/reader path. The focused regression and all 54 adjacent SQL tests pass locally. Hosted Linux and macOS CLI tests and the complete PR CI pass on `fb96931be004166a479cc031aca4b1db05f4b78d`. --- rust/lancedb/src/remote/sql_test.rs | 33 +++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 471966731..d94defac4 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -607,7 +607,15 @@ impl FlightService for TestSqlService { )); } if query == "SELECT exchange stall" { - return Ok(Response::new(futures::stream::pending().boxed())); + let dropped = DropSignal(self.exchange_drops.clone()); + return Ok(Response::new( + futures::stream::pending() + .map(move |message| { + let _dropped = &dropped; + message + }) + .boxed(), + )); } let rows = parameters.ok_or_else(|| Status::invalid_argument("exchange without parameters"))?; @@ -990,13 +998,26 @@ async fn an_abandoned_reader_leaves_the_rows_for_the_next_one() { async fn a_reader_that_times_out_reports_the_failure() { let mut client_config = ClientConfig::default(); client_config.timeout_config.timeout = Some(Duration::from_millis(200)); - let (client, _shutdown) = start_sql_service(TestSqlService::default(), client_config).await; + let service = TestSqlService::default(); + let drops = service.exchange_drops.clone(); + let (client, _shutdown) = start_sql_service(service, client_config).await; - let stalled = client - .execute(parameterized("SELECT exchange stall", parameter_row())) - .await - .unwrap(); + // Real loopback I/O must finish before the clock can advance to the timeout. + // A blocking task inhibits Tokio's automatic clock advance during submission. + tokio::time::pause(); + let submission_client = client.clone(); + let stalled = tokio::task::spawn_blocking(move || { + tokio::runtime::Handle::current().block_on( + submission_client.execute(parameterized("SELECT exchange stall", parameter_row())), + ) + }) + .await + .unwrap() + .unwrap(); + assert_eq!(drops.load(Ordering::SeqCst), 0); assert_overall_timeout(stalled.reader().await, "result"); + tokio::time::resume(); + wait_for(&drops, 1, "a timed-out reader must end the call").await; let Err(retried) = stalled.reader().await else { panic!("the rows are gone, so a second reader cannot succeed"); }; From 9b13e8f72530c8b1950c09685f6920711154a539 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:39 +0800 Subject: [PATCH 28/75] feat(python): materialize remote blobs at the query snapshot (#4973) Python remote queries materialize Blob v2 payloads with `blob_mode="bytes"` through synchronous and asynchronous `to_arrow`, `to_list`, `to_pandas`, and `to_batches`. Deferred reads bind to the actual producing dataset without changing the caller's live table handle, including concurrent writes and same-name DROP/CREATE. Trust only the authoritative `x-lancedb-query-version` plus `x-lancedb-query-snapshot`. A numeric version alone cannot distinguish a recreated table; the ordinary live watermark and user-supplied Arrow metadata cannot establish provenance. An independent immutable handle carries the original identity through every batch, byte-limit split, and large-Blob Range fallback, and requires a verified response echo before accepting payloads. Aliases, NULL/empty results, rerankers, and hybrid legs retain consistent provenance. Missing capability, mixed identities, or a serving node ignoring the precondition fails explicitly; ordinary descriptor queries remain available on older servers. The source docs distinguish Enterprise SQL payload bytes from SDK descriptors. Server dependency: https://github.com/lancedb/sophon/pull/10211. Validation uses retained, independently audited local evidence: 724 Python cases passed (one optional PyAV skip), 67 focused SDK Rust cases passed, 36 server checks passed, and 15 actual REST/SDK scenarios passed across retained runs. These cover sync/async and Arrow file/stream recreation, concurrent overwrite, deletion of a selected version, legacy capabilities, forged IPC metadata, WAL exclusion, and actual mid-batch recreation. The original aggregate experiment exited 101 because its extra harness assumed a Python batch size would split the native result; its 36 server checks and 13 completed scenarios remain valid. The corrected native-batch experiment passed separately for sync and async. No aggregate all-green claim is made. The public batched-range operation has separate cross-partition identity integration in https://github.com/lancedb/sophon/pull/10219 and https://github.com/lancedb/lancedb/pull/4994. This change does not claim to fix that loop. Realtime/MemWAL remains outside Blob v2 GA, without disabling existing writes or compaction. No dependency pins changed. Merge/rollout hold remains: upgrade every serving node before enabling the new SDK capability, verify proxy forwarding of both authoritative headers and the verification echo, and preserve queried versions for later reads. Missing or inconsistent capability fails explicitly; identity does not retain versions or authenticate storage paths. Actual deployed proxy/Cloud/PE behavior and production retention remain unverified. Old SDKs do not gain incarnation protection from a server-only upgrade. Published documentation retains the Early access badge and released Enterprise instructions, including explicit fetches for copying. The new Enterprise `blob_mode="bytes"` guidance, snapshot-bound copy example, future streaming restrictions and GA wording remain source-only MDX drafts until release. The correction distinguishing released Enterprise SQL bytes from SDK descriptors remains visible. Documentation validation checked comment boundaries, visible instructions, Python example syntax and whitespace; the site was not built. This documentation-only revision reuses the implementation evidence above. --- docs/web/management/table.mdx | 102 +++++- docs/web/sql/dql/blob-descriptor.mdx | 8 +- python/python/lancedb/_lancedb.pyi | 7 +- python/python/lancedb/query.py | 138 ++++++-- python/python/tests/test_remote_db.py | 457 +++++++++++++++++++++++-- python/src/table.rs | 16 +- rust/lancedb/src/remote/table.rs | 171 ++++++++- rust/lancedb/src/remote/table/blobs.rs | 30 +- rust/lancedb/src/table.rs | 23 ++ 9 files changed, 876 insertions(+), 76 deletions(-) diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 23fdbdb4a..031342fbc 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -375,8 +375,16 @@ file, up to 64 KiB by default, and larger values are stored outside it. A `blob` column keeps metadata separate from the payload bytes, so queries can filter rows without loading the blobs. -Most queries return descriptors, which contain metadata about the blob instead -of its bytes. You can +{/* Draft for Blob v2 GA. Confirm release status before removing Early access. + +Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled +are outside the GA support scope. +*/} + +SDK queries return descriptors by default, which contain metadata about the +blob instead of its bytes. Enterprise SQL queries return payload bytes by +default; use `blob_descriptor(column)` to select metadata instead. With an SDK, +you can [read the bytes in the query results](#multimodal-blob-query-results) or [fetch them by row ID](#multimodal-read-blobs). @@ -500,14 +508,41 @@ the default `"lazy"` mode because it would open `BlobFile` handles. Query with `blob_mode="descriptions"`, then read bytes with `fetch_blobs` or `fetch_blob_files`. +{/* Draft for the Enterprise Python bytes release. Replace the released instructions above only after SDK and serving-node rollout. + +`blob_mode="bytes"` also supports Enterprise queries. The SDK locks all blob +fetches, including streaming batches, to both the version in +`x-lancedb-query-version` and the incarnation/revision identity in +`x-lancedb-query-snapshot`, captured from the same query response. Every payload +request verifies that identity against the actual opened dataset before reading +rows. Concurrent writes therefore preserve the selected payloads. Dropping and +recreating a table, even at the same location and version, cannot substitute the +replacement's bytes: the original snapshot is served or the read fails explicitly. + +Upgrade the SDK and every serving node to support snapshot identities. A server +that reports only a numeric query version, a legacy `x-lancedb-version` watermark, +or Arrow schema metadata does not enable deferred bytes. Missing or unsupported +identities raise `NotImplementedError`; use `"descriptions"` until the upgrade is +complete. Ordinary queries, descriptors, and independent `fetch_blobs` calls keep +working. Old SDKs keep their existing behavior and do not gain this protection +from a server-only upgrade. Realtime/MemWAL and historical manifests without a +native transaction identity do not support deferred bytes. Snapshot identities +do not retain old versions; deleting the selected version still fails explicitly. +In-memory tables and namespace `QueryTable` pushdown do not support bytes mode. +On an Enterprise table, sync `Table.to_pandas()` and `Table.to_arrow()` are not +supported; use `table.search()` instead. A query's `to_pandas()` also raises in +the default `"lazy"` mode because remote lazy handles are not supported. +*/} + ###### Copy a subset of blob rows {#multimodal-copy-subset} -Blob query results describe the stored payload; they are not the bytes to -insert into another table. These APIs return different values: +SDK descriptors identify stored payloads; materialize the bytes before inserting +them into another table. These APIs return different values: | Read path | Value | | --- | --- | -| SQL or an Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | +| Enterprise SQL | Raw payload bytes by default. | +| An SDK Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | | `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. | | A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. | @@ -545,6 +580,50 @@ Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches for larger subsets; `fetch_blobs` materializes all requested bytes in memory. For incremental decoding, use `fetch_blob_files` instead. +{/* Draft for the Enterprise Python bytes release. Replace the copy example above when snapshot-bound remote bytes are released. + +For Enterprise tables, prefer server-side `CREATE TABLE AS SELECT` or +`INSERT INTO ... SELECT` to copy blobs without a client round trip: + +```sql +CREATE TABLE image_subset AS SELECT id, image FROM images WHERE id < 100; +-- To append to an existing destination: +INSERT INTO image_subset SELECT id, image FROM images WHERE id >= 100 AND id < 200; +``` + +For SDK copies, query with `blob_mode="bytes"` to bind selection and payload +reads to one snapshot. The following example copies up to 100 rows from an +existing `images` table with an integer `id` and a blob `image` column. + +```python +import lancedb +import pyarrow as pa + +source = db.open_table("images") +hits = ( + source.search() + .where("id < 100") + .select(["id", "image"]) + .limit(100) + .to_arrow(blob_mode="bytes") +) +subset = db.create_table( + "image_subset", + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), +) +if hits.num_rows: + subset.add(hits) +``` + +Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches +for larger subsets; `fetch_blobs` materializes all requested bytes in memory. +For incremental decoding, use `fetch_blob_files` instead. + +Remote bytes mode requires a server that supports snapshot-bound Blob reads. +Older servers and Realtime/MemWAL tables can still return descriptors, but +bytes mode raises an explicit unsupported-operation error before fetching payloads. +*/} + `blob_mode="bytes"` materializes top-level and struct-nested blob columns. It raises `ValueError` when the selected columns include blobs inside a list. Select those columns with `blob_mode="descriptions"`, or leave @@ -579,6 +658,19 @@ overwrite the table, use a separate reader checked out to a fixed version before querying. Otherwise, an overwrite can invalidate the row IDs used to fetch bytes and raise `ValueError`. +{/* Draft for the Enterprise Python bytes release. Replace the streaming restrictions above after release. + +Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, +including no blobs inside lists, namespace `QueryTable` pushdown, or query +shapes that cannot preserve their row results. Enterprise queries require a +valid `x-lancedb-query-version` and `x-lancedb-query-snapshot` response headers. +Legacy v1 bytes are limited to +eligible local plain scans. For local queries, if concurrent writers can +overwrite the table, use a separate reader checked out to a fixed version +before querying. Otherwise, an overwrite can invalidate the row IDs used to +fetch bytes and raise `ValueError`. +*/} + ###### Optional pandas examples {#multimodal-blob-pandas} The lazy-handle calls below require pylance. The query example expects `tbl_async`, diff --git a/docs/web/sql/dql/blob-descriptor.mdx b/docs/web/sql/dql/blob-descriptor.mdx index 5021f2d20..7ba83311c 100644 --- a/docs/web/sql/dql/blob-descriptor.mdx +++ b/docs/web/sql/dql/blob-descriptor.mdx @@ -15,10 +15,10 @@ SELECT id, blob_descriptor(video) AS descriptor FROM videos ``` -A [BlobV2](/management/table#managed-blobs) column's bytes are not fetched by -a plain `SELECT`: that already returns `large_binary`, the same as any other -binary column. `blob_descriptor` instead returns a small struct describing -where the payload lives, without reading it. Pass one row's descriptor to +A plain `SELECT` of a [BlobV2](/management/table#managed-blobs) column returns +its payload as `large_binary`. `blob_descriptor` instead returns a small +struct describing where the payload lives, without reading the payload. +Pass one row's descriptor to the SDK's blob file reader to open that payload directly: diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 15234532d..956806cde 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -749,7 +749,12 @@ class Table: def take_row_ids(self, row_ids: list[int]) -> TakeQuery: ... async def blob_columns(self) -> list[str]: ... async def fetch_blobs( - self, column: str, row_ids: list[int] + self, + column: str, + row_ids: list[int], + *, + version: Optional[int] = None, + snapshot_identity: Optional[str] = None, ) -> pa.LargeBinaryArray: ... async def fetch_blob_ranges( self, diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index bab40be95..f99aaeb73 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -4,6 +4,7 @@ from __future__ import annotations import asyncio +import re from abc import ABC, abstractmethod from concurrent.futures import ThreadPoolExecutor from datetime import timedelta @@ -194,20 +195,57 @@ def _unsupported_blob_pandas_error(reason: str) -> RuntimeError: ) -def _supports_local_blob_fetch( +def _supports_blob_fetch( async_table: "AsyncTable", pushdown_operations: Iterable[str] ) -> bool: - # Remote tables and QueryTable pushdown answer queries on a server, so a - # fetch through this handle could read another version. - return async_table._inner._is_native() and "QueryTable" not in pushdown_operations + # Remote queries carry their producing snapshot in response metadata. + # Namespace QueryTable pushdown has no equivalent snapshot contract. + return ( + not async_table._inner._is_native() or "QueryTable" not in pushdown_operations + ) + + +def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]: + value = (schema.metadata or {}).get(b"lancedb:query_version", b"") + if not value.isdigit() or not 0 < int(value) < 2**64: + raise NotImplementedError( + "blob_mode='bytes' requires a stable table snapshot: the query response " + "has a missing, invalid, or inconsistent x-lancedb-query-version header. " + "Upgrade the server and use a table without Realtime/MemWAL, or use " + "blob_mode='descriptions'." + ) + identity = (schema.metadata or {}).get(b"lancedb:query_snapshot", b"") + if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity): + raise NotImplementedError( + "blob_mode='bytes' requires a trustworthy query snapshot identity: " + "missing or unsupported x-lancedb-query-snapshot. Upgrade the server " + "on every serving node, or use blob_mode='descriptions'." + ) + return int(value), identity.decode("ascii") + + +def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table: + """Preserve a snapshot only when every query leg used the same identity.""" + keys = (b"lancedb:query_version", b"lancedb:query_snapshot") + snapshots = { + tuple((source.schema.metadata or {}).get(key) for key in keys) + for source in sources + } + metadata = dict(result.schema.metadata or {}) + for key in keys: + metadata.pop(key, None) + snapshot = next(iter(snapshots)) if len(snapshots) == 1 else None + if snapshot is not None and all(value is not None for value in snapshot): + metadata.update(zip(keys, snapshot)) + return result.replace_schema_metadata(metadata) def _blob_bytes_without_snapshot_error() -> NotImplementedError: return NotImplementedError( "blob_mode='bytes' cannot safely materialize blob columns without a " - "stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown " - "run the query on a server, so the blob fetch could read another table " - "version. Use blob_mode='descriptions' to inspect descriptors. To read " + "stable table snapshot. Namespace QueryTable pushdown does not bind " + "the query and blob fetches to one table version. " + "Use blob_mode='descriptions' to inspect descriptors. To read " "payloads, select row IDs with with_row_id(True), then call " "table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, " "row_ids). Keep the source unchanged between selection and fetching." @@ -1297,9 +1335,9 @@ class LanceQueryBuilder(ABC): columns without pylance. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - LanceDB Enterprise blob queries support only ``"descriptions"`` until a - stable - table snapshot can bind the query and blob fetches. + Enterprise queries support ``"bytes"`` at the query response's + snapshot and ``"descriptions"`` without payload reads. Remote + ``"lazy"`` handles are not supported. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and optional flattening. @@ -1307,6 +1345,10 @@ class LanceQueryBuilder(ABC): validate_blob_mode(blob_mode) if _is_remote_query_table(self._table): blob_sources = self._validated_blob_sources(blob_mode) + if blob_mode == "bytes": + return flatten_columns( + self.to_arrow(timeout=timeout, blob_mode=blob_mode), flatten + ).to_pandas(**kwargs) return _finish_remote_pandas( self.to_arrow(timeout=timeout), blob_mode=blob_mode, @@ -1629,7 +1671,8 @@ class LanceQueryBuilder(ABC): _query_is_plain_blob_scan(query) and getattr(self, "_reranker", None) is None and not _query_needs_lance_scanner(self) - and _supports_local_blob_fetch( + and self._table._table._inner._is_native() + and _supports_blob_fetch( self._table._table, getattr(self._table, "_pushdown_operations", ()), ) @@ -1650,11 +1693,12 @@ class LanceQueryBuilder(ABC): if blob_mode != "bytes": return blob_sources reject_unfetchable_blob_columns(schema, self._columns, blob_sources) - if blob_sources and not _supports_local_blob_fetch( + if blob_sources and not _supports_blob_fetch( self._table._table, getattr(self._table, "_pushdown_operations", ()) ): raise _blob_bytes_without_snapshot_error() - reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources) + if not _is_remote_query_table(self._table): + reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources) return blob_sources def _blob_output_schema(self) -> pa.Schema: @@ -1667,9 +1711,20 @@ class LanceQueryBuilder(ABC): return tbl if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) - return replace_blob_columns_with_bytes_sync( - tbl, blob_sources, self._table.fetch_blobs - ) + reject_unmatched_blob_outputs(tbl.schema, blob_sources) + if _is_remote_query_table(self._table) and blob_sources: + version, identity = _remote_blob_snapshot(tbl.schema) + + async def fetch_at_version(column, row_ids): + return await self._table._table._inner.fetch_blobs( + column, row_ids, version=version, snapshot_identity=identity + ) + + def fetch_blobs(column, row_ids): + return LOOP.run(fetch_at_version(column, row_ids)) + else: + fetch_blobs = self._table.fetch_blobs + return replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs) def _finalize_blob_query_table( self, @@ -2386,6 +2441,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): rs_table = result_set.read_all() result_set = self._reranker.rerank_vector(self._str_query, rs_table) check_reranker_result(result_set) + result_set = _merge_query_snapshot(result_set, rs_table) # convert result_set back to RecordBatchReader result_set = pa.RecordBatchReader.from_batches( result_set.schema, result_set.to_batches() @@ -2599,8 +2655,10 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): query = self._query_for_scan(blob_sources) results = self._table._execute_query(query, timeout=timeout).read_all() if self._reranker is not None: + source = results results = self._reranker.rerank_fts(self._query, results) check_reranker_result(results) + results = _merge_query_snapshot(results, source) return self._finalize_blob_query_table( results, blob_mode=blob_mode, blob_sources=blob_sources ) @@ -2847,6 +2905,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): with_row_ids=True, offset=self._offset, ) + results = _merge_query_snapshot(results, fts_results, vector_results) return self._finish_hybrid_results( results, blob_mode=blob_mode, blob_sources=blob_sources ) @@ -3559,9 +3618,8 @@ class AsyncQueryBase(object): _query_is_plain_blob_scan(query) and getattr(self, "_reranker", None) is None and not _query_needs_lance_scanner(self) - and _supports_local_blob_fetch( - self._table, self._table._pushdown_operations - ) + and self._table._inner._is_native() + and _supports_blob_fetch(self._table, self._table._pushdown_operations) ) def select(self, columns: Union[List[str], dict[str, str]]) -> Self: @@ -3766,11 +3824,14 @@ class AsyncQueryBase(object): if blob_mode != "bytes": return blob_sources reject_unfetchable_blob_columns(schema, projection, blob_sources) - if blob_sources and not _supports_local_blob_fetch( + if blob_sources and not _supports_blob_fetch( self._table, self._table._pushdown_operations ): raise _blob_bytes_without_snapshot_error() - reject_unmatched_blob_outputs(await self._blob_output_schema(), blob_sources) + if self._table._inner._is_native(): + reject_unmatched_blob_outputs( + await self._blob_output_schema(), blob_sources + ) return blob_sources async def _blob_output_schema(self) -> pa.Schema: @@ -3783,9 +3844,21 @@ class AsyncQueryBase(object): return tbl if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) - return await replace_blob_columns_with_bytes( - tbl, blob_sources, self._table.fetch_blobs - ) + reject_unmatched_blob_outputs(tbl.schema, blob_sources) + if ( + self._table is not None + and not self._table._inner._is_native() + and blob_sources + ): + version, identity = _remote_blob_snapshot(tbl.schema) + + async def fetch_blobs(column, row_ids): + return await self._table._inner.fetch_blobs( + column, row_ids, version=version, snapshot_identity=identity + ) + else: + fetch_blobs = self._table.fetch_blobs + return await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs) async def to_arrow( self, @@ -3811,7 +3884,8 @@ class AsyncQueryBase(object): ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. ``"bytes"`` returns payload bytes for supported row-addressable blob columns and raises for blobs inside lists. - LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``. + Enterprise queries fetch bytes at the version reported by the query + response. Namespace query pushdown refuses ``"bytes"``. """ blob_sources = await self._validated_blob_sources(blob_mode) if blob_mode == "bytes" and blob_sources: @@ -3893,9 +3967,9 @@ class AsyncQueryBase(object): columns without pylance. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - LanceDB Enterprise blob queries support only ``"descriptions"`` until a - stable - table snapshot can bind the query and blob fetches. + Enterprise queries support ``"bytes"`` at the query response's + snapshot and ``"descriptions"`` without payload reads. Remote + ``"lazy"`` handles are not supported. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and optional flattening. @@ -3903,6 +3977,9 @@ class AsyncQueryBase(object): validate_blob_mode(blob_mode) if self._table is not None and not self._table._inner._is_native(): await self._validated_blob_sources(blob_mode) + if blob_mode == "bytes": + tbl = await self.to_arrow(timeout=timeout, blob_mode=blob_mode) + return flatten_columns(tbl, flatten).to_pandas(**kwargs) return await self._remote_to_pandas( flatten=flatten, timeout=timeout, blob_mode=blob_mode, **kwargs ) @@ -4508,7 +4585,9 @@ class AsyncFTSQuery(AsyncStandardQuery): ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: + source = results results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) return AsyncRecordBatchReader(results, max_batch_length=max_batch_length) @@ -4835,7 +4914,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: + source = results results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) return AsyncRecordBatchReader(results, max_batch_length=max_batch_length) @@ -5027,6 +5108,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): ): result = result.drop(["_rowid"]) + result = _merge_query_snapshot(result, fts_results, vector_results) return AsyncRecordBatchReader(result, max_batch_length=max_batch_length) async def explain_plan(self, verbose: Optional[bool] = False): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 448fd6c39..561a0f900 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5462,14 +5462,34 @@ def blob_descriptor_take_table(): @contextlib.contextmanager -def blob_remote_table(*, server_version=Version("0.5.0"), location=None): +def blob_remote_table( + *, + server_version=Version("0.5.0"), + location=None, + version_header="1", + framing="file", + requests=None, + state=None, + empty=False, + schema_version=None, + search_scores=False, + snapshot_supported=True, + identity_header="v1:" + "a" * 64, + verify_identity=True, +): + if state is None: + state = {"version": 1} + def handler(request): if request.path == "/v1/table/test/describe/": + content_len = int(request.headers.get("Content-Length", 0)) + body = json.loads(request.rfile.read(content_len)) if content_len else {} request.send_response(200) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", str(server_version)) request.end_headers() response = dict(BLOB_DESCRIBE_RESPONSE) + response["version"] = body.get("version") or state["version"] if location is not None: response["location"] = str(location) request.wfile.write(json.dumps(response).encode()) @@ -5502,9 +5522,22 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): elif request.path == "/v1/table/test/query/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) + if requests is not None: + requests.append(("query", body)) columns = body.get("columns") - assert columns in (None, ["id", "image"], ["id"], ["image"]) - if columns == ["id"]: + assert columns in ( + None, + ["id", "image"], + ["id"], + ["image"], + {"payload": "image"}, + ) + if isinstance(columns, dict): + response_table = blob_query_response_table().select(["image", "_rowid"]) + response_table = response_table.rename_columns(["payload", "_rowid"]) + if not body.get("with_row_id", False): + response_table = response_table.drop(["_rowid"]) + elif columns == ["id"]: response_table = blob_query_response_table().select(["id"]) else: if columns == ["image"]: @@ -5521,25 +5554,86 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): response_table = blob_query_response_table() if not body.get("with_row_id", False): response_table = response_table.drop(["_rowid"]) + if search_scores and not body.get("filter", "").startswith("_rowid IN"): + if body.get("vector"): + response_table = response_table.append_column( + "_distance", pa.array([0.1, 0.2, 0.3], type=pa.float32()) + ) + elif body.get("full_text_query"): + response_table = response_table.append_column( + "_score", pa.array([3.0, 2.0, 1.0], type=pa.float32()) + ) + if empty: + response_table = response_table.slice(0, 0) + if schema_version is not None: + response_table = response_table.replace_schema_metadata( + { + b"lancedb:query_version": schema_version.encode(), + b"lancedb:query_snapshot": ("v1:" + "f" * 64).encode(), + } + ) request.send_response(200) - request.send_header("Content-Type", "application/vnd.apache.arrow.file") - request.send_header("x-lancedb-version", "1") + request.send_header( + "Content-Type", f"application/vnd.apache.arrow.{framing}" + ) + header = ( + version_header(body) if callable(version_header) else version_header + ) + if header is not None: + request.send_header("x-lancedb-version", header) + if snapshot_supported: + request.send_header("x-lancedb-query-version", header) + identity = ( + identity_header(body) + if callable(identity_header) + else identity_header + ) + if identity is not None: + request.send_header("x-lancedb-query-snapshot", identity) request.end_headers() - with pa.ipc.new_file(request.wfile, response_table.schema) as writer: - writer.write_table(response_table) + writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream + with writer_factory(request.wfile, response_table.schema) as writer: + writer.write_table(response_table, max_chunksize=1) elif request.path == "/v1/table/test/fetch_blobs/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) assert body["column"] == "image" - assert body["row_ids"] == [10, 20, 30] + if requests is not None: + requests.append(("fetch_blobs", body)) + payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""} + if state["version"] > 1 and body.get("version") != 1: + payloads = {row: b"new-version" for row in payloads} response_table = pa.table( - {"image": pa.array([b"alpha", None, b"gamma"], type=pa.large_binary())} + { + "image": pa.array( + [payloads[row] for row in body["row_ids"]], + type=pa.large_binary(), + ) + } ) request.send_response(200) request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + if verify_identity and request.headers.get("x-lancedb-query-snapshot"): + request.send_header( + "x-lancedb-query-snapshot", + request.headers["x-lancedb-query-snapshot"], + ) request.end_headers() with pa.ipc.new_stream(request.wfile, response_table.schema) as writer: writer.write_table(response_table) + elif request.path == "/v1/table/test/insert/": + if request.headers.get("Transfer-Encoding") == "chunked": + while size := int(request.rfile.readline().split(b";")[0], 16): + request.rfile.read(size) + assert request.rfile.read(2) == b"\r\n" + assert request.rfile.read(2) == b"\r\n" + else: + request.rfile.read(int(request.headers.get("Content-Length", 0))) + state["version"] += 1 + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps({"version": state["version"]}).encode()) else: request.send_response(404) request.end_headers() @@ -5548,6 +5642,222 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): yield db.open_table("test") +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +@pytest.mark.parametrize("method", ["to_arrow", "to_list", "to_pandas", "to_batches"]) +async def test_remote_blob_bytes_conversion(use_async, framing, method): + if method == "to_pandas": + pytest.importorskip("pandas") + requests = [] + with blob_remote_table(framing=framing, requests=requests) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + query = query.select(["id", "image"]) + if method == "to_batches": + kwargs = {"max_batch_length" if use_async else "batch_size": 1} + reader = query.to_batches(blob_mode="bytes", **kwargs) + if use_async: + reader = await reader + batches = [batch async for batch in reader] + else: + batches = list(reader) + assert all(batch.num_rows == 1 for batch in batches) + result = pa.Table.from_batches(batches, schema=reader.schema).to_pylist() + else: + result = getattr(query, method)(blob_mode="bytes") + if use_async: + result = await result + if method == "to_arrow": + assert result.schema.field("image").type == pa.large_binary() + result = result.to_pylist() + elif method == "to_pandas": + result = result.to_dict("records") + assert result == [ + {"id": 1, "image": b"alpha"}, + {"id": 2, "image": None}, + {"id": 3, "image": b"gamma"}, + ] + fetches = [body for path, body in requests if path == "fetch_blobs"] + assert fetches + assert all(body["version"] == 1 for body in fetches) + assert [row for body in fetches for row in body["row_ids"]] == [10, 20, 30] + descriptor_queries = [ + body + for path, body in requests + if path == "query" and body.get("filter", "").startswith("_rowid IN") + ] + assert all(body["version"] == 1 for body in descriptor_queries) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_keeps_query_snapshot_during_writes(use_async, framing): + requests = [] + state = {"version": 1} + with blob_remote_table( + framing=framing, requests=requests, state=state + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + kwargs = {"max_batch_length" if use_async else "batch_size": 1} + reader = query.select(["id", "image"]).to_batches(blob_mode="bytes", **kwargs) + if use_async: + reader = await reader + # The query has selected v1; commit v2 before consuming any payloads. + write = table.add([{"id": 4, "image": b"new-version"}]) + if use_async: + await write + version = await table.version() if use_async else table.version + assert version == 2 + if use_async: + rows = [row async for batch in reader for row in batch.to_pylist()] + else: + rows = [row for batch in reader for row in batch.to_pylist()] + assert [row["image"] for row in rows] == [b"alpha", None, b"gamma"] + fetches = [body for path, body in requests if path == "fetch_blobs"] + assert all(body["version"] == 1 for body in fetches) + # Snapshot fetches must not check out the caller's live handle. + version = await table.version() if use_async else table.version + assert version == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("version_header", [None, "invalid", "0", "-1", str(2**64)]) +async def test_remote_blob_bytes_invalid_snapshot(use_async, version_header): + requests = [] + with blob_remote_table( + version_header=version_header, requests=requests, schema_version="1" + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_empty_results(use_async, framing): + requests = [] + with blob_remote_table( + empty=True, framing=framing, requests=requests + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + result = query.to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result.num_rows == 0 + assert result.schema.field("image").type == pa.large_binary() + assert result.column_names == ["id", "image"] + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("kind", ["vector", "fts", "hybrid"]) +@pytest.mark.parametrize("rerank", [False, True]) +async def test_remote_blob_bytes_search_queries(use_async, kind, rerank): + with blob_remote_table(search_scores=True) as remote_table: + if use_async: + query = remote_table._table.query() + if kind in ("vector", "hybrid"): + query = query.nearest_to([1.0, 2.0]) + if kind in ("fts", "hybrid"): + query = query.nearest_to_text("hello") + elif kind == "vector": + query = remote_table.search([1.0, 2.0], vector_column_name="vector") + elif kind == "fts": + query = remote_table.search("hello", query_type="fts") + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + if rerank: + from lancedb.rerankers import RRFReranker + + class StripMetadataReranker(RRFReranker): + def rerank_vector(self, query, vector_results): + return vector_results.append_column( + "_relevance_score", pa.array([3.0, 2.0, 1.0]) + ).replace_schema_metadata(None) + + def rerank_fts(self, query, fts_results): + return self.rerank_vector(query, fts_results) + + def rerank_hybrid(self, query, vector_results, fts_results): + return ( + super() + .rerank_hybrid(query, vector_results, fts_results) + .replace_schema_metadata(None) + ) + + kwargs = {"query_string": "hello"} if kind == "vector" else {} + query = query.rerank(StripMetadataReranker(), **kwargs) + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result["image"].to_pylist() == [b"alpha", None, b"gamma"] + assert "_rowid" not in result.column_names + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_hybrid_rejects_different_snapshots(use_async): + def header(body): + return "2" if body.get("full_text_query") else "1" + + requests = [] + with blob_remote_table( + search_scores=True, version_header=header, requests=requests + ) as remote_table: + if use_async: + query = ( + remote_table._table.query() + .nearest_to([1.0, 2.0]) + .nearest_to_text("hello") + ) + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + with pytest.raises( + NotImplementedError, match="inconsistent x-lancedb-query-version" + ): + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("with_row_id", [False, True]) +async def test_remote_blob_bytes_alias_and_explicit_row_ids(use_async, with_row_id): + with blob_remote_table() as remote_table: + query = remote_table._table.query() if use_async else remote_table.search() + query = query.select({"payload": "image"}) + if with_row_id: + query = query.with_row_id() if use_async else query.with_row_id(True) + result = query.to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result["payload"].to_pylist() == [b"alpha", None, b"gamma"] + assert ("_rowid" in result.column_names) == with_row_id + if with_row_id: + assert result["_rowid"].to_pylist() == [10, 20, 30] + + def test_remote_blob_columns_and_fetch(): with blob_remote_table() as table: assert table.blob_columns() == ["image"] @@ -5569,7 +5879,7 @@ def test_sync_remote_blob_pandas_avoids_storage_access( raise AssertionError("remote storage must not be opened") monkeypatch.setattr(lance, "dataset", fail_dataset) - with blob_remote_table(location=location) as table: + with blob_remote_table(location=location, version_header=None) as table: monkeypatch.setattr(table, "to_lance", fail_dataset) query = table.search().select(["id", "image"]) if blob_mode == "descriptions": @@ -5582,8 +5892,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access( NotImplementedError, match="stable table snapshot" ) as exc: query.to_pandas(blob_mode=blob_mode) - assert "fetch_blobs(column, row_ids)" in str(exc.value) - assert "with_row_id(True)" in str(exc.value) + if blob_mode == "bytes": + assert "x-lancedb-query-version" in str(exc.value) + else: + assert "fetch_blobs(column, row_ids)" in str(exc.value) + assert "with_row_id(True)" in str(exc.value) @pytest.mark.asyncio @@ -5667,7 +5980,7 @@ async def test_async_remote_blob_descriptions_to_pandas_uses_server(monkeypatch) @pytest.mark.asyncio @pytest.mark.parametrize("blob_mode", ["bytes", "lazy"]) async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode): - with blob_remote_table() as remote_table: + with blob_remote_table(version_header=None) as remote_table: table = remote_table._table async def fail_uri(): @@ -5692,8 +6005,8 @@ async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob @pytest.mark.parametrize("method", ["to_arrow", "to_list"]) -def test_remote_search_bytes_refused_before_query(monkeypatch, method): - with blob_remote_table() as table: +def test_remote_search_bytes_requires_response_version(method): + with blob_remote_table(version_header=None) as table: query = table.search().select(["id", "image"]) descriptions = getattr(query, method)(blob_mode="descriptions") images = ( @@ -5703,19 +6016,15 @@ def test_remote_search_bytes_refused_before_query(monkeypatch, method): ) assert "_lance_row_id" not in images[0] - def fail_query(*args, **kwargs): - raise AssertionError("bytes must be refused before the query runs") - - monkeypatch.setattr(table, "_execute_query", fail_query) - with pytest.raises(NotImplementedError, match="stable table snapshot"): + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): getattr(query, method)(blob_mode="bytes") with pytest.raises(ValueError, match="blob_mode must be one of"): table.to_pandas(blob_mode="handles") @pytest.mark.asyncio -async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch): - with blob_remote_table() as remote_table: +async def test_async_remote_to_arrow_bytes_requires_response_version(monkeypatch): + with blob_remote_table(version_header=None) as remote_table: table = remote_table._table async def fail_fetch(*args, **kwargs): @@ -5723,8 +6032,7 @@ async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch): monkeypatch.setattr(table, "fetch_blobs", fail_fetch) query = table.query().select(["id", "image"]) - monkeypatch.setattr(query, "to_batches", fail_fetch) - with pytest.raises(NotImplementedError, match="stable table snapshot"): + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): await query.to_arrow(blob_mode="bytes") with pytest.raises(NotImplementedError, match="stable table snapshot"): await table.to_arrow(blob_mode="bytes") @@ -5821,7 +6129,7 @@ def test_remote_blob_query_to_pandas(): @pytest.mark.parametrize("blob_mode", ["default", "lazy", "bytes"]) def test_remote_blob_query_to_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode): - with blob_remote_table() as table: + with blob_remote_table(version_header=None) as table: def fail_fetch(*args, **kwargs): raise AssertionError("blob fetch must not use an unpinned remote table") @@ -6884,3 +7192,102 @@ def test_remote_optimize_rejects_explicit_pruning_before_submitting(): table.optimize(delete_unverified=True) assert server.tickets == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_rejects_legacy_watermark(use_async, framing): + requests = [] + with blob_remote_table( + framing=framing, + snapshot_supported=False, + version_header="1", + schema_version="1", + requests=requests, + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + descriptors = query.to_arrow(blob_mode="descriptions") + if use_async: + descriptors = await descriptors + assert descriptors.num_rows == 3 + assert pa.types.is_struct(descriptors.schema.field("image").type) + query = table.query() if use_async else table.search() + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("identity_header", [None, "", "v2:" + "a" * 64, "v1:broken"]) +async def test_remote_blob_bytes_requires_trustworthy_identity( + use_async, identity_header +): + requests = [] + with blob_remote_table( + identity_header=identity_header, schema_version="1", requests=requests + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + # Ordinary descriptors still work, even with forged Arrow schema metadata. + result = query.to_arrow(blob_mode="descriptions") + if use_async: + result = await result + assert result.num_rows == 3 + with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_rejects_unverified_serving_node(use_async): + with blob_remote_table(verify_identity=False) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + with pytest.raises( + NotImplementedError, match="did not verify the query snapshot identity" + ): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnations( + use_async, +): + requests = [] + + def identity(body): + return "v1:" + ("b" if body.get("full_text_query") else "a") * 64 + + with blob_remote_table( + search_scores=True, identity_header=identity, requests=requests + ) as remote_table: + if use_async: + query = ( + remote_table._table.query() + .nearest_to([1.0, 2.0]) + .nearest_to_text("hello") + ) + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + with pytest.raises( + NotImplementedError, match="inconsistent x-lancedb-query-version" + ): + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) diff --git a/python/src/table.rs b/python/src/table.rs index e76bae00a..31cf8d25c 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1978,14 +1978,28 @@ impl Table { } /// Read blob bytes for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids))] + #[pyo3(signature = (column, row_ids, *, version=None, snapshot_identity=None))] pub fn fetch_blobs( self_: PyRef<'_, Self>, column: String, row_ids: Vec, + version: Option, + snapshot_identity: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { + let inner = match (version, snapshot_identity) { + (None, None) => inner, + (Some(version), Some(identity)) => inner + .query_snapshot_with_identity(version, &identity) + .await + .infer_error()?, + _ => { + return Err(PyValueError::new_err( + "deferred blob reads require both query version and snapshot identity", + )); + } + }; let blobs: LargeBinaryArray = inner .fetch_blobs(column.as_str(), &row_ids) .await diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index cc495a83f..d560a4802 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -95,6 +95,34 @@ const MIN_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-ve const MIN_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-timestamp"); const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-read-version"); const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version"); +const QUERY_SNAPSHOT_HEADER: &str = "x-lancedb-query-snapshot"; + +fn valid_query_snapshot_identity(value: &str) -> bool { + value.strip_prefix("v1:").is_some_and(|digest| { + digest.len() == 64 + && digest + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} + +fn check_query_snapshot_response( + expected: Option<&str>, + response: &reqwest::Response, +) -> Result<()> { + if let Some(expected) = expected + && response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + != Some(expected) + { + return Err(Error::NotSupported { message: "Blob response did not verify the query snapshot identity; upgrade every serving node".into() }); + } + Ok(()) +} + +const QUERY_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-query-version"); /// Asks for stream framing, which is decoded as it arrives. Servers that do not /// stream query results ignore this and answer with file framing. const QUERY_ACCEPT: &str = @@ -613,6 +641,7 @@ pub struct RemoteTable { /// Stamped onto every branch-accepting request so reads and writes resolve /// on the branch's own version chain rather than main's. branch: Option, + expected_query_snapshot: Option, } impl std::fmt::Debug for RemoteTable { @@ -855,6 +884,7 @@ impl RemoteTable { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -891,6 +921,7 @@ impl RemoteTable { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, + expected_query_snapshot: None, } } @@ -1170,20 +1201,37 @@ impl RemoteTable { .and_then(|value| value.to_str().ok()) .map(str::to_owned); let framing = resolve_arrow_ipc_framing(content_type.as_deref(), request_id)?; + let table_version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); - match framing { + // Legacy version headers are freshness watermarks, not proof that the + // query and a later Blob read use the same immutable dataset. + let query_version = response + .headers() + .get(&QUERY_VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); + + let query_identity = response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .map(str::to_owned); + + let stream = match framing { ArrowIpcFraming::Stream => { - let table_version = response - .headers() - .get(&VERSION_HEADER) - .and_then(|value| value.to_str().ok()) - .and_then(|value| value.parse().ok()); ipc_stream::read_ipc_stream( response.bytes_stream(), request_id.to_string(), table_version, ) - .await + .await? } ArrowIpcFraming::File => { // File framing keeps its footer at the end, so the whole body is @@ -1192,9 +1240,21 @@ impl RemoteTable { let reader = FileReader::try_new(Cursor::new(body), None)?; let schema = reader.schema(); let stream = futures::stream::iter(reader).map_err(DataFusionError::from); - Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + Box::pin(RecordBatchStreamAdapter::new(schema, stream)) as SendableRecordBatchStream } + }; + // Bind subsequent blob reads to the response's snapshot, never to a + // version sampled from the live table before or after the query. + let mut metadata = stream.schema().metadata().clone(); + metadata.remove("lancedb:query_version"); + metadata.remove("lancedb:query_snapshot"); + if let Some(identity) = query_identity { + metadata.insert("lancedb:query_snapshot".into(), identity); } + if let Some(version) = query_version { + metadata.insert("lancedb:query_version".into(), version.to_string()); + } + Ok(with_stream_metadata(stream, metadata)) } fn apply_query_params( @@ -1620,9 +1680,37 @@ impl RemoteTable { streams.await? }; + if let Some(first) = streams.first() { + let schema = first.schema(); + if streams.iter().skip(1).any(|stream| { + stream.schema().metadata().get("lancedb:query_version") + != schema.metadata().get("lancedb:query_version") + }) { + return Err(Error::Runtime { + message: "Remote query responses refer to different table snapshots; retry the query against a fixed version".into(), + }); + } + } + + let identities_agree = streams.first().is_none_or(|first| { + streams.iter().skip(1).all(|stream| { + stream.schema().metadata().get("lancedb:query_snapshot") + == first.schema().metadata().get("lancedb:query_snapshot") + }) + }); Ok(streams .into_iter() .map(|stream| { + // Ordinary descriptor queries remain usable during an upgrade. + // Deferred bytes require every leg's identity, so never preserve + // the first leg's capability when another leg lacks or differs. + let stream = if identities_agree { + stream + } else { + let mut metadata = stream.schema().metadata().clone(); + metadata.remove("lancedb:query_snapshot"); + with_stream_metadata(stream, metadata) + }; let stream = restore_projection_order(stream, &query.base().select); match deadline { Some((deadline, timeout)) => { @@ -1673,6 +1761,26 @@ impl RemoteTable { } } +fn with_stream_metadata( + stream: SendableRecordBatchStream, + metadata: HashMap, +) -> SendableRecordBatchStream { + let schema = Arc::new( + stream + .schema() + .as_ref() + .clone() + .with_metadata(metadata.clone()), + ); + let batches = stream.map(move |batch| { + batch.map(|mut batch| { + batch.schema_metadata_mut().clone_from(&metadata); + batch + }) + }); + Box::pin(RecordBatchStreamAdapter::new(schema, batches)) +} + fn restore_projection_order( stream: Pin>, select: &Select, @@ -1921,6 +2029,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -1948,6 +2057,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -1984,6 +2094,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } } @@ -2570,6 +2681,23 @@ impl BaseTable for RemoteTable { } } } + async fn query_snapshot_with_identity( + &self, + version: u64, + identity: &str, + ) -> Result> { + if version == 0 || !valid_query_snapshot_identity(identity) { + return Err(Error::InvalidInput { + message: "invalid or unsupported query snapshot identity".into(), + }); + } + let mut snapshot = self.with_branch(self.branch.clone()); + *snapshot.version.write().await = Some(version); + snapshot.reset_freshness(None, true); + snapshot.expected_query_snapshot = Some(identity.to_owned()); + Ok(Arc::new(snapshot)) + } + async fn query_snapshot(&self) -> Result> { let description = self.describe().await?; let TableDescription { @@ -6704,8 +6832,15 @@ mod tests { assert_eq!(request_sizes.lock().unwrap().as_slice(), &[1024, 1]); } + #[rstest::rstest] + #[case(false)] + #[case(true)] #[tokio::test] - async fn test_fetch_blobs_splits_byte_limited_requests_and_reads_large_blob_by_range() { + async fn test_fetch_blobs_splits_byte_limited_requests_and_reads_large_blob_by_range( + #[case] guarded: bool, + ) { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // Simulate a lower byte cap so this test exercises the same 400 response // without allocating 64 MiB of blob data. let requests = Arc::new(std::sync::Mutex::new(Vec::new())); @@ -6714,8 +6849,15 @@ mod tests { "my_table", semver::Version::new(0, 5, 0), move |request| { + if guarded { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + } let path = request.url().path(); if path == "/v1/table/my_table/describe/" { + assert!( + !guarded, + "a later describe cannot establish the producing identity" + ); return http::Response::builder() .status(200) .body(br#"{"version":42,"schema":{"fields":[]}}"#.to_vec()) @@ -6766,6 +6908,7 @@ mod tests { return http::Response::builder() .status(200) .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .body(write_ipc_stream_uncompressed(&batch)) .unwrap(); } @@ -6781,12 +6924,14 @@ mod tests { match range { "bytes=0-0" => http::Response::builder() .status(206) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .header(reqwest::header::CONTENT_RANGE, "bytes 0-0/10") .header(VERSION_HEADER, "42") .body(b"0".to_vec()) .unwrap(), "bytes=0-9" => http::Response::builder() .status(206) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .header(reqwest::header::CONTENT_RANGE, "bytes 0-9/10") .body(b"0123456789".to_vec()) .unwrap(), @@ -6795,6 +6940,14 @@ mod tests { }, ); + let table = if guarded { + table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap() + } else { + table + }; let blobs = table .fetch_blobs("image", &[10, 20, 30, 40, 20]) .await diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 345b731c5..a0051c955 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -33,8 +33,8 @@ use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; use crate::table::{AnyQuery, BaseTable}; use super::{ - FreshnessHeaders, FreshnessState, ReadSnapshot, RemoteTable, VERSION_HEADER, - freshness_headers_snapshot, + FreshnessHeaders, FreshnessState, QUERY_SNAPSHOT_HEADER, ReadSnapshot, RemoteTable, + VERSION_HEADER, check_query_snapshot_response, freshness_headers_snapshot, }; // The Cloud route rejects larger row-id lists. Its separate 64 MiB byte limit @@ -93,6 +93,7 @@ struct TableBlobRangeRequester { version: Option, branch: Option, source_uri: Option, + expected_query_snapshot: Option, source_commit_micros: Option, row_is_address: bool, freshness: Arc>, @@ -125,6 +126,9 @@ impl BlobRangeRequester for TableBlobRangeRequester { .apply(self.client.get(&self.path)) .header(header::RANGE, range_header) }; + if let Some(identity) = &self.expected_query_snapshot { + request = request.header(QUERY_SNAPSHOT_HEADER, identity); + } if let Some(version) = version.or(self.version) { request = request.query(&[("version", version)]); } @@ -140,6 +144,10 @@ impl BlobRangeRequester for TableBlobRangeRequester { request = request.query(&[("source_commit_micros", timestamp)]); } let (request_id, response) = self.client.send_with_retry(request, None, true).await?; + if response.status().is_success() || response.status() == StatusCode::RANGE_NOT_SATISFIABLE + { + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + } // Preserve 416 size-probe responses so the caller can detect empty blobs. if response.status() == StatusCode::RANGE_NOT_SATISFIABLE && matches!(mode, RangeRequestMode::SizeProbe) @@ -531,7 +539,11 @@ impl RemoteTable { // A dotted path needs client-side validation because the server may // report an internal type mismatch when the path crosses a list. Use // an already cached schema for top-level list fields as well. - if column.contains('.') || self.schema_cache.try_get().is_some() { + // Guarded readers must validate the producing identity on the server + // before consulting any schema resolved from a later logical binding. + if self.expected_query_snapshot.is_none() + && (column.contains('.') || self.schema_cache.try_get().is_some()) + { let schema = self.schema().await?; crate::blob::reject_list_blob_column(schema.as_ref(), column)?; } @@ -539,6 +551,9 @@ impl RemoteTable { } async fn explain_list_blob_bad_request(&self, column: &str, error: Error) -> Error { + if self.expected_query_snapshot.is_some() { + return error; + } let is_bad_request = match &error { Error::Http { status_code: Some(code), @@ -648,9 +663,17 @@ impl RemoteTable { .client .post(&format!("/v1/table/{}/fetch_blobs/", self.identifier)) .json(&body); + let request = if let Some(identity) = &self.expected_query_snapshot { + request.header(QUERY_SNAPSHOT_HEADER, identity) + } else { + request + }; let (request_id, response) = self .send_with_freshness(request, true, read_snapshot.freshness) .await?; + if response.status().is_success() { + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + } let mut stream = match self.read_arrow_response(&request_id, response).await { Ok(stream) => stream, Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), @@ -1023,6 +1046,7 @@ impl RemoteTable { version: read_snapshot.version, branch: source.map_or_else(|| self.branch.clone(), |source| source.branch.clone()), source_uri: source.map(|source| source.uri.clone()), + expected_query_snapshot: self.expected_query_snapshot.clone(), source_commit_micros: source.map(|source| source.committed_at_micros), row_is_address: source.is_some_and(|source| source.row_is_address), freshness: Arc::new(std::sync::Mutex::new(read_snapshot.freshness_state)), diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 18a5b7ddf..db68ab290 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -832,6 +832,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "blob_columns is not supported on this table type".into(), }) } + /// Bind a remote payload reader to an identity from its producing query. + async fn query_snapshot_with_identity( + &self, + _version: u64, + _identity: &str, + ) -> Result> { + Err(Error::NotSupported { + message: "query snapshot identities are not supported on this table type".into(), + }) + } /// Materialize blob bytes for the given row ids. See [`Table::fetch_blobs`]. async fn fetch_blobs(&self, _column: &str, _row_ids: &[u64]) -> Result { Err(Error::NotSupported { @@ -1352,6 +1362,19 @@ impl Table { }) } + /// Create an independent remote handle constrained by a query response. + #[doc(hidden)] + pub async fn query_snapshot_with_identity(&self, version: u64, identity: &str) -> Result { + Ok(Self { + inner: self + .inner + .query_snapshot_with_identity(version, identity) + .await?, + database: self.database.clone(), + embedding_registry: self.embedding_registry.clone(), + }) + } + /// Count the number of rows in this dataset. /// /// # Arguments From 9755c57d4111425b81f6fe4494ed58a3bf5cc416 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 03:20:20 +0800 Subject: [PATCH 29/75] fix: prune Function outcomes for replaced fragments (#5005) An input-preserving merge can fail freshness preservation after a successful data write: the replaced fragment loses its signature, but its known/failed-row records remain and fail sidecar validation. This affects tables with persisted Function outcome metadata. Prune both outcome maps with the same live-fragment set used for signatures and row state. Outcomes on untouched fragments remain intact, and inserted rows remain pending fill. The regression performs a real mixed update/insert and reopens the resulting snapshot to check both output columns. Native validation on Linux: the exact regression fails before the fix with `failure evidence names a fragment without a signature`. At `20b10d80408cb455d9e5827f5d7d36a117622dea`, all 24 discovered `table::freshness::tests::function_write_` cases pass, including the new real merge regression. Test lists, counts and logs were retained and SHA-256 verified. [Current-head CI passed both workspace Clippy configurations](https://github.com/lancedb/lancedb/actions/runs/43274052568/job/131377627811). A separate package-only, default-feature Clippy command reported dead-code errors in seven files unchanged from the base; that local failure is retained rather than represented as a pass. Other hosted gates are pending. This does not claim downstream Sophon integration or deployed acceptance. --- rust/lancedb/src/table/freshness.rs | 97 +++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 477020fc3..645653a46 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -1879,6 +1879,8 @@ pub async fn preserve_function_freshness( pending_fill.retain(|id, _| live.contains(id)); state.signatures.retain(|id, _| live.contains(id)); state.row_state.retain(|id, _| live.contains(id)); + state.failure_coverage.retain(|id, _| live.contains(id)); + state.failed_rows.retain(|id, _| live.contains(id)); state.basis.clear(); let reference = write_sidecar(dataset, &state.normalize()?).await?; let fill_reference = if pending_fill.is_empty() { @@ -3029,6 +3031,101 @@ mod tests { } } + #[tokio::test] + async fn function_write_prunes_outcomes_for_replaced_fragments() { + let table = fresh_function_table().await; + let mut dataset = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .as_ref() + .clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + let failures = FailureEvidence { + known_rows: BTreeMap::from([ + (0, RoaringBitmap::from_iter([0, 1])), + (1, RoaringBitmap::from_iter([0, 1])), + ]), + failed_rows: BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]), + }; + for column in ["search_text", "search_token_count"] { + record_freshness_with_failures( + &mut dataset, + None, + column, + "fb_01K3TEXT", + &inputs, + signatures.clone(), + &failures, + ) + .await + .unwrap(); + } + + // Replace all of fragment 0, insert one uncomputed row, and leave + // fragment 1 (including its retained failure evidence) untouched. + let source = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "e"]), + ("spare", Int32, [1, 1, 1]) + ) + .unwrap(); + let mut merge = + MergeInsertBuilder::try_new(Arc::new(dataset), vec!["title".into()]).unwrap(); + merge.when_matched(WhenMatched::UpdateAll); + merge.when_not_matched(WhenNotMatched::InsertAll); + let (merged, stats) = merge + .try_build() + .unwrap() + .execute_reader(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + let mut dataset = merged.as_ref().clone(); + assert!(!dataset.get_fragments().iter().any(|f| f.id() == 0)); + assert!(dataset.get_fragments().iter().any(|f| f.id() == 1)); + preserve_function_freshness( + &mut dataset, + FunctionWrite::Merge { + source_schema: &source.schema(), + on: &["title".into()], + num_inserted_rows: stats.num_inserted_rows, + }, + ) + .await + .unwrap(); + + let reopened = dataset + .checkout_version(dataset.version().version) + .await + .unwrap(); + for column in ["search_text", "search_token_count"] { + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&reopened, column, "fb_01K3TEXT", &inputs) + .await + .unwrap() + else { + panic!("the preserved sidecar should retain failure evidence"); + }; + assert_eq!( + failures.known_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([0, 1]))]) + ); + assert_eq!( + failures.failed_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]) + ); + assert_eq!(staleness.pending_fill.len(), 1); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] From 1806dc232395d2a446a2eef17886194b5dd27051 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 12 Nov 2026 11:34:14 -0800 Subject: [PATCH 30/75] ci(java): publish beta releases to Fury instead of Maven Central (#5011) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Java publishing has failed since `v0.42.0-beta.10` because the `lancedb` Sonatype org hit Maven Central's monthly release-count limit: ```text Publishing blocked: your organization has reached its monthly release count limit. Grace period ended 2026-11-08. Usage resets 2026-12-01. ``` This sends beta tags to `https://maven.fury.io/lancedb/` instead, matching how Python publishes betas to `pypi.fury.io/lancedb`. Stable releases still go to Maven Central. ```text tag contains "beta" -> setup-java server "fury" -> mvn deploy -P deploy-to-fury otherwise -> setup-java server "ossrh" -> mvn deploy -P deploy-to-ossrh ``` - `java/pom.xml`: new `deploy-to-fury` profile that points `distributionManagement` at Fury. - `java/README.md`: explains how to add the Fury and `maven.lance.org` repositories to use a beta. Requires a `FURY_TOKEN` secret with push access to the `lancedb` Fury account. The token is passed as the Maven username with a placeholder password. That follows Gemfury's convention but hasn't been tested against Fury yet. ## Evidence Running the beta path locally (`deploy -pl lancedb-core -am -P deploy-to-fury`) against a file repository deployed `lancedb-parent` (POM) and `lancedb-core` (JAR, POM, sources, javadoc). `help:effective-pom -P deploy-to-fury` resolves the release repository to `https://maven.fury.io/lancedb/`. ## Merge Risk **Door:** Two-way. This only changes where future betas are published; reverting the workflow restores Central publishing. **Blast Radius:** `release-ci`. Beta consumers need the extra repository; stable consumers are unaffected. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .github/workflows/java-publish.yml | 20 +++++++++++++----- java/README.md | 34 ++++++++++++++++++++++++++++++ java/pom.xml | 9 ++++++++ 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/.github/workflows/java-publish.yml b/.github/workflows/java-publish.yml index 094aa552a..35d052de9 100644 --- a/.github/workflows/java-publish.yml +++ b/.github/workflows/java-publish.yml @@ -39,9 +39,11 @@ jobs: distribution: temurin java-version: 8 cache: "maven" - server-id: ossrh - server-username: SONATYPE_USER - server-password: SONATYPE_TOKEN + # Betas go to Fury and stable releases to Maven Central, which limits + # how many releases an organization may publish each month. + server-id: ${{ contains(github.ref, 'beta') && 'fury' || 'ossrh' }} + server-username: ${{ contains(github.ref, 'beta') && 'FURY_TOKEN' || 'SONATYPE_USER' }} + server-password: ${{ contains(github.ref, 'beta') && 'FURY_PASSWORD' || 'SONATYPE_TOKEN' }} gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} gpg-passphrase: MAVEN_GPG_PASSPHRASE - name: Set git config @@ -52,8 +54,16 @@ jobs: if: github.event_name == 'pull_request' run: | ./mvnw --batch-mode -DskipTests package -pl lancedb-core -am - - name: Publish - if: startsWith(github.ref, 'refs/tags/v') + - name: Publish to Fury + if: startsWith(github.ref, 'refs/tags/v') && contains(github.ref, 'beta') + run: | + ./mvnw --batch-mode -DskipTests deploy -pl lancedb-core -am -P deploy-to-fury + env: + FURY_TOKEN: ${{ secrets.FURY_TOKEN }} + # Fury authenticates with the token as the username; the password is ignored. + FURY_PASSWORD: NOPASS + - name: Publish to Maven Central + if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, 'beta') run: | echo "use-agent" >> ~/.gnupg/gpg.conf echo "pinentry-mode loopback" >> ~/.gnupg/gpg.conf diff --git a/java/README.md b/java/README.md index fd163b9f1..85e7e85ba 100644 --- a/java/README.md +++ b/java/README.md @@ -1,5 +1,39 @@ # LanceDB Java Enterprise Client +## Installation + +Stable releases of `com.lancedb:lancedb-core` are published to Maven Central. + +Beta releases are published to `https://maven.fury.io/lancedb/` instead. They +depend on Lance beta releases, which are published to `https://maven.lance.org`. +To use a beta, add both repositories alongside Maven Central: + +```xml + + + lancedb + https://maven.fury.io/lancedb/ + + + lance + https://maven.lance.org + + +``` + +For Gradle: + +```kotlin +repositories { + mavenCentral() + maven { url = uri("https://maven.fury.io/lancedb/") } + maven { url = uri("https://maven.lance.org") } +} +``` + +Use an explicit version, including the full `-beta.N` suffix. Beta versions are +Maven releases, not `SNAPSHOT` versions. + ## Configuration and Initialization ### LanceDB Cloud (legacy) diff --git a/java/pom.xml b/java/pom.xml index df709fb4f..fc89ebe4c 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -318,6 +318,15 @@ + + deploy-to-fury + + + fury + https://maven.fury.io/lancedb/ + + + deploy-to-ossrh From 6d24446a3043fcb22a73c2c9aed21b62a5648938 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 04:03:04 +0800 Subject: [PATCH 31/75] feat: add negotiated batched blob range reads across SDKs (#4994) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Existing Rust and Python blob range calls must keep working when only the SDK is upgraded. Add negotiated batched range reads across Rust, Python sync/async and TypeScript, preserving ordered NULLs, duplicates and branch/version reads with splitting and reassembly at 1,024 ranges or 64 MiB per request. Only a successful describe response advertising `x-lancedb-blob-ranges: 1` selects the batched endpoint. Missing or unknown capability values select the existing descriptor-query plus BlobFile Range GET route before the operation. Endpoint failures never switch protocols. HTTP 400 preserves the server message and request ID as Rust `InvalidInput` / Python `ValueError`; other errors retain their existing semantics. The operation binds both numeric version and immutable snapshot identity from its producing query or first range response. Every later partition and oversized-range piece sends that original identity and requires an equal response identity before decoding. Same-name table recreation therefore fails explicitly instead of returning mixed old/new payloads; no partial array is returned on later failure. Targets `main`. The read-buffering prerequisite #4979, safe-write prerequisite #4977 and deferred-query identity prerequisite #4973 are merged into main; #5000 also supplies the merged SQL timeout-test prerequisite. Server support is [Sophon #10219](https://github.com/lancedb/sophon/pull/10219), including #10211. Exact SDK `1497b508324662180086a4d1e0a6eb9e0b3970db` and server `f39712c2c150b220eb831e00f6663c9eef32dce5` passed a real local SDK → REST → PE experiment: one Rust harness test, 14 assertion groups, 38 REST range requests and 34 PE RPCs. All four sync/async × warm/cold table-recreation cases failed explicitly before the second descriptor lookup or PE dispatch, with no mixed payload or partial result. The other groups retained 1,025-range success, 70 MiB reassembly, branch/version reads, overwrite snapshot consistency, error behavior and TypeScript buffer ownership. Bindings were rebuilt and their loaded hashes verified. This is local interoperability evidence, not Cloud, mixed-fleet or deployed header-forwarding acceptance. The server dependency upgrade, External/cache/URI-policy acceptance and validated rollout remain required. Enforcing PE support must precede QN and SDK enablement; identity does not retain versions or freeze External objects. This PR does not claim deployed support or complete ENT-3100/GA acceptance. Published documentation retains the Early access badge and released Enterprise instructions, including explicit fetches for copying. The new Enterprise `blob_mode="bytes"` guidance, snapshot-bound copy example, future streaming restrictions and GA wording remain source-only MDX drafts until release. The correction distinguishing released Enterprise SQL bytes from SDK descriptors remains visible. Documentation validation checked comment boundaries, visible instructions, Python example syntax and whitespace; the site was not built. The main integration keeps these release gates unchanged. Main integration at `0491d9bdcc65ce5d52ea93e1083c89e951ea4f9d` normally merges main `9b13e8f72530c8b1950c09685f6920711154a539`, including its Lance beta.18 dependency. Focused current-source validation passed: 493 remote-table/query/Blob/IPC/write-progress Rust tests, 23 shared create/write-body tests, 59 native Blob integration tests and 7 public HTTP range tests. Rebuilt Python passed 468 selected tests (one optional PyAV test skipped), and rebuilt TypeScript passed 194 selected tests across four suites; lint/format, TypeScript compilation and API documentation generation passed. Shared tests include actual HTTP multipart failures, acknowledgment boundaries, dictionary compaction and native Blob compaction. The 598 unrelated Jest cases excluded by the focused shared-suite selector were not run. The retained 14-group joint REST/PE experiment used the earlier exact candidates stated above. Operation-identity/range/IPC code is unchanged, but dependencies and shared write interfaces changed with main; the new local checks validate the SDK combination and do not constitute a fresh final-head SDK/server joint, Cloud or rollout run. Early access and every remaining server/External/cache/policy/dependency/rollout condition remain in force. CI snapshot on this head (2026-11-12 18:30 UTC): `build-no-lock` failed in the standalone `ci/tests/test_build_no_lock.py` fixture at the retained-rlib assertion, before the actual SDK no-lock build. The fixture, helper and Rust workflow are byte-identical to main; the fixture does not load SDK source. The underlying CI/environment cause is not diagnosed here. Other jobs remained pending/running at the snapshot, so CI is not reported as passing. Failure: https://github.com/lancedb/lancedb/actions/runs/43280277756/job/131399418284. --- docs/src/js/classes/Table.md | 42 ++ docs/src/js/globals.md | 1 + docs/src/js/type-aliases/BlobRangeRequest.md | 39 ++ docs/web/management/table.mdx | 27 + nodejs/__test__/blob_ranges.test.ts | 589 ++++++++++++++++ nodejs/__test__/table.test.ts | 37 + nodejs/lancedb/blob.ts | 10 + nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 49 +- nodejs/src/blob.rs | 50 +- nodejs/src/table.rs | 29 +- python/python/lancedb/table.py | 12 +- python/python/tests/test_blob_ranges.py | 380 +++++++++++ python/python/tests/test_remote_db.py | 46 +- rust/lancedb/src/blob.rs | 2 +- rust/lancedb/src/remote/db.rs | 10 +- rust/lancedb/src/remote/table.rs | 28 + rust/lancedb/src/remote/table/blobs.rs | 400 ++++++++++- .../src/remote/table/blobs/aggregate.rs | 136 +++- rust/lancedb/src/table.rs | 21 +- rust/lancedb/tests/remote_blob_ranges.rs | 634 ++++++++++++++++++ 21 files changed, 2473 insertions(+), 70 deletions(-) create mode 100644 docs/src/js/type-aliases/BlobRangeRequest.md create mode 100644 nodejs/__test__/blob_ranges.test.ts create mode 100644 python/python/tests/test_blob_ranges.py create mode 100644 rust/lancedb/tests/remote_blob_ranges.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 431796843..3150d94ec 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -650,6 +650,48 @@ tables; no partial handles are returned. *** +### fetchBlobRanges() + +```ts +abstract fetchBlobRanges( + column, + requests, + options?): Promise<(null | Buffer)[]> +``` + +Materializes row-specific byte ranges at the table's current checkout. +Preserves request order, duplicates, and nulls. Zero length returns an empty +buffer for a non-null blob. Invalid ranges or missing rows reject the entire +call. See [Table.fetchBlobs](Table.md#fetchblobs) for row-ID validity across versions. + +Remote tables use the batched endpoint when the server advertises support, +splitting at 1024 ranges and 64 MiB, including individual larger ranges. +Older servers use descriptor queries and BlobFile range reads. Both protocols +use one exact branch and version. Errors from an advertised endpoint propagate +without switching protocols. All output bytes occupy memory. + +#### Parameters + +* **column**: `string` + +* **requests**: readonly [`BlobRangeRequest`](../type-aliases/BlobRangeRequest.md)[] + +* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md) + +#### Returns + +`Promise`<(`null` \| `Buffer`)[]> + +#### Example + +```ts +const bytes = await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1024n }, +]); +``` + +*** + ### fetchBlobs() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 19d7ceb97..beed7c8af 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -169,6 +169,7 @@ - [BlobMode](type-aliases/BlobMode.md) - [BlobOptions](type-aliases/BlobOptions.md) - [BlobRange](type-aliases/BlobRange.md) +- [BlobRangeRequest](type-aliases/BlobRangeRequest.md) - [BlobReadOptions](type-aliases/BlobReadOptions.md) - [BlobUri](type-aliases/BlobUri.md) - [Data](type-aliases/Data.md) diff --git a/docs/src/js/type-aliases/BlobRangeRequest.md b/docs/src/js/type-aliases/BlobRangeRequest.md new file mode 100644 index 000000000..daa231260 --- /dev/null +++ b/docs/src/js/type-aliases/BlobRangeRequest.md @@ -0,0 +1,39 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobRangeRequest + +# Type Alias: BlobRangeRequest + +```ts +type BlobRangeRequest: object; +``` + +One row-specific range for [Table.fetchBlobRanges](../classes/Table.md#fetchblobranges). + +## Type declaration + +### length + +```ts +length: bigint; +``` + +Number of bytes to read, as a uint64. Zero returns an empty non-null value. + +### offset + +```ts +offset: bigint; +``` + +Byte offset from the beginning of the logical blob, as a uint64. + +### rowId + +```ts +rowId: bigint | number; +``` + +A row ID from a query with row IDs enabled. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 031342fbc..bf6bf3edd 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -736,6 +736,10 @@ The other fetch methods load bytes directly: | Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | | Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | +{/* Draft for the TypeScript cross-row Blob range release. Replace the row above: +| Byte slices across many rows in one call | `fetch_blob_ranges` | `fetchBlobRanges` | `fetch_blob_ranges` | +*/} + - `fetch_blobs` returns the full bytes for each row ID in order. Null blobs produce null entries, and empty blobs produce empty byte strings. - `fetch_blob_files` loads bytes when you call `read`, `read_range`, or @@ -759,6 +763,21 @@ The other fetch methods load bytes directly: +{/* Draft for the TypeScript cross-row Blob range release. + +Upcoming-release draft: TypeScript adds `fetchBlobRanges` for cross-row slices. +Until that SDK release is available, use `fetchBlobFiles` and `readRanges`. +Server-side batching requires a deployment with the validated range capability; +older servers continue using the descriptor and Range path selected before the +read. An error from the selected batched endpoint is returned without fallback. +A batched call keeps the native snapshot identity from its first range response +across every partition and requires each serving node to verify it. Missing identity +support or a replaced/deleted snapshot fails the whole call; upgrade all serving +nodes before selecting the batched endpoint with a new SDK. +Custom TypeScript `Table` subclasses must implement the new abstract method. + +*/} + Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, `read_ranges` reads more than one slice of one blob. Python takes `(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an @@ -770,6 +789,14 @@ exclusive `end`, and Rust takes `start..end` ranges: + {/* Draft for the TypeScript cross-row Blob range release. + {`// Upcoming-release draft: slices from more than one row. +const slices = await blobTable.fetchBlobRanges("image", [ + { rowId: rowIds[0]!, offset: 0n, length: 6n }, + { rowId: rowIds[1]!, offset: 7n, length: 5n }, +]); +`}{"\n"} + */} {TsBlobApiRanges} diff --git a/nodejs/__test__/blob_ranges.test.ts b/nodejs/__test__/blob_ranges.test.ts new file mode 100644 index 000000000..7d2fab566 --- /dev/null +++ b/nodejs/__test__/blob_ranges.test.ts @@ -0,0 +1,589 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { createHash } from "crypto"; +import { getEventListeners } from "events"; +import { createReadStream } from "fs"; +import * as http from "http"; +import { AddressInfo } from "net"; +import { + Table as ArrowTable, + Binary, + Field, + LargeBinary, + Struct, + Uint8, + Uint32, + Uint64, + Utf8, + tableToIPC, + vectorFromArray, +} from "apache-arrow"; +import { BlobRangeRequest, Connection, Table, connect } from "../lancedb"; + +jest.setTimeout(30000); + +const IDENTITY = `v1:${"a".repeat(64)}`; +const MIB = 1024 * 1024; +type Range = { + // biome-ignore lint/style/useNamingConvention: Matches the server JSON contract. + row_id: number; + offset: number; + length: number; +}; +type Request = { + column: string; + branch: string | null; + version: number | null; + ranges: Range[]; + identity?: string; +}; + +function payload(row: number, offset: number, length: number, version: number) { + const bytes = Buffer.alloc(length); + for (let i = 0; i < length; i++) { + bytes[i] = (row * 17 + ((offset + i) % 251) + version) % 251; + } + return bytes; +} + +async function withRangeServer( + run: (db: Connection, calls: Request[], paths: string[]) => Promise, + fault?: string | number, + capability: string | null = "1", + onStall?: () => void, +) { + let takes = 0; + const calls: Request[] = []; + const paths: string[] = []; + const server = http.createServer((req, res) => { + req.setTimeout(15000); + paths.push(req.url ?? ""); + if ( + req.url === "/v1/table/test/describe/" || + req.url === "/v1/table/test/branches/list/" + ) { + res.writeHead(200, { + "Content-Type": "application/json", + "phalanx-version": "1.13.0-beta.0", + ...(req.url.endsWith("/describe/") && capability !== null + ? { "x-lancedb-blob-ranges": capability } + : {}), + }); + const response = req.url.endsWith("branches/list/") + ? { + branches: { + experiment: { + parentBranch: null, + parentVersion: 1, + createAt: 1, + manifestSize: 1, + }, + }, + } + : { version: 8, schema: { fields: [] } }; + res.end(JSON.stringify(response)); + return; + } + if (capability !== "1" && req.method === "GET") { + const url = new URL(req.url!, "http://localhost"); + expect(url.searchParams.get("branch")).toBe("experiment"); + 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); + return; + } + expect(req.method).toBe("POST"); + expect(req.url).toBe( + capability === "1" + ? "/v1/table/test/fetch_blob_ranges/" + : "/v1/table/test/query/", + ); + const chunks: Buffer[] = []; + let size = 0; + req.on("data", (chunk: Buffer) => { + size += chunk.length; + expect(size).toBeLessThanOrEqual(256 * 1024); + chunks.push(chunk); + }); + req.on("end", () => { + if (capability !== "1") { + const body = JSON.parse(Buffer.concat(chunks).toString()) as { + branch: string; + version: number; + filter: string; + }; + expect(body.branch).toBe("experiment"); + expect(body.version).toBe(3); + takes++; + const ids = (body.filter.match(/\d+/g) ?? []) + .map(Number) + .filter((id) => [10, 20, 40].includes(id)) + .reverse(); + const descriptor = new Struct([ + new Field("kind", new Uint8(), false), + new Field("position", new Uint64(), false), + new Field("size", new Uint64(), false), + new Field("blob_id", new Uint32(), false), + new Field("blob_uri", new Utf8(), false), + ]); + const arrow = new ArrowTable({ + image: vectorFromArray( + ids.map((id) => + id === 20 + ? null + : { + kind: 0, + position: 0n, + size: id === 40 ? 0n : 5n, + // biome-ignore lint/style/useNamingConvention: Arrow descriptor field. + blob_id: 0, + // biome-ignore lint/style/useNamingConvention: Arrow descriptor field. + blob_uri: "", + }, + ), + descriptor, + ), + _rowid: vectorFromArray(ids.map(BigInt), new Uint64()), + }); + expect(takes).toBeGreaterThan(0); + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + "x-lancedb-version": "3", + }) + .end(tableToIPC(arrow, "stream")); + return; + } + const body = JSON.parse(Buffer.concat(chunks).toString()) as Request; + body.identity = req.headers["x-lancedb-query-snapshot"] as + | string + | undefined; + calls.push(body); + expect(body.column).toBe("image"); + expect(body.branch).toBe("experiment"); + expect(body.ranges.length).toBeLessThanOrEqual(1024); + expect( + body.ranges.reduce((sum, range) => sum + range.length, 0), + ).toBeLessThanOrEqual(64 * MIB); + const version = body.version ?? (calls.length === 1 ? 7 : 8); + const failure = + calls.length > 1 || String(fault).startsWith("first-") + ? fault + : undefined; + if (failure === "recreated" || failure === "gone") { + res + .writeHead(failure === "recreated" ? 400 : 404) + .end("query snapshot identity mismatch: source gone or replaced"); + return; + } + if (failure === "stall" && calls.length === 2) { + res.writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + "x-lancedb-version": "7", + "x-lancedb-query-snapshot": IDENTITY, + }); + res.flushHeaders(); + onStall?.(); + return; + } + if (typeof failure === "number") { + res.writeHead(failure).end("ordinary server failure"); + return; + } + if (failure === "disconnect") { + req.socket.destroy(); + return; + } + let values = body.ranges.map((range) => + range.row_id === 20 + ? null + : payload(range.row_id, range.offset, range.length, version), + ); + if (failure === "count") values = []; + if (failure === "length") values = [Buffer.alloc(0)]; + const arrow = new ArrowTable({ + [failure === "column" ? "wrong" : "value"]: vectorFromArray( + values, + failure === "type" ? new Binary() : new LargeBinary(), + ), + }); + let ipc = tableToIPC(arrow, "stream"); + if (failure === "eos") ipc = ipc.subarray(0, ipc.length - 8); + if (failure === "body") ipc = ipc.subarray(0, Math.floor(ipc.length / 2)); + res.writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + connection: "close", + "Content-Length": ipc.length + (failure === "transport" ? 10 : 0), + ...(failure === "version" ? {} : { "x-lancedb-version": version }), + ...(["missing-identity", "first-missing-identity"].includes( + String(failure), + ) + ? {} + : { + "x-lancedb-query-snapshot": + failure === "wrong-identity" + ? `v1:${"b".repeat(64)}` + : failure === "first-invalid-identity" + ? "broken" + : IDENTITY, + }), + }); + // Fragment the generated IPC payload across actual HTTP writes. + for (let i = 0; i < ipc.length; i += 8192) + res.write(ipc.subarray(i, i + 8192)); + res.end(); + }); + }); + server.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const port = (server.address() as AddressInfo).port; + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${port}`, + clientConfig: { + retryConfig: { retries: 2, connectRetries: 2, readRetries: 2 }, + blobRequestConcurrency: 1, + timeoutConfig: { timeout: 20 }, + }, + }); + try { + await run(db, calls, paths); + } finally { + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + } +} + +async function open(db: Connection, version?: number): Promise
{ + return db.openTable("test", [], { branch: "experiment", version }); +} + +describe("fetchBlobRanges", () => { + it.each([null, "0", "2"])( + "uses old routes before data requests for capability %s", + async (capability) => { + await withRangeServer( + async (db, calls, paths) => { + // Reopening exercises both the initial and cached database describe paths. + for (let i = 0; i < 2; i++) { + const table = await open(db, 3); + const requests = [ + { rowId: 10n, offset: 1n, length: 3n }, + { rowId: 20n, offset: 0n, length: 1n }, + { rowId: 40n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 5n, length: 0n }, + { rowId: 10n, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("lph"), + null, + Buffer.alloc(0), + Buffer.alloc(0), + Buffer.from("lph"), + ]); + for (const row of [ + { rowId: 10n, offset: 4n, length: 2n }, + { rowId: 99n, offset: 0n, length: 1n }, + ]) + await expect( + table.fetchBlobRanges("image", [row]), + ).rejects.toThrow(); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + expect(paths).toHaveLength(before); + } + expect(calls).toHaveLength(0); + expect(paths.some((path) => path.includes("fetch_blob_ranges"))).toBe( + false, + ); + }, + undefined, + capability, + ); + }, + ); + + it("renegotiates advertised support when reopening a cached table", async () => { + await withRangeServer(async (db, calls) => { + for (let i = 0; i < 2; i++) { + const table = await open(db); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, i === 0 ? 7 : 8)]); + } + expect(calls).toHaveLength(2); + }); + }); + + it("cancels while waiting for a later response body and releases the only permit", async () => { + let markStalled!: () => void; + const stalled = new Promise((resolve) => { + markStalled = resolve; + }); + await withRangeServer( + async (db, calls) => { + const table = await open(db); + const controller = new AbortController(); + const pending = table.fetchBlobRanges( + "image", + Array.from({ length: 2049 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + { signal: controller.signal }, + ); + const rejected = expect(pending).rejects.toMatchObject({ + name: "AbortError", + }); + await stalled; + controller.abort(); + await rejected; + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + expect(calls).toHaveLength(2); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, 8)]); + expect(calls).toHaveLength(3); + }, + "stall", + "1", + () => markStalled(), + ); + }); + it.each([undefined, 3])( + "preserves order, nulls, duplicates and snapshot (checkout %s)", + async (version) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db, version); + const requests: BlobRangeRequest[] = Array.from( + { length: 1025 }, + (_, i) => ({ + rowId: i % 9 === 0 ? 20 : 10 + (i % 7), + offset: BigInt(i), + length: BigInt(i % 4), + }), + ); + requests.push( + { rowId: 10n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 2n, length: 3n }, + { rowId: 10n, offset: 2n, length: 3n }, + ); + const result = await table.fetchBlobRanges("image", requests); + expect(result).toEqual( + requests.map((range) => + Number(range.rowId) === 20 + ? null + : payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + version ?? 7, + ), + ), + ); + expect(calls.map((body) => body.version)).toEqual([ + version ?? null, + version ?? 7, + ]); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, version ?? 8)]); + expect(calls[2].version).toBe(version ?? null); + expect( + paths.filter((path) => path.endsWith("fetch_blob_ranges/")), + ).toHaveLength(3); + }); + }, + ); + + it("partitions the byte budget and reassembles one range larger than 64 MiB", async () => { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = [ + { rowId: 10n, offset: 3n, length: BigInt(65 * MIB) }, + { rowId: 30n, offset: 7n, length: 2n }, + ]; + const result = await table.fetchBlobRanges("image", requests); + for (const [i, range] of requests.entries()) { + expect(result[i]?.length).toBe(Number(range.length)); + expect( + createHash("sha256") + .update(result[i] as Buffer) + .digest("hex"), + ).toBe( + createHash("sha256") + .update( + payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + 7, + ), + ) + .digest("hex"), + ); + } + expect(calls).toHaveLength(2); + expect(calls.map((body) => body.version)).toEqual([null, 7]); + }); + }); + + it.each([ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ])("rejects the whole call after a later %s failure", async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(); + expect(calls).toHaveLength(2); + expect( + paths.every( + (path) => + path.endsWith("describe/") || + path.endsWith("branches/list/") || + path.endsWith("fetch_blob_ranges/"), + ), + ).toBe(true); + }, fault); + }); + + it.each(["missing-identity", "wrong-identity", "recreated", "gone"])( + "retains original identity through row and byte partitions (%s)", + async (fault) => { + for (const huge of [false, true]) { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = huge + ? [{ rowId: 10n, offset: 0n, length: BigInt(64 * MIB + 1) }] + : Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })); + await expect( + table.fetchBlobRanges("image", requests), + ).rejects.toThrow(); + expect(calls.map((call) => call.identity)).toEqual([ + undefined, + IDENTITY, + ]); + expect(calls.map((call) => call.version)).toEqual([null, 7]); + }, fault); + } + }, + ); + + it.each(["first-missing-identity", "first-invalid-identity"])( + "requires a first authoritative bulk identity (%s)", + async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(/snapshot identity/); + expect(calls).toHaveLength(1); + expect(paths).toHaveLength(before + 1); + }, fault); + }, + ); + + it("validates integers, overflow and cancellation and leaves empty calls at zero I/O", async () => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + for (const request of [ + { rowId: -1, offset: 0n, length: 1n }, + { rowId: 1.5, offset: 0n, length: 1n }, + { rowId: Number.MAX_SAFE_INTEGER + 1, offset: 0n, length: 1n }, + { rowId: -1n, offset: 0n, length: 1n }, + { rowId: 1n << 64n, offset: 0n, length: 1n }, + { rowId: 10n, offset: -1n, length: 1n }, + { rowId: 10n, offset: 0n, length: -1n }, + { rowId: 10n, offset: 0n, length: 1n << 64n }, + { rowId: 20n, offset: (1n << 64n) - 1n, length: 1n }, + ]) { + await expect( + table.fetchBlobRanges("image", [request]), + ).rejects.toThrow(); + } + // Runtime type validation must also reject a number passed as an offset. + await expect( + table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0 as unknown as bigint, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + controller.abort(new Error("cancelled by caller")); + await expect( + table.fetchBlobRanges( + "image", + [{ rowId: 10n, offset: 0n, length: 1n }], + { signal: controller.signal }, + ), + ).rejects.toThrow("cancelled by caller"); + expect(paths).toHaveLength(before); + expect(calls).toHaveLength(0); + }); + }); + + it("records the loaded native artifact", async () => { + const artifacts = Object.keys(require.cache).filter( + (path) => path.endsWith(".node") && path.includes("lancedb"), + ); + expect(artifacts.length).toBeGreaterThan(0); + for (const path of artifacts) { + const hash = createHash("sha256"); + for await (const chunk of createReadStream(path)) hash.update(chunk); + console.log( + `loaded native artifact=${path} sha256=${hash.digest("hex")}`, + ); + } + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index b803e9043..59d6929b4 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3019,6 +3019,43 @@ describe("when dealing with blob columns", () => { expect(bytes.map((b) => b?.toString())).toEqual(["new", "hi"]); }); + it("fetchBlobRanges reads local ranges with order, duplicates, nulls and validation", async () => { + const { table, rowIds } = await openBlobTable(); + const [alphaId, betaId, nullId] = rowIds; + const requests = [ + { rowId: betaId, offset: 1n, length: 3n }, + { rowId: alphaId, offset: 0n, length: 2n }, + { rowId: nullId, offset: 0n, length: 1n }, + { rowId: alphaId, offset: 5n, length: 0n }, + { rowId: betaId, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("eta"), + Buffer.from("al"), + null, + Buffer.alloc(0), + Buffer.from("eta"), + ]); + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + await expect( + table.fetchBlobRanges("image", [ + { rowId: alphaId, offset: 4n, length: 2n }, + ]), + ).rejects.toThrow(); + await expect( + table.fetchBlobRanges("image", [ + { rowId: (1n << 63n) - 1n, offset: 0n, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + expect( + await table.fetchBlobRanges("image", requests, { + signal: controller.signal, + }), + ).toHaveLength(5); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + }); + it("discovers blob columns", async () => { const { table } = await openBlobTable(); expect(await table.blobColumns()).toEqual(["image"]); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 67e662175..a46484314 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -305,6 +305,16 @@ export async function runWithSignal( } } +/** One row-specific range for {@link Table.fetchBlobRanges}. */ +export type BlobRangeRequest = { + /** A row ID from a query with row IDs enabled. */ + rowId: bigint | number; + /** Byte offset from the beginning of the logical blob, as a uint64. */ + offset: bigint; + /** Number of bytes to read, as a uint64. Zero returns an empty non-null value. */ + length: bigint; +}; + /** A half-open byte range `[start, end)` for {@link BlobFile.readRanges}. */ export type BlobRange = { start: bigint; diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 35697dc8c..08a254bdb 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -91,6 +91,7 @@ export type { BlobInput, BlobOptions, BlobRange, + BlobRangeRequest, BlobReadOptions, BlobUri, } from "./blob"; diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 185088424..136eb1d6c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -17,7 +17,12 @@ import { tableFromIPC, } from "./arrow"; -import { BlobFile, BlobReadOptions, runWithSignal } from "./blob"; +import { + BlobFile, + BlobRangeRequest, + BlobReadOptions, + runWithSignal, +} from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; import { IndexOptions } from "./indices"; import { Job } from "./job"; @@ -683,6 +688,31 @@ export abstract class Table { options?: BlobReadOptions, ): Promise<(Buffer | null)[]>; + /** + * Materializes row-specific byte ranges at the table's current checkout. + * Preserves request order, duplicates, and nulls. Zero length returns an empty + * buffer for a non-null blob. Invalid ranges or missing rows reject the entire + * call. See {@link Table.fetchBlobs} for row-ID validity across versions. + * + * Remote tables use the batched endpoint when the server advertises support, + * splitting at 1024 ranges and 64 MiB, including individual larger ranges. + * Older servers use descriptor queries and BlobFile range reads. Both protocols + * use one exact branch and version. Errors from an advertised endpoint propagate + * without switching protocols. All output bytes occupy memory. + * + * @example + * ```ts + * const bytes = await table.fetchBlobRanges("image", [ + * { rowId: 10n, offset: 0n, length: 1024n }, + * ]); + * ``` + */ + abstract fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]>; + /** * Opens lazy blob handles for `column` at the given row IDs using the * table's current checkout. @@ -1510,6 +1540,23 @@ export class LocalTable extends Table { return values.map((value) => value ?? null); } + async fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]> { + const rowIds = rowIdsToBigInts(requests.map((request) => request.rowId)); + const ranges = requests.map((request, i) => ({ + rowId: rowIds[i], + offset: request.offset, + length: request.length, + })); + const values = await runWithSignal(options?.signal, (signal) => + this.inner.fetchBlobRanges(column, ranges, signal), + ); + return values.map((value) => value ?? null); + } + async fetchBlobFiles( column: string, rowIds: readonly (bigint | number)[], diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs index 59cf61af6..b55154019 100644 --- a/nodejs/src/blob.rs +++ b/nodejs/src/blob.rs @@ -21,6 +21,25 @@ pub struct BlobRange { pub end: BigInt, } +#[napi(object)] +pub struct BlobRangeRequest { + pub row_id: BigInt, + pub offset: BigInt, + pub length: BigInt, +} + +impl BlobRangeRequest { + pub(crate) fn parse(self) -> napi::Result { + let row_id = parse_u64(self.row_id, "row id")?; + let offset = parse_u64(self.offset, "offset")?; + let length = parse_u64(self.length, "length")?; + offset + .checked_add(length) + .ok_or_else(|| napi::Error::from_reason("blob range offset + length overflows u64"))?; + Ok(lancedb::blob::BlobRangeRequest::new(row_id, offset, length)) + } +} + #[napi] pub struct BlobFile { inner: Arc, @@ -205,14 +224,25 @@ pub fn parse_row_ids(row_ids: Vec) -> napi::Result> { .collect() } -pub fn copy_blob_buffers(array: LargeBinaryArray) -> Vec> { - (0..array.len()) - .map(|i| { - if array.is_null(i) { - None - } else { - Some(Buffer::from(array.value(i).to_vec())) - } - }) - .collect() +pub fn copy_blob_buffers(array: LargeBinaryArray) -> napi::Result>> { + let allocation_error = + |error| napi::Error::from_reason(format!("cannot allocate blob result: {error}")); + let mut result = Vec::new(); + result + .try_reserve_exact(array.len()) + .map_err(allocation_error)?; + for value in array.iter() { + let buffer = value + .map(|value| { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(value.len()) + .map_err(allocation_error)?; + bytes.extend_from_slice(value); + Ok::<_, napi::Error>(Buffer::from(bytes)) + }) + .transpose()?; + result.push(buffer); + } + Ok(result) } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 7076bbec1..f6abeb553 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -17,7 +17,7 @@ use napi::bindgen_prelude::*; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; -use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable}; +use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; use crate::error::NapiErrorExt; use crate::index::Index; use crate::job::JobFailureInfo; @@ -420,7 +420,32 @@ impl Table { .fetch_blobs(column.as_str(), &row_ids) .await .default_error()?; - Ok(copy_blob_buffers(array)) + copy_blob_buffers(array) + }) + } + + #[napi(catch_unwind)] + pub fn fetch_blob_ranges<'env>( + &self, + env: &'env Env, + column: String, + requests: Vec, + signal: Option, + ) -> napi::Result>>> { + let mut ranges = Vec::new(); + ranges.try_reserve_exact(requests.len()).map_err(|error| { + napi::Error::from_reason(format!("cannot allocate blob range requests: {error}")) + })?; + for request in requests { + ranges.push(request.parse()?); + } + let table = self.inner_ref()?.clone(); + spawn_abortable(env, signal, async move { + let array = table + .fetch_blob_ranges(column.as_str(), ranges) + .await + .default_error()?; + copy_blob_buffers(array) }) } diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 3161eda30..5f0af7a66 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2661,8 +2661,12 @@ class Table(ABC): results are returned. Row IDs can be obtained from a query with ``with_row_id(True)``. - LanceDB Enterprise reads the requested ranges through version-pinned blob - handles using HTTP byte-range requests. + LanceDB Enterprise uses the batched endpoint when the server advertises + support, partitioning at 1024 ranges and 64 MiB, including individual + larger ranges. Older servers use descriptor queries and BlobFile range + reads. Both protocols read one exact branch and version without changing + the table's checkout. Errors from an advertised endpoint propagate without + switching protocols. The final output occupies memory. """ @abstractmethod @@ -8652,6 +8656,10 @@ class AsyncTable: column: str, requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: + """Materialize row-specific byte ranges. + + See [Table.fetch_blob_ranges][lancedb.table.Table.fetch_blob_ranges]. + """ return await self._inner.fetch_blob_ranges(column, list(requests)) async def fetch_blob_files( diff --git a/python/python/tests/test_blob_ranges.py b/python/python/tests/test_blob_ranges.py new file mode 100644 index 000000000..c65dfb8ae --- /dev/null +++ b/python/python/tests/test_blob_ranges.py @@ -0,0 +1,380 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Exercise the public sync/async range APIs over bounded loopback HTTP.""" + +import asyncio +import hashlib +import json +from pathlib import Path +import socket +import threading + +import lancedb._lancedb as native +import pyarrow as pa +import pytest + +from lancedb.remote.errors import HttpError, TableNotFoundError +from test_remote_db import mock_lancedb_connection + +MIB = 1024 * 1024 +IDENTITY = "v1:" + "a" * 64 +ROUTE = "/v1/table/test/fetch_blob_ranges/" + + +def payload(row, offset, length, version): + pattern = bytes((row * 17 + i + version) % 251 for i in range(251)) + start = offset % 251 + return (pattern * ((start + length + 250) // 251))[start : start + length] + + +class RangeServer: + def __init__(self, fault=None): + self.fault = fault + self.calls = [] + self.fetches = [] + self.identities = [] + self.stalled = threading.Event() + self.release = threading.Event() + + def __call__(self, request): + request.connection.settimeout(15) + size = int(request.headers.get("Content-Length", 0)) + assert size <= 256 * 1024 + body = json.loads(request.rfile.read(size) or b"{}") + self.calls.append((request.command, request.path, body)) + if request.path in ( + "/v1/table/test/describe/", + "/v1/table/test/branches/list/", + ): + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.send_header("phalanx-version", "1.13.0-beta.0") + if request.path.endswith("/describe/"): + request.send_header("x-lancedb-blob-ranges", "1") + request.end_headers() + response = ( + { + "branches": { + "experiment": { + "parentBranch": None, + "parentVersion": 1, + "createAt": 1, + "manifestSize": 1, + } + } + } + if request.path.endswith("branches/list/") + else {"version": 8, "schema": {"fields": []}} + ) + request.wfile.write(json.dumps(response).encode()) + return + assert (request.command, request.path) == ("POST", ROUTE) + self.fetches.append(body) + self.identities.append(request.headers.get("x-lancedb-query-snapshot")) + assert body["column"] == "image" + assert body["branch"] == "experiment" + ranges = body["ranges"] + assert len(ranges) <= 1024 + assert sum(r["length"] for r in ranges) <= 64 * MIB + version = body["version"] or (7 if len(self.fetches) == 1 else 8) + values = [ + None + if r["row_id"] == 20 + else payload(r["row_id"], r["offset"], r["length"], version) + for r in ranges + ] + fault = ( + self.fault + if len(self.fetches) > 1 or str(self.fault).startswith("first-") + else None + ) + if fault in ("recreated", "gone"): + request.send_response(400 if fault == "recreated" else 404) + request.end_headers() + request.wfile.write( + b"query snapshot identity mismatch: source gone or replaced" + ) + return + if fault == "stall" and len(self.fetches) == 2: + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", str(version)) + request.send_header("x-lancedb-query-snapshot", IDENTITY) + request.end_headers() + request.wfile.flush() + self.stalled.set() + assert self.release.wait(15), "test did not release stalled response" + return + if fault == "structured400": + request.send_response(400) + request.send_header("x-lancedb-error-code", "invalid_input") + request.end_headers() + request.wfile.write(b'{"error":"range exceeds blob size"}') + return + if isinstance(fault, int): + request.send_response(fault) + request.end_headers() + request.wfile.write(b"ordinary server failure") + return + if fault == "disconnect": + request.connection.shutdown(socket.SHUT_RDWR) + return + column = "wrong" if fault == "column" else "value" + data_type = pa.binary() if fault == "type" else pa.large_binary() + if fault == "count": + values = [] + elif fault == "length": + values = [b""] + batch = pa.table({column: pa.array(values, type=data_type)}) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, batch.schema) as writer: + writer.write_table(batch, max_chunksize=257) + ipc = sink.getvalue().to_pybytes() + if fault == "eos": + ipc = ipc[:-8] + elif fault == "body": + ipc = ipc[: len(ipc) // 2] + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + if fault != "version": + request.send_header("x-lancedb-version", str(version)) + if fault not in ("missing-identity", "first-missing-identity"): + identity = ( + "broken" + if fault == "first-invalid-identity" + else "v1:" + "b" * 64 + if fault == "wrong-identity" + else IDENTITY + ) + request.send_header("x-lancedb-query-snapshot", identity) + request.send_header( + "Content-Length", str(len(ipc) + (10 if fault == "transport" else 0)) + ) + request.end_headers() + for i in range(0, len(ipc), 8192): + request.wfile.write(ipc[i : i + 8192]) + + +async def fetch(table, requests, use_async): + result = table.fetch_blob_ranges("image", requests) + return await result if use_async else result + + +def api(db, use_async, version=None): + table = db.open_table("test", branch="experiment", version=version) + return table._table if use_async else table + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("version", [None, 3]) +async def test_range_sdk_order_snapshot_and_overwrite(use_async, version): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async, version) + requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)] + requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)] + result = await fetch(table, requests, use_async) + assert isinstance(result, pa.LargeBinaryArray) + assert result.to_pylist() == [ + None if row == 20 else payload(row, offset, length, version or 7) + for row, offset, length in requests + ] + assert [b["version"] for b in handler.fetches] == [version, version or 7] + result = await fetch(table, [(10, 0, 1)], use_async) + assert result.to_pylist() == [payload(10, 0, 1, version or 8)] + assert handler.fetches[-1]["version"] == version + assert len(handler.fetches) == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_cached_reopen_negotiates_capability(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + for version in (7, 8): + table = api(db, use_async) + result = await fetch(table, [(10, 0, 1)], use_async) + assert result.to_pylist() == [payload(10, 0, 1, version)] + assert len(handler.fetches) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_large_single_and_aggregate_budget(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + requests = [ + (10, 3, 33 * MIB), + (30, 7, 33 * MIB), + (40, 11, 70 * MIB), + (20, 0, 2**64 - 1), + ] + # The loopback server advances latest after the first partition. + result = await fetch(table, requests, use_async) + assert len(result) == 4 + for i, (row, offset, length) in enumerate(requests[:3]): + expected = payload(row, offset, length, 7) + assert ( + hashlib.sha256(result[i].as_buffer()).digest() + == hashlib.sha256(expected).digest() + ) + assert len(result[i].as_buffer()) == length + assert result[3].as_py() is None + assert len(handler.fetches) == 3 + assert [b["version"] for b in handler.fetches] == [None, 7, 7] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "fault", + [ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ], +) +async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault): + handler = RangeServer(fault=fault) + with mock_lancedb_connection( + handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2} + ) as db: + table = api(db, use_async) + with pytest.raises(Exception) as exc: + await fetch(table, [(10, 0, 1)] * 1025, use_async) + if fault == 404: + assert isinstance(exc.value, TableNotFoundError) + assert isinstance(exc.value.__cause__, HttpError) + assert exc.value.__cause__.status_code == 404 + else: + assert not isinstance(exc.value, ValueError) + if isinstance(fault, int): + assert exc.value.status_code == fault + assert len(handler.fetches) == 2 + assert all( + path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE) + for _, path, _ in handler.calls + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_structured_400_preserves_value_error(use_async): + handler = RangeServer(fault="structured400") + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + with pytest.raises(ValueError, match="range exceeds blob size"): + await fetch(table, [(10, 0, 1)] * 1025, use_async) + assert len(handler.fetches) == 2 + + +@pytest.mark.asyncio +async def test_range_sdk_async_cancel_releases_only_request_permit(): + handler = RangeServer(fault="stall") + with mock_lancedb_connection(handler, blob_request_concurrency=1) as db: + table = api(db, True) + pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True)) + try: + assert await asyncio.to_thread(handler.stalled.wait, 10) + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert len(handler.fetches) == 2 + result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5) + assert result.to_pylist() == [payload(10, 0, 1, 8)] + assert len(handler.fetches) == 3 + finally: + pending.cancel() + handler.release.set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_integer_validation_and_empty_zero_io(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + before = len(handler.calls) + assert (await fetch(table, [], use_async)).to_pylist() == [] + for request in [ + (-1, 0, 1), + (2**64, 0, 1), + (10, -1, 1), + (10, 0, -1), + (10, 0, 2**64), + (10, 0.5, 1), + (20, 2**64 - 1, 1), + (10, 0), + ]: + with pytest.raises((ValueError, OverflowError, TypeError)): + await fetch(table, [request], use_async) + assert len(handler.calls) == before + + +def test_range_sdk_loaded_artifact_identity(): + artifact = Path(native.__file__).resolve() + digest = hashlib.sha256() + with artifact.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}") + assert artifact.is_file() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "fault", ["missing-identity", "wrong-identity", "recreated", "gone"] +) +@pytest.mark.parametrize("huge", [False, True]) +async def test_range_sdk_original_identity_survives_every_partition( + use_async, fault, huge +): + handler = RangeServer(fault=fault) + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025 + error = ( + ValueError + if fault == "recreated" + else TableNotFoundError + if fault == "gone" + else NotImplementedError + ) + with pytest.raises( + error, match="snapshot identity" if fault != "gone" else None + ): + await fetch(table, requests, use_async) + assert handler.identities == [None, IDENTITY] + assert len(handler.fetches) == 2 + assert [body["version"] for body in handler.fetches] == [None, 7] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"]) +async def test_range_sdk_bulk_requires_identity_before_payload_acceptance( + use_async, fault +): + handler = RangeServer(fault=fault) + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + before = len(handler.calls) + with pytest.raises(NotImplementedError, match="snapshot identity"): + await fetch(table, [(10, 0, 1)] * 1025, use_async) + assert len(handler.fetches) == 1 + assert len(handler.calls) == before + 1 diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 561a0f900..4f707f041 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5466,6 +5466,7 @@ def blob_remote_table( *, server_version=Version("0.5.0"), location=None, + range_capability=None, version_header="1", framing="file", requests=None, @@ -5487,6 +5488,8 @@ def blob_remote_table( request.send_response(200) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", str(server_version)) + if range_capability is not None: + request.send_header("x-lancedb-blob-ranges", range_capability) request.end_headers() response = dict(BLOB_DESCRIBE_RESPONSE) response["version"] = body.get("version") or state["version"] @@ -5594,6 +5597,42 @@ def blob_remote_table( writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream with writer_factory(request.wfile, response_table.schema) as writer: writer.write_table(response_table, max_chunksize=1) + elif ( + range_capability == "1" + and request.path == "/v1/table/test/fetch_blob_ranges/" + ): + size = int(request.headers["Content-Length"]) + body = json.loads(request.rfile.read(size)) + payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""} + values = [] + for item in body["ranges"]: + row, offset, length = ( + item[key] for key in ("row_id", "offset", "length") + ) + error = None + if row not in payloads: + error = "only 1 exist" + elif payloads[row] is not None and offset + length > len(payloads[row]): + error = "range exceeds blob size" + if error: + request.send_response(400) + request.end_headers() + request.wfile.write(error.encode()) + return + payload = payloads[row] + values.append( + None if payload is None else payload[offset : offset + length] + ) + response_table = pa.table( + {"value": pa.array(values, type=pa.large_binary())} + ) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", "1") + request.send_header("x-lancedb-query-snapshot", "v1:" + "a" * 64) + request.end_headers() + with pa.ipc.new_stream(request.wfile, response_table.schema) as writer: + writer.write_table(response_table) elif request.path == "/v1/table/test/fetch_blobs/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) @@ -5901,8 +5940,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access( @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) -async def test_remote_fetch_blob_ranges(use_async): - with blob_remote_table() as remote_table: +@pytest.mark.parametrize("range_capability", [None, "0", "2", "1"]) +async def test_remote_fetch_blob_ranges(use_async, range_capability): + with blob_remote_table( + server_version="1.13.0-beta.0", range_capability=range_capability + ) as remote_table: table = remote_table._table if use_async else remote_table requests = [ (30, 2, 3), diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index ead1f2410..82f502250 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -356,7 +356,7 @@ impl BlobFile { /// /// `row_id` is obtained from a query with row ids enabled. /// `offset` and `length` are relative to the beginning of the logical blob. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct BlobRangeRequest { /// Row id of the blob value to read. pub row_id: u64, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index b562f41df..578e3bbab 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1655,9 +1655,9 @@ impl Database for RemoteDatabase { let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; let rsp = RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; - self.client.check_response(&request_id, rsp).await?; + let rsp = self.client.check_response(&request_id, rsp).await?; - Ok(Arc::new(RemoteTable::new_with_sql_client( + let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), self.db_name.clone(), request.name, @@ -1665,7 +1665,9 @@ impl Database for RemoteDatabase { identifier, version, self.sql_client.clone(), - ))) + )); + table.seed_blob_ranges_capability(rsp.headers()); + Ok(table) } else { // Describe the table to confirm it exists before moving on. let req = self @@ -1676,6 +1678,7 @@ impl Database for RemoteDatabase { RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; let rsp = self.client.check_response(&request_id, rsp).await?; let version = parse_server_version(&request_id, &rsp)?; + let describe_headers = rsp.headers().clone(); let describe_body = rsp.text().await.ok(); let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), @@ -1686,6 +1689,7 @@ impl Database for RemoteDatabase { version.clone(), self.sql_client.clone(), )); + table.seed_blob_ranges_capability(&describe_headers); // This describe already carries the schema, so hand it to the table // instead of making the first schema read fetch it again. A version or // branch pin applied after this invalidates the cache. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index d560a4802..fdb547afa 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -86,6 +86,7 @@ use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::io::Cursor; use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime}; use tokio::sync::RwLock; @@ -634,6 +635,8 @@ pub struct RemoteTable { version: Arc>>, location: RwLock>, schema_cache: BackgroundCache, + // Only a successful describe can opt into the batched range protocol. + blob_ranges_supported: Arc, // WAL-PK-FUSION: delete, with its initializers below. wal_pk_fusion: PkFusionMemory, freshness: Arc>, @@ -881,6 +884,7 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -888,6 +892,15 @@ impl RemoteTable { } } + pub(super) fn seed_blob_ranges_capability(&self, headers: &http::HeaderMap) { + self.blob_ranges_supported.store( + headers + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + } + /// Seed the schema cache from a `describe` body the caller already fetched. /// /// Best effort. `open_table` succeeds today without reading this body, so a @@ -918,6 +931,7 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: self.blob_ranges_supported.clone(), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, @@ -1067,6 +1081,7 @@ impl RemoteTable { }; let response = self.check_table_response(&request_id, response).await?; + self.seed_blob_ranges_capability(response.headers()); match response.text().await { Ok(body) => { @@ -1943,6 +1958,7 @@ async fn fetch_schema( read_snapshot: ReadSnapshot, branch: Option, freshness: Arc>, + blob_ranges_supported: Arc, ) -> Result { let mut body = serde_json::json!({ "version": read_snapshot.version }); if let Some(branch) = &branch { @@ -1969,6 +1985,13 @@ async fn fetch_schema( let response = client.check_response(&request_id, response).await?; freshness_headers.observe_headers(&freshness, response.headers()); + blob_ranges_supported.store( + response + .headers() + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); let body = response.text().await.map_err(|e| { let status_code = e.status(); Error::Http { @@ -2026,6 +2049,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2054,6 +2078,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2091,6 +2116,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2885,6 +2911,7 @@ impl BaseTable for RemoteTable { let table_name = self.name.clone(); let branch = self.branch.clone(); let freshness = self.freshness.clone(); + let blob_ranges_supported = self.blob_ranges_supported.clone(); match self .schema_cache @@ -2896,6 +2923,7 @@ impl BaseTable for RemoteTable { read_snapshot, branch, freshness, + blob_ranges_supported, ) .await }) diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index a0051c955..3367d2218 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -35,11 +35,13 @@ use crate::table::{AnyQuery, BaseTable}; use super::{ FreshnessHeaders, FreshnessState, QUERY_SNAPSHOT_HEADER, ReadSnapshot, RemoteTable, VERSION_HEADER, check_query_snapshot_response, freshness_headers_snapshot, + valid_query_snapshot_identity, }; // The Cloud route rejects larger row-id lists. Its separate 64 MiB byte limit // is handled by splitting a rejected request below. const MAX_FETCH_BLOBS_ROW_IDS: usize = 1024; +const MAX_FETCH_BLOB_RANGE_BYTES: u64 = 64 * 1024 * 1024; fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { matches!(error, Error::Http { @@ -599,7 +601,7 @@ impl RemoteTable { read_snapshot.version = Some(self.describe_read_snapshot(read_snapshot).await?.version); } let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); - let mut blobs = BlobAccumulator::new(row_ids.len()); + let mut blobs = BlobAccumulator::new(row_ids.len())?; while let Some(ids) = pending.pop() { match self .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) @@ -642,7 +644,7 @@ impl RemoteTable { } } - Ok(blobs.finish()) + Ok(blobs.finish()?) } async fn fetch_blobs_chunk( @@ -725,11 +727,88 @@ impl RemoteTable { Ok(()) } - /// Materialize ranges through version-pinned handles, preserving nulls and order. + /// Materialize ranges using the protocol advertised by a successful describe. pub(super) async fn fetch_blob_ranges_impl( &self, column: &str, requests: &[BlobRangeRequest], + ) -> Result { + let mut blobs = BlobAccumulator::new(requests.len())?; + if requests.is_empty() { + return Ok(blobs.finish()?); + } + for request in requests { + request + .offset + .checked_add(request.length) + .ok_or_else(|| Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + })?; + } + self.reject_list_blob_path_if_known(column).await?; + if !self.blob_ranges_supported.load(Ordering::Relaxed) { + return self.fetch_blob_ranges_legacy(column, requests).await; + } + // Select the protocol before issuing data requests. An advertised endpoint + // failing in a mixed deployment must fail truthfully, without fallback. + let mut snapshot = self.snapshot_read_state().await; + let mut identity = self.expected_query_snapshot.clone(); + let mut index = 0; + let mut consumed = 0; + let mut ranges = Vec::new(); + ranges + .try_reserve_exact(MAX_FETCH_BLOBS_ROW_IDS) + .map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + while index < requests.len() { + ranges.clear(); + let continuation = consumed != 0; + let mut budget = MAX_FETCH_BLOB_RANGE_BYTES; + while index < requests.len() && ranges.len() < MAX_FETCH_BLOBS_ROW_IDS { + let request = requests[index]; + let remaining = request.length - consumed; + if budget == 0 && remaining != 0 { + break; + } + let length = remaining.min(budget); + // The full range was checked above; all subranges fit within it. + ranges.push(BlobRangeRequest::new( + request.row_id, + request.offset + consumed, + length, + )); + consumed += length; + budget -= length; + if consumed == request.length { + index += 1; + consumed = 0; + } else { + break; + } + } + let array = self + .fetch_blob_ranges_chunk(column, &ranges, &mut snapshot, &mut identity) + .await?; + // A null has no bytes to partition. Avoid sending arbitrarily many + // empty fragments for a null with a very large requested length. + if consumed != 0 && array.is_null(array.len() - 1) { + index += 1; + consumed = 0; + } + if continuation { + blobs.append_continuation(&array)?; + } else { + blobs.append(&array)?; + } + } + Ok(blobs.finish()?) + } + + async fn fetch_blob_ranges_legacy( + &self, + column: &str, + requests: &[BlobRangeRequest], ) -> Result { let row_ids = requests .iter() @@ -738,16 +817,12 @@ impl RemoteTable { let files = self.fetch_blob_files_impl(column, &row_ids).await?; let mut builder = LargeBinaryBuilder::with_capacity(requests.len(), 0); for (file, request) in files.into_iter().zip(requests) { - let end = - request - .offset - .checked_add(request.length) - .ok_or_else(|| Error::InvalidInput { - message: "blob range offset + length overflows u64".into(), - })?; match file { Some(file) => { - let bytes = file.read_range(request.offset..end).await?; + // Overflow was checked before selecting either protocol. + let bytes = file + .read_range(request.offset..request.offset + request.length) + .await?; builder.append_value(bytes); } None => builder.append_null(), @@ -756,6 +831,162 @@ impl RemoteTable { Ok(builder.finish()) } + async fn fetch_blob_ranges_chunk( + &self, + column: &str, + ranges: &[BlobRangeRequest], + snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result { + let _permit = self + .client + .blob_request_semaphore + .clone() + .acquire_owned() + .await + .expect("blob request semaphore is never closed"); + let body = serde_json::json!({ + "column": column, + "version": snapshot.version, + "branch": self.branch, + "ranges": ranges, + }); + let request = self + .client + .post(&format!("/v1/table/{}/fetch_blob_ranges/", self.identifier)) + .json(&body); + let request = if let Some(expected) = identity.as_deref() { + request.header(super::QUERY_SNAPSHOT_HEADER, expected) + } else { + request + }; + let (request_id, response) = self + .send_with_freshness(request, false, snapshot.freshness) + .await?; + // The range operation defines 400 as invalid input. Let the established + // checker decode structured/plain server errors before normalizing it. + let response = self + .check_table_response(&request_id, response) + .await + .map_err(|error| { + if let Error::Http { + source, + request_id, + status_code: Some(StatusCode::BAD_REQUEST), + } = error + { + Error::InvalidInput { + message: format!("fetch_blob_ranges (request {request_id}): {source}"), + } + } else { + error + } + })?; + let invalid = |message: String| Error::Http { + source: format!("fetch_blob_ranges: {message}").into(), + request_id: request_id.clone(), + status_code: None, + }; + let version = response.headers().get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version != 0) + .ok_or_else(|| invalid("missing or invalid x-lancedb-version; a server supporting the batched range endpoint is required".into()))?; + if snapshot.version.is_some_and(|expected| expected != version) { + return Err(invalid(format!( + "response version {version} differs from requested version {:?}", + snapshot.version + ))); + } + // Do not decode or accept any payload before establishing/verifying the + // identity. A later partition can never replace the original expectation. + check_query_snapshot_response(identity.as_deref(), &response)?; + if identity.is_none() { + let actual = response.headers().get(super::QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .ok_or_else(|| Error::NotSupported { + message: "Batched Blob ranges require a snapshot identity; upgrade every serving node".into(), + })?; + *identity = Some(actual.to_owned()); + } + snapshot.version = Some(version); + // This endpoint's contract is stream framing. Keep the bounded, fallible + // IPC path from #4979 instead of buffering an Arrow file response. + let content_type = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if !content_type + .split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case(crate::remote::ARROW_STREAM_CONTENT_TYPE) + { + return Err(invalid(format!( + "expected Arrow IPC stream, got '{content_type}'" + ))); + } + let mut stream = super::ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.clone(), + Some(version), + ) + .await?; + let schema = stream.schema(); + if !matches!( + schema + .field_with_name("value") + .map(|field| field.data_type()), + Ok(DataType::LargeBinary) + ) { + return Err(invalid( + "response requires a LargeBinary column named 'value'".into(), + )); + } + let mut blobs = BlobAccumulator::new(ranges.len())?; + let mut rows = 0usize; + let mut bytes = 0u64; + while let Some(batch) = stream.try_next().await? { + let array = batch + .column_by_name("value") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| { + invalid("response requires a LargeBinary column named 'value'".into()) + })?; + let end = rows + .checked_add(array.len()) + .filter(|end| *end <= ranges.len()) + .ok_or_else(|| invalid("response has more rows than requested".into()))?; + let offsets = array.value_offsets(); + bytes = bytes + .checked_add((offsets[array.len()] - offsets[0]) as u64) + .filter(|bytes| *bytes <= MAX_FETCH_BLOB_RANGE_BYTES) + .ok_or_else(|| invalid("response exceeds 64 MiB of range bytes".into()))?; + for (i, range) in ranges[rows..end].iter().enumerate() { + if array.is_valid(i) && array.value_length(i) as u64 != range.length { + return Err(invalid(format!( + "row {} returned {} bytes for requested length {}", + rows + i, + array.value_length(i), + range.length + ))); + } + } + blobs.append(array)?; + rows = end; + } + if rows != ranges.len() { + return Err(invalid(format!( + "returned {rows} rows for {} ranges", + ranges.len() + ))); + } + Ok(blobs.finish()?) + } + /// Open seekable handles for `row_ids`. /// /// Descriptors for the requested rows come from one `_rowid` take query per @@ -1666,10 +1897,155 @@ mod tests { let error = table.fetch_blob_ranges("image", &ranges).await.unwrap_err(); assert!(error.to_string().contains(message), "{error}"); // Missing rows and invalid ranges fail without reading any bytes. - assert_eq!(requests.lock().unwrap().len(), 1); + assert!(matches!(error, Error::InvalidInput { .. })); + assert_eq!( + requests.lock().unwrap().len(), + usize::from(!message.contains("overflows")) + ); } } + #[tokio::test] + async fn remote_blob_ranges_keep_producing_query_identity_from_first_request() { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let calls = Arc::new(StdMutex::new(Vec::new())); + let captured = calls.clone(); + let table = RemoteTable::new_mock( + "my_table".into(), + move |request| { + assert_eq!( + request.url().path(), + "/v1/table/my_table/fetch_blob_ranges/" + ); + assert_eq!( + request.headers()[super::super::QUERY_SNAPSHOT_HEADER], + IDENTITY + ); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["version"], 42); + let rows = body["ranges"].as_array().unwrap().len(); + captured.lock().unwrap().push(rows); + let batch = RecordBatch::try_from_iter([( + "value", + Arc::new(LargeBinaryArray::from(vec![Some(b"A".as_slice()); rows])) + as Arc, + )]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "42") + .header(super::super::QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(bytes) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let snapshot = table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap(); + let ranges = snapshot + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(b"A".as_slice()); 1025]) + ); + assert_eq!(*calls.lock().unwrap(), [1024, 1]); + assert!(table.snapshot_read_state().await.version.is_none()); + } + + #[tokio::test] + async fn remote_blob_ranges_cancel_releases_the_only_request_permit() { + use std::sync::atomic::AtomicUsize; + let entered = Arc::new(tokio::sync::Notify::new()); + let started = entered.clone(); + let calls = Arc::new(AtomicUsize::new(0)); + let captured = calls.clone(); + let table = Arc::new(RemoteTable::new_mock_with_version_and_config( + "my_table".into(), + move |request| { + assert!(request.url().path().ends_with("/fetch_blob_ranges/")); + if captured.fetch_add(1, Ordering::SeqCst) == 0 { + started.notify_one(); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header( + super::super::QUERY_SNAPSHOT_HEADER, + format!("v1:{}", "a".repeat(64)), + ) + .body(reqwest::Body::wrap_stream(futures::stream::pending::< + std::result::Result, + >())) + .unwrap() + } else { + http::Response::builder() + .status(400) + .header("x-lancedb-error-code", "invalid_input") + .body(reqwest::Body::from( + r#"{"error":"range exceeds blob size"}"#, + )) + .unwrap() + } + }, + Some(Version::new(1, 13, 0)), + crate::remote::ClientConfig { + blob_request_concurrency: Some(1), + ..Default::default() + }, + )); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let reader_table = table.clone(); + let reader = tokio::spawn(async move { + reader_table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + }); + tokio::time::timeout(Duration::from_secs(5), entered.notified()) + .await + .unwrap(); + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + let error = tokio::time::timeout( + Duration::from_secs(5), + table.fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1)]), + ) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds blob size")); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn remote_blob_ranges_reject_overflow_before_http() { + let (table, requests) = mock_take_blob_table(vec![], Some("7")); + let error = table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err(); + assert!(error.to_string().contains("overflows u64"), "{error}"); + assert!(requests.lock().unwrap().is_empty()); + } + #[tokio::test] async fn remote_blob_ranges_accept_empty_requests_without_http() { let (table, requests) = mock_take_blob_table(vec![], Some("7")); diff --git a/rust/lancedb/src/remote/table/blobs/aggregate.rs b/rust/lancedb/src/remote/table/blobs/aggregate.rs index e8e794fa0..68bc20c88 100644 --- a/rust/lancedb/src/remote/table/blobs/aggregate.rs +++ b/rust/lancedb/src/remote/table/blobs/aggregate.rs @@ -6,75 +6,143 @@ use std::collections::VecDeque; use arrow_array::{Array, LargeBinaryArray}; -use arrow_buffer::{Buffer, MutableBuffer, NullBufferBuilder, OffsetBuffer}; +use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer}; use arrow_schema::ArrowError; +fn allocation_error(error: impl std::fmt::Display) -> ArrowError { + ArrowError::ComputeError(format!("cannot allocate blob result: {error}")) +} + pub(super) struct BlobAccumulator { offsets: Vec, - nulls: NullBufferBuilder, + validity: Vec, values: VecDeque, bytes: i64, + has_nulls: bool, } impl BlobAccumulator { - pub(super) fn new(rows: usize) -> Self { - let mut offsets = Vec::with_capacity(rows + 1); + pub(super) fn new(rows: usize) -> Result { + let capacity = rows + .checked_add(1) + .ok_or_else(|| allocation_error("row count overflow"))?; + let mut offsets = Vec::new(); + offsets + .try_reserve_exact(capacity) + .map_err(allocation_error)?; offsets.push(0); - Self { + let mut validity = Vec::new(); + let validity_bytes = rows / 8 + usize::from(!rows.is_multiple_of(8)); + validity + .try_reserve_exact(validity_bytes) + .map_err(allocation_error)?; + Ok(Self { offsets, - nulls: NullBufferBuilder::new(rows), + validity, values: VecDeque::new(), bytes: 0, - } + has_nulls: false, + }) } pub(super) fn append(&mut self, array: &LargeBinaryArray) -> Result<(), ArrowError> { + self.append_inner(array, false) + } + + /// The first value continues the preceding response's final logical range. + pub(super) fn append_continuation( + &mut self, + array: &LargeBinaryArray, + ) -> Result<(), ArrowError> { + self.append_inner(array, true) + } + + fn append_inner( + &mut self, + array: &LargeBinaryArray, + continuation: bool, + ) -> Result<(), ArrowError> { + let rows = self.offsets.len() - 1; + if continuation + && (rows == 0 + || array.is_empty() + || (self.validity[(rows - 1) / 8] & (1 << ((rows - 1) % 8)) != 0) + != array.is_valid(0)) + { + return Err(ArrowError::ComputeError( + "inconsistent nulls in split blob range".into(), + )); + } let offsets = array.value_offsets(); let start = offsets[0]; let length = offsets[array.len()] - start; let total = self.bytes.checked_add(length).ok_or_else(|| { - ArrowError::ComputeError("fetch_blobs result exceeds i64 byte offsets".into()) + ArrowError::ComputeError("blob result exceeds i64 byte offsets".into()) })?; - self.offsets.extend( - offsets[1..] - .iter() - .map(|offset| self.bytes + (*offset - start)), - ); - if let Some(nulls) = array.nulls() { - self.nulls.append_buffer(nulls); - } else { - self.nulls.append_n_non_nulls(array.len()); - } + let skip = usize::from(continuation); + self.offsets + .try_reserve(array.len() - skip) + .map_err(allocation_error)?; + let new_rows = rows + .checked_add(array.len() - skip) + .ok_or_else(|| allocation_error("row count overflow"))?; + let validity_bytes = new_rows / 8 + usize::from(new_rows % 8 != 0); + self.validity + .try_reserve(validity_bytes - self.validity.len()) + .map_err(allocation_error)?; + self.validity.resize(validity_bytes, 0); if length != 0 { + self.values.try_reserve(1).map_err(allocation_error)?; self.values.push_back( array .values() .slice_with_length(start as usize, length as usize), ); } + if continuation { + *self.offsets.last_mut().unwrap() = self.bytes + (offsets[1] - start); + } + self.offsets.extend( + offsets[1 + skip..] + .iter() + .map(|offset| self.bytes + (*offset - start)), + ); + for i in skip..array.len() { + let row = rows + i - skip; + if array.is_valid(i) { + self.validity[row / 8] |= 1 << (row % 8); + } else { + self.has_nulls = true; + } + } self.bytes = total; Ok(()) } - pub(super) fn finish(mut self) -> LargeBinaryArray { + pub(super) fn finish(mut self) -> Result { let values = match self.values.len() { 0 => Buffer::default(), 1 => self.values.pop_front().unwrap(), _ => { - let mut values = MutableBuffer::new(self.bytes as usize); - // Do not retain all decoded batches alongside the final allocation. + let length = usize::try_from(self.bytes).map_err(allocation_error)?; + let mut values = Vec::new(); + values.try_reserve_exact(length).map_err(allocation_error)?; // Drop each source allocation immediately after copying its bytes. while let Some(chunk) = self.values.pop_front() { values.extend_from_slice(&chunk); } - values.into() + Buffer::from_vec(values) } }; - LargeBinaryArray::new( + let rows = self.offsets.len() - 1; + let nulls = self + .has_nulls + .then(|| NullBuffer::new(BooleanBuffer::new(Buffer::from_vec(self.validity), 0, rows))); + Ok(LargeBinaryArray::new( OffsetBuffer::new(self.offsets.into()), values, - self.nulls.finish(), - ) + nulls, + )) } } @@ -85,9 +153,9 @@ mod tests { #[test] fn single_buffer_is_not_copied() { let array = LargeBinaryArray::from(vec![Some(b"alpha".as_slice()), None, Some(b"")]); - let mut result = BlobAccumulator::new(3); + let mut result = BlobAccumulator::new(3).unwrap(); result.append(&array).unwrap(); - let output = result.finish(); + let output = result.finish().unwrap(); assert_eq!(output.values().as_ptr(), array.values().as_ptr()); assert_eq!(output, array); } @@ -101,21 +169,27 @@ mod tests { Some(b""), Some(b"beta"), ]); - let mut result = BlobAccumulator::new(6); + let mut result = BlobAccumulator::new(6).unwrap(); result.append(&array.slice(1, 3)).unwrap(); result.append(&array.slice(4, 1)).unwrap(); result.append(&array.slice(2, 2)).unwrap(); assert_eq!( - result.finish(), + result.finish().unwrap(), LargeBinaryArray::from(vec![ Some(b"alpha".as_slice()), None, Some(b""), Some(b"beta"), None, - Some(b""), + Some(b"") ]) ); - assert_eq!(BlobAccumulator::new(0).finish().len(), 0); + assert_eq!(BlobAccumulator::new(0).unwrap().finish().unwrap().len(), 0); + } + + #[test] + fn impossible_capacity_is_an_error() { + assert!(BlobAccumulator::new(usize::MAX).is_err()); + assert!(BlobAccumulator::new(usize::MAX / 2).is_err()); } } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index db68ab290..4959b2842 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1452,8 +1452,13 @@ impl Table { /// ranges for the same blob. The output has the same length and order as /// the requests. Null blobs produce null output slots; empty ranges on /// non-null blobs produce empty byte strings. - /// LanceDB Enterprise tables read through version-pinned [`BlobFile`] handles using - /// HTTP byte-range requests. + /// LanceDB Enterprise uses the batched endpoint when the server advertises + /// support, splitting calls at 1024 ranges and 64 MiB of requested bytes. + /// Individual larger ranges are partitioned and reassembled into one result. + /// Older servers use descriptor queries and [`Self::fetch_blob_files`] range + /// reads. Both protocols read one exact branch and version without changing + /// this handle's checkout. The final materialized output still occupies memory. + /// Errors from an advertised endpoint propagate without switching protocols. /// /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no @@ -1486,10 +1491,14 @@ impl Table { column: impl AsRef, requests: impl IntoIterator, ) -> Result { - let requests = requests.into_iter().collect::>(); - self.inner - .fetch_blob_ranges(column.as_ref(), &requests) - .await + let mut ranges = Vec::new(); + for request in requests { + ranges.try_reserve(1).map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + ranges.push(request); + } + self.inner.fetch_blob_ranges(column.as_ref(), &ranges).await } /// Open lazy [`BlobFile`] handles for the given row ids. diff --git a/rust/lancedb/tests/remote_blob_ranges.rs b/rust/lancedb/tests/remote_blob_ranges.rs new file mode 100644 index 000000000..51c49fe09 --- /dev/null +++ b/rust/lancedb/tests/remote_blob_ranges.rs @@ -0,0 +1,634 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +#![cfg(feature = "remote")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{Array, ArrayRef, LargeBinaryArray, RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use lancedb::Table; +use lancedb::blob::BlobRangeRequest; +use lancedb::remote::{ClientConfig, RetryConfig, TimeoutConfig}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; + +const MIB: u64 = 1024 * 1024; +const IDENTITY: &str = "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const ROUTE: &str = "/v1/table/test/fetch_blob_ranges/"; + +struct Reply { + status: u16, + version: Option, + body: Vec, + declared_extra: usize, + identity: Option<&'static str>, +} + +fn ipc(column: &str, values: ArrayRef) -> Vec { + let batch = RecordBatch::try_from_iter([(column, values)]).unwrap(); + let mut body = Vec::new(); + let mut writer = StreamWriter::try_new(&mut body, &batch.schema()).unwrap(); + // Multiple batches exercise response assembly as well as HTTP partitions. + let mid = batch.num_rows() / 2; + writer.write(&batch.slice(0, mid)).unwrap(); + writer + .write(&batch.slice(mid, batch.num_rows() - mid)) + .unwrap(); + writer.finish().unwrap(); + drop(writer); + body +} + +fn legacy_reply(path: &str, body: &Value, takes: usize) -> Reply { + use arrow_array::{StructArray, UInt8Array, UInt32Array, UInt64Array}; + let version = body["version"] + .as_u64() + .unwrap_or(if takes == 1 { 7 } else { 8 }); + if path.ends_with("/query/") { + assert_eq!(body["branch"], "experiment"); + assert_eq!(body["columns"], json!(["image"])); + let filter = body["filter"].as_str().unwrap(); + let ids = filter + .split_once('(') + .unwrap() + .1 + .trim_end_matches(')') + .split(',') + .map(|id| id.trim().parse::().unwrap()) + .filter(|id| [10, 20, 30, 40].contains(id)) + .rev() + .collect::>(); + let fields = lance_core::datatypes::BLOB_V2_DESC_FIELDS.clone(); + let descriptors = StructArray::new( + fields, + vec![ + Arc::new(UInt8Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from( + ids.iter() + .map(|id| if *id == 40 { 0 } else { 5 }) + .collect::>(), + )), + Arc::new(UInt32Array::from(vec![0; ids.len()])), + Arc::new(StringArray::from(vec![""; ids.len()])), + ], + Some(ids.iter().map(|id| *id != 20).collect()), + ); + let batch = RecordBatch::try_from_iter([ + ("image", Arc::new(descriptors) as ArrayRef), + ("_rowid", Arc::new(UInt64Array::from(ids)) as ArrayRef), + ]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + Reply { + status: 200, + version: Some(version), + body: bytes, + declared_extra: 0, + identity: Some(IDENTITY), + } + } else { + assert!(path.contains("branch=experiment"), "{path}"); + let version = path + .split("version=") + .nth(1) + .unwrap() + .split('&') + .next() + .unwrap() + .parse::() + .unwrap(); + let range = body["range"] + .as_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap(); + let (start, end) = range.split_once('-').unwrap(); + let start = start.parse::().unwrap(); + let end = end.parse::().unwrap(); + let payload = if version == 8 { b"ALPHA" } else { b"alpha" }; + Reply { + status: 206, + version: Some(version), + body: payload[start..=end].to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + } + } +} + +fn reply(values: Vec>>, version: u64) -> Reply { + Reply { + status: 200, + version: Some(version), + body: ipc( + "value", + Arc::new(LargeBinaryArray::from_iter( + values.iter().map(|v| v.as_deref()), + )), + ), + declared_extra: 0, + identity: Some(IDENTITY), + } +} + +fn byte(row: u64, offset: u64, version: u64) -> u8 { + ((row * 17 + offset % 251 + version) % 251) as u8 +} + +fn serve_ranges(body: &Value, version: u64) -> Reply { + assert_eq!(body["column"], "image"); + let ranges = body["ranges"].as_array().unwrap(); + assert!(ranges.len() <= 1024); + assert!( + ranges + .iter() + .map(|r| r["length"].as_u64().unwrap()) + .sum::() + <= 64 * MIB + ); + let values = ranges + .iter() + .map(|r| { + let row = r["row_id"].as_u64().unwrap(); + let offset = r["offset"].as_u64().unwrap(); + let length = r["length"].as_u64().unwrap(); + (row != 20).then(|| { + (offset..offset + length) + .map(|i| byte(row, i, version)) + .collect() + }) + }) + .collect(); + reply(values, version) +} + +struct Server { + url: String, + calls: Arc>>, + task: tokio::task::JoinHandle<()>, + identities: Arc>>>, +} + +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl Server { + async fn new(handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static) -> Self { + Self::with_capability(handler, Some("1")).await + } + + async fn with_capability( + handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static, + capability: Option<&'static str>, + ) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let calls = Arc::new(Mutex::new(Vec::new())); + let captured = calls.clone(); + let identities = Arc::new(Mutex::new(Vec::new())); + let captured_identities = identities.clone(); + let task = tokio::spawn(async move { + let mut fetches = 0; + let mut takes = 0; + loop { + let (socket, _) = listener.accept().await.unwrap(); + let captured = captured.clone(); + let result = tokio::time::timeout(Duration::from_secs(20), async { + let mut socket = BufReader::new(socket); + let mut line = String::new(); + socket.read_line(&mut line).await?; + let path = line.split_whitespace().nth(1).unwrap().to_string(); + let method = line.split_whitespace().next().unwrap().to_string(); + let mut range = String::new(); + let mut length = 0; + let mut identity = None; + loop { + line.clear(); + socket.read_line(&mut line).await?; + assert!(line.len() <= 16384); + if line == "\r\n" { break; } + if let Some((name, value)) = line.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse::().unwrap(); + } + if name.eq_ignore_ascii_case("x-lancedb-query-snapshot") { identity = Some(value.trim().to_owned()); } + if name.eq_ignore_ascii_case("range") { range = value.trim().to_string(); } + } + } + assert!(length <= 256 * 1024); + let mut bytes = vec![0; length]; + socket.read_exact(&mut bytes).await?; + let body = if method == "GET" { json!({"range": range}) } else if bytes.is_empty() { json!({}) } else { serde_json::from_slice(&bytes).unwrap() }; + captured.lock().unwrap().push((path.clone(), body.clone())); + let response = if path == "/v1/table/test/describe/" { + Reply { status: 200, version: None, body: serde_json::to_vec(&json!({"version": 8, "schema": {"fields": []}})).unwrap(), declared_extra: 0, identity: None } + } else if path == "/v1/table/test/branches/list/" { + Reply { status: 200, version: None, body: br#"{"branches":{"experiment":{"parentBranch":null,"parentVersion":1,"createAt":1,"manifestSize":1}}}"#.to_vec(), declared_extra: 0, identity: None } + } else if capability != Some("1") { + assert_ne!(path, ROUTE, "unknown capability must select old routes first"); + takes += usize::from(path.ends_with("/query/")); + legacy_reply(&path, &body, takes) + } else { + assert_eq!(path, ROUTE, "unexpected legacy or fallback request"); + fetches += 1; + captured_identities.lock().unwrap().push(identity); + handler(&body, fetches) + }; + if response.status == 0 { return Ok::<_, std::io::Error>(()); } + let version = response.version.map(|v| format!("x-lancedb-version: {v}\r\n")).unwrap_or_default(); + let capability = if path.ends_with("/describe/") { capability.map(|value| format!("x-lancedb-blob-ranges: {value}\r\n")).unwrap_or_default() } else { String::new() }; + let content_type = if path == ROUTE || path.ends_with("/query/") { "application/vnd.apache.arrow.stream" } else { "application/json" }; + let content_range = if method == "GET" { format!("Content-Range: {}/5\r\n", body["range"].as_str().unwrap().replace("bytes=", "bytes ")) } else { String::new() }; + let identity = if path == ROUTE { response.identity.map(|id| format!("x-lancedb-query-snapshot: {id}\r\n")).unwrap_or_default() } else { String::new() }; + let header = format!("HTTP/1.1 {} Response\r\nContent-Type: {content_type}\r\nphalanx-version: 1.13.0-beta.0\r\n{capability}{version}{identity}{content_range}Content-Length: {}\r\nConnection: close\r\n\r\n", response.status, response.body.len() + response.declared_extra); + socket.write_all(header.as_bytes()).await?; + for chunk in response.body.chunks(8192) { socket.write_all(chunk).await?; } + socket.shutdown().await?; + Ok(()) + }).await; + // A client rejecting a malformed schema may close the body early. + assert!(result.is_ok(), "loopback request timed out"); + } + }); + Self { + url, + calls, + task, + identities, + } + } + + async fn table(&self, version: Option) -> Table { + let db = lancedb::connect("db://dev") + .api_key("fake") + .region("us-east-1") + .host_override(&self.url) + .client_config(ClientConfig { + retry_config: RetryConfig { + retries: Some(2), + connect_retries: Some(2), + read_retries: Some(2), + ..Default::default() + }, + timeout_config: TimeoutConfig { + timeout: Some(Duration::from_secs(30)), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let mut open = db.open_table("test").branch("experiment"); + if let Some(version) = version { + open = open.version(version); + } + open.execute().await.unwrap() + } +} + +#[tokio::test] +async fn public_ranges_work_on_old_routes_only_servers() { + for capability in [None, Some("0"), Some("2")] { + for checkout in [None, Some(3)] { + let server = Server::with_capability( + |_, _| panic!("new endpoint must not be requested"), + capability, + ) + .await; + let table = server.table(checkout).await; + let cloned = table.clone(); + let ranges = [ + BlobRangeRequest::new(10, 1, 3), + BlobRangeRequest::new(20, 0, 1), + BlobRangeRequest::new(40, 0, 0), + BlobRangeRequest::new(10, 5, 0), + BlobRangeRequest::new(10, 1, 3), + ]; + let result = cloned.fetch_blob_ranges("image", ranges).await.unwrap(); + assert_eq!( + result, + LargeBinaryArray::from(vec![ + Some(b"lph".as_slice()), + None, + Some(b"".as_slice()), + Some(b"".as_slice()), + Some(b"lph".as_slice()) + ]) + ); + let result = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!( + result.value(0), + if checkout.is_none() { b"A" } else { b"a" } + ); + for ranges in [ + vec![BlobRangeRequest::new(10, 4, 2)], + vec![BlobRangeRequest::new(99, 0, 1)], + ] { + assert!(matches!( + table.fetch_blob_ranges("image", ranges).await.unwrap_err(), + lancedb::Error::InvalidInput { .. } + )); + } + assert!( + !server + .calls + .lock() + .unwrap() + .iter() + .any(|(path, _)| path == ROUTE) + ); + } + } +} + +#[tokio::test] +async fn public_ranges_keep_order_nulls_and_snapshot_without_pinning_live_handle() { + for checkout in [None, Some(3)] { + let server = Server::new(move |body, call| { + assert_eq!(body["branch"], "experiment"); + let expected = checkout.or((call > 1 && call < 3).then_some(7)); + assert_eq!(body["version"].as_u64(), expected); + serve_ranges( + body, + body["version"] + .as_u64() + .unwrap_or(if call == 1 { 7 } else { 8 }), + ) + }) + .await; + let table = server.table(checkout).await; + let mut requests = (0..1025) + .map(|i| BlobRangeRequest::new(if i % 9 == 0 { 20 } else { 10 + i % 7 }, i, i % 4)) + .collect::>(); + requests.extend([ + BlobRangeRequest::new(10, 0, 0), + BlobRangeRequest::new(10, 2, 3), + BlobRangeRequest::new(10, 2, 3), + ]); + let result = table + .fetch_blob_ranges("image", requests.clone()) + .await + .unwrap(); + assert_eq!(result.len(), requests.len()); + for (i, request) in requests.iter().enumerate() { + assert_eq!(result.is_null(i), request.row_id == 20); + if request.row_id != 20 { + let expected = (request.offset..request.offset + request.length) + .map(|j| byte(request.row_id, j, checkout.unwrap_or(7))) + .collect::>(); + assert_eq!(result.value(i), expected); + } + } + let next = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!(next.value(0), [byte(10, 0, checkout.unwrap_or(8))]); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); + } +} + +#[tokio::test] +async fn public_ranges_partition_bytes_and_reassemble_large_single_range() { + let server = Server::new(|body, call| { + assert_eq!(body["version"].as_u64(), (call > 1).then_some(7)); + serve_ranges(body, 7) + }) + .await; + let table = server.table(None).await; + let requests = [ + BlobRangeRequest::new(10, 3, 33 * MIB), + BlobRangeRequest::new(30, 7, 33 * MIB), + BlobRangeRequest::new(40, 11, 70 * MIB), + BlobRangeRequest::new(20, 0, u64::MAX), + ]; + let result = table.fetch_blob_ranges("image", requests).await.unwrap(); + assert_eq!(result.len(), 4); + for (i, request) in requests[..3].iter().enumerate() { + assert_eq!(result.value_length(i) as u64, request.length); + assert!( + result + .value(i) + .iter() + .enumerate() + .all(|(j, value)| *value == byte(request.row_id, request.offset + j as u64, 7)) + ); + } + assert!(result.is_null(3)); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); +} + +#[tokio::test] +async fn public_ranges_reject_malformed_responses_and_http_failures_without_fallback() { + for case in 0..16 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + // Fail after one successful partition to prove no partial success. + if call == 1 { + return response; + } + match case { + 0 => response.body = ipc("value", Arc::new(StringArray::from(vec!["bad"]))), + 1 => { + response.body = ipc( + "wrong", + Arc::new(LargeBinaryArray::from(vec![Some(b"a".as_slice())])), + ) + } + 2 => response = reply(vec![], 7), + 3 => response = reply(vec![Some(vec![1]), Some(vec![2])], 7), + 4 => response.body.truncate(response.body.len() - 8), + 5 => response.body.truncate(response.body.len() / 2), + 6 => response.declared_extra = 10, + 7 => response = reply(vec![Some(vec![])], 7), + 8 => response.version = None, + 9 => response.version = Some(8), + 10..=14 => { + response.status = [401, 403, 404, 429, 500][case - 10]; + response.body = b"ordinary failure".to_vec(); + } + 15 => response.status = 0, + _ => unreachable!(), + } + response + }) + .await; + let table = server.table(None).await; + let requests = vec![BlobRangeRequest::new(10, 0, 1); 1025]; + assert!( + table.fetch_blob_ranges("image", requests).await.is_err(), + "case {case}" + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2, + "case {case}" + ); + } +} + +#[tokio::test] +async fn public_ranges_validate_locally_and_propagate_server_range_errors() { + let server = Server::new(|_, _| Reply { + status: 400, + version: None, + body: b"range exceeds blob size or missing row".to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + assert_eq!(table.fetch_blob_ranges("image", []).await.unwrap().len(), 0); + assert!( + table + .fetch_blob_ranges("image", [BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err() + .to_string() + .contains("overflows u64") + ); + assert_eq!(server.calls.lock().unwrap().len(), before); + let error = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 9, 2)]) + .await + .unwrap_err(); + assert!(matches!(error, lancedb::Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds")); +} + +#[tokio::test] +async fn public_ranges_require_original_identity_on_every_partition() { + for huge in [false, true] { + for case in 0..5 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + if call == 2 { + response.identity = match case { + 0 => None, // Old serving node ignores the precondition. + 1 => Some("invalid"), + _ => Some( + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ), + }; + if case == 3 || case == 4 { + response.status = if case == 3 { 400 } else { 404 }; + response.body = + b"query snapshot identity mismatch: gone or replaced".to_vec(); + } else { + // Identity verification must win over malformed payload. + response.body = b"not Arrow".to_vec(); + } + } + response + }) + .await; + let table = server.table(None).await; + let requests = if huge { + vec![BlobRangeRequest::new(10, 0, 64 * MIB + 1)] + } else { + vec![BlobRangeRequest::new(10, 0, 1); 1025] + }; + let error = table + .fetch_blob_ranges("image", requests) + .await + .unwrap_err(); + if case < 3 { + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + } else if case == 3 { + assert!( + matches!(error, lancedb::Error::InvalidInput { .. }), + "{error}" + ); + } else { + assert!( + matches!(error, lancedb::Error::TableNotFound { .. }), + "{error}" + ); + } + assert_eq!( + *server.identities.lock().unwrap(), + [None, Some(IDENTITY.into())] + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2 + ); + } + } +} + +#[tokio::test] +async fn public_ranges_cannot_establish_identity_from_numeric_version_or_describe() { + for identity in [None, Some("invalid"), Some("v2:unsupported")] { + let server = Server::new(move |_, call| { + assert_eq!(call, 1, "no failure fallback, replay or second partition"); + let mut response = reply(vec![Some(b"A".to_vec()); 1024], 7); + response.identity = identity; + response.body = b"not Arrow".to_vec(); + response + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + let error = table + .fetch_blob_ranges("image", vec![BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap_err(); + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + assert_eq!(server.calls.lock().unwrap().len(), before + 1); + } +} From cababaecf08a12bdd97a157cac16751c13350274 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 06:22:35 +0800 Subject: [PATCH 32/75] feat(remote): discover server builds and retain error provenance (#4999) Remote callers can use `db.server_info()` in Rust and Python, including synchronous and asynchronous Python connections, to identify the responding server without submitting a query or Job. Typed results describe the query-node build, component versions, Function protocol and configured images. Older servers without the endpoint return an explicit unsupported error. REST and Flight errors retain the reported build in diagnostic text and Rust `RemoteErrorMetadata.server`. Typed table/job-not-found errors preserve their HTTP source and classification, including the schema-cache path; masked REST errors can obtain provenance from the response header. Unknown build information stays absent. The matching native Python SDK was exercised against a real localhost server (`8829b074` client / `43920fa` server): sync/async discovery, both SQL version forms and actual REST/Flight error provenance passed. The product files match this branch; private validation drivers are excluded. Focused coverage includes typed 404 errors, masked errors, and the public schema-cache regression. Deployment and published-package acceptance remain separate. Server counterpart: https://github.com/lancedb/sophon/pull/10234. Related: ENT-3565. --- docs/src/python/python.md | 12 +++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/db.py | 23 +++++ python/python/lancedb/remote/db.py | 9 ++ python/python/lancedb/server_info.py | 33 +++++++ python/python/tests/test_remote_db.py | 87 +++++++++++++++++ python/src/connection.rs | 8 ++ rust/lancedb/src/connection.rs | 18 ++++ rust/lancedb/src/database.rs | 7 ++ rust/lancedb/src/error.rs | 77 ++++++++++++--- rust/lancedb/src/lib.rs | 1 + rust/lancedb/src/remote/db.rs | 133 +++++++++++++++++++++++++- rust/lancedb/src/remote/sql.rs | 13 ++- rust/lancedb/src/remote/sql_test.rs | 47 +++++++++ rust/lancedb/src/remote/table.rs | 60 +++++++++--- rust/lancedb/src/server_info.rs | 56 +++++++++++ 16 files changed, 553 insertions(+), 32 deletions(-) create mode 100644 python/python/lancedb/server_info.py create mode 100644 rust/lancedb/src/server_info.rs diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 0e7164c1a..058f2529a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -37,6 +37,18 @@ embedding_functions`. Prefer keyword arguments for optional parameters. ::: lancedb.db.DBConnection +Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection) +to include the responding server's release, Git revision, build date and Function +runtime information in a bug report. It returns a JSON-compatible dictionary and +does not submit a query or job. Configured images are distinct from the version +of an already running job. During a rolling upgrade, successive requests can +reach different query-node builds. Embedded connections and older servers without +the endpoint raise `NotImplementedError`. + +::: lancedb.server_info.ServerBuildInfo + +::: lancedb.server_info.ServerInfo + Resource listings return iterators. Use `list(db.list_tables())` to collect all table names. `db.list_tables().tables` is a list of the first page; `limit` controls its page size and `page_token` resumes at a saved token. The same diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 956806cde..ffdd68e5f 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -185,6 +185,7 @@ class Connection(object): limit: Optional[int], ) -> list[str]: ... # Deprecated: Use list_tables instead async def open_job(self, job_id: str) -> Job: ... + async def server_info(self) -> str: ... async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( self, request_json: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 59fa5b4c6..b4e5c6182 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -58,6 +58,7 @@ from lance_namespace import ( from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from . import __version__ +from .server_info import ServerInfo from ._lancedb import _append_doc_url, connect as lancedb_connect # type: ignore from .functions import FunctionVersion, FunctionDefinition from .graph import ( @@ -1476,6 +1477,22 @@ class DBConnection(EnforceOverrides): ) ) + def server_info(self) -> ServerInfo: + """Return the responding server's build and Function runtime information. + + This call submits no query, Function, or job. The response is a + JSON-compatible dictionary, convenient to include in a bug report:: + + info = db.server_info() + print(info["query_node"]) # release, git_sha, build_date + + Requires System Usage permission. Embedded connections and older + servers without this endpoint raise ``NotImplementedError``. + Different calls can reach different builds during a rolling upgrade. + Configured images do not identify the version of a running job. + """ + raise NotImplementedError("Server build discovery requires a remote connection") + def list_gpu_classes(self) -> List[GpuClass]: """List the operator-configured Function GPU classes. @@ -3653,6 +3670,12 @@ class AsyncConnection(object): """ return _opened_job(await self._inner.open_job(job_id)) + async def server_info(self) -> ServerInfo: + """Read the responding server's build information. See + [DBConnection.server_info][lancedb.db.DBConnection.server_info]. + """ + return json.loads(await self._inner.server_info()) + async def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See [DBConnection.list_gpu_classes][lancedb.db.DBConnection.list_gpu_classes]. diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index a06af5d62..911766674 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -4,6 +4,8 @@ from __future__ import annotations +from lancedb.server_info import ServerInfo + from dataclasses import replace from datetime import timedelta import json @@ -966,6 +968,13 @@ class RemoteDBConnection(DBConnection): """ return Job(LOOP.run(self._conn.open_job(job_id))) + @override + def server_info(self) -> ServerInfo: + """Read the responding server's build information. See + [DBConnection.server_info][lancedb.db.DBConnection.server_info]. + """ + return LOOP.run(self._conn.server_info()) + @override def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See diff --git a/python/python/lancedb/server_info.py b/python/python/lancedb/server_info.py new file mode 100644 index 000000000..d53c6c380 --- /dev/null +++ b/python/python/lancedb/server_info.py @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Remote server build information returned as JSON-compatible dictionaries.""" + +from typing import Optional, TypedDict + + +class ServerBuildInfo(TypedDict): + """Immutable identity compiled into a server executable.""" + + release: str + git_sha: str + build_date: Optional[str] + + +class ServerInfo(TypedDict): + """The responding query node and its configured Function runtime. + + ``query_node`` can be ``None`` when the executable has no build metadata. + ``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling + upgrade, separate requests can reach different query-node builds. + Configured images do not establish the version of a running job. + """ + + query_node: Optional[ServerBuildInfo] + lance_version: str + lancedb_version: str + function_worker_protocol_version: int + configured_query_node_image: Optional[str] + configured_job_worker_image: Optional[str] + configured_sql_job_image: Optional[str] + configured_gpu_worker_image: Optional[str] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 4f707f041..ca2516fda 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -6539,6 +6539,93 @@ def test_remote_job_handle_reports_its_own_detail(): } +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("known_build", [False, True]) +@pytest.mark.asyncio +async def test_remote_server_info(is_async, known_build): + requests = [] + expected = { + "query_node": { + "release": "1.2.3", + "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + } + if known_build + else None, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_query_node_image": "example.invalid/query:configured", + "configured_job_worker_image": "example.invalid/cpu:configured", + "configured_sql_job_image": "example.invalid/cli:configured", + "configured_gpu_worker_image": "example.invalid/worker:configured", + } + + def handler(request): + requests.append((request.command, request.path)) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(expected).encode()) + + if is_async: + async with mock_lancedb_connection_async(handler) as db: + actual = await db.server_info() + else: + with mock_lancedb_connection(handler) as db: + actual = db.server_info() + + assert actual == expected + assert json.loads(json.dumps(actual)) == expected + assert requests == [("GET", "/v1/server/info")] + + +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("status", [404, 403]) +@pytest.mark.asyncio +async def test_remote_server_info_errors(is_async, status): + requests = [] + + def handler(request): + requests.append((request.command, request.path)) + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "error": "discovery unavailable", + "server": { + "release": "1.2.3", + "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }, + } + ).encode() + ) + + expected_error = NotImplementedError if status == 404 else HttpError + with pytest.raises(expected_error) as caught: + if is_async: + async with mock_lancedb_connection_async(handler) as db: + await db.server_info() + else: + with mock_lancedb_connection(handler) as db: + db.server_info() + + if status == 404: + assert "/v1/server/info" in str(caught.value) + else: + # Permission responses do not carry the input-error classifier header. + # The native HTTP error and Python conversion must retain provenance. + assert "discovery unavailable" in str(caught.value) + assert "1.2.3" in str(caught.value) + assert "0123456789ab" in str(caught.value) + assert "2024-01-01T00:00:00Z" in str(caught.value) + assert caught.value.status_code == 403 + assert requests == [("GET", "/v1/server/info")] + + @pytest.mark.parametrize("is_async", [False, True]) @pytest.mark.asyncio async def test_remote_list_gpu_classes(is_async): diff --git a/python/src/connection.rs b/python/src/connection.rs index 1a99c1372..2bf01a6f7 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1285,6 +1285,14 @@ impl Connection { )) } + pub fn server_info(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let info = inner.server_info().await.infer_error()?; + serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string())) + }) + } + pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index fa35dc459..cc398e32b 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -1303,6 +1303,24 @@ impl Connection { self.database().list_gpu_classes().await } + /// Read the responding server's build and Function runtime information. + /// + /// This request does not submit a query, Function, or job. It requires + /// System Usage permission. Embedded databases and older servers without + /// `GET /v1/server/info` return [`Error::NotSupported`]. During a rolling + /// upgrade, separate requests can report different query-node builds. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let info = db.server_info().await?; + /// println!("{:?}", info.query_node); + /// # Ok(()) + /// # } + /// ``` + pub async fn server_info(&self) -> Result { + self.database().server_info().await + } + /// List server-side jobs across the database's tables. /// /// Results are fetched lazily, one page at a time. See [`Listing`] diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 7b4859faa..23ed9fc3d 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -479,6 +479,13 @@ pub trait Database: async fn list_gpu_classes(&self) -> Result> { gpu_class_catalog_not_supported() } + + /// Read the responding remote server's build identity. + async fn server_info(&self) -> Result { + Err(crate::Error::NotSupported { + message: "Server build discovery requires a remote LanceDB connection".into(), + }) + } /// Create a materialized view through a remote catalog and return its /// initial-population job. Local connections use the native declaration /// path directly. diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 89ad7a229..6aed94d71 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -64,6 +64,8 @@ impl RemoteResourceIdentity { #[derive(Debug, Clone, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RemoteErrorMetadata { + /// Build of the executable that produced the error, when reported. + pub server: Option, /// Machine-readable input error code, when available. pub error_code: Option, /// SQL job that failed, when the request ran in an isolated job. @@ -84,6 +86,8 @@ impl RemoteErrorMetadata { .map(str::to_owned) }; Self { + server: header("x-lancedb-server-build") + .and_then(|value| serde_json::from_str(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header("x-lancedb-sql-job-id"), job_request_id: header("x-job-request-id"), @@ -119,7 +123,7 @@ pub(crate) fn parse_flight_resource_identity(value: &str) -> Option, @@ -131,17 +135,28 @@ impl HttpErrorSource { pub(crate) fn new( message: String, response_body: Option<&str>, - metadata: RemoteErrorMetadata, + mut metadata: RemoteErrorMetadata, ) -> Self { let details = response_body.and_then(parse_http_error_details); + let body = + response_body.and_then(|body| serde_json::from_str::(body).ok()); + if metadata.server.is_none() { + metadata.server = body + .as_ref() + .and_then(|body| body.get("server").cloned()) + .and_then(|server| serde_json::from_value(server).ok()); + } let message = if metadata.error_code.is_some() { - response_body - .and_then(|body| serde_json::from_str::(body).ok()) + body.as_ref() .and_then(|body| body.get("error")?.as_str().map(str::to_owned)) .unwrap_or(message) } else { message }; + let message = match &metadata.server { + Some(server) => format!("{message} [server: {server}]"), + None => message, + }; Self { message, details, @@ -317,6 +332,18 @@ impl Display for JobFailure { } } +fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static)) -> String { + #[cfg(feature = "remote")] + if let Some(server) = _source + .downcast_ref::() + .and_then(Error::remote_error_metadata) + .and_then(|metadata| metadata.server.as_ref()) + { + return format!(" [server: {server}]"); + } + String::new() +} + #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { @@ -324,7 +351,7 @@ pub enum Error { InvalidTableName { name: String, reason: String }, #[snafu(display("Invalid input, {message}"))] InvalidInput { message: String }, - #[snafu(display("Table '{name}' was not found"))] + #[snafu(display("Table '{name}' was not found{}", server_build_suffix(source.as_ref())))] TableNotFound { name: String, source: BoxError }, #[snafu(display( "Table '{name}' exists but could not be loaded (it may be corrupt or incomplete): {source}" @@ -385,8 +412,8 @@ pub enum Error { }, #[snafu(display("Job{} was cancelled", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobCancelled { job_id: Option }, - #[snafu(display("Job '{job_id}' was not found"))] - JobNotFound { job_id: String }, + #[snafu(display("Job '{job_id}' was not found{}", server_build_suffix(source.as_ref())))] + JobNotFound { job_id: String, source: BoxError }, // 3rd party / external errors #[snafu(display("object_store error: {source}"))] @@ -576,7 +603,7 @@ impl Error { match self { Self::Http { status_code, .. } => *status_code, Self::Retry { status_code, .. } => *status_code, - Self::TableNotFound { source, .. } => { + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => { source.downcast_ref::().and_then(Self::status_code) } Self::JobFailed { failure, .. } => { @@ -623,7 +650,7 @@ impl Error { Self::Retry { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), - Self::TableNotFound { source, .. } => source + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), Self::JobFailed { failure, .. } => failure @@ -635,9 +662,35 @@ impl Error { } } - /// A copy of an error that other partitions of a DataFusion plan still hold. - /// Only an interrupted response can be copied, because it shares its source. - fn clone_shared(&self) -> Option { + /// Copy supported errors without flattening sources retained by a shared plan + /// or schema cache. + pub(crate) fn clone_shared(&self) -> Option { + #[cfg(feature = "remote")] + match self { + Self::Http { + source, + request_id, + status_code, + } => { + return source + .downcast_ref::() + .map(|source| Self::Http { + source: Box::new(source.clone()), + request_id: request_id.clone(), + status_code: *status_code, + }); + } + Self::TableNotFound { name, source } => { + return source + .downcast_ref::() + .and_then(Self::clone_shared) + .map(|source| Self::TableNotFound { + name: name.clone(), + source: Box::new(source), + }); + } + _ => {} + } #[cfg(feature = "remote")] if let Self::ResponseInterrupted { request_id, diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 0f02d90cf..9f800d593 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -216,6 +216,7 @@ pub mod query; pub mod remote; pub mod rerankers; pub mod secrets; +pub mod server_info; pub mod sql; pub mod storage_integration; pub mod table; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 578e3bbab..92523ec34 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1242,16 +1242,39 @@ impl Database for RemoteDatabase { let handle = super::job::RemoteJob::new(self.client.clone(), job_id.to_string()); match crate::job::JobHandle::describe(&handle).await { Ok(description) => Ok(Job::opened(Box::new(handle), description)), - Err(Error::Http { - status_code: Some(StatusCode::NOT_FOUND), - .. - }) => Err(Error::JobNotFound { + Err( + error @ Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }, + ) => Err(Error::JobNotFound { job_id: job_id.to_string(), + source: Box::new(error), }), Err(err) => Err(err), } } + async fn server_info(&self) -> Result { + let req = self.client.get("/v1/server/info"); + let (request_id, response) = self.client.send(req).await?; + let response = match self.client.check_response(&request_id, response).await { + Ok(response) => response, + Err(Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }) => { + return Err(Error::NotSupported { + message: "Server build discovery requires a newer LanceDB server; \ + GET /v1/server/info returned 404 Not Found" + .into(), + }); + } + Err(error) => return Err(error), + }; + response.json().await.err_to_http(request_id) + } + async fn list_gpu_classes(&self) -> Result> { #[derive(serde::Deserialize)] struct Response { @@ -4155,6 +4178,106 @@ mod tests { } } + #[tokio::test] + async fn test_server_info_preserves_remote_provenance() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/server/info"); + http::Response::builder().status(200).body(serde_json::json!({ + "query_node": { "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" }, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_gpu_worker_image": "example.invalid/worker:configured", + "future_component": "ignored" + }).to_string()).unwrap() + }); + let info = conn.server_info().await.unwrap(); + let build = info.query_node.unwrap(); + assert_eq!(build.release, "1.2.3"); + assert_eq!(build.git_sha, "0123456789ab"); + assert_eq!(build.build_date.as_deref(), Some("2024-01-01T00:00:00Z")); + assert_eq!(info.function_worker_protocol_version, 25); + assert_eq!( + info.configured_gpu_worker_image.as_deref(), + Some("example.invalid/worker:configured") + ); + } + + #[tokio::test] + async fn test_server_info_error_provenance_survives_classification() { + for target in ["table", "job", "masked"] { + let conn = Connection::new_with_handler(move |_| { + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + if target == "masked" { + http::Response::builder() + .status(500) + .header("x-lancedb-server-build", server.to_string()) + .body("Internal server error".to_string()) + .unwrap() + } else { + http::Response::builder() + .status(404) + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let error = match target { + "table" => conn.open_table("missing").execute().await.unwrap_err(), + "job" => conn.open_job("missing").await.unwrap_err(), + _ => conn.server_info().await.unwrap_err(), + }; + match target { + "table" => assert!(matches!(&error, Error::TableNotFound { .. })), + "job" => assert!(matches!(&error, Error::JobNotFound { .. })), + _ => assert_eq!( + error.status_code(), + Some(http::StatusCode::INTERNAL_SERVER_ERROR) + ), + } + let server = error + .remote_error_metadata() + .unwrap() + .server + .as_ref() + .unwrap(); + assert_eq!(server.git_sha, "0123456789ab"); + assert_eq!(server.release, "1.2.3"); + let message = error.to_string(); + assert!(message.contains("0123456789ab"), "{message}"); + assert!(message.contains("2024-01-01T00:00:00Z"), "{message}"); + } + } + + #[tokio::test] + async fn test_server_info_distinguishes_unsupported_from_denied() { + for status in [404, 403] { + let conn = Connection::new_with_handler(move |_| { + http::Response::builder() + .status(status) + .body("unavailable") + .unwrap() + }); + let error = conn.server_info().await.unwrap_err(); + if status == 404 { + assert!( + matches!(error, Error::NotSupported { message } if message.contains("/v1/server/info")) + ); + } else { + assert!(matches!( + error, + Error::Http { + status_code: Some(http::StatusCode::FORBIDDEN), + .. + } + )); + } + } + } + #[tokio::test] async fn test_list_gpu_classes_reports_configured_hardware() { let conn = Connection::new_with_handler(|request| { @@ -4368,7 +4491,7 @@ mod tests { }); let err = conn.open_job("nope").await.unwrap_err(); assert!( - matches!(&err, Error::JobNotFound { job_id } if job_id == "nope"), + matches!(&err, Error::JobNotFound { job_id, .. } if job_id == "nope"), "{err:?}" ); } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 949b078e3..9c34f8f90 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -1797,6 +1797,11 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .map(str::to_owned) }; let metadata = crate::error::RemoteErrorMetadata { + server: status + .metadata() + .get_bin("x-lancedb-server-build-bin") + .and_then(|value| value.to_bytes().ok()) + .and_then(|value| serde_json::from_slice(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header(SQL_JOB_ID_METADATA_KEY), job_request_id: header("x-job-request-id"), @@ -1805,8 +1810,12 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .and_then(crate::error::parse_flight_resource_identity), }; let sql_job_id = metadata.job_id.clone(); + let mut message = status.message().to_owned(); + if let Some(server) = &metadata.server { + message.push_str(&format!(" [server: {server}]")); + } let error = Error::Sql { - message: status.message().into(), + message: message.clone(), request_id: request_id.into(), grpc_code: status.code() as i32, metadata: Box::new(metadata), @@ -1816,7 +1825,7 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro job_id: Some(sql_job_id.clone()), failure: Box::new(JobFailure { phase: None, - message: Some(status.message().into()), + message: Some(message), traceback: None, retryable: None, sql_job_id: Some(sql_job_id), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d94defac4..eb994f7dd 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -33,6 +33,53 @@ use crate::remote::table::RemoteTable; use crate::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; use crate::table::BaseTable; +#[test] +fn server_info_survives_flight_error_and_job_wrapping() { + for with_job in [false, true] { + let mut status = tonic::Status::invalid_argument("invalid query"); + status + .metadata_mut() + .insert("x-lancedb-error-code", "invalid_query".parse().unwrap()); + let build = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" + }) + .to_string(); + status.metadata_mut().insert_bin( + "x-lancedb-server-build-bin", + tonic::metadata::MetadataValue::from_bytes(build.as_bytes()), + ); + if with_job { + status + .metadata_mut() + .insert(SQL_JOB_ID_METADATA_KEY, "job-original".parse().unwrap()); + } + let error = sql_status_error("request-original", &status); + let text = error.to_string(); + assert!(text.contains("invalid query"), "{text}"); + assert!(text.contains("1.2.3"), "{text}"); + assert!(text.contains("0123456789ab"), "{text}"); + assert!(text.contains("2024-01-01T00:00:00Z"), "{text}"); + assert_eq!( + error.remote_error_metadata().unwrap().error_code.as_deref(), + Some("invalid_query") + ); + match error { + Error::JobFailed { job_id, .. } if with_job => { + assert_eq!(job_id.as_deref(), Some("job-original")) + } + Error::Sql { + grpc_code, + request_id, + .. + } if !with_job => { + assert_eq!(grpc_code, tonic::Code::InvalidArgument as i32); + assert_eq!(request_id, "request-original"); + } + other => panic!("unexpected error classification: {other}"), + } + } +} + #[derive(Debug, Default)] struct DelayedHeaderProvider { delay_next: AtomicBool, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index fdb547afa..dcceb4260 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1939,7 +1939,7 @@ fn base_media_type(content_type: &str) -> &str { fn unwrap_shared_error(arc: Arc) -> Error { match Arc::try_unwrap(arc) { Ok(err) => err, - Err(arc) => match &*arc { + Err(arc) => arc.clone_shared().unwrap_or_else(|| match &*arc { Error::TableNotFound { name, source } => Error::TableNotFound { name: name.clone(), source: source.to_string().into(), @@ -1947,7 +1947,7 @@ fn unwrap_shared_error(arc: Arc) -> Error { _ => Error::Runtime { message: arc.to_string(), }, - }, + }), } } @@ -1971,17 +1971,8 @@ async fn fetch_schema( let (request_id, response) = client.send_with_retry(request, None, true).await?; - if response.status() == StatusCode::NOT_FOUND { - let body = response.text().await.ok().unwrap_or_default(); - return Err(Error::TableNotFound { - name: table_name.to_string(), - source: Box::new(Error::Http { - source: body.into(), - request_id, - status_code: Some(StatusCode::NOT_FOUND), - }), - }); - } + let response = + RemoteTable::::handle_table_not_found(table_name, response, &request_id).await?; let response = client.check_response(&request_id, response).await?; freshness_headers.observe_headers(&freshness, response.headers()); @@ -4922,6 +4913,49 @@ mod tests { assert_eq!(schema, expected); } + #[tokio::test] + async fn test_server_info_survives_schema_cache_errors() { + let expected = crate::server_info::ServerBuildInfo { + release: "1.2.3".into(), + git_sha: "0123456789ab".into(), + build_date: Some("2024-01-01T00:00:00Z".into()), + }; + for header_only in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + let response = http::Response::builder().status(404); + if header_only { + response + .header("x-lancedb-server-build", server.to_string()) + .body("missing".to_string()) + .unwrap() + } else { + response + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let original = Arc::new(table.schema().await.unwrap_err()); + // Keep another reader's reference alive to exercise the shared result. + let shared = unwrap_shared_error(original.clone()); + for error in [original.as_ref(), &shared] { + assert!(matches!(error, Error::TableNotFound { name, .. } if name == "my_table")); + assert_eq!(error.status_code(), Some(StatusCode::NOT_FOUND)); + assert_eq!( + error + .remote_error_metadata() + .and_then(|metadata| metadata.server.as_ref()), + Some(&expected), + ); + assert!(error.to_string().contains("0123456789ab")); + } + } + } + #[tokio::test] async fn test_count_rows() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/server_info.rs b/rust/lancedb/src/server_info.rs new file mode 100644 index 000000000..48daf508b --- /dev/null +++ b/rust/lancedb/src/server_info.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Remote server provenance for diagnostics without submitting a query or job. + +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Immutable identity compiled into a server executable. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerBuildInfo { + /// Release of this executable. + pub release: String, + /// Git revision used to build the executable. + pub git_sha: String, + /// UTC RFC 3339 build timestamp, when known. + pub build_date: Option, +} + +impl fmt::Display for ServerBuildInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} (git {}, built {})", + self.release, + self.git_sha, + self.build_date.as_deref().unwrap_or("unknown") + ) + } +} + +/// Identity of the query node that answered a discovery request. +/// +/// Different requests can reach different versions during a rolling upgrade. +/// Configured images do not establish which version a running job uses. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerInfo { + /// The responding executable; absent if its identity was not initialized. + pub query_node: Option, + /// Lance library linked into the responding server. + pub lance_version: String, + /// LanceDB library linked into the responding server. + pub lancedb_version: String, + /// Function worker protocol supported by this server build. + pub function_worker_protocol_version: u16, + /// Configured query-node image, not an independently observed digest. + pub configured_query_node_image: Option, + /// Default CPU/job worker image; existing jobs can retain earlier pins. + pub configured_job_worker_image: Option, + /// CLI image configured for newly launched SQL jobs. + pub configured_sql_job_image: Option, + /// Configured GPU worker image, not an observation of a running worker. + pub configured_gpu_worker_image: Option, +} From f863ea5e0858f7a081206488ee7e33ec4e34d88d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 06:34:38 +0800 Subject: [PATCH 33/75] feat(rust): support cross-table blob copies in DataFusion (#4976) `INSERT INTO target SELECT ... FROM source` currently cannot copy Blob v2 descriptors into an independent table. This enables copies from a single native source snapshot through projections, filters, sorting, and limits, while preserving descriptor queries such as `SELECT payload.size`. Source-owned payloads become target-owned data, so subsequent source mutation, compaction, or deletion does not invalidate the copy; nested fields retain their named identity across metadata differences, child reordering, scalar casts, and nullable parents. External blobs remain URI/range references under the destination's existing authorization policy: a destination that independently registers the matching external base accepts the copy, while an unregistered destination rejects it without committing. Source base registrations are not transferred, and `allow_external_blob_outside_bases` is not relaxed. JOIN, UNION, aggregation, and computed descriptors are rejected during planning. This addresses the DataFusion cross-table copy portion of OSS-696; remote/cloud execution and Realtime/MemWAL remain outside this support boundary. Local acceptance covers 15 passing DataFusion Blob integration cases, including byte reads after physical source-directory deletion, authorized and unauthorized External ranges, and a source-read failure after an earlier partition has written an uncommitted data file, with both the live destination and an independently reopened manifest unchanged. Existing regression evidence also includes 195 DataFusion unit tests and 59 Blob integration tests. Rust formatting and whitespace checks passed. Remote-feature builds, cloud/S3 execution, clippy, and the full workspace suite were not run. --- rust/lancedb/src/table/datafusion.rs | 99 ++- .../src/table/datafusion/blob_materialize.rs | 615 +++++++++++++++ rust/lancedb/src/table/datafusion/insert.rs | 4 + rust/lancedb/tests/datafusion_blob_schema.rs | 707 +++++++++++++++++- 4 files changed, 1380 insertions(+), 45 deletions(-) create mode 100644 rust/lancedb/src/table/datafusion/blob_materialize.rs diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 81df7d300..22ec5caeb 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -4,6 +4,7 @@ //! This module contains adapters to allow LanceDB tables to be used as DataFusion table providers. mod blob_coerce; +mod blob_materialize; mod blob_nulls; pub mod cast; pub mod insert; @@ -31,7 +32,7 @@ use lance_core::{ datatypes::{Projection, Schema as LanceSchema}, }; -use super::{AnyQuery, BaseTable}; +use super::{AnyQuery, BaseTable, NativeTableExt}; use crate::{ Error, Result, query::{QueryExecutionOptions, QueryFilter, QueryRequest, Select}, @@ -199,7 +200,8 @@ impl ExecutionPlan for MetadataEraserExec { pub enum BlobSchema { /// Expose Blob v2 descriptors (`kind`, `position`, `size`, `blob_id`, `blob_uri`) /// and legacy v1 descriptors (`position`, `size`). Scans support all blob fields; - /// SQL INSERT into Blob v2 tables is unsupported. + /// SQL INSERT SELECT materializes descriptors from a single native-table + /// snapshot; remote and Realtime/MemWAL sources are not supported. #[default] Read, /// Expose Blob v2 write inputs (`data`, `uri`, `position`, `size`) and legacy @@ -213,9 +215,33 @@ pub enum BlobSchema { /// /// Defaults to [`BlobSchema::Read`], matching the descriptor schema produced by /// scans without fetching blob bytes. Use [`Self::with_blob_schema`] to enable -/// SQL INSERT into blob columns. Legacy v1 blobs expose descriptors in read mode -/// and `LargeBinary` inputs in write mode; write-mode descriptor scans fail with -/// a schema mismatch. Tables without blob columns behave the same in both modes. +/// SQL INSERT with logical blob inputs. In read mode, INSERT SELECT can copy +/// Blob v2 descriptors from a single native-table snapshot into target-owned +/// payloads, including projections, filters, sorting, and limits. JOIN, UNION, +/// aggregation, and computed descriptors fail during planning because their +/// source row addresses cannot be established safely. Legacy v1 blobs expose +/// descriptors in read mode and `LargeBinary` inputs in write mode; write-mode +/// descriptor scans fail with a schema mismatch. Tables without blob columns +/// behave the same in both modes. +/// Descriptor copying requires a native source table; remote and Realtime/MemWAL +/// sources are not supported by this materialization path. +/// +/// With read adapters registered as `source` and `target`, copying blobs needs +/// no payload UDF or explicit system columns: +/// +/// ```sql +/// INSERT INTO target SELECT * FROM source WHERE id > 10; +/// ``` +/// +/// The target owns the copied payloads independently of subsequent source +/// compaction or deletion. External URI references retain their external +/// storage semantics and remain subject to the target's registered external +/// bases; copying a descriptor does not authorize a new external location. +/// +/// Materialization allocates payload bytes for each input batch outside the +/// DataFusion memory pool. For large blobs, configure a conservative +/// `SessionConfig::with_batch_size`; the pool limit alone does not bound these +/// allocations, and a single blob can still exceed that limit. #[derive(Debug)] pub struct BaseTableAdapter { table: Arc, @@ -440,13 +466,55 @@ impl TableProvider for BaseTableAdapter { ..Default::default() }; - let plan = self - .table - .create_plan(&AnyQuery::Query(query), options) + // The scan and any later INSERT rewrite must use the same snapshot, + // even if the live table advances between planning and execution. + let projects_descriptors = match projection { + Some(indices) => indices + .iter() + .any(|index| blob_nulls::has_descriptor(provider_schema.field(*index))), + None => provider_schema + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)), + }; + let snapshot = if self.blob_schema == BlobSchema::Read + && self.table.as_native().is_some() + && projects_descriptors + { + Some( + self.table + .query_snapshot() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?, + ) + } else { + None + }; + let source = snapshot.as_ref().unwrap_or(&self.table); + let plan = source + .create_plan(&AnyQuery::Query(query.clone()), options.clone()) .map_err(|err| DataFusionError::External(err.into())) .await?; let plan = blob_nulls::mask_plan(plan)?; - let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let mut plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + if let Some(snapshot) = snapshot + && plan + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + let dataset = snapshot + .as_native() + .unwrap() + .dataset + .get() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + plan = Arc::new(blob_materialize::BlobScanExec::new( + plan, snapshot, dataset, query, options, + )); + } if self.blob_schema == BlobSchema::Write { let schema = match projection { Some(projection) => Arc::new(provider_schema.project(projection)?), @@ -509,17 +577,30 @@ impl TableProvider for BaseTableAdapter { input: Arc, insert_op: InsertOp, ) -> DataFusionResult> { + let has_descriptors = input + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + || (blob_materialize::has_source_scan(&input) + && input + .schema() + .fields() + .iter() + .any(|field| blob_materialize::has_descriptor(field))); if self.blob_schema == BlobSchema::Read && self .schema .fields() .iter() .any(|field| blob_nulls::has_descriptor(field)) + && !has_descriptors { return Err(DataFusionError::NotImplemented( "SQL INSERT into Blob v2 tables requires BlobSchema::Write".into(), )); } + let input = blob_materialize::materialize(input, self.write_schema.as_ref()).await?; let mode = match insert_op { InsertOp::Append => WriteMode::Append, InsertOp::Overwrite => WriteMode::Overwrite, diff --git a/rust/lancedb/src/table/datafusion/blob_materialize.rs b/rust/lancedb/src/table/datafusion/blob_materialize.rs new file mode 100644 index 000000000..22d0a023d --- /dev/null +++ b/rust/lancedb/src/table/datafusion/blob_materialize.rs @@ -0,0 +1,615 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Preserve scan provenance until INSERT can materialize source-owned blobs. +//! +//! External descriptors remain references and must satisfy the destination's +//! existing external-base policy; source authorization grants no target trust. + +use std::fmt; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use datafusion_common::{DataFusionError, Result, tree_node::TreeNodeRecursion}; +use datafusion_execution::{SendableRecordBatchStream, TaskContext}; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::{ + PhysicalExpr, ScalarFunctionExpr, + expressions::{CastExpr, Column, Literal}, +}; +use datafusion_physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, + coalesce_partitions::CoalescePartitionsExec, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + filter::FilterExec, + limit::{GlobalLimitExec, LocalLimitExec}, + projection::ProjectionExec, + repartition::RepartitionExec, + sorts::{sort::SortExec, sort_preserving_merge::SortPreservingMergeExec}, + stream::RecordBatchStreamAdapter, +}; +use futures::{FutureExt, TryStreamExt, future::BoxFuture}; +use lance::{Dataset, dataset::BlobV2BatchRewritePlan}; +use lance_core::{ + ROW_ADDR, + datatypes::{BlobV2Layout, Schema as LanceSchema}, +}; + +use super::{BaseTable, MetadataEraserExec, blob_nulls}; +use crate::{ + query::{QueryExecutionOptions, QueryRequest, Select}, + table::AnyQuery, +}; + +const HIDDEN_ROW_ADDR: &str = "__lancedb_blob_rowaddr"; + +// Expressions such as CASE can retain the descriptor layout while dropping +// extension metadata. They still require proven provenance before writing. +pub(super) fn has_descriptor(field: &Field) -> bool { + contains_layout(field.data_type(), BlobV2Layout::Descriptor) +} + +fn descriptor_for_target(input: &Field, target: &Field) -> bool { + if crate::blob::is_blob(target) { + return matches!(input.data_type(), DataType::Struct(fields) + if BlobV2Layout::classify(fields) == Some(BlobV2Layout::Descriptor)); + } + match (input.data_type(), target.data_type()) { + (DataType::Struct(input), DataType::Struct(target)) => target.iter().any(|target| { + input + .find(target.name()) + .is_some_and(|(_, input)| descriptor_for_target(input, target)) + }), + ( + DataType::List(input) | DataType::LargeList(input) | DataType::FixedSizeList(input, _), + DataType::List(target) + | DataType::LargeList(target) + | DataType::FixedSizeList(target, _), + ) => descriptor_for_target(input, target), + _ => false, + } +} + +fn contains_layout(data_type: &DataType, layout: BlobV2Layout) -> bool { + match data_type { + DataType::Struct(fields) => { + BlobV2Layout::classify(fields) == Some(layout) + || fields + .iter() + .any(|field| contains_layout(field.data_type(), layout)) + } + DataType::List(item) | DataType::LargeList(item) | DataType::FixedSizeList(item, _) => { + contains_layout(item.data_type(), layout) + } + _ => false, + } +} + +pub(super) fn has_source_scan(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.children().iter().any(|child| has_source_scan(child)) +} + +#[expect( + deprecated, + reason = "DataFusion 55 still accepts CoalesceBatchesExec plans" +)] +fn preserves_row_identity(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input + .downcast_ref::() + .is_some() + || input.downcast_ref::().is_some() +} + +fn provenance_error(detail: impl fmt::Display) -> DataFusionError { + DataFusionError::Plan(format!( + "Blob INSERT SELECT requires descriptors from one source table snapshot with an \ + unambiguous row address; {detail}. JOIN, UNION, aggregation, and computed blob \ + descriptors are not supported" + )) +} + +/// A transparent scan boundary. It retains the snapshot and scan request, rather +/// than exposing a system column to SELECT * or fetching any payloads on reads. +#[derive(Debug)] +pub(super) struct BlobScanExec { + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, +} + +impl BlobScanExec { + pub(super) fn new( + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, + ) -> Self { + Self { + input, + source, + dataset, + query, + options, + } + } + + async fn with_row_address(&self) -> Result { + let mut query = self.query.clone(); + let Select::Columns(columns) = &mut query.select else { + return Err(provenance_error( + "source scan has no explicit column projection", + )); + }; + if !columns.iter().any(|name| name == ROW_ADDR) { + columns.push(ROW_ADDR.to_owned()); + } + let plan = self + .source + .create_plan(&AnyQuery::Query(query), self.options.clone()) + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + let plan = blob_nulls::mask_plan(plan)?; + let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let schema = plan.schema(); + let mut projection: Vec<(Arc, String)> = self + .input + .schema() + .fields() + .iter() + .map(|field| { + Ok(( + Arc::new(Column::new(field.name(), schema.index_of(field.name())?)) as _, + field.name().clone(), + )) + }) + .collect::>()?; + projection.push(( + Arc::new(Column::new(ROW_ADDR, schema.index_of(ROW_ADDR)?)), + HIDDEN_ROW_ADDR.into(), + )); + Ok(Provenance { + plan: Arc::new(ProjectionExec::try_new(projection, plan)?), + dataset: self.dataset.clone(), + fields: self + .input + .schema() + .fields() + .iter() + .map(|field| Some(field.name().clone())) + .collect(), + }) + } +} + +impl DisplayAs for BlobScanExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "BlobScanExec: version={}", + self.dataset.version().version + ) + } +} + +impl ExecutionPlan for BlobScanExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "BlobScanExec" + } + fn properties(&self) -> &Arc { + self.input.properties() + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid scan children"))?; + Ok(Arc::new(Self::new( + input, + self.source.clone(), + self.dataset.clone(), + self.query.clone(), + self.options.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + self.input.execute(partition, context) + } +} + +struct Provenance { + plan: Arc, + dataset: Arc, + // Source field path for each output column, before the hidden address. + fields: Vec>, +} + +fn source_field(expr: &Arc, fields: &[Option]) -> Option { + if let Some(column) = expr.downcast_ref::() { + return fields.get(column.index()).cloned().flatten(); + } + let call = expr.downcast_ref::()?; + call.fun().inner().downcast_ref::()?; + let (root, path) = call.args().split_first()?; + let mut source = source_field(root, fields)?; + for component in path { + let name = component + .downcast_ref::()? + .value() + .try_as_str() + .flatten()?; + source.push('.'); + source.push_str(name); + } + Some(source) +} + +fn with_provenance(input: Arc) -> BoxFuture<'static, Result> { + async move { + if let Some(scan) = input.downcast_ref::() { + return scan.with_row_address().await; + } + let children = input.children(); + // An explicit allowlist keeps row identity from silently propagating + // through a future operator that changes cardinality or column meaning. + if children.len() != 1 || !preserves_row_identity(&input) { + return Err(provenance_error(format!( + "cannot establish provenance through {}", + input.name() + ))); + } + let mut provenance = with_provenance(children[0].clone()).await?; + if let Some(projection) = input.downcast_ref::() { + let fields = projection + .expr() + .iter() + .map(|expr| source_field(&expr.expr, &provenance.fields)) + .collect(); + let mut expressions: Vec<(Arc, String)> = projection + .expr() + .iter() + .map(|expr| (expr.expr.clone(), expr.alias.clone())) + .collect(); + expressions.push(( + Arc::new(Column::new( + HIDDEN_ROW_ADDR, + provenance.plan.schema().fields().len() - 1, + )), + HIDDEN_ROW_ADDR.into(), + )); + provenance.plan = Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + provenance.fields = fields; + } else { + if input.schema() != children[0].schema() { + return Err(provenance_error(format!( + "{} changes the source schema", + input.name() + ))); + } + provenance.plan = input.replace_children( + vec![provenance.plan], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + } + Ok(provenance) + } + .boxed() +} + +/// Defer only a container coercion whose Blob leaves retain their named paths. +/// Descriptor leaves are atomic: casting their members is never provenance. +fn can_defer_blob_cast(source: &Field, cast_type: &DataType, target: &Field) -> bool { + if crate::blob::is_blob(target) { + let (DataType::Struct(source), DataType::Struct(cast)) = (source.data_type(), cast_type) + else { + return false; + }; + return BlobV2Layout::classify(source) == Some(BlobV2Layout::Descriptor) + && (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Logical) + || (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Descriptor) + && source.len() == cast.len() + && source.iter().zip(cast).all(|(source, cast)| { + source.name() == cast.name() && source.data_type() == cast.data_type() + }))); + } + match (source.data_type(), cast_type, target.data_type()) { + (DataType::Struct(source), DataType::Struct(cast), DataType::Struct(target)) => { + source.len() == cast.len() + && source.len() == target.len() + && target.iter().all(|target| { + source + .find(target.name()) + .zip(cast.find(target.name())) + .is_some_and(|((_, source), (_, cast))| { + can_defer_blob_cast(source, cast.data_type(), target) + }) + }) + } + (DataType::List(source), DataType::List(cast), DataType::List(target)) + | (DataType::LargeList(source), DataType::LargeList(cast), DataType::LargeList(target)) => { + can_defer_blob_cast(source, cast.data_type(), target) + } + ( + DataType::FixedSizeList(source, source_len), + DataType::FixedSizeList(cast, cast_len), + DataType::FixedSizeList(target, target_len), + ) => { + source_len == cast_len + && source_len == target_len + && can_defer_blob_cast(source, cast.data_type(), target) + } + _ => !has_descriptor(source) && cast_type == target.data_type(), + } +} + +pub(super) async fn materialize( + input: Arc, + target_schema: &Schema, +) -> Result> { + if !target_schema + .fields() + .iter() + .any(|field| crate::blob::field_tree_has_blob_v2(field)) + { + return Ok(input); + } + // INSERT may cast containers for metadata, field order, scalar siblings, + // or a Write adapter's logical layout. Bind the original Blob leaves and + // materialize before applying the target coercion. Other expressions still + // have to pass the Column/GetField provenance checks below. + let input = if let Some(projection) = input.downcast_ref::() { + let mut changed = false; + let expressions = projection + .expr() + .iter() + .map(|projected| { + let mut expr = projected.expr.clone(); + if let Some(cast) = expr.downcast_ref::() + && let Ok(target) = target_schema.field_with_name(&projected.alias) + && crate::blob::field_tree_has_blob_v2(target) + && let source = cast + .expr() + .return_field(projection.input().schema().as_ref())? + && has_descriptor(&source) + { + if !can_defer_blob_cast( + &source, + &cast.data_type(projection.input().schema().as_ref())?, + target, + ) { + return Err(provenance_error(format!( + "cast of column '{}' does not preserve Blob leaf identity", + projected.alias + ))); + } + expr = cast.expr().clone(); + changed = true; + } + Ok((expr, projected.alias.clone())) + }) + .collect::>>()?; + if changed { + Arc::new(ProjectionExec::try_new( + expressions, + projection.input().clone(), + )?) as Arc + } else { + input + } + } else { + input + }; + let rewrite_columns: Vec = input + .schema() + .fields() + .iter() + .map(|field| { + target_schema + .field_with_name(field.name()) + .is_ok_and(|target| descriptor_for_target(field, target)) + }) + .collect(); + if !rewrite_columns.iter().any(|rewrite| *rewrite) { + return Ok(input); + } + let provenance = with_provenance(input.clone()).await?; + let mut source_schema = LanceSchema::default(); + let mut expressions: Vec<(Arc, String)> = Vec::new(); + for (index, (field, source)) in input + .schema() + .fields() + .iter() + .zip(&provenance.fields) + .enumerate() + { + let name = format!("__lancedb_blob_column_{index}"); + if rewrite_columns[index] { + let source = source.as_ref().ok_or_else(|| { + provenance_error(format!("column '{}' has no source", field.name())) + })?; + let mut source_field = provenance + .dataset + .schema() + .field(source) + .ok_or_else(|| provenance_error(format!("source field '{source}' is missing")))? + .clone(); + if !crate::blob::field_tree_has_blob_v2(&Field::from(&source_field)) { + return Err(provenance_error(format!( + "source field '{source}' is not a Blob v2 column" + ))); + } + source_field.name = name.clone(); + source_schema.fields.push(source_field); + } + expressions.push((Arc::new(Column::new(field.name(), index)), name)); + } + expressions.push(( + Arc::new(Column::new(HIDDEN_ROW_ADDR, provenance.fields.len())), + ROW_ADDR.into(), + )); + let plan: Arc = + Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + // preserve_managed=false forces even managed source payloads to become + // target-owned bytes instead of retaining source storage references. + let rewrite = Arc::new(BlobV2BatchRewritePlan::try_new( + &source_schema, + plan.schema().as_ref(), + false, + false, + )?); + let schema = Arc::new(Schema::new( + rewrite + .output_schema() + .fields() + .iter() + .zip(input.schema().fields()) + .map(|(rewritten, original)| rewritten.as_ref().clone().with_name(original.name())) + .collect::>(), + )); + let plan = Arc::new(MaterializeBlobsExec::new( + plan, + provenance.dataset, + rewrite, + schema, + )); + super::cast::cast_to_table_schema(plan, target_schema) + .map_err(|error| DataFusionError::External(Box::new(error))) +} + +struct MaterializeBlobsExec { + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + properties: Arc, +} + +impl fmt::Debug for MaterializeBlobsExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MaterializeBlobsExec") + .field("input", &self.input) + .finish_non_exhaustive() + } +} + +impl MaterializeBlobsExec { + fn new( + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + ) -> Self { + // Rewriting changes column types; descriptor equivalences/orderings do + // not describe the resulting payload structs. + let properties = Arc::new(PlanProperties::new( + datafusion_physical_expr::EquivalenceProperties::new(schema.clone()), + datafusion_physical_expr::Partitioning::UnknownPartitioning( + input.output_partitioning().partition_count(), + ), + input.properties().emission_type, + input.properties().boundedness, + )); + Self { + input, + dataset, + rewrite, + schema, + properties, + } + } +} + +impl DisplayAs for MaterializeBlobsExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "MaterializeBlobsExec") + } +} + +impl ExecutionPlan for MaterializeBlobsExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "MaterializeBlobsExec" + } + fn properties(&self) -> &Arc { + &self.properties + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid rewrite children"))?; + Ok(Arc::new(Self::new( + input, + self.dataset.clone(), + self.rewrite.clone(), + self.schema.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + let dataset = self.dataset.clone(); + let rewrite = self.rewrite.clone(); + let schema = self.schema.clone(); + let stream = self + .input + .execute(partition, context)? + .and_then(move |batch| { + let dataset = dataset.clone(); + let rewrite = rewrite.clone(); + let schema = schema.clone(); + async move { + let batch = rewrite.transform_batch(&dataset, batch).await?; + Ok(RecordBatch::try_new(schema, batch.columns().to_vec())?) + } + }); + Ok(Box::pin(RecordBatchStreamAdapter::new( + self.schema.clone(), + stream, + ))) + } +} diff --git a/rust/lancedb/src/table/datafusion/insert.rs b/rust/lancedb/src/table/datafusion/insert.rs index ec1e603d2..a2d5f34c9 100644 --- a/rust/lancedb/src/table/datafusion/insert.rs +++ b/rust/lancedb/src/table/datafusion/insert.rs @@ -195,6 +195,7 @@ impl ExecutionPlan for InsertExec { context: Arc, ) -> DataFusionResult { let input_stream = self.input.execute(partition, context)?; + let input_plan = self.input.clone(); let dataset = self.dataset.clone(); let mut write_params = self.write_params.clone(); let partial_transactions = self.partial_transactions.clone(); @@ -227,6 +228,9 @@ impl ExecutionPlan for InsertExec { )); let stream = futures::stream::once(async move { + // Source blob snapshots must outlive the final target commit, not + // only the consumption of the input stream. + let _input_plan = input_plan; if let Some(tracker) = tracker && write_params.write_progress.is_none() { diff --git a/rust/lancedb/tests/datafusion_blob_schema.rs b/rust/lancedb/tests/datafusion_blob_schema.rs index d51c182f6..5af3122ab 100644 --- a/rust/lancedb/tests/datafusion_blob_schema.rs +++ b/rust/lancedb/tests/datafusion_blob_schema.rs @@ -571,66 +571,701 @@ async fn legacy_blob_write_mode_rejects_descriptor_scans_and_keeps_scalar_scans( } #[tokio::test] -async fn copying_non_null_descriptors_between_tables_commits_no_rows() { +async fn copying_descriptors_materializes_payloads_and_preserves_snapshot() { + use std::collections::HashMap; + use std::num::NonZeroUsize; + + use lancedb::blob::{BlobOptions, blob_with_options}; + use lancedb::table::OptimizeAction; + + for managed in [false, true] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let payload = blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(8), + dedicated_size_threshold: NonZeroUsize::new(32), + }, + ); + let values: Vec> = vec![ + Some(b"hi"), + Some(&[2; 16]), + Some(&[3; 64]), + None, + Some(b""), + Some(b"skip"), + ]; + let schema = Arc::new(Schema::new_with_metadata( + vec![Field::new("id", DataType::Int64, false), payload], + HashMap::from([("lance.blob.managed".into(), managed.to_string())]), + )); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2, 3, 4, 5, 6])), + blob_inputs(values.clone()), + ], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_batch_size(2) + .with_target_partitions(2), + ); + register(&ctx, &source, BlobSchema::Read).await; + // Descriptor queries and SELECT * retain their original read schema. + let sizes = sql(&ctx, "SELECT payload.size FROM docs ORDER BY id").await; + assert_eq!( + sizes + .column(0) + .as_primitive::() + .value(2), + 64 + ); + assert_eq!(sql(&ctx, "SELECT * FROM docs").await.num_columns(), 2); + let kinds = sql(&ctx, "SELECT payload.kind FROM docs ORDER BY id").await; + let kinds = kinds + .column(0) + .as_primitive::(); + if !managed { + assert_eq!( + kinds.value(0), + lance_core::datatypes::BlobKind::Inline as u8 + ); + assert_eq!( + kinds.value(1), + lance_core::datatypes::BlobKind::Packed as u8 + ); + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Dedicated as u8 + ); + } else { + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Managed as u8 + ); + } + let (_destination_tmp, destination) = empty_table(vec![ + blob("copied", true), + Field::new("id", DataType::Int64, false), + ]) + .await; + let writer = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode); + ctx.register_table("destination", Arc::new(writer)).unwrap(); + let plan = ctx.sql("INSERT INTO destination (id, copied) SELECT id + 10, payload AS copied FROM docs WHERE id > 0 AND (payload.size IS NULL OR payload.size < 100) ORDER BY id DESC LIMIT 5 OFFSET 1") + .await.unwrap().create_physical_plan().await.unwrap(); + // A live-table change after planning must not change the source + // version used to decode the descriptors in this insert. + source.delete("id = 1").await.unwrap(); + datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(destination.count_rows(None).await.unwrap(), 5); + source.optimize(OptimizeAction::All).await.unwrap(); + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let reader = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID]) + .unwrap(); + ctx.register_table("copied_rows", Arc::new(reader)).unwrap(); + let ids = sql(&ctx, "SELECT _rowid FROM copied_rows ORDER BY id").await; + let ids = ids + .column(0) + .as_primitive::() + .values(); + assert_eq!( + destination.fetch_blobs("copied", ids).await.unwrap(), + LargeBinaryArray::from(values[..5].to_vec()) + ); + } + } +} + +#[tokio::test] +async fn copying_nested_descriptors_preserves_parent_nulls_and_field_identity() { + use arrow_array::Int32Array; + use lancedb::blob::{BlobOptions, blob_with_options}; + + for difference in ["metadata", "order", "scalar"] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let children = vec![ + Arc::new(Field::new("note", DataType::Utf8, true)), + Arc::new(Field::new("rank", DataType::Int32, true)), + Arc::new(blob_with_options( + "clip", + true, + BlobOptions { + inline_size_threshold: Some(8), + ..Default::default() + }, + )), + ]; + let extra_field = Field::new("extra", DataType::Struct(children.clone().into()), true); + let extra = StructArray::new( + children.into(), + vec![ + Arc::new(StringArray::from(vec![ + Some("a"), + Some("hidden"), + Some("c"), + ])), + Arc::new(Int32Array::from(vec![1, 2, 3])), + blob_inputs(vec![Some(b"hi"), Some(b"hidden"), Some(b"")]), + ], + Some(NullBuffer::from(vec![true, false, true])), + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + extra_field, + ])), + vec![Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let mut target_children = vec![ + Field::new("note", DataType::Utf8, true), + Field::new( + "rank", + if difference == "scalar" { + DataType::Int64 + } else { + DataType::Int32 + }, + true, + ), + blob("clip", true), + ]; + if difference == "order" { + target_children.swap(0, 2); + } + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + Field::new("extra", DataType::Struct(target_children.into()), true), + blob("flattened", true), + ]) + .await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + for expression in [ + "CASE WHEN id = 1 THEN extra ELSE NULL END", + "named_struct('note', extra.note, 'rank', extra.rank, 'clip', extra.clip)", + ] { + let query = format!( + "INSERT INTO destination SELECT id, {expression} AS extra, extra.clip AS flattened FROM docs" + ); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{difference}, {mode:?}: {error}" + ); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } + sql(&ctx, "INSERT INTO destination SELECT id, extra, extra.clip AS flattened FROM docs ORDER BY id DESC").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let ids = row_ids(&ctx, &destination).await; + let expected = + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, Some(b"".as_slice())]); + assert_eq!( + destination.fetch_blobs("extra.clip", &ids).await.unwrap(), + expected, + "{difference}, {mode:?}" + ); + assert_eq!( + destination.fetch_blobs("flattened", &ids).await.unwrap(), + expected + ); + let nested = sql(&ctx, "SELECT extra FROM read_docs ORDER BY id").await; + let extra = nested.column(0).as_struct(); + assert!(extra.is_null(1)); + assert_eq!( + extra + .column_by_name("note") + .unwrap() + .as_string::() + .value(2), + "c" + ); + let rank = extra.column_by_name("rank").unwrap(); + if difference == "scalar" { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } else { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } + } + } +} + +#[tokio::test] +async fn ordinary_descriptor_shaped_structs_remain_plain_data() { + let fields = vec![ + Field::new("id", DataType::Int64, false), + Field::new( + "raw", + DataType::Struct( + vec![ + Field::new("kind", DataType::UInt8, true), + Field::new("position", DataType::UInt64, true), + Field::new("size", DataType::UInt64, true), + Field::new("blob_id", DataType::UInt32, true), + Field::new("blob_uri", DataType::Utf8, true), + ] + .into(), + ), + true, + ), + ]; + let (source_tmp, source) = empty_table(fields.clone()).await; + let (_destination_tmp, destination) = empty_table(fields).await; + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + sql(&ctx, "INSERT INTO docs VALUES (1, named_struct('kind', 1, 'position', 2, 'size', 3, 'blob_id', 4, 'blob_uri', 'plain data'))").await; + let expected = sql(&ctx, "SELECT * FROM docs").await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + sql(&ctx, "INSERT INTO destination SELECT * FROM docs").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let actual = sql(&ctx, "SELECT * FROM destination").await; + assert_eq!(actual.columns(), expected.columns()); +} + +#[tokio::test] +async fn ambiguous_descriptor_sources_fail_during_planning_without_writing() { let (_tmp, source) = empty_table(vec![ Field::new("id", DataType::Int64, false), blob("payload", true), ]) .await; - let ctx = SessionContext::new_with_config( - SessionConfig::new() - .with_batch_size(1) - .with_target_partitions(1), - ); + let ctx = SessionContext::new(); register(&ctx, &source, BlobSchema::Write).await; sql( &ctx, "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", ) .await; - sql(&ctx, "INSERT INTO docs VALUES (2, NULL)").await; register(&ctx, &source, BlobSchema::Read).await; - let (_dest_tmp, destination) = empty_table( - source - .schema() - .await - .unwrap() - .fields() - .iter() - .map(|f| f.as_ref().clone()) - .collect(), - ) + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) .await; let writer = BaseTableAdapter::try_new(destination.base_table().clone()) .await - .unwrap() - .with_blob_schema(BlobSchema::Write); + .unwrap(); ctx.register_table("destination", Arc::new(writer)).unwrap(); let version = destination.version().await.unwrap(); - // The null row is valid and reaches the writer before the non-null - // descriptor. Even if it is written to a fragment, it must not be committed. - let plan = ctx - .sql("INSERT INTO destination SELECT id, payload FROM docs ORDER BY id DESC") + for select in [ + "SELECT a.id, a.payload FROM docs a JOIN docs b ON a.id = b.id", + "SELECT id, payload FROM docs UNION ALL SELECT id, payload FROM docs", + "SELECT id, payload FROM docs GROUP BY id, payload", + "SELECT id, CASE WHEN id = 1 THEN payload ELSE NULL END AS payload FROM docs", + ] { + let query = format!("INSERT INTO destination {select}"); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{query}: {error}" + ); + } + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + assert_eq!(destination.version().await.unwrap(), version); +} + +#[tokio::test] +async fn external_descriptor_copy_obeys_destination_bases_and_preserves_ranges() { + use lance::dataset::WriteParams; + use lance_core::datatypes::BlobKind; + use lance_table::format::BasePath; + use lancedb::table::WriteOptions; + + let external_tmp = tempdir().unwrap(); + let payload = b"0123456789abcdef"; + let path = external_tmp.path().join("payload.bin"); + std::fs::write(&path, payload).unwrap(); + let uri = url::Url::from_file_path(&path).unwrap().to_string(); + let base_uri = url::Url::from_directory_path(external_tmp.path()) + .unwrap() + .to_string(); + let base = |id| BasePath { + id, + name: Some("external".into()), + path: base_uri.clone(), + is_dataset_root: false, + }; + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ])); + let DataType::Struct(children) = schema.field(1).data_type().clone() else { + unreachable!() + }; + let input = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + Arc::new(StructArray::new( + children, + vec![ + Arc::new(LargeBinaryArray::from(vec![ + None, + Some(b"inline".as_slice()), + ])), + Arc::new(StringArray::from(vec![Some(uri.as_str()), None])), + Arc::new(UInt64Array::from(vec![Some(4), None])), + Arc::new(UInt64Array::from(vec![Some(6), None])), + ], + None, + )), + ], + ) + .unwrap(); + for source_registered in [false, true] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let source = db + .create_empty_table("source", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: source_registered.then(|| vec![base(7)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + source + .add(input.clone()) + .allow_external_blob_outside_bases(!source_registered) + .execute() + .await + .unwrap(); + for mode in [BlobSchema::Read, BlobSchema::Write] { + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let descriptor = sql(&ctx, "SELECT payload.blob_id FROM docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + if source_registered { 7 } else { 0 } + ); + for authorized in [false, true] { + let destination_tmp = tempdir().unwrap(); + let destination_db = connect(destination_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let destination = destination_db + .create_empty_table("destination", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: authorized.then(|| vec![base(11)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + ctx.deregister_table("destination").unwrap(); + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let result = ctx + .sql("INSERT INTO destination SELECT * FROM docs ORDER BY id") + .await + .unwrap() + .collect() + .await; + if !authorized { + let error = result.unwrap_err().to_string(); + assert!( + error.contains("outside registered external bases"), + "{error}" + ); + let reopened = destination_db + .open_table("destination") + .execute() + .await + .unwrap(); + assert_eq!(reopened.version().await.unwrap(), version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); + // A logical URI input has the same destination authorization boundary. + ctx.register_table( + "logical_target", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write), + ), + ) + .unwrap(); + let error = ctx.sql(&format!("INSERT INTO logical_target SELECT 3, named_struct('data', NULL, 'uri', '{uri}')")).await.unwrap().collect().await.unwrap_err().to_string(); + assert!( + error.contains("allow_external_blob_outside_bases"), + "{error}" + ); + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } else { + result.unwrap(); + let ids = row_ids(&ctx, &destination).await; + let descriptor = sql(&ctx, "SELECT payload.kind, payload.blob_id, payload.blob_uri, payload.position, payload.size FROM read_docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + BlobKind::External as u8 + ); + assert_eq!( + descriptor + .column(1) + .as_primitive::() + .value(0), + 11 + ); + assert_eq!( + descriptor.column(2).as_string::().value(0), + "payload.bin" + ); + assert_eq!( + descriptor + .column(3) + .as_primitive::() + .value(0), + 4 + ); + assert_eq!( + descriptor + .column(4) + .as_primitive::() + .value(0), + 6 + ); + assert_eq!( + destination.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![ + Some(&payload[4..10]), + Some(b"inline".as_slice()) + ]) + ); + let files = destination.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[0].as_ref().unwrap(); + assert_eq!(file.uri(), Some("payload.bin")); + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let registered = &dataset.manifest().base_paths[&11]; + let resolved = + url::Url::parse(&format!("{}/", registered.path.trim_end_matches('/'))) + .unwrap() + .join(file.uri().unwrap()) + .unwrap(); + assert_eq!(resolved.as_str(), uri); + assert_eq!(file.position(), Some(4)); + assert_eq!(file.size(), 6); + } + } + } + } +} + +#[tokio::test] +async fn source_payload_failure_after_written_partition_does_not_commit() { + use datafusion_physical_plan::{ + ExecutionPlanProperties, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + union::UnionExec, + }; + use futures::TryStreamExt; + use lancedb::blob::{BlobOptions, blob_with_options}; + use std::num::NonZeroUsize; + + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(0), + dedicated_size_threshold: NonZeroUsize::new(1), + }, + ), + ])); + let source = db + .create_table( + "docs", + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + blob_inputs(vec![Some(&[1; 64]), Some(&[2; 64])]), + ], + ) + .unwrap(), + ) + .execute() + .await + .unwrap(); + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_target_partitions(1) + .with_batch_size(1), + ); + register(&ctx, &source, BlobSchema::Read).await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + let first = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 1") .await .unwrap() .create_physical_plan() .await .unwrap(); - let error = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + let second = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 2") .await - .unwrap_err(); - assert!(error.to_string().contains("blob"), "{error}"); + .unwrap() + .create_physical_plan() + .await + .unwrap(); + assert_eq!(first.name(), "InsertExec"); + assert_eq!(second.name(), "InsertExec"); + // Combine already validated SQL inputs only to control partition scheduling: + // finish one real uncommitted write before faulting the next payload read. + let input = UnionExec::try_new(vec![ + first.children()[0].clone(), + second.children()[0].clone(), + ]) + .unwrap(); + assert_eq!(input.output_partitioning().partition_count(), 2); + let insert = first + .replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let batches: Vec = insert + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 1 + ); assert_eq!(destination.count_rows(None).await.unwrap(), 0); assert_eq!(destination.version().await.unwrap(), version); - sql( - &ctx, - "INSERT INTO destination SELECT id, payload FROM docs WHERE payload IS NULL", - ) - .await; - let ids = row_ids(&ctx, &destination).await; - assert_eq!(ids.len(), 1); - assert_eq!( - destination.fetch_blobs("payload", &ids).await.unwrap(), - LargeBinaryArray::from(vec![None::<&[u8]>]) + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let data_dir = _destination_tmp.path().join("docs.lance").join("data"); + assert!( + std::fs::read_dir(data_dir).unwrap().next().is_some(), + "first partition must have written a data file" ); + let ids = row_ids(&ctx, &source).await; + let files = source.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[1].as_ref().unwrap(); + assert_eq!( + file.kind(), + Some(lance_core::datatypes::BlobKind::Dedicated) + ); + let missing_path = std::path::Path::new("/").join(file.data_path().unwrap().as_ref()); + drop(files); + std::fs::remove_file(&missing_path).unwrap(); + let error = insert + .execute(1, ctx.task_ctx()) + .unwrap() + .try_collect::>() + .await + .unwrap_err() + .to_string(); + assert!( + error.contains(missing_path.file_name().unwrap().to_str().unwrap()), + "{error}" + ); + // Check both the live handle and an independently reopened manifest. + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + let reopened = lance::Dataset::open(dataset.uri()).await.unwrap(); + assert_eq!(reopened.version().version, version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); } From 9302287bed205bc017979681fa31b9b8e6ae450f Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 14:57:00 -0800 Subject: [PATCH 34/75] fix: accept defining queries in Python materialized views (#4980) Python materialized-view creation now accepts a complete defining SQL query across sync, async, remote, and namespace connections, including creation jobs: ```python view = db.create_materialized_view( "events_by_kind", query="SELECT kind, count(*) AS n FROM events GROUP BY kind", ) ``` `query` is mutually exclusive with `source`, `select`, `where`, and `limit`. Existing source-based calls remain supported. Adds Rust `Connection::create_materialized_view_from_query`: embedded connections plan through `MaterializedViewDefinition::from_sql`, while remote connections submit the full query for server-side parsing. Includes regression coverage for grouping, UNNEST, query forwarding, creation jobs, and argument validation. --- docs/src/python/python.md | 14 ++ .../materialized-views.mdx | 28 +-- python/python/lancedb/_lancedb.pyi | 8 +- python/python/lancedb/db.py | 60 ++++-- python/python/lancedb/materialized_view.py | 10 + python/python/lancedb/namespace.py | 16 +- python/python/lancedb/remote/db.py | 8 +- .../python/tests/test_materialized_views.py | 175 +++++++++++++-- python/src/connection.rs | 50 ++++- rust/lancedb/src/materialized_view.rs | 199 +++++++++++++++--- rust/lancedb/src/remote/sql_test.rs | 55 +++++ 11 files changed, 536 insertions(+), 87 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 058f2529a..4ce325b2f 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -627,6 +627,20 @@ remain available, as do LanceDB Enterprise operations. The same feature requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary eager `add_columns` transforms remain available. +Pass a complete defining SQL query with `query=` to use grouping, Functions +in `FROM`, or `UNNEST`: + +```python +view = db.create_materialized_view( + "events_by_kind", + query="SELECT kind, count(*) AS n FROM events GROUP BY kind", +) +``` + +`query` is mutually exclusive with `source`, `select`, `where`, and `limit`. +It is also accepted by asynchronous connections and `create_materialized_view_async`. +The backend SQL parser determines which query shapes are supported. + In LanceDB Enterprise, creation accepts `auto_refresh_enabled` and `auto_refresh_interval_seconds`: diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 0f9494c9f..617eb7525 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -20,19 +20,19 @@ In SQL this is [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view#create). ## Create a view {#create} A materialized view is defined by a SQL query, so it is created with one. -From Python, run the statement on an [Enterprise connection](/basics/catalog#enterprise) -with [`execute_query`](/basics/sql#sql-from-python); the SQL is the same -either way: +From Python, pass the defining query to `create_materialized_view` on an +[Enterprise connection](/basics/catalog#enterprise): ```python Python icon="python" -db.execute_query(""" - CREATE MATERIALIZED VIEW frames_captioned AS - SELECT frame_id, video_id, ts, caption - FROM frames - WHERE selected = true -""").read_all() -view = db.open_materialized_view("frames_captioned") +view = db.create_materialized_view( + "frames_captioned", + query=""" + SELECT frame_id, video_id, ts, caption + FROM frames + WHERE selected = true + """, +) ``` ```sql SQL icon="database" @@ -43,9 +43,11 @@ WHERE selected = true ``` -`execute_query` returns once the result stream is readable, not once the -statement has finished, so `.read_all()` waits out the full creation before -the next line opens it. +`create_materialized_view` waits for creation and initial population, then +returns the view handle. Use `create_materialized_view_async` to submit a job +and wait for it separately. Both methods accept `query=` on synchronous and +asynchronous connections. `query` cannot be combined with `source`, `select`, +`where`, or `limit`; put those clauses in the query itself. The query defines the view: here, the `frames` table's `frame_id`, `video_id`, `ts` and `caption` columns, filtered to the frames selected for diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index ffdd68e5f..5897ddd0c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -349,24 +349,28 @@ class Connection(object): async def create_materialized_view( self, name: str, - source: str, + source: Optional[str] = None, projections: Optional[List[Tuple[str, str]]] = None, filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + *, + query: Optional[str] = None, ) -> Table: ... async def create_materialized_view_async( self, name: str, - source: str, + source: Optional[str] = None, projections: Optional[List[Tuple[str, str]]] = None, filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + *, + query: Optional[str] = None, ) -> Job: ... def list_materialized_views( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b4e5c6182..7d690abe3 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -79,6 +79,7 @@ from .materialized_view import ( MaterializedViewSource, SelectArg, normalize_select, + _validate_create_materialized_view, ) from .secrets import ( EnvVarSecret, @@ -698,8 +699,9 @@ class DBConnection(EnforceOverrides): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -722,8 +724,12 @@ class DBConnection(EnforceOverrides): ---------- name: str The name of the view. - source: str - The name of the source table. + source: str, optional + The name of the source table. Required when ``query`` is omitted. + query: str, optional + The complete defining SQL query, including any GROUP BY or FROM + Function. Mutually exclusive with ``source``, ``select``, ``where`` + and ``limit``. Supported query shapes depend on the backend. select: list or dict, optional The view's columns: column names, ``(alias, SQL expression)`` pairs, or a dict of the same. Omitting it selects every source @@ -745,6 +751,13 @@ class DBConnection(EnforceOverrides): Returns ------- MaterializedView + + Examples + -------- + >>> view = db.create_materialized_view( # doctest: +SKIP + ... "events_by_kind", + ... query="SELECT kind, count(*) AS n FROM events GROUP BY kind", + ... ) """ raise NotImplementedError( _append_doc_url( @@ -756,8 +769,9 @@ class DBConnection(EnforceOverrides): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2108,8 +2122,9 @@ class LanceDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2144,6 +2159,7 @@ class LanceDBConnection(DBConnection): self._conn.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -2158,8 +2174,9 @@ class LanceDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2171,6 +2188,7 @@ class LanceDBConnection(DBConnection): self._conn.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -3390,8 +3408,9 @@ class AsyncConnection(object): async def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -3407,9 +3426,15 @@ class AsyncConnection(object): See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ - source, native_options = await self._materialized_view_source( - source, select, where, limit - ) + _validate_create_materialized_view(source, query, select, where, limit) + if source is not None: + source, native_options = await self._materialized_view_source( + source, select, where, limit + ) + else: + native_options = {} + if query is not None: + native_options["query"] = query inner = await self._inner.create_materialized_view( name, source, @@ -3426,8 +3451,9 @@ class AsyncConnection(object): async def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -3441,9 +3467,15 @@ class AsyncConnection(object): Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. """ - source, native_options = await self._materialized_view_source( - source, select, where, limit - ) + _validate_create_materialized_view(source, query, select, where, limit) + if source is not None: + source, native_options = await self._materialized_view_source( + source, select, where, limit + ) + else: + native_options = {} + if query is not None: + native_options["query"] = query inner = await self._inner.create_materialized_view_async( name, source, diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 7b8c8c6a4..dc04f89f8 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -134,6 +134,16 @@ def _quote_identifier(name: str) -> str: return f"`{escaped}`" +def _validate_create_materialized_view(source, query, select, where, limit): + if query is not None: + if any(value is not None for value in (source, select, where, limit)): + raise ValueError( + "query cannot be combined with source, select, where or limit" + ) + elif source is None: + raise ValueError("either source or query must be provided") + + def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]: """``select`` items may be a column name, an ``(alias, expression)`` pair, or a dict of the same. A bare name projects itself and is quoted, so any diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index aa9025641..72dc78c8b 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -696,8 +696,9 @@ class LanceNamespaceDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -715,6 +716,7 @@ class LanceNamespaceDBConnection(DBConnection): self._inner.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -730,8 +732,9 @@ class LanceNamespaceDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -743,6 +746,7 @@ class LanceNamespaceDBConnection(DBConnection): self._inner.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -1339,8 +1343,9 @@ class AsyncLanceNamespaceDBConnection: async def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1352,6 +1357,7 @@ class AsyncLanceNamespaceDBConnection: view = await self._inner.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -1366,8 +1372,9 @@ class AsyncLanceNamespaceDBConnection: async def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1379,6 +1386,7 @@ class AsyncLanceNamespaceDBConnection: return await self._inner.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 911766674..db3ab554c 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -792,8 +792,9 @@ class RemoteDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -807,6 +808,7 @@ class RemoteDBConnection(DBConnection): self._conn.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -828,8 +830,9 @@ class RemoteDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -841,6 +844,7 @@ class RemoteDBConnection(DBConnection): self._conn.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index bf964102b..1ea0c1cb9 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -10,6 +10,7 @@ import lancedb import pytest import pyarrow as pa from lancedb.db import AsyncConnection +from lancedb.exceptions import JobFailedError from lancedb.materialized_view import MaterializedViewDefinition from lancedb.remote.db import RemoteDBConnection from utils import start_server_thread @@ -175,7 +176,8 @@ async def test_remote_refresh_reports_unknown_metrics( assert not any("count_rows" in path for path in requests) -def test_sync_remote_create_uses_public_async_connection(): +@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"]) +def test_sync_remote_create_uses_public_async_connection(query): calls = [] class StubAsyncTable: @@ -190,6 +192,7 @@ def test_sync_remote_create_uses_public_async_connection(): name, source, *, + query=None, select=None, where=None, limit=None, @@ -201,6 +204,7 @@ def test_sync_remote_create_uses_public_async_connection(): ( name, source, + query, select, where, limit, @@ -219,18 +223,24 @@ def test_sync_remote_create_uses_public_async_connection(): db.db_name = "example" db.serialize = lambda: "{}" - view = db.create_materialized_view( - "adults", - "people", - select=["name"], - where="age >= 18", - limit=10, - with_no_data=True, - auto_refresh_enabled=True, - auto_refresh_interval_seconds=0.5, - ) + if query is None: + view = db.create_materialized_view( + "adults", + "people", + select=["name"], + where="age >= 18", + limit=10, + with_no_data=True, + auto_refresh_enabled=True, + auto_refresh_interval_seconds=0.5, + ) + assert calls == [ + ("adults", "people", None, ["name"], "age >= 18", 10, True, True, 0.5) + ] + else: + view = db.create_materialized_view("adults", query=query) + assert calls == [("adults", None, query, None, None, None, False, None, None)] assert view.name == "adults" - assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)] db.drop_materialized_view("adults", namespace_path=["analytics"]) assert calls[-1] == ("drop", "adults", ["analytics"]) @@ -790,3 +800,144 @@ def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False) assert view.table.count_rows() == 3 + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("namespace", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "query, expected", + [ + ( + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + [{"kind": "a", "n": 2}, {"kind": "b", "n": 1}], + ), + ( + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + [{"id": 1, "tag": "x"}, {"id": 1, "tag": "y"}, {"id": 3, "tag": "z"}], + ), + ], +) +async def test_query_defined_materialized_view( + tmp_path, sync, namespace, background, query, expected +): + if namespace: + connect = lancedb.connect_namespace if sync else lancedb.connect_namespace_async + db = connect("dir", {"root": str(tmp_path)}, storage_options=STABLE_ROW_IDS) + elif sync: + db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS) + else: + db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) + rows = [ + {"id": 1, "kind": "a", "tags": ["x", "y"]}, + {"id": 2, "kind": "a", "tags": []}, + {"id": 3, "kind": "b", "tags": ["z"]}, + ] + if sync: + db.create_table("events", rows, storage_options=STABLE_ROW_IDS) + if background: + db.create_materialized_view_async("result", query=query).wait() + view = db.open_materialized_view("result") + else: + view = db.create_materialized_view("result", query=query) + actual = view.table.to_arrow().to_pylist() + assert view.definition.query == query + view.refresh() + refreshed = view.table.to_arrow().to_pylist() + else: + await db.create_table("events", rows, storage_options=STABLE_ROW_IDS) + if background: + job = await db.create_materialized_view_async("result", query=query) + await job.wait() + view = await db.open_materialized_view("result") + else: + view = await db.create_materialized_view("result", query=query) + actual = (await view.table.to_arrow()).to_pylist() + assert (await view.definition()).query == query + await view.refresh() + refreshed = (await view.table.to_arrow()).to_pylist() + assert sorted(actual, key=str) == sorted(expected, key=str) + assert sorted(refreshed, key=str) == sorted(expected, key=str) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "clauses", + [{"source": "people"}, {"select": []}, {"select": {}}, {"where": ""}, {"limit": 0}], +) +async def test_query_rejects_source_clauses_before_submission( + sync, background, clauses +): + connect = lancedb.connect if sync else lancedb.connect_async + db = connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1") + if not sync: + db = await db + create = ( + db.create_materialized_view_async if background else db.create_materialized_view + ) + with pytest.raises(ValueError, match="query cannot be combined"): + if sync: + create("invalid", query="SELECT * FROM people", **clauses) + else: + await create("invalid", query="SELECT * FROM people", **clauses) + with pytest.raises(ValueError, match="either source or query"): + if sync: + create("missing") + else: + await create("missing") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize( + "query", + [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ], +) +async def test_remote_create_forwards_defining_query(sync, query): + native = CapturingCreateConnection() + db = AsyncConnection(native) + if sync: + remote = RemoteDBConnection.__new__(RemoteDBConnection) + remote._conn = db + job = remote.create_materialized_view_async("result", query=query) + job.wait() + else: + job = await db.create_materialized_view_async("result", query=query) + await job.wait() + assert native.calls[0][0:2] == ("result", None) + assert native.calls[0][2]["query"] == query + + +@pytest.mark.experimental_functions +@pytest.mark.parametrize("background", [False, True]) +def test_query_with_no_data_and_invalid_query(tmp_path, background): + db = make_db(tmp_path) + query = "SELECT name FROM people WHERE age >= 18" + if background: + db.create_materialized_view_async( + "adults", query=query, with_no_data=True + ).wait() + view = db.open_materialized_view("adults") + else: + view = db.create_materialized_view("adults", query=query, with_no_data=True) + assert view.table.count_rows() == 0 + view.refresh() + assert view.table.count_rows() == 2 + create = ( + db.create_materialized_view_async if background else db.create_materialized_view + ) + error = JobFailedError if background else ValueError + with pytest.raises(error, match="unsupported clause"): + result = create("invalid", query="SELECT * FROM people ORDER BY age") + if background: + result.wait() + assert "invalid" not in db.table_names() diff --git a/python/src/connection.rs b/python/src/connection.rs index 2bf01a6f7..a32c00be1 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -26,6 +26,7 @@ use lancedb::{ database::{CreateTableMode, Database, ReadConsistency}, function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, + materialized_view::CreateMaterializedViewBuilder, }; use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, @@ -34,6 +35,27 @@ use pyo3::{ types::{PyAnyMethods, PyDict, PyDictMethods, PyList}, }; +fn materialized_view_builder( + connection: &LanceConnection, + name: String, + source: Option, + query: Option, + has_clauses: bool, +) -> PyResult { + match (source, query) { + (None, Some(query)) if !has_clauses => { + Ok(connection.create_materialized_view_from_query(name, query)) + } + (Some(source), None) => Ok(connection.create_materialized_view(name, source)), + (None, None) => Err(PyValueError::new_err( + "either source or query must be provided", + )), + _ => Err(PyValueError::new_err( + "query cannot be combined with source, select, where or limit", + )), + } +} + #[pyclass] pub struct Connection { inner: Option, @@ -483,21 +505,29 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + query: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder; if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -520,21 +550,29 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + query: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder; if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index bd7fbb942..9920cd893 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1574,14 +1574,15 @@ async fn prepare_with( } /// Builds a materialized view. Created by -/// [`Connection::create_materialized_view`]. +/// [`Connection::create_materialized_view`] or +/// [`Connection::create_materialized_view_from_query`]. pub struct CreateMaterializedViewBuilder { connection: Connection, name: String, namespace: Vec, - source: String, + input: MaterializedViewInput, source_namespace: Vec, - projections: Vec<(String, String)>, + projections: Option>, filter: Option, limit: Option, with_no_data: bool, @@ -1589,6 +1590,11 @@ pub struct CreateMaterializedViewBuilder { auto_refresh_interval_seconds: Option, } +enum MaterializedViewInput { + Source(String), + Query(String), +} + fn source_sql_identifier( namespace_path: &[String], source: &str, @@ -1609,14 +1615,14 @@ fn source_sql_identifier( } impl CreateMaterializedViewBuilder { - pub(crate) fn new(connection: Connection, name: String, source: String) -> Self { + fn new(connection: Connection, name: String, input: MaterializedViewInput) -> Self { Self { connection, name, namespace: Vec::new(), - source, + input, source_namespace: Vec::new(), - projections: Vec::new(), + projections: None, filter: None, limit: None, with_no_data: false, @@ -1644,10 +1650,12 @@ impl CreateMaterializedViewBuilder { mut self, columns: impl IntoIterator, impl Into)>, ) -> Self { - self.projections = columns - .into_iter() - .map(|(output, expression)| (output.into(), expression.into())) - .collect(); + self.projections = Some( + columns + .into_iter() + .map(|(output, expression)| (output.into(), expression.into())) + .collect(), + ); self } @@ -1697,22 +1705,38 @@ impl CreateMaterializedViewBuilder { } fn query(&self) -> Result { + if let MaterializedViewInput::Query(query) = &self.input { + if !self.source_namespace.is_empty() + || self.projections.is_some() + || self.filter.is_some() + || self.limit.is_some() + { + return Err(Error::InvalidInput { + message: "a defining query cannot be combined with source_namespace, select, only_if or limit".into(), + }); + } + return Ok(query.clone()); + } + let MaterializedViewInput::Source(source) = &self.input else { + unreachable!() + }; fn quote(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) } - let projection = if self.projections.is_empty() { - "*".to_string() - } else { - self.projections - .iter() - .map(|(output, expression)| format!("{expression} AS {}", quote(output))) - .collect::>() - .join(", ") - }; + let projection = + if let Some(projections) = self.projections.as_ref().filter(|p| !p.is_empty()) { + projections + .iter() + .map(|(output, expression)| format!("{expression} AS {}", quote(output))) + .collect::>() + .join(", ") + } else { + "*".to_string() + }; let source = source_sql_identifier( &self.source_namespace, - &self.source, + source, self.connection.uri().starts_with("db://"), ); let mut query = format!("SELECT {projection} FROM {source}"); @@ -1775,19 +1799,33 @@ impl CreateMaterializedViewBuilder { .to_string(), }); } - let source = self - .connection - .open_table(&self.source) - .namespace(self.source_namespace.clone()) - .execute() - .await?; - let prepared = prepare_declaration( - &source, - (!self.projections.is_empty()).then_some(self.projections.as_slice()), - self.filter.as_deref(), - self.limit, - ) - .await?; + let prepared = match &self.input { + MaterializedViewInput::Source(name) => { + let source = self + .connection + .open_table(name) + .namespace(self.source_namespace.clone()) + .execute() + .await?; + prepare_declaration( + &source, + self.projections.as_deref().filter(|p| !p.is_empty()), + self.filter.as_deref(), + self.limit, + ) + .await? + } + MaterializedViewInput::Query(_) => { + let definition = MaterializedViewDefinition::from_sql(&self.query()?)?; + let source = self + .connection + .open_table(&definition.source_table) + .namespace(definition.source_namespace.clone()) + .execute() + .await?; + prepare_definition(&source, definition).await? + } + }; let view = prepared.create_in(&self.namespace, &self.name).await?; if !self.with_no_data { view.refresh().execute().await?; @@ -2067,7 +2105,41 @@ impl Connection { name: impl Into, source: impl Into, ) -> CreateMaterializedViewBuilder { - CreateMaterializedViewBuilder::new(self.clone(), name.into(), source.into()) + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Source(source.into()), + ) + } + + /// Define a materialized view using a complete SQL query. + /// + /// Embedded connections parse the query with + /// [`MaterializedViewDefinition::from_sql`]. Remote connections send the + /// query to the server, which determines the supported SQL syntax. + /// Put projections, predicates and limits in the query rather than using + /// the builder's source-specific methods. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn create(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let view = db.create_materialized_view_from_query( + /// "events_by_kind", + /// "SELECT kind, count(*) AS n FROM events GROUP BY kind", + /// ).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_materialized_view_from_query( + &self, + name: impl Into, + query: impl Into, + ) -> CreateMaterializedViewBuilder { + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Query(query.into()), + ) } /// Open the materialized view named `name`. @@ -2229,6 +2301,65 @@ mod tests { ); } + #[tokio::test] + async fn query_builder_rejects_source_clauses() { + let conn = connect("memory://").execute().await.unwrap(); + let builder = || conn.create_materialized_view_from_query("mv", "SELECT * FROM src"); + for invalid in [ + builder().select([("x", "x")]), + builder().select(Vec::<(String, String)>::new()), + builder().only_if("x > 0"), + builder().limit(0), + builder().source_namespace(vec!["ns".into()]), + ] { + assert!(matches!(invalid.query(), Err(Error::InvalidInput { .. }))); + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn create_from_query_supports_grouping_and_background_population() { + let conn = connect("memory://").execute().await.unwrap(); + conn.create_table( + "src", + record_batch!(("kind", Utf8, ["a", "a", "b"])).unwrap(), + ) + .execute() + .await + .unwrap(); + let query = "SELECT kind, count(*) AS n FROM src GROUP BY kind"; + let view = conn + .create_materialized_view_from_query("groups", query) + .with_no_data(true) + .execute() + .await + .unwrap(); + assert_eq!(view.definition_sql(), query); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + view.refresh().execute().await.unwrap(); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); + conn.create_materialized_view_from_query("background", query) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + conn.open_materialized_view("background") + .await + .unwrap() + .table() + .count_rows(None) + .await + .unwrap(), + 2 + ); + } + #[test] fn sql_definition_defaults_share_one_metadata_value() { let metadata = HashMap::from([( diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index eb994f7dd..d25c72830 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1137,6 +1137,61 @@ async fn catalog_connections_use_explicit_sql_endpoint_and_database_scope() { server.await.unwrap().unwrap(); } +#[tokio::test] +async fn remote_query_builder_sends_the_complete_query() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let incoming = futures::stream::try_unfold(listener, |listener| async { + let (socket, _) = listener.accept().await?; + Ok::<_, std::io::Error>(Some((socket, listener))) + }); + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(FlightServiceServer::new(service)) + .serve_with_incoming_shutdown(incoming, async { + let _ = shutdown_rx.await; + }), + ); + let connection = crate::connect("db://analytics") + .region("us-east-1") + .api_key("test-key") + .host_override("http://127.0.0.1:1") + .sql_host_override(&format!("grpc://{address}")) + .execute() + .await + .unwrap(); + for query in [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ] { + connection + .create_materialized_view_from_query("result", query) + .auto_refresh_enabled(false) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + statements.lock().unwrap().last().unwrap(), + &format!( + "CREATE MATERIALIZED VIEW \"result\" WITH (auto_refresh_enabled = false) AS {query}" + ) + ); + } + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + #[tokio::test] async fn remote_create_uses_sql_and_preserves_options_and_namespace() { for defer in [false, true] { From db098ba812ff9cf47e7c8ba5c1a2d58485b6d510 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 12:34:31 +0800 Subject: [PATCH 35/75] fix(ci): support Cargo 1.100 artifact layout in cleanup fixture (#5010) Cargo 1.100 moves intermediate compiler artifacts into per-unit build directories and emits `build_script_build` instead of `build-script-build`. The unlocked-build fixture currently fails on its old rlib path before the SDK build starts, even though the library survives cleanup. Discover compiler inputs recursively and accept both build-script names while preserving the library, generated-input, ordinary-executable, discarded-test, linker-failure and outside-target assertions. The standalone fixture reproduces the failure before this change and passes afterward on Rust/Cargo 1.100.0; it also passes on 1.97.0. Fault injection confirms missing libraries and other retained inputs still fail their assertions. Production cleanup and normal workflow coverage are unchanged. --- ci/tests/test_build_no_lock.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ci/tests/test_build_no_lock.py b/ci/tests/test_build_no_lock.py index 634e8d333..f760d2bfc 100644 --- a/ci/tests/test_build_no_lock.py +++ b/ci/tests/test_build_no_lock.py @@ -88,9 +88,11 @@ class BuildNoLockTest(unittest.TestCase): self.assertTrue((target / "fixture_cli").is_file()) # Cargo guarantees this binary for test execution, not compile-time reads. subprocess.run([str(target / "fixture_cli")], check=True) - self.assertTrue(list((target / "deps").glob("libartifact_fixture*.rlib"))) - self.assertTrue(list((target / "build").glob("*/build-script-build"))) - self.assertTrue(list((target / "build").glob("*/out/generated.rs"))) + # Cargo 1.100 nests compiler inputs in per-unit build directories and + # names the build-script executable build_script_build. + self.assertTrue(list(target.rglob("libartifact_fixture*.rlib"))) + self.assertTrue(list((target / "build").rglob("build[-_]script[-_]build"))) + self.assertTrue(list((target / "build").rglob("out/generated.rs"))) def test_link_failure_preserves_cargo_status_and_diagnostic(self): with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp: From bab22a3fbd0f120b6d9e23cd4f3ee37621bb9bb5 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 00:21:58 -0800 Subject: [PATCH 36/75] feat(python): bundle Function package resources (#4987) A package shipped through `code=` currently loses its non-Python files. This breaks vendored packages that read JSON configuration, manifests, prompts, or binary resources after deployment. Include regular package resources in a separate base64-encoded `python_bundle.resources` map, preserving exact bytes and relative paths. Both source and resources contribute to the artifact digest. UTF-8 Python source bytes retain their original line endings as well, so manifests that hash vendor code continue to match. For example, `@function(code=[my_package])` can use `importlib.resources.files("my_package").joinpath("models.json").read_text()` on the worker. Hidden files and caches are excluded; symlinks and unsafe paths warn instead of following files outside the package. Source-only bundles retain their existing wire form. Resource bundles require matching server support. Adds an isolated-import regression with a vendored subpackage, JSON metadata, binary data, SHA256 verification, preserved CRLF bytes, and resource-only version changes. Local builds and tests are disabled by request. Ruff formatting and linting run locally; CI runs the tests. --- docs/src/python/python.md | 12 ++ docs/web/management/function.mdx | 21 ++- python/python/lancedb/functions.py | 92 ++++++++------ .../python/tests/test_function_packaging.py | 120 ++++++++++++++++-- 4 files changed, 187 insertions(+), 58 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 4ce325b2f..36f47c8f0 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1420,3 +1420,15 @@ name; omitting it allows matching reads of any revision. Prefixes must be concre paths without wildcards or traversal. This integration does not make Hugging Face a writable database location for `ATTACH DATABASE`. Dataset SQL sources select a matching integration automatically, with no integration argument in the query. + + +### Function package resources + +`@function(code=[my_package])` includes the package’s Python modules and data +files, including vendored subpackages. Resource paths and bytes are preserved, +so `importlib.resources` and package integrity checks work after deployment. +Changing a resource changes the Function artifact digest. This requires a server +that accepts `python_bundle.resources`. + +Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or +`conda=` for platform-specific dependencies and `models=` for large model snapshots. diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index bebbe1169..04c146bb1 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -499,13 +499,20 @@ def caption(jpeg: bytes) -> str: Each module in `code` is captured and shipped the same way the function -itself is: as source, snapshotted at registration. Only `.py` source files are -included; package data such as JSON, YAML, prompt, or tokenizer files is not -copied. `@function` warns before registration when it skips such files from a -package in `code`, naming the affected paths. To use a package that includes -the required resources, install it with `pip=` or `conda=` and remove that -package from `code`; otherwise the Python-only copied package shadows the -installed distribution. +itself is: as source, snapshotted at registration. Packages also include regular +data files such as JSON, YAML, prompts, and tokenizer files, including resources +inside vendored subpackages. Resource paths and bytes are preserved for +`importlib.resources` and package integrity checks. Changing a resource changes +the Function artifact's identity. Caches, hidden paths, symlinks, and unsafe +paths are excluded. + +Package resources require matching SDK and server support. Upgrade query nodes +and Function image-building workers before registering resource bundles; older +servers reject them. Older SDKs ship only Python source and warn when excluding +package data. On deployments without resource-bundle support, install the +package with `pip=` or `conda=` and omit it from `code` so the copied package does +not shadow the installed distribution. Use environment dependencies for +platform-specific packages and `models=` for large model snapshots. ## Drop it {#drop} diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 92be658a8..f04d3d481 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -22,6 +22,7 @@ import symtable import json import linecache import math +import os import re import sys import textwrap @@ -29,6 +30,7 @@ import types import warnings from collections.abc import Mapping, Sequence from datetime import date, datetime +from pathlib import Path from typing import ( Annotated, Any, @@ -2104,18 +2106,12 @@ class _SourcePackager: self._require_importable(node.module) -def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]: - """The Python source files of the modules and packages in ``code=``, - keyed by their path on the Function's import path. - - Package resources are not part of the source artifact. Warn about files - and excluded directories that the walk leaves behind instead of silently - producing a Function that will fail later on the worker. - """ - import os - from pathlib import Path - +def _code_files( + modules: Sequence[Any], +) -> tuple[dict[str, str], dict[str, str], frozenset[str]]: + """Source and byte-preserving package resources on the Function import path.""" files: dict[str, str] = {} + resources: dict[str, str] = {} names: set[str] = set() for module in modules: if not isinstance(module, types.ModuleType): @@ -2149,35 +2145,50 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]] sources = [] skipped = set() for directory, subdirectories, filenames in os.walk(root): - # Only importable modules travel: data files, caches, and - # directories that are not identifiers cannot be imported. kept = [] for child in sorted(subdirectories): - if child == "__pycache__": + path = Path(directory) / child + if child == "__pycache__" or child.startswith("."): continue - if _SOURCE_PATH_COMPONENT.fullmatch(child): + if not path.is_symlink() and re.fullmatch( + r"[A-Za-z0-9_][A-Za-z0-9_.-]*", child + ): kept.append(child) else: - relative = (Path(directory) / child).relative_to(root) + relative = path.relative_to(root) skipped.add(f"{name}/{relative.as_posix()}/") subdirectories[:] = kept for filename in sorted(filenames): + path = Path(directory) / filename stem, suffix = os.path.splitext(filename) - if suffix in {".pyc", ".pyo"}: + if suffix in {".pyc", ".pyo"} or filename.startswith("."): continue - if suffix == ".py" and _SOURCE_PATH_COMPONENT.fullmatch(stem): - sources.append(Path(directory) / filename) + relative = path.relative_to(root) + key = f"{name}/{relative.as_posix()}" + if ( + path.is_symlink() + or not path.is_file() + or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", filename) + ): + skipped.add(key) + elif suffix == ".py": + if all( + _SOURCE_PATH_COMPONENT.fullmatch(part) + for part in relative.with_suffix("").parts + ): + sources.append(path) + else: + skipped.add(key) else: - relative = (Path(directory) / filename).relative_to(root) - skipped.add(f"{name}/{relative.as_posix()}") + resources[key] = base64.b64encode(path.read_bytes()).decode( + "ascii" + ) if skipped: - skipped_paths = ", ".join(sorted(skipped)) warnings.warn( - f"code= ships Python .py modules only; package {name!r} " - f"will not include: {skipped_paths}. Install a package that " - "includes the required resources with pip= or conda=, and " - f"remove {name!r} from code= so the copied package cannot " - "shadow the installed distribution.", + "code= cannot ship these package paths: " + f"{', '.join(sorted(skipped))}. " + "Use regular files with safe relative names and importable " + "Python module names.", UserWarning, ) for path in sources: @@ -2188,12 +2199,12 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]] if not file or not file.endswith(".py"): raise ValueError(f"code= ships Python source; module {name!r} has none") files[f"{name}.py"] = _source_text(Path(file)) - return files, frozenset(names) + return files, resources, frozenset(names) def _source_text(path) -> str: try: - return path.read_text(encoding="utf-8") + return path.read_bytes().decode("utf-8") except UnicodeDecodeError as error: raise ValueError(f"code= ships UTF-8 source; {path} is not UTF-8") from error @@ -2449,14 +2460,17 @@ class FunctionDefinition: UserWarning, stacklevel=3, ) - code_files, code_modules = _code_files(code) + code_files, code_resources, code_modules = _code_files(code) entry_source = _SourcePackager( code_modules, frozenset(_requirement_name(package) for package in packages) ).package(function, signature) if code_files: kind = _PYTHON_BUNDLE_ARTIFACT + bundle = {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}} + if code_resources: + bundle["resources"] = code_resources source = json.dumps( - {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}}, + bundle, ensure_ascii=False, sort_keys=True, separators=(",", ":"), @@ -2802,13 +2816,15 @@ def function( immutable Function version; per-refresh aggregate GPU budgets are selected through ``refresh_column`` instead of registration. code : sequence of module, optional - Top-level modules or packages whose importable ``.py`` files ship - with the Function and are importable by their own names. Package data - files are not copied. To use a package that includes required data - resources, install it with ``pip=`` or ``conda=`` and remove that - package from ``code=`` so the copied Python package cannot shadow the - installed distribution. ``@function`` warns when it skips files from a - package in ``code=``. + Top-level modules or packages shipped with the Function and importable + by their own names. Package resources, including binary data and + vendored subpackages, retain their relative paths and exact bytes. + Source and resource changes both create a new Function version. + Caches and hidden paths are excluded. Symlinks and unsafe paths are + skipped with a warning. Compiled dependencies must match the remote + runtime; use ``pip=`` or ``conda=`` for platform-specific distributions + and ``models=`` for large model snapshots. Resource bundles require + server support for the ``python_bundle.resources`` field. models : sequence of HuggingFaceModel, optional Immutable Hugging Face repository snapshots prepared in the worker node cache before user code starts. A Function may declare a diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 2e285aa33..fcefc9110 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -7,6 +7,7 @@ from __future__ import annotations import base64 import importlib +import hashlib import json import subprocess import sys @@ -628,6 +629,102 @@ def test_binding_passes_initialization_as_constants(): version(text=col("body"), model=object()) +def test_vendored_package_resources_survive_an_isolated_import( + tmp_path, helper_package +): + package = helper_package( + "fx_vendor", + { + "__init__.py": "from .vendor.model import predict", + "vendor/__init__.py": "", + "vendor/model.py": """ + import hashlib + import json + from importlib.resources import files + + def predict(value): + root = files("fx_vendor") + payload = root.joinpath("label-maps/payload.bin").read_bytes() + metadata = json.loads(root.joinpath("models.json").read_text()) + source = root.joinpath("vendor/model.py").read_bytes() + source_digest = hashlib.sha256(source).hexdigest() + assert source_digest == metadata["source_sha256"] + assert hashlib.sha256(payload).hexdigest() == metadata["sha256"] + return value + metadata["offset"] + """, + "models.json": "{}", + }, + ) + payload = b"\x00\xff\r\nvendored model data" + package_root = Path(package.__file__).parent + (package_root / "label-maps").mkdir() + (package_root / "label-maps/payload.bin").write_bytes(payload) + module_path = package_root / "vendor/model.py" + module_bytes = ( + module_path.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n") + ) + module_path.write_bytes(module_bytes) + (package_root / "models.json").write_bytes( + json.dumps( + { + "sha256": hashlib.sha256(payload).hexdigest(), + "source_sha256": hashlib.sha256(module_bytes).hexdigest(), + "offset": 7, + } + ).encode() + + b"\r\n" + ) + + entry = helper_package( + "fx_vendor_entry", + { + "__init__.py": """ + import fx_vendor + from lancedb import function + + @function(code=[fx_vendor]) + def vendored(value: int) -> int: + return fx_vendor.predict(value) + """ + }, + ) + vendored = entry.vendored + + first_digest = vendored.registration_request.artifact.digest + bundle = json.loads(artifact(vendored)) + isolated = tmp_path / "isolated" + isolated.mkdir() + for name, content in bundle["files"].items(): + target = isolated / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content.encode("utf-8")) + for name, content in bundle["resources"].items(): + target = isolated / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(base64.b64decode(content)) + assert (isolated / "fx_vendor/models.json").read_bytes().endswith(b"\r\n") + result = subprocess.run( + [ + sys.executable, + "-I", + "-c", + "import sys; sys.path.insert(0, sys.argv[1]); " + "from user_function import vendored; assert vendored(3) == 10", + str(isolated), + ], + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr + (package_root / "models.json").write_text('{"offset": 8}') + assert ( + function(code=[package])( + vendored._function + ).registration_request.artifact.digest + != first_digest + ) + + def test_code_packages_ship_as_a_bundle_and_version_with_their_source( tmp_path, helper_package ): @@ -672,14 +769,13 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source( first = define() assert len(caught) == 1 warning = str(caught[0].message) - assert "fx_helpers/fixtures/data.json" in warning + assert "fx_helpers/fixtures/data.json" not in warning assert "fx_helpers/not-a-module.py" in warning - assert warning.index("fx_helpers/fixtures/data.json") < warning.index( - "fx_helpers/not-a-module.py" - ) - assert "remove 'fx_helpers' from code=" in warning - assert "pip=" in warning - assert "conda=" in warning + + assert "safe relative names" in warning + assert "importable Python module names" in warning + resources = json.loads(artifact(first))["resources"] + assert base64.b64decode(resources["fx_helpers/fixtures/data.json"]) == b"{}" assert "__pycache__" not in warning assert ".pyc" not in warning shipped = bundle_files(first) @@ -732,7 +828,7 @@ def test_code_package_cache_artifacts_do_not_warn(helper_package): ] -def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_package): +def test_code_package_resources_keep_nonidentifier_directories(helper_package): resources = helper_package( "fx_resources", { @@ -748,11 +844,9 @@ def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_packag def resource_boundary(value: int) -> int: return value - assert len(caught) == 1 - warning = str(caught[0].message) - assert "fx_resources/label-maps/" in warning - assert "remove 'fx_resources' from code=" in warning - assert "labels.json" not in warning + assert not caught + resources = json.loads(artifact(resource_boundary))["resources"] + assert base64.b64decode(resources["fx_resources/label-maps/labels.json"]) == b"{}" assert sorted(bundle_files(resource_boundary)) == [ "fx_resources/__init__.py", "user_function.py", From 927b24394866c835b7f7c3e27a3ee10845a9bf46 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Fri, 13 Nov 2026 09:38:50 -0800 Subject: [PATCH 37/75] fix(remote): preserve branches in cache prewarm requests (#5012) Calling `prewarm_data` or `prewarm_index` on a checked-out remote branch currently targets main. Both methods omit the branch context, which can warm the wrong snapshot, miss a branch-only index, or fail when the branch's minimum read version is ahead of main. This PR carries the table handle's branch through the existing request helpers. Main requests retain their existing format, with no public API changes. --- rust/lancedb/src/remote/table.rs | 71 ++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index dcceb4260..9b64ab56d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4548,10 +4548,10 @@ impl BaseTable for RemoteTable { async fn prewarm_index(&self, index_name: &str) -> Result<()> { let encoded_name = urlencoding::encode(index_name); - let request = self.client.post(&format!( + let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/index/{encoded_name}/prewarm/", self.identifier - )); + ))); let (request_id, response) = self.send(request, true).await?; if response.status() == StatusCode::NOT_FOUND { return Err(Error::IndexNotFound { @@ -4567,9 +4567,10 @@ impl BaseTable for RemoteTable { "/v1/table/{}/page_cache/prewarm/", self.identifier )); - let body = serde_json::json!({ + let mut body = serde_json::json!({ "columns": columns.unwrap_or_default(), }); + self.apply_branch_body(&mut body); request = request.json(&body); let (request_id, response) = self.send(request, true).await?; self.check_table_response(&request_id, response).await?; @@ -13018,6 +13019,70 @@ mod tests { .unwrap(); } + #[tokio::test] + async fn test_prewarm_data_sends_the_checked_out_branch() { + use lance::dataset::refs::Ref; + + let table = + Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { + match request.url().path() { + "/v1/table/my_table/branches/create/" => { + http::Response::builder().status(200).body("{}").unwrap() + } + "/v1/table/my_table/page_cache/prewarm/" => { + let body = request_body_json(&request); + assert_eq!(body["branch"], "dev"); + assert_eq!(body["columns"], json!(["payload"])); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"prewarm-job"}"#) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let branch = table + .create_branch("dev", Ref::Version(None, None)) + .await + .unwrap(); + branch + .prewarm_data(Some(vec!["payload".into()])) + .await + .unwrap(); + } + + #[tokio::test] + async fn test_prewarm_index_sends_the_checked_out_branch() { + use lance::dataset::refs::Ref; + + let table = + Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { + match request.url().path() { + "/v1/table/my_table/branches/create/" => { + http::Response::builder().status(200).body("{}").unwrap() + } + "/v1/table/my_table/index/my_index/prewarm/" => { + let branch = request + .url() + .query_pairs() + .find(|(key, _)| key == "branch") + .map(|(_, value)| value.into_owned()); + assert_eq!(branch.as_deref(), Some("feature/dev")); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"prewarm-job"}"#) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let branch = table + .create_branch("feature/dev", Ref::Version(None, None)) + .await + .unwrap(); + branch.prewarm_index("my_index").await.unwrap(); + } + #[tokio::test] async fn test_drop_index() { let table = Table::new_with_handler("my_table", |request| { From 1765747f916d6eb7f3fbbcc105591e5835ea3684 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 11:02:07 -0800 Subject: [PATCH 38/75] fix: allow updates to Function input columns (#4985) Updating an input column on a table with a Function binding currently fails before the write, although the write path already preserves freshness for bindings whose inputs are unchanged. Allow input updates through the normal update builder while retaining supported binding-metadata validation and the guard against writing computed or internal assignment outputs directly. Lance rewrites only the matched rows. Their affected Function outputs keep their previous values and their changed input signatures make them eligible for refresh; unchanged fragments retain their freshness. Rewrites affecting only unrelated inputs keep the existing freshness-preservation path. For a table whose Function reads `title`, this update now succeeds while retaining the previous computed values until refresh: ```python table.update(where="id = 7", values={"title": "revised"}) ``` Server consumers need this crate update before remote input updates gain the behavior. Adds regressions for a one-row input update, retained output values, freshness scope, independent binding preservation, and atomic rejection of mixed input/output writes. Local builds and tests are disabled by request; CI runs the regressions. --- rust/lancedb/src/table/computed_columns.rs | 54 ++++++++- rust/lancedb/src/table/freshness.rs | 122 +++++++++++++++++++++ rust/lancedb/src/table/update.rs | 33 +++--- 3 files changed, 192 insertions(+), 17 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index d09a790a3..64e90b246 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -1757,10 +1757,20 @@ pub(crate) fn ensure_not_written<'a>( schema: &ArrowSchema, written: impl IntoIterator, ) -> Result<()> { - let declared: Vec = computed_columns(schema) + ensure_supported_function_metadata(schema)?; + let mut declared: Vec = computed_columns(schema) .into_iter() .map(|declaration| declaration.name) .collect(); + declared.extend( + function_bindings(schema)? + .into_iter() + .filter_map(|binding| { + binding + .assignment() + .map(|assignment| assignment.output_name.clone()) + }), + ); for name in written { if declared.iter().any(|declared| *declared == root(name)) { return Err(Error::InvalidInput { @@ -2532,10 +2542,15 @@ pub(crate) mod test_support { )]) .await .unwrap(); - let inputs = ["title".to_string(), "body".to_string()]; + let schema = dataset.schema(); let outputs = bindings .iter() .flat_map(|binding| { + let inputs = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); let assignment = binding.assignment().map(|assignment| { ( assignment.output_name.clone(), @@ -2547,9 +2562,9 @@ pub(crate) mod test_support { .iter() .map(|output| (output.output_name.clone(), output.output_ordinal)) .chain(assignment) - .map(|(name, ordinal)| { + .map(move |(name, ordinal)| { ( - dataset.schema().field(&name).unwrap().id as u32, + schema.field(&name).unwrap().id as u32, function_computed_column_metadata( binding.binding_id(), ordinal, @@ -4144,6 +4159,37 @@ mod tests { ArrowSchema::new(fields) } + #[test] + fn input_writes_preserve_the_assignment_column_guard() { + let mut raw: Value = serde_json::to_value(test_support::text_features_binding("")).unwrap(); + raw["assignment"] = serde_json::json!({ + "output_name": "__function_assignment_fb_01K3TEXT", "output_field_id": -1, + }); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["outputs"][1]["nullable"] = Value::Bool(true); + raw["output_schema"]["fields"].as_array_mut().unwrap().push(serde_json::json!({ + "name": "__function_assignment_fb_01K3TEXT", "nullable": true, "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let schema = ArrowSchema::new_with_metadata( + valid_function_binding_schema(true, true, &binding) + .fields() + .to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.into(), + function_bindings_metadata(&[binding]).unwrap(), + )]), + ); + ensure_not_written(&schema, ["title", "body"]).unwrap(); + for output in [ + "search_text", + "search_token_count", + "__function_assignment_fb_01K3TEXT", + ] { + assert!(ensure_not_written(&schema, [output]).is_err(), "{output}"); + } + } + #[test] fn test_non_nullable_function_inputs_can_bind_to_nullable_parameters() { let binding = FunctionBinding::from_json(include_str!( diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 645653a46..563a2a4e5 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -2646,6 +2646,8 @@ mod tests { use lance_file::version::ConcreteFileVersion; use lance_table::format::overlay::{DataOverlayFile, OverlayCoverage}; + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + const COLUMN: &str = "doubled"; const EXPRESSION: &str = "value * 2"; @@ -3126,6 +3128,126 @@ mod tests { } } + #[tokio::test] + async fn input_update_dirties_only_the_updated_rows_and_retains_outputs() { + let table = fresh_function_table().await; + let result = table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + assert_eq!(result.rows_updated, 1); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for output in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, output).await; + let mut dirty_rows = 0; + for fragment in dataset.get_fragments() { + if stale.needs_recompute(fragment.id() as u32) { + let batch = fragment + .scan() + .project(&["title"]) + .unwrap() + .try_into_batch() + .await + .unwrap(); + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}"); + dirty_rows += batch.num_rows(); + } + } + assert_eq!(dirty_rows, 1, "{stale:?}"); + } + assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1); + } + + #[tokio::test] + async fn input_update_keeps_an_independent_function_binding_fresh() { + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, ["x", "y", "z", "w"]), + ("search_text", Utf8, ["a x", "b y", "c z", "d w"]), + ("search_token_count", Int64, [2, 2, 2, 2]), + ("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]), + ("search_token_count_other", Int64, [2, 2, 2, 2]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("independent_functions", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut other = serde_json::to_value(text_features_binding("_other")).unwrap(); + other["inputs"][1]["field_path"] = serde_json::json!("title"); + other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone(); + let bindings = [ + text_features_binding(""), + serde_json::from_value(other).unwrap(), + ]; + stamp_bindings(&table, &bindings).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + for binding in &bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let inputs = fields_for_paths(dataset.schema(), &paths).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + } + native.dataset.update(dataset); + table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .needs_recompute(2) + ); + let other = &bindings[1]; + let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap(); + for output in other.outputs() { + let stale = + staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs) + .await + .unwrap(); + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 55980c5ff..93e8a08ea 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -103,11 +103,6 @@ pub(crate) async fn execute_update( // 1. Snapshot the current dataset let dataset = table.dataset.get().await?; crate::materialized_view::ensure_not_a_view(&table.name, &dataset.schema().metadata, "update")?; - super::computed_columns::ensure_not_function_bound( - &arrow_schema::Schema::from(dataset.schema()), - "update", - update.columns.iter().map(|(name, _)| name.as_str()), - )?; super::computed_columns::ensure_not_written( &arrow_schema::Schema::from(dataset.schema()), update.columns.iter().map(|(name, _)| name.as_str()), @@ -473,26 +468,38 @@ mod tests { assert_eq!(0, tbl.count_rows(Some("i == 0".to_string())).await.unwrap()); } - /// A Function binding protects only the columns it reads or writes; any - /// other column updates as on a plain table. #[tokio::test] - async fn update_on_a_function_table_refuses_only_bound_columns() { + async fn update_allows_function_inputs_but_protects_outputs() { let table = crate::table::computed_columns::test_support::bound_table().await; - let result = table.update().column("spare", "7").execute().await.unwrap(); + let result = table + .update() + .column("title", "'changed'") + .execute() + .await + .unwrap(); assert_eq!(result.rows_updated, 1); - for column in ["title", "search_text"] { + assert_eq!( + table + .count_rows(Some("title = 'changed' AND search_text = 'a b'".into())) + .await + .unwrap(), + 1 + ); + for column in ["search_text", "search_token_count"] { + let version = table.version().await.unwrap(); let err = table .update() - .column(column, "'x'") + .column("title", "'must not commit'") + .column(column, "NULL") .execute() .await .unwrap_err(); assert!( matches!(&err, crate::Error::InvalidInput { message } - if message.contains(&format!("update of '{column}'")) - && message.contains("a Function binding reads or writes it")), + if message.contains("is computed") && message.contains("cannot be written directly")), "{column}: {err:?}" ); + assert_eq!(table.version().await.unwrap(), version); } } } From 3a980054a19dc51f53979a04142468f57478d156 Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:24:55 -0800 Subject: [PATCH 39/75] docs: standardize Realtime Engine naming (#4969) The Enterprise feature name was inconsistently written as "Real Time Engine" and "real time engine". Standardize it to **Realtime Engine** in eight website guides, including page and sidebar titles, descriptions, prose, link labels, cards, and search keywords. The remaining MemWAL references describe Lance's open source format or literal API/job identifiers, including `memwal_compaction` and `memwal_catchup_`, and are preserved. Only `docs/web/*.mdx` pages change; SDK source, generated API reference, code examples, URL destinations, and section anchors are unchanged. Validation: - `git diff --check` passes. - Reviewed all MemWAL and Realtime Engine references under `docs/`. - Verified each changed file differs only by the intended naming substitutions and preserves code blocks, inline code, links, anchors, and MemWAL identifiers. - Confirmed no split or hyphenated "real time engine" names remain in website guides. - No snippets needed regeneration because code examples are unchanged. Vale and Mintlify are not installed locally, so their checks were not run locally. --- docs/web/basics/sdk.mdx | 2 +- docs/web/enterprise/distributed-real-time-read.mdx | 2 +- docs/web/enterprise/distributed-real-time-write.mdx | 4 ++-- docs/web/enterprise/realtime-engine-compaction.mdx | 12 ++++++------ docs/web/ingestion/realtime-write.mdx | 8 ++++---- docs/web/search/realtime-read.mdx | 8 ++++---- docs/web/sql/ddl/table.mdx | 2 +- docs/web/tables/realtime-engine.mdx | 10 +++++----- 8 files changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index 2ff1a4ba7..0274c039a 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -53,7 +53,7 @@ without a LanceDB SDK. For SQL queries, connect through LanceDB's Java client builds on this Lance Namespace Java core: table creation, listing and most other catalog operations go through the generated `LanceNamespace` interface talking to Enterprise's Namespace endpoint. -The [real time engine](/tables/realtime-engine) is the one area with its own, +The [Realtime Engine](/tables/realtime-engine) is the one area with its own, LanceDB-specific Java client on top, since RTE's LSM write path is not part of the Lance Namespace Client SDK Specification. diff --git a/docs/web/enterprise/distributed-real-time-read.mdx b/docs/web/enterprise/distributed-real-time-read.mdx index 1b6a582c4..7442474ec 100644 --- a/docs/web/enterprise/distributed-real-time-read.mdx +++ b/docs/web/enterprise/distributed-real-time-read.mdx @@ -1,7 +1,7 @@ --- title: "Distributed RTE Read" sidebarTitle: "Distributed RTE Read" -description: "How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine." +description: "How a query combines the Realtime Engine's fresh tier with the ordinary distributed query-serving path, machine to machine." icon: "network-wired" availability: embedded: unavailable diff --git a/docs/web/enterprise/distributed-real-time-write.mdx b/docs/web/enterprise/distributed-real-time-write.mdx index ac91e2d0d..e75497360 100644 --- a/docs/web/enterprise/distributed-real-time-write.mdx +++ b/docs/web/enterprise/distributed-real-time-write.mdx @@ -3,7 +3,7 @@ title: "Distributed RTE Write" sidebarTitle: "Distributed RTE Write" description: "How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it." icon: "bolt" -keywords: ["rte", "real time engine", "shard", "sharding", "horizontal scaling", "write throughput"] +keywords: ["rte", "realtime engine", "shard", "sharding", "horizontal scaling", "write throughput"] availability: embedded: unavailable enterprise: available @@ -128,7 +128,7 @@ throughput than this provides. Enable RTE and write to a table; the same call on Embedded or Enterprise. - + MemWAL, shards, memtables and SSTables -- the shared architecture. diff --git a/docs/web/enterprise/realtime-engine-compaction.mdx b/docs/web/enterprise/realtime-engine-compaction.mdx index e04429ab8..fb1a68481 100644 --- a/docs/web/enterprise/realtime-engine-compaction.mdx +++ b/docs/web/enterprise/realtime-engine-compaction.mdx @@ -1,7 +1,7 @@ --- -title: "Real Time Engine compaction" +title: "Realtime Engine compaction" sidebarTitle: "RTE Compaction" -description: "How Enterprise automatically folds a Real Time Engine shard's SSTables into the base table and catches its indexes up." +description: "How Enterprise automatically folds a Realtime Engine shard's SSTables into the base table and catches its indexes up." icon: "compress" availability: embedded: unavailable @@ -11,7 +11,7 @@ availability: [Distributed Compaction](/enterprise/distributed-compaction) merges small base-table fragments and reclaims deleted rows -- the same operation [Compaction](/maintenance/compaction) describes for LanceDB Embedded. A -table with the [real time engine](/tables/realtime-engine) enabled has a +table with the [Realtime Engine](/tables/realtime-engine) enabled has a second, unrelated compaction: folding a shard's accumulated SSTables into the base table and catching the base table's indexes up over the rows that just landed. This produces two job types, `memwal_compaction` and @@ -176,9 +176,9 @@ manifest update in step 6 is the single point where a row's SSTable copy stops being listed, and it only commits after `merge_insert` has already written that row into the base table. -A table queried *without* the real time engine's live path only sees data +A table queried *without* the Realtime Engine's live path only sees data once it has been folded into the base table, so its staleness bound tracks -whichever trigger fires -- wider either way than the real time engine's +whichever trigger fires -- wider either way than the Realtime Engine's own millisecond-scale freshness. A shard under steady write pressure compacts on the count or bytes trigger, within `WAL_COMPACTION_INTERVAL_SECS` plus the compaction job's own runtime. A shard that never gathers enough @@ -197,7 +197,7 @@ for what a live RTE read sees instead. ## What to read next {#next} - + The MemWAL format, shards, and WAL nodes this page assumes. diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx index 5b61e67bc..21b6eb2fa 100644 --- a/docs/web/ingestion/realtime-write.mdx +++ b/docs/web/ingestion/realtime-write.mdx @@ -1,15 +1,15 @@ --- title: "RTE Write (Upsert)" sidebarTitle: "RTE Write (Upsert)" -description: "Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." +description: "Enable the Realtime Engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] +keywords: ["rte", "realtime engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] availability: embedded: available enterprise: available --- -The [real time engine](/tables/realtime-engine) puts an LSM-style write tier in +The [Realtime Engine](/tables/realtime-engine) puts an LSM-style write tier in front of a table, turning many small writes into a few large commits. This page covers enabling it and writing to a table; for querying an RTE table, see [RTE reads](/search/realtime-read). @@ -239,6 +239,6 @@ for the numbers. - [RTE reads](/search/realtime-read) — query an RTE table - [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales this -- [How the real time engine works](/tables/realtime-engine#memwal-format) +- [How the Realtime Engine works](/tables/realtime-engine#memwal-format) - [Merge insert](/ingestion/merge-insert) - [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx index 19c5bc2ab..d87d98c81 100644 --- a/docs/web/search/realtime-read.mdx +++ b/docs/web/search/realtime-read.mdx @@ -1,15 +1,15 @@ --- title: "RTE reads" sidebarTitle: "RTE Read" -description: "Query a table with the real time engine enabled and get writes back within milliseconds of being written, merged transparently with the base table." +description: "Query a table with the Realtime Engine enabled and get writes back within milliseconds of being written, merged transparently with the base table." icon: "magnifying-glass" -keywords: ["rte", "real time engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] +keywords: ["rte", "realtime engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] availability: embedded: available enterprise: available --- -A table with the [real time engine](/tables/realtime-engine) enabled queries +A table with the [Realtime Engine](/tables/realtime-engine) enabled queries the same way as any other table — nothing about `search`, filtering, or SQL changes. This page covers what you get back; for enabling RTE and writing to a table, see [RTE writes](/ingestion/realtime-write). For how Enterprise @@ -79,6 +79,6 @@ available. - [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table - [Distributed RTE Read](/enterprise/distributed-real-time-read) — combining results across machines in Enterprise -- [How the real time engine works](/tables/realtime-engine#memwal-format) +- [How the Realtime Engine works](/tables/realtime-engine#memwal-format) - [Hybrid search](/search/hybrid-search) - [Vector search](/search/vector-search) diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index 6e751667e..ab0ff64bf 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -176,7 +176,7 @@ ALTER TABLE t UNSET RTE ``` -The [real time engine](/tables/realtime-engine) puts a write-ahead log in front +The [Realtime Engine](/tables/realtime-engine) puts a write-ahead log in front of the table, making small frequent writes cheap by batching them out of the commit path. `sharding` and `buckets` spread the log so concurrent writers do not contend on one place; `bucket` sharding names its `column`, which must be diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx index 5c6983cc5..09e933894 100644 --- a/docs/web/tables/realtime-engine.mdx +++ b/docs/web/tables/realtime-engine.mdx @@ -1,21 +1,21 @@ --- -title: "Real Time engine (RTE)" -sidebarTitle: "Real Time Engine (RTE)" +title: "Realtime Engine (RTE)" +sidebarTitle: "Realtime Engine (RTE)" description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] +keywords: ["rte", "realtime engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] availability: embedded: available enterprise: available --- -## What is the real time engine? {#what-is-rte} +## What is the Realtime Engine? {#what-is-rte} Every write to a LanceDB table is normally a commit to the underlying Lance dataset. That is ideal for bulk loads, but a stream of small upserts becomes a stream of small commits, and each write is only visible once its commit lands. -The real time engine (RTE) puts an LSM-style write tier in front of the table. +The Realtime Engine (RTE) puts an LSM-style write tier in front of the table. It turns many small writes into a few large commits, and makes each write **searchable within milliseconds** of being acknowledged. It is enabled per table, and nothing about how you query that table changes. From 7d50d2d28f84559672d15f8d91e06bf55cc2fa3d Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 13 Nov 2026 11:44:40 -0800 Subject: [PATCH 40/75] chore(deps): bump Rust deps flagged by security scans (#5035) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Bumps the Rust dependencies flagged by Aikido that have a semver-compatible fix available. Supersedes #5009 (rustls in the docs lockfile is included here). Root `Cargo.lock`: | Crate | From | To | | --- | --- | --- | | mio | 1.2.0 | 1.2.5 | | smallvec | 1.15.1 | 1.16.5 | | thread_local | 1.1.9 | 1.1.10 | | tinyvec | 1.11.0 | 1.13.3 | | zerocopy / zerocopy-derive | 0.8.48 | 0.8.63 | | event-listener | 5.4.1 | 5.4.2 | | arrayvec | 0.7.6 | 0.7.8 | | wasm-bindgen (+ js-sys, web-sys) | 0.2.121 | 0.2.130 | | getrandom 0.4 | 0.4.2 | 0.4.3 (drops wasip3 → wasmparser 0.244) | | brotli | 3.5.0 | 9.1.1 (via `random_word` dev-dep 0.4.3 → 1.0.0) | `docs/web-tests/rs/Cargo.lock` gets the same crates plus rustls, hyper, h2, moka, bytes, crossbeam-epoch and anyhow. That crate is not a workspace member, so cargo refused to resolve it; it now has an empty `[workspace]` table. Still open, blocked upstream: quick-xml 0.41 (lance-io), rand 0.9 (datafusion/lance/candle), heapless 0.8 (rstar via geo), paste, unsafe-libyaml (rattler_conda_types, lindera), fast-float/smartstring (polars 0.39), number_prefix (needs hf-hub 1.0 migration), zstd 0.13 (arrow-ipc). ## Merge Risk **Door:** two-way. Lockfile patch/minor bumps and a dev-only dependency. **Blast Radius:** none expected; no source changes. The docs crate is not built in CI. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 282 +++++++------------------------- docs/web-tests/rs/Cargo.lock | 301 ++++++++--------------------------- docs/web-tests/rs/Cargo.toml | 4 + rust/lancedb/Cargo.toml | 2 +- 4 files changed, 127 insertions(+), 462 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index efe0338cd..22b0f1e6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,15 +63,15 @@ dependencies = [ [[package]] name = "alloc-no-stdlib" -version = "2.0.4" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" [[package]] name = "alloc-stdlib" -version = "0.2.2" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ "alloc-no-stdlib", ] @@ -221,9 +221,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" @@ -1474,9 +1474,9 @@ dependencies = [ [[package]] name = "brotli" -version = "3.5.0" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1485,9 +1485,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "2.5.1" +version = "6.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -2261,7 +2261,7 @@ checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" dependencies = [ "cpubits", "ctutils", - "getrandom 0.4.2", + "getrandom 0.4.3", "hybrid-array", "num-traits", "rand_core 0.10.1", @@ -2285,7 +2285,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "hybrid-array", "rand_core 0.10.1", ] @@ -3504,11 +3504,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -4248,17 +4247,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if 1.0.4", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -4939,12 +4936,6 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -5275,13 +5266,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if 1.0.4", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -6243,12 +6233,6 @@ dependencies = [ "spin 0.9.9", ] -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "lexical-core" version = "1.0.6" @@ -6704,9 +6688,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.0" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -8550,16 +8534,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.117", -] - [[package]] name = "primefield" version = "0.14.0" @@ -8870,7 +8844,7 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.1", "rand_pcg", @@ -8973,7 +8947,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -9061,15 +9035,13 @@ dependencies = [ [[package]] name = "random_word" -version = "0.4.3" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07eed67a16dde2cc3c7f65c072acd8d5b2e53d4aab95067c320db851c7651f29" +checksum = "5d9299243acac3cb4f35c9f78d5ad29c87e70cd916a70f293d8526e54049c340" dependencies = [ "ahash", "brotli", - "once_cell", - "paste", - "rand 0.8.6", + "rand 0.10.1", "unicase", ] @@ -10528,9 +10500,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] @@ -11014,7 +10986,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.2", + "getrandom 0.4.3", "once_cell", "rustix 1.1.4", "windows-sys 0.61.2", @@ -11113,9 +11085,9 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if 1.0.4", ] @@ -11183,18 +11155,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.11.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokenizers" @@ -11744,12 +11707,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "unicode_categories" version = "0.1.1" @@ -11836,7 +11793,7 @@ version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -11919,16 +11876,7 @@ version = "1.0.3+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] @@ -11942,12 +11890,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if 1.0.4", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -11955,19 +11902,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -11975,48 +11923,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -12043,23 +11969,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.11.1", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -12579,100 +12493,12 @@ version = "0.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.11.1", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "wkb" version = "0.9.2" @@ -12775,7 +12601,7 @@ dependencies = [ "countio", "futures", "futures-util", - "getrandom 0.4.2", + "getrandom 0.4.3", "heapify", "itertools 0.14.0", "lz4_flex 0.13.1", @@ -12912,18 +12738,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -12999,7 +12825,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e408c6cc4699dd017d53dc080cd51c2cea2b5354af57a1479bd265ed42911487" dependencies = [ "crc32fast", - "getrandom 0.4.2", + "getrandom 0.4.3", "indexmap 2.14.0", "libc", "memchr", diff --git a/docs/web-tests/rs/Cargo.lock b/docs/web-tests/rs/Cargo.lock index 6e288950e..85384c8af 100644 --- a/docs/web-tests/rs/Cargo.lock +++ b/docs/web-tests/rs/Cargo.lock @@ -87,9 +87,9 @@ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "ar_archive_writer" @@ -129,9 +129,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" @@ -683,9 +683,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cast" @@ -1019,9 +1019,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] @@ -1904,7 +1904,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1993,7 +1993,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2004,11 +2004,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -2289,17 +2288,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -2317,9 +2314,9 @@ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" [[package]] name = "h2" -version = "0.4.12" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2475,9 +2472,9 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" [[package]] name = "hyper" -version = "1.8.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -2490,7 +2487,6 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -2699,12 +2695,6 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -2808,7 +2798,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2876,7 +2866,7 @@ dependencies = [ "portable-atomic", "portable-atomic-util", "serde_core", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2917,11 +2907,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.83" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] @@ -3607,12 +3598,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "lexical-core" version = "1.0.6" @@ -3925,9 +3910,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", @@ -3936,9 +3921,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.12.11" +version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8261cd88c312e0004c1d51baad2980c66528dfdb2bee62003e643a4d8f86b077" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" dependencies = [ "async-lock", "crossbeam-channel", @@ -3949,7 +3934,6 @@ dependencies = [ "futures-util", "parking_lot", "portable-atomic", - "rustc_version", "smallvec", "tagptr", "uuid", @@ -4062,7 +4046,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4919,7 +4903,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "itertools 0.14.0", "log", "multimap", @@ -5020,7 +5004,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.3", "rand_pcg", @@ -5046,7 +5030,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.59.0", ] [[package]] @@ -5113,7 +5097,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -5520,14 +5504,14 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.11.0", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -5861,9 +5845,9 @@ checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "smartstring" @@ -5900,7 +5884,7 @@ version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.117", @@ -5912,7 +5896,7 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f103c50866b8743da9429b8a581d81a27c2d3a9c4ac7df8f8571c1dd7896eda" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.117", @@ -6247,7 +6231,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.2", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6301,9 +6285,9 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if", ] @@ -6371,18 +6355,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" @@ -6646,12 +6621,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -6700,7 +6669,7 @@ version = "1.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -6731,9 +6700,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -6750,26 +6719,16 @@ version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ - "wit-bindgen 0.46.0", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -6777,22 +6736,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.56" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836d9622d604feee9e5de25ac10e3ea5f2d65b41eac0d9ce72eb5deae707ce7c" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ - "cfg-if", "js-sys", - "once_cell", + "tokio", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6800,48 +6757,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.6", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -6855,23 +6790,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.10.0", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.83" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b32828d774c412041098d182a8b38b16ea816958e07cf40eec2bc080ae137ac" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -6909,7 +6832,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7254,94 +7177,6 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.10.0", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "writeable" version = "0.6.2" @@ -7388,18 +7223,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.31" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.31" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", diff --git a/docs/web-tests/rs/Cargo.toml b/docs/web-tests/rs/Cargo.toml index 8bc594c3c..1e1de2e45 100644 --- a/docs/web-tests/rs/Cargo.toml +++ b/docs/web-tests/rs/Cargo.toml @@ -1,3 +1,7 @@ +# Standalone crate pinned to a published lancedb release, not part of the root +# workspace. Without this, cargo commands here fail to resolve the workspace. +[workspace] + [package] name = "rs" version = "0.1.0" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 737c385c1..ef5da44c5 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -118,7 +118,7 @@ lance-testing = { workspace = true } # production remote feature so Python wheels do not resolve its Axum 0.7 stack. lance-namespace-impls = { workspace = true, features = ["rest-adapter"] } tempfile = { workspace = true } -random_word = { version = "0.4.3", features = ["en"] } +random_word = { version = "1.0.0", features = ["en"] } tokio = { workspace = true, features = ["io-util", "macros", "net", "test-util"] } uuid = { workspace = true } walkdir = "2" From b061c3627c46ec3d310cddb0aa45f022f8c4aad2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:35:52 -0800 Subject: [PATCH 41/75] feat(python): support exist_ok when creating views (#4984) Add `exist_ok=False` to synchronous and asynchronous Python view creation. Passing `True` sends `CREATE VIEW IF NOT EXISTS` and returns the existing view's stored query and schema unchanged; the default continues to fail on an existing name. ```python view = db.create_view("recent_orders", query, exist_ok=True) view = await async_db.create_view("recent_orders", query, exist_ok=True) ``` Requires a SQL server supporting `CREATE VIEW IF NOT EXISTS`. Rust gains an awaitable builder with `.exist_ok(true)`. Existing `.create_view(...).await` calls continue to work; callers requiring `Future` must convert the builder, and custom `Database` implementations must accept the new `exist_ok` argument. Includes Python round-trip coverage and Rust coverage for direct/deferred results and metadata preservation. --- docs/web/sql/ddl/view.mdx | 10 +++ python/python/lancedb/_lancedb.pyi | 7 ++- python/python/lancedb/db.py | 36 ++++++++--- python/python/lancedb/remote/db.py | 11 +++- python/python/tests/test_view_creation.py | 71 ++++++++++++++++++++++ python/src/connection.rs | 4 +- rust/lancedb/src/connection.rs | 24 +++++--- rust/lancedb/src/connection/create_view.rs | 62 +++++++++++++++++++ rust/lancedb/src/database.rs | 1 + rust/lancedb/src/remote/db.rs | 3 +- rust/lancedb/src/remote/sql/view.rs | 7 ++- rust/lancedb/src/remote/sql_test.rs | 28 ++++++++- 12 files changed, 239 insertions(+), 25 deletions(-) create mode 100644 python/python/tests/test_view_creation.py create mode 100644 rust/lancedb/src/connection/create_view.rs diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index e039fc43a..3d94292ab 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -23,6 +23,16 @@ catalog removal; physical cleanup can continue afterward. ## CREATE VIEW {#create} +{/* Draft for the view exist_ok release. + +`CREATE VIEW IF NOT EXISTS` creates a missing view and returns an existing +view's stored query and schema unchanged. Without `IF NOT EXISTS`, an existing +name is an error. In Python, use `db.create_view(name, query, exist_ok=True)`; +in Rust, use `db.create_view(name, query, &namespace).exist_ok(true).await?`. +Returning an existing view requires `SELECT` on that view. + +*/} + ```sql SQL icon="database" CREATE VIEW "recent_matches" AS diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5897ddd0c..56b644abb 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -253,7 +253,12 @@ class Connection(object): self, name: str, namespace_path: Optional[List[str]] = None ) -> Tuple[str, int, int]: ... async def create_view( - self, name: str, query: str, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ... async def describe_view( self, name: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 7d690abe3..020c79be0 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1273,7 +1273,12 @@ class DBConnection(EnforceOverrides): ) def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: """Create a view: a named query the database plans on every read. @@ -1281,9 +1286,10 @@ class DBConnection(EnforceOverrides): is refused now rather than at the first read. A view holds no rows, and its readers see its sources as they are at read time. - There is no replace: a name already taken is an error, and changing a - view is a drop followed by a create. LanceDB Embedded connections raise - ``NotImplementedError``. + A name already taken is an error unless ``exist_ok=True``, which returns + the existing view's stored query and schema without changing them. + Changing a view is a drop followed by a create. LanceDB Embedded + connections raise ``NotImplementedError``. >>> import lancedb >>> db = lancedb.connect("db://my_database") # doctest: +SKIP @@ -2592,10 +2598,17 @@ class LanceDBConnection(DBConnection): @override def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: return LOOP.run( - self._conn.create_view(name, query, namespace_path=namespace_path) + self._conn.create_view( + name, query, exist_ok=exist_ok, namespace_path=namespace_path + ) ) @override @@ -4107,7 +4120,12 @@ class AsyncConnection(object): ) async def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: """Create a view: a named query the database plans on every read. @@ -4115,7 +4133,9 @@ class AsyncConnection(object): [DBConnection.create_view][lancedb.DBConnection.create_view]. """ return _view_description( - await self._inner.create_view(name, query, list(namespace_path or [])) + await self._inner.create_view( + name, query, list(namespace_path or []), exist_ok=exist_ok + ) ) async def describe_view( diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index db3ab554c..ea9468331 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1197,10 +1197,17 @@ class RemoteDBConnection(DBConnection): @override def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: return LOOP.run( - self._conn.create_view(name, query, namespace_path=namespace_path) + self._conn.create_view( + name, query, exist_ok=exist_ok, namespace_path=namespace_path + ) ) @override diff --git a/python/python/tests/test_view_creation.py b/python/python/tests/test_view_creation.py new file mode 100644 index 000000000..410356da0 --- /dev/null +++ b/python/python/tests/test_view_creation.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "existing"), + [(None, False), (False, False), (True, False), (True, True)], +) +async def test_create_view_exist_ok_preserves_server_metadata( + asynchronous, exist_ok, existing +): + flight = pytest.importorskip("pyarrow.flight") + original_query = "SELECT 'original' AS original" + submitted_query = ( + "SELECT 'replacement' AS replacement" if existing else original_query + ) + schema = { + "fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}], + "metadata": { + "lancedb::view::default_db": "analytics", + "lancedb::view::default_namespace": "team", + }, + } + result = pa.table( + {"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]} + ) + + class ViewServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with ViewServer() as server: + connection_options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + if asynchronous: + db = await lancedb.connect_async("db://analytics", **connection_options) + view = await db.create_view( + "saved", submitted_query, namespace_path=["team"], **kwargs + ) + else: + db = lancedb.connect("db://analytics", **connection_options) + view = db.create_view( + "saved", submitted_query, namespace_path=["team"], **kwargs + ) + (request,) = server.requests + + prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW" + assert f'{prefix} "saved" AS {submitted_query}'.encode() in request + assert view.name == "saved" + assert view.namespace_path == ["team"] + assert view.default_namespace_path == ["team"] + assert view.query == original_query + assert view.schema.names == ["original"] diff --git a/python/src/connection.rs b/python/src/connection.rs index a32c00be1..ffa59fd02 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1158,18 +1158,20 @@ impl Connection { }) } - #[pyo3(signature = (name, query, namespace_path=None))] + #[pyo3(signature = (name, query, namespace_path=None, *, exist_ok=false))] pub fn create_view( self_: PyRef<'_, Self>, name: String, query: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { let view = inner .create_view(name, query, &namespace_path) + .exist_ok(exist_ok) .await .infer_error()?; view_description_to_py(view) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index cc398e32b..c7a058502 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -53,6 +53,9 @@ use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; mod create_secret; mod create_table; +mod create_view; + +pub use create_view::CreateViewBuilder; pub use create_secret::CreateSecretBuilder; @@ -976,9 +979,10 @@ impl Connection { /// refused now rather than at the first read. A view holds no rows, and /// its readers see its sources as they are at read time. /// - /// There is no replace: a name already taken is an error, and changing a - /// view is a drop followed by a create, each authorized against what it - /// actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. + /// A name already taken is an error unless [`CreateViewBuilder::exist_ok`] is + /// true, which returns the stored definition and schema without changing them. + /// Changing a view is a drop followed by a create, each authorized against what + /// it actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// # Example /// @@ -1011,16 +1015,18 @@ impl Connection { /// # Ok(()) /// # } /// ``` - pub async fn create_view( + pub fn create_view( &self, name: impl AsRef, query: impl AsRef, namespace_path: &[String], - ) -> Result { - validate_view_reference(name.as_ref(), namespace_path)?; - self.internal - .create_view(name.as_ref(), query.as_ref(), namespace_path) - .await + ) -> CreateViewBuilder { + CreateViewBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + query.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// What this database records about one view: its defining query and the diff --git a/rust/lancedb/src/connection/create_view.rs b/rust/lancedb/src/connection/create_view.rs new file mode 100644 index 000000000..bd80ca6e7 --- /dev/null +++ b/rust/lancedb/src/connection/create_view.rs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_view_reference; +use crate::view::ViewDescription; + +/// Configure creation of a view with [`super::Connection::create_view`]. +#[must_use] +pub struct CreateViewBuilder { + database: Arc, + name: String, + query: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateViewBuilder { + pub(super) fn new( + database: Arc, + name: String, + query: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + query, + namespace_path, + exist_ok: false, + } + } + + /// Return the existing view without changing its definition if it exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the view or return the existing view when `exist_ok` is true. + pub async fn execute(self) -> Result { + validate_view_reference(&self.name, &self.namespace_path)?; + self.database + .create_view(&self.name, &self.query, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateViewBuilder { + type Output = Result; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 23ed9fc3d..39e361a39 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -693,6 +693,7 @@ pub trait Database: _name: &str, _query: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result { view_ops_not_supported() } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 92523ec34..a05bb07b7 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1099,11 +1099,12 @@ impl Database for RemoteDatabase { name: &str, query: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .create_view(name, query, namespace_path) + .create_view(name, query, namespace_path, exist_ok) .await } async fn describe_view( diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index 0c2229684..513113187 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -99,13 +99,18 @@ impl SqlClient { name: &str, query: &str, namespace: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace)?; let namespace_path = namespace.to_vec(); + let if_not_exists = if exist_ok { " IF NOT EXISTS" } else { "" }; self.object_job( ExecuteQueryRequest { - query: format!("CREATE VIEW {} AS {query}", quote_identifier(name)), + query: format!( + "CREATE VIEW{if_not_exists} {} AS {query}", + quote_identifier(name) + ), default_namespace_path: namespace.to_vec(), parameters: None, }, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d25c72830..6a3f30390 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -24,6 +24,7 @@ use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; use crate::Connection; use crate::database::Database; +use crate::embeddings::MemoryRegistry; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::RemoteCatalogOptions; use crate::remote::client::HeaderProvider; @@ -3710,26 +3711,49 @@ async fn view_create_and_describe_return_metadata_through_sql() { ..Default::default() }; let statements = service.statements.clone(); + let headers = service.headers.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { panic!("unexpected REST request"); }) .with_sql_client(client); - let created = db + let connection = Connection::new(Arc::new(db), Arc::new(MemoryRegistry::new())); + let created = connection .create_view("adults", "SELECT name FROM people", &["team".into()]) .await .unwrap(); - let described = db.describe_view("adults", &["team".into()]).await.unwrap(); + let existing = connection + .create_view( + "adults", + "SELECT replacement FROM other_people", + &["team".into()], + ) + .exist_ok(true) + .await + .unwrap(); + let described = connection + .describe_view("adults", &["team".into()]) + .await + .unwrap(); assert_eq!(created, described); + assert_eq!(existing, described); assert_eq!(created.schema.fields()[0].name(), "name"); assert_eq!(created.default_namespace_path, ["team"]); assert_eq!( statements.lock().unwrap().as_slice(), [ "CREATE VIEW \"adults\" AS SELECT name FROM people", + "CREATE VIEW IF NOT EXISTS \"adults\" AS SELECT replacement FROM other_people", "DESCRIBE VIEW \"adults\"" ] ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); shutdown.send(()).unwrap(); } } From 2c3c30dbdf02a4dc9f725b00701b995954e228b1 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:35:54 -0800 Subject: [PATCH 42/75] feat(python): support exist_ok for Function creation (#4992) Adds `exist_ok=False` to Python Function creation and job submission. `exist_ok=True` sends `CREATE FUNCTION IF NOT EXISTS` and returns the stored immutable version, preserving its code, credentials and execution settings. The default retains the current version-creation behavior. ```python version = db.create_function(analyze_caption, exist_ok=True) ``` The option also exists on the Rust registration request and is kept out of the canonical Function definition payload. Includes sync/async/background protocol and stored-version coverage. Requires matching SQL server support. BREAKING CHANGE: Rust `FunctionRegistrationRequest` struct literals must initialize `exist_ok`; legacy serialized requests default to false. No local builds or tests were run, as requested. --- docs/web/management/function.mdx | 13 ++++ docs/web/sql/ddl/function.mdx | 9 +++ python/python/lancedb/_lancedb.pyi | 6 +- python/python/lancedb/db.py | 25 +++++++- python/python/lancedb/remote/db.py | 6 +- python/python/tests/test_function_creation.py | 63 +++++++++++++++++++ python/src/connection.rs | 6 +- rust/lancedb/src/function.rs | 7 +++ rust/lancedb/src/remote/sql/function.rs | 11 +++- rust/lancedb/src/remote/sql_test.rs | 20 +++++- 10 files changed, 155 insertions(+), 11 deletions(-) create mode 100644 python/python/tests/test_function_creation.py diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 04c146bb1..aae67ceb9 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -111,6 +111,19 @@ with `db.get_function(name, version=...)`. The version may be an integer or its string form. Omit `version` to resolve and return the latest currently visible revision. +{/* Draft for the function exist_ok release. + +Use `exist_ok=True` on `create_function` or `create_function_async` to return +the existing named version without changing its code, credentials or settings. +This requires a deployment that supports the option. The default retains the +current behavior of registering a new version. + +```python +version = db.create_function(embed, exist_ok=True) +``` + +*/} + The SQL command submits an internal `create_function` image-build job and waits for publication. The SDK returns the SQL query handle. Query handles diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 95c2d4d6e..55e2d6fe7 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -16,6 +16,15 @@ availability: ## CREATE FUNCTION {#create} +{/* Draft for the function exist_ok release. + +`CREATE FUNCTION IF NOT EXISTS` preserves an existing named Function version, +including its code, credentials and execution settings. In Python, pass +`exist_ok=True` to `create_function` or `create_function_async`. The default +retains the existing version-creation behavior. + +*/} + ```sql SQL icon="database" CREATE FUNCTION f(x int64) RETURNS int64 diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 56b644abb..44523fd42 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -188,7 +188,11 @@ class Connection(object): async def server_info(self) -> str: ... async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( - self, request_json: str, namespace_path: Optional[List[str]] = None + self, + request_json: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> Job: ... async def get_function( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 020c79be0..050b20727 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1004,10 +1004,14 @@ class DBConnection(EnforceOverrides): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. + ``exist_ok=True`` returns the existing named Function version unchanged. + By default, registration retains its existing version-creation behavior. + The server builds the OCI image and registers the completed artifact. This is the blocking counterpart of :meth:`create_function_async`. LanceDB Embedded connections raise ``NotImplementedError``. @@ -1040,7 +1044,10 @@ class DBConnection(EnforceOverrides): ``` """ return self.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ).wait() def create_function_async( @@ -1048,10 +1055,14 @@ class DBConnection(EnforceOverrides): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: """Submit a scalar Python function for building and registration. + ``exist_ok=True`` preserves an existing named version and its metadata. + The default retains the existing version-creation behavior. + The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. @@ -2396,11 +2407,15 @@ class LanceDBConnection(DBConnection): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ) ) return Job(job) @@ -3732,10 +3747,14 @@ class AsyncConnection(object): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[FunctionVersion]: """Submit a scalar Python function for building and registration. + ``exist_ok=True`` preserves an existing named version and its metadata. + The default retains the existing version-creation behavior. + The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. @@ -3749,7 +3768,7 @@ class AsyncConnection(object): raise TypeError("create_function_async requires a @function definition") request = definition.bind_secrets(secrets) inner = await self._inner.create_function_async( - request.to_canonical_json(), namespace_path + request.to_canonical_json(), namespace_path, exist_ok=exist_ok ) return _typed_job(inner, FunctionVersion.from_json) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ea9468331..870b85b1e 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -992,11 +992,15 @@ class RemoteDBConnection(DBConnection): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ) ) return Job(job) diff --git a/python/python/tests/test_function_creation.py b/python/python/tests/test_function_creation.py new file mode 100644 index 000000000..823dba7b9 --- /dev/null +++ b/python/python/tests/test_function_creation.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +import lancedb +from lancedb.functions import function + + +@pytest.mark.asyncio +@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"]) +@pytest.mark.parametrize("exist_ok", [None, False, True]) +async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/first_class_functions/v1" + / "remote_function_version.canonical.json" + ) + stored = json.loads(fixture.read_text()) + result = pa.table({"definition": [json.dumps(stored)]}) + + @function(name=stored["name"]) + def replacement(value: float) -> float: + return value * 2 + + class FunctionServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with FunctionServer() as server: + options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + kwargs["namespace_path"] = ["team"] + if entry == "async_job": + db = await lancedb.connect_async("db://analytics", **options) + job = await db.create_function_async(replacement, **kwargs) + version = await job.wait() + else: + db = lancedb.connect("db://analytics", **options) + if entry == "sync_job": + version = db.create_function_async(replacement, **kwargs).wait() + else: + version = db.create_function(replacement, **kwargs) + (request,) = server.requests + + prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION" + assert f'{prefix} "{stored["name"]}" FROM '.encode() in request + assert b'"exist_ok"' not in request + assert json.loads(version.to_canonical_json()) == stored diff --git a/python/src/connection.rs b/python/src/connection.rs index ffa59fd02..dabecc048 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -903,15 +903,17 @@ impl Connection { }) } - #[pyo3(signature = (request_json, namespace_path=None))] + #[pyo3(signature = (request_json, namespace_path=None, *, exist_ok=false))] pub fn create_function_async( self_: PyRef<'_, Self>, request_json: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); - let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) + let mut request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) .infer_error()?; + request.exist_ok = exist_ok; let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index e3d47948e..d1b63f2ad 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -834,6 +834,9 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s /// database already holds, which Sophon resolves inside the remote runtime. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FunctionRegistrationRequest { + /// Preserve an existing named Function version instead of registering a new one. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, /// Default retries of failed user-code calls. Enterprise only. #[serde(default, skip_serializing_if = "Option::is_none")] pub retry_policy: Option, @@ -876,6 +879,10 @@ pub struct FunctionRegistrationRequest { pub models: Vec, } +fn is_false(value: &bool) -> bool { + !*value +} + impl FunctionRegistrationRequest { /// Decode a registration request supplied by an SDK language binding. pub fn from_json(json: &str) -> Result { diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index c2b5aba06..19a1a6cbc 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -34,13 +34,22 @@ impl SqlClient { validate_function_name(&request.name)?; validate_namespace(namespace)?; let name = quote_identifier(&request.name); + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let mut body = serde_json::to_value(request).map_err(|error| Error::Runtime { message: error.to_string(), })?; body.as_object_mut().unwrap().remove("name"); + body.as_object_mut().unwrap().remove("exist_ok"); self.object_job( ExecuteQueryRequest { - query: format!("CREATE FUNCTION {name} FROM {}", literal(&body.to_string())), + query: format!( + "CREATE FUNCTION{if_not_exists} {name} FROM {}", + literal(&body.to_string()) + ), default_namespace_path: namespace.to_vec(), parameters: None, }, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 6a3f30390..e1780f118 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3087,7 +3087,16 @@ async fn function_creation_and_description_use_sql_query_handles() { const REQUEST: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" ); - for (defer, with_models) in [(false, false), (false, true), (true, false), (true, true)] { + for (defer, with_models, exist_ok) in [ + (false, false, false), + (false, true, false), + (true, false, false), + (true, true, false), + (false, false, true), + (false, true, true), + (true, false, true), + (true, true, true), + ] { let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); request_json["batch_size"] = serde_json::json!(2); request_json["max_concurrency"] = serde_json::json!(4); @@ -3113,9 +3122,11 @@ async fn function_creation_and_description_use_sql_query_handles() { let expected_models = version_json["image"].get("models"); let mut expected_request = request_json.clone(); expected_request.as_object_mut().unwrap().remove("name"); - let request = + let mut request = crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) .unwrap(); + assert!(!request.exist_ok); + request.exist_ok = exist_ok; let result = RecordBatch::try_from_iter(vec![( "definition", Arc::new(StringArray::from(vec![version_json.to_string()])) as ArrayRef, @@ -3151,7 +3162,10 @@ async fn function_creation_and_description_use_sql_query_handles() { { let seen = statements.lock().unwrap(); let encoded = seen[0] - .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .strip_prefix(&format!( + "CREATE FUNCTION{} \"normalize_score\" FROM '", + if exist_ok { " IF NOT EXISTS" } else { "" } + )) .unwrap() .strip_suffix('\'') .unwrap(); From a0eb6b4b71d7b59a5047387a32563b098e349418 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:37:08 -0800 Subject: [PATCH 43/75] feat(python): support exist_ok for storage integrations (#4986) Adds `exist_ok=False` to sync and async Python storage integration creation. `exist_ok=True` sends `CREATE STORAGE INTEGRATION IF NOT EXISTS` and returns the server's stored configuration, preserving the prefix, credentials and external ID. ```python integration = db.create_storage_integration( "raw", storage_provider="S3", storage_prefix="s3://customer-bucket/raw/", aws_role_arn="arn:aws:iam::123456789012:role/access", exist_ok=True, ) ``` The non-exhaustive Rust request also supports `.exist_ok(true)` for every provider. Requires a SQL server supporting this syntax. Includes protocol and provider SQL coverage. No local builds or tests were run, as requested. --- docs/web/sql/ddl/storage-integration.mdx | 10 +++ python/python/lancedb/db.py | 13 +++ python/python/lancedb/remote/db.py | 2 + .../test_storage_integration_creation.py | 85 +++++++++++++++++++ .../lancedb/src/remote/storage_integration.rs | 53 +++++++++++- rust/lancedb/src/storage_integration.rs | 26 ++++++ 6 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 python/python/tests/test_storage_integration_creation.py diff --git a/docs/web/sql/ddl/storage-integration.mdx b/docs/web/sql/ddl/storage-integration.mdx index 37351f971..9444824ac 100644 --- a/docs/web/sql/ddl/storage-integration.mdx +++ b/docs/web/sql/ddl/storage-integration.mdx @@ -28,6 +28,16 @@ CREATE STORAGE INTEGRATION ``` +{/* Draft for the storage-integration exist_ok release. + +`IF NOT EXISTS` returns an existing integration unchanged, including its provider, +storage prefix, credential references and external ID. In the Python SDK, pass +`exist_ok=True` to `create_storage_integration`. The default reports an error when +the name already exists. +Returning an existing integration requires `USAGE` on that integration. + +*/} + `STORAGE_PROVIDER` and `STORAGE_PREFIX` are required for every provider. `STORAGE_PREFIX` is the URI prefix the integration covers -- a query only matches an integration whose prefix is a prefix of the URI it reads. diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 050b20727..39c9eb1d5 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -432,8 +432,12 @@ class DBConnection(EnforceOverrides): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: + """Register storage access, preserving existing configuration with + ``exist_ok=True``. Existing names are errors by default. + """ raise NotImplementedError def describe_storage_integration( @@ -2503,6 +2507,7 @@ class LanceDBConnection(DBConnection): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: return LOOP.run( @@ -2520,6 +2525,7 @@ class LanceDBConnection(DBConnection): azure_client_secret_secret=azure_client_secret_secret, gcp_credentials_json_secret=gcp_credentials_json_secret, huggingface_token_secret=huggingface_token_secret, + exist_ok=exist_ok, namespace_path=namespace_path, ) ) @@ -3888,6 +3894,7 @@ class AsyncConnection(object): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: """Register cloud storage access using database-owned credential Secrets. @@ -3902,6 +3909,10 @@ class AsyncConnection(object): optionally set ``huggingface_token_secret`` to a Secret containing the token; omitting it selects anonymous access at the default rate limits. Registration returns setup instructions without verifying storage access. + + ``exist_ok=True`` returns the stored configuration unchanged when the + integration exists, preserving its provider, prefix and credential + bindings. Existing names are errors by default. """ azure_options = ( azure_tenant_id_secret, @@ -4010,6 +4021,8 @@ class AsyncConnection(object): "aws_access_key_id_secret": reference(aws_access_key_id_secret), "aws_secret_access_key_secret": reference(aws_secret_access_key_secret), } + if exist_ok: + request["exist_ok"] = True info = await self._inner.create_storage_integration( validate_secret_name(name), json.dumps(request), diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 870b85b1e..9221c7ceb 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1091,6 +1091,7 @@ class RemoteDBConnection(DBConnection): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: return LOOP.run( @@ -1108,6 +1109,7 @@ class RemoteDBConnection(DBConnection): azure_client_secret_secret=azure_client_secret_secret, gcp_credentials_json_secret=gcp_credentials_json_secret, huggingface_token_secret=huggingface_token_secret, + exist_ok=exist_ok, namespace_path=namespace_path, ) ) diff --git a/python/python/tests/test_storage_integration_creation.py b/python/python/tests/test_storage_integration_creation.py new file mode 100644 index 000000000..13b94d741 --- /dev/null +++ b/python/python/tests/test_storage_integration_creation.py @@ -0,0 +1,85 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "existing"), + [(None, False), (False, False), (True, False), (True, True)], +) +async def test_storage_integration_exist_ok_preserves_server_metadata( + asynchronous, exist_ok, existing +): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/storage_integration.json" + ) + stored = json.loads(fixture.read_text()) + stored["namespace_path"] = ["team"] + columns = {} + for key, value in stored.items(): + if isinstance(value, (dict, list)): + value = json.dumps(value) + columns[key] = pa.array([None], type=pa.string()) if value is None else [value] + result = pa.table(columns) + prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"] + role = ( + "arn:aws:iam::999999999999:role/replacement" + if existing + else stored["aws_role_arn"] + ) + + class IntegrationServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with IntegrationServer() as server: + connection_options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + kwargs.update( + storage_provider="S3", + storage_prefix=prefix, + aws_role_arn=role, + namespace_path=["team"], + ) + uri = f"db://{stored['database']}" + if asynchronous: + db = await lancedb.connect_async(uri, **connection_options) + info = await db.create_storage_integration(stored["name"], **kwargs) + else: + db = lancedb.connect(uri, **connection_options) + info = db.create_storage_integration(stored["name"], **kwargs) + (request,) = server.requests + + command = ( + "CREATE STORAGE INTEGRATION IF NOT EXISTS" + if exist_ok + else "CREATE STORAGE INTEGRATION" + ) + assert f'{command} "raw"'.encode() in request + assert prefix.encode() in request + assert role.encode() in request + assert info.storage_prefix == stored["storage_prefix"] + assert info.aws_role_arn == stored["aws_role_arn"] + assert info.aws_external_id == stored["aws_external_id"] + assert info.created_at_millis == stored["created_at_millis"] + assert info.namespace_path == ["team"] diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs index bdba4f1df..48dab4c6a 100644 --- a/rust/lancedb/src/remote/storage_integration.rs +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -54,6 +54,11 @@ pub(super) fn create_sql( namespace: &[String], request: &CreateStorageIntegrationRequest, ) -> Result { + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; if request.storage_provider != StorageProvider::HuggingFace && request.huggingface_token_secret.is_some() { @@ -77,7 +82,7 @@ pub(super) fn create_sql( )); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -115,7 +120,7 @@ pub(super) fn create_sql( .as_ref() .ok_or_else(|| invalid("GCP integrations require gcp_credentials_json_secret"))?; return Ok(format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", object_name(name, namespace)?, literal(&request.storage_prefix), secret_name(reference)? @@ -135,7 +140,7 @@ pub(super) fn create_sql( .filter(|account| !account.is_empty()) .ok_or_else(|| invalid("Azure integrations require azure_storage_account"))?; let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", object_name(name, namespace)?, literal(&request.storage_prefix), literal(account) @@ -169,7 +174,7 @@ pub(super) fn create_sql( return Err(invalid("S3 integrations cannot contain Azure options")); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -283,6 +288,46 @@ mod tests { use super::*; + #[test] + fn create_if_not_exists_preserves_provider_options() { + let secret = SecretReference::new("credential"); + let requests = [ + CreateStorageIntegrationRequest::s3("s3://bucket/", "role"), + CreateStorageIntegrationRequest::s3_with_secrets( + "s3://bucket/", + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::azure( + "az://container/", + "account", + secret.clone(), + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::gcp("gs://bucket/", secret), + CreateStorageIntegrationRequest::huggingface("hf://datasets/acme/data/"), + ]; + for request in requests { + let legacy_json = serde_json::to_value(&request).unwrap(); + assert!(legacy_json.get("exist_ok").is_none()); + let decoded: CreateStorageIntegrationRequest = + serde_json::from_value(legacy_json).unwrap(); + assert!(!decoded.exist_ok); + let strict = create_sql("raw", &[], &request).unwrap(); + let guarded = request.exist_ok(true); + assert_eq!(serde_json::to_value(&guarded).unwrap()["exist_ok"], true); + assert_eq!( + create_sql("raw", &[], &guarded).unwrap(), + strict.replacen( + "CREATE STORAGE INTEGRATION ", + "CREATE STORAGE INTEGRATION IF NOT EXISTS ", + 1, + ) + ); + } + } + #[test] fn sql_quotes_values_and_keeps_secret_root_namespace_explicit() { let role = CreateStorageIntegrationRequest::s3("s3://bucket/it's/", "role'value"); diff --git a/rust/lancedb/src/storage_integration.rs b/rust/lancedb/src/storage_integration.rs index 50bfc0aca..587528037 100644 --- a/rust/lancedb/src/storage_integration.rs +++ b/rust/lancedb/src/storage_integration.rs @@ -40,6 +40,9 @@ impl SecretReference { #[derive(Debug, Clone, Serialize, Deserialize)] #[non_exhaustive] pub struct CreateStorageIntegrationRequest { + /// Return the stored configuration unchanged when the integration already exists. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, pub storage_provider: StorageProvider, pub storage_prefix: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -77,12 +80,31 @@ pub enum StorageProvider { HuggingFace, } +fn is_false(value: &bool) -> bool { + !*value +} + impl CreateStorageIntegrationRequest { + /// Return an existing integration without changing its configuration. + /// Defaults to false, which reports an error for an existing name. + /// + /// ``` + /// use lancedb::storage_integration::CreateStorageIntegrationRequest; + /// let config = CreateStorageIntegrationRequest::huggingface( + /// "hf://datasets/acme/data/", + /// ).exist_ok(true); + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Register a prefix and the customer-owned IAM role authorized to access it. pub fn s3(storage_prefix: impl Into, aws_role_arn: impl Into) -> Self { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: Some(aws_role_arn.into()), aws_access_key_id_secret: None, aws_secret_access_key_secret: None, @@ -105,6 +127,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: None, aws_access_key_id_secret: Some(access_key), aws_secret_access_key_secret: Some(secret_key), @@ -138,6 +161,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Azure, storage_prefix: storage_prefix.into(), + exist_ok: false, azure_storage_account: Some(storage_account.into()), azure_tenant_id_secret: Some(tenant_id), azure_client_id_secret: Some(client_id), @@ -163,6 +187,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Gcp, storage_prefix: storage_prefix.into(), + exist_ok: false, gcp_credentials_json_secret: Some(credentials_json), huggingface_token_secret: None, aws_role_arn: None, @@ -189,6 +214,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::HuggingFace, storage_prefix: storage_prefix.into(), + exist_ok: false, huggingface_token_secret: None, gcp_credentials_json_secret: None, aws_role_arn: None, From 4db0d5c7f50a61d1c01a9ef409c11e3ba09d04eb Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:48:26 -0800 Subject: [PATCH 44/75] feat(python): support exist_ok when cloning tables (#4990) Adds `exist_ok=False` to Python table cloning and `.exist_ok(true)` to the Rust clone builder. An existing target is returned with its data and version history unchanged; strict duplicate errors remain the default. ```python snapshot = db.clone_table("snapshot", source_uri, exist_ok=True) ``` Embedded cloning skips source reads for an existing target and handles typed creation conflicts. Remote cloning forwards the option to the server. Includes sync/async preservation and remote request coverage, plus SQL syntax documentation for `CREATE TABLE IF NOT EXISTS target CLONE source`. Requires a server supporting the option for remote clones. BREAKING CHANGE: Rust `CloneTableRequest` struct literals must initialize the new `exist_ok` field; `CloneTableRequest::new` remains compatible. No local builds or tests were run, as requested. --- docs/web/management/table.mdx | 12 ++++ docs/web/sql/ddl/table.mdx | 10 ++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 8 +++ python/python/lancedb/remote/db.py | 4 ++ python/python/tests/test_clone_creation.py | 36 ++++++++++++ python/src/connection.rs | 6 +- rust/lancedb/src/connection.rs | 30 +++++++++- rust/lancedb/src/database.rs | 3 + rust/lancedb/src/database/listing.rs | 65 ++++++++++++++-------- rust/lancedb/src/remote/db.rs | 16 +++++- 11 files changed, 162 insertions(+), 30 deletions(-) create mode 100644 python/python/tests/test_clone_creation.py diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index bf6bf3edd..8031a4c49 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -270,6 +270,18 @@ Renaming is not supported on a local directory connection. In LanceDB Enterprise whether a table can be renamed or cloned at all depends on how the deployment stores its catalog. +{/* Draft for the table-clone exist_ok release. + +Pass `exist_ok=True` to keep an existing target table, including its data and +version history, instead of reporting a duplicate. The source is used only when +the target is missing. Remote use requires a deployment that supports this option. + +```python +db.clone_table("docs_snapshot", source_uri="s3://bucket/db/documents.lance", exist_ok=True) +``` + +*/} + A **shallow** clone (the default) references the source's data files rather than copying them, so it is fast and cheap regardless of table size. It is the practical way to branch an experiment off a known version, or to pin a training diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index ab0ff64bf..c8c42d4e0 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -205,6 +205,16 @@ Dropping, renaming, or retyping a column is an SDK operation ## CLONE {#clone} +{/* Draft for the table-clone exist_ok release. + +Use `CREATE TABLE IF NOT EXISTS target CLONE source` to preserve an existing +target unchanged. The Python equivalent is +`db.clone_table("target", source_uri, exist_ok=True)`. Omitting the option reports +an error for an existing target. A skipped clone does not copy rows or change +the target's version history. + +*/} + ```sql SQL icon="database" CREATE TABLE docs_snapshot CLONE documents diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 44523fd42..d5c024959 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -347,6 +347,8 @@ class Connection(object): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + *, + exist_ok: bool = False, ) -> Table: ... async def rename_table( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 39c9eb1d5..18ca9cf6f 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -2271,6 +2271,7 @@ class LanceDBConnection(DBConnection): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> LanceTable: """Clone a table from a source table. @@ -2295,6 +2296,8 @@ class LanceDBConnection(DBConnection): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -2310,6 +2313,7 @@ class LanceDBConnection(DBConnection): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) ) return LanceTable.open( @@ -3595,6 +3599,7 @@ class AsyncConnection(object): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> AsyncTable: """Clone a table from a source table. @@ -3619,6 +3624,8 @@ class AsyncConnection(object): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -3633,6 +3640,7 @@ class AsyncConnection(object): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) return AsyncTable(table) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 9221c7ceb..69b691004 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -576,6 +576,7 @@ class RemoteDBConnection(DBConnection): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> Table: """Clone a table from a source table. @@ -595,6 +596,8 @@ class RemoteDBConnection(DBConnection): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -612,6 +615,7 @@ class RemoteDBConnection(DBConnection): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) ) return RemoteTable( diff --git a/python/python/tests/test_clone_creation.py b/python/python/tests/test_clone_creation.py new file mode 100644 index 000000000..6c12420c5 --- /dev/null +++ b/python/python/tests/test_clone_creation.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous): + source_uri = str(tmp_path / "source.lance") + if asynchronous: + db = await lancedb.connect_async(tmp_path) + await db.create_table("source", [{"id": 1}]) + table = await db.clone_table("target", source_uri, exist_ok=True) + assert (await table.to_arrow()).to_pylist() == [{"id": 1}] + await table.add([{"id": 2}]) + version = await table.version() + with pytest.raises(ValueError, match="already exists"): + await db.clone_table("target", source_uri) + kept = await db.clone_table("target", "missing.lance", exist_ok=True) + assert await kept.version() == version + assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}] + else: + db = lancedb.connect(tmp_path) + db.create_table("source", [{"id": 1}]) + table = db.clone_table("target", source_uri, exist_ok=True) + assert table.to_arrow().to_pylist() == [{"id": 1}] + table.add([{"id": 2}]) + version = table.version + with pytest.raises(ValueError, match="already exists"): + db.clone_table("target", source_uri) + kept = db.clone_table("target", "missing.lance", exist_ok=True) + assert kept.version == version + assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}] diff --git a/python/src/connection.rs b/python/src/connection.rs index dabecc048..8763822cc 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -457,7 +457,8 @@ impl Connection { }) } - #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true, *, exist_ok=false))] pub fn clone_table( self_: PyRef<'_, Self>, target_table_name: String, @@ -466,6 +467,7 @@ impl Connection { source_version: Option, source_tag: Option, is_shallow: bool, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); @@ -477,7 +479,7 @@ impl Connection { if let Some(tag) = source_tag { builder = builder.source_tag(tag); } - builder = builder.is_shallow(is_shallow); + builder = builder.is_shallow(is_shallow).exist_ok(exist_ok); future_into_py(self_.py(), async move { let table = builder.execute().await.infer_error()?; diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index c7a058502..6dacbbbea 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -433,6 +433,21 @@ impl CloneTableBuilder { } } + /// Preserve an existing target without reading or cloning the source. + /// Defaults to false, which reports a duplicate-name error. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let table = db.clone_table("snapshot", "s3://bucket/source.lance") + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.request.exist_ok = exist_ok; + self + } + /// Set the source version to clone from pub fn source_version(mut self, version: u64) -> Self { self.request.source_version = Some(version); @@ -633,7 +648,8 @@ impl Connection { /// Creates a new table by cloning from an existing source table. /// By default, this performs a shallow clone where the new table shares /// the underlying data files with the source table. - /// The target table name must be unused. An existing table is left unchanged. + /// The target table name must be unused by default. Use + /// [`CloneTableBuilder::exist_ok`] to open an existing target unchanged. /// /// # Parameters /// - `target_table_name`: The name of the new table to create @@ -2787,6 +2803,14 @@ mod tests { "unexpected clone error: {err:?}" ); + let preserved = db + .clone_table(target, "missing-source.lance") + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(preserved.name(), target); + // Reopen both tables to verify that the failed clone left their data and versions intact. for (name, expected_data) in [("source", source_data), ("target", target_data)] { let table = db.open_table(name).execute().await.unwrap(); @@ -2804,8 +2828,9 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { let tmp_dir = tempdir().unwrap(); let uri = tmp_dir.path().to_str().unwrap(); let db = connect(uri).execute().await.unwrap(); @@ -2830,6 +2855,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table("cloned_table", source_uri) + .exist_ok(exist_ok) .execute() .await .unwrap(); diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 39e361a39..638ae0dd5 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -163,6 +163,8 @@ impl CreateTableRequest { /// sharing the same data, deletion, and index files. #[derive(Clone, Debug)] pub struct CloneTableRequest { + /// Preserve an existing target rather than returning a duplicate-name error. + pub exist_ok: bool, /// The name of the target table to create pub target_table_name: String, /// The namespace path for the target table. Empty list represents root namespace. @@ -184,6 +186,7 @@ pub struct CloneTableRequest { impl CloneTableRequest { pub fn new(target_table_name: String, source_uri: String) -> Self { Self { + exist_ok: false, target_table_name, target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index d5749f974..765c8af3d 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1119,40 +1119,47 @@ impl Database for ListingDatabase { }; let target_uri = self.table_uri(&request.target_table_name)?; - match DatasetBuilder::from_uri(&target_uri) + let exists = match DatasetBuilder::from_uri(&target_uri) .with_read_params(read_params.clone()) .load() .await { - Ok(_) => { + Ok(_) if !request.exist_ok => { return Err(Error::TableAlreadyExists { name: request.target_table_name, }); } - Err(lance::Error::DatasetNotFound { .. }) => {} + Ok(_) => true, + Err(lance::Error::DatasetNotFound { .. }) => false, Err(err) => return Err(err.into()), + }; + + if !exists { + let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) + .with_read_params(read_params.clone()) + .load() + .await + .map_err(|e| -> Error { e.into() })?; + + let version_ref = match (request.source_version, request.source_tag) { + (Some(v), None) => Ok(Ref::Version(None, Some(v))), + (None, Some(tag)) => Ok(Ref::Tag(tag)), + (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), + _ => Err(Error::InvalidInput { + message: "Cannot specify both source_version and source_tag".to_string(), + }), + }?; + + match source_dataset + .shallow_clone(&target_uri, version_ref, Some(storage_params)) + .await + { + Ok(_) => {} + Err(lance::Error::DatasetAlreadyExists { .. }) if request.exist_ok => {} + Err(error) => return Err(error.into()), + } } - let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) - .with_read_params(read_params.clone()) - .load() - .await - .map_err(|e| -> Error { e.into() })?; - - let version_ref = match (request.source_version, request.source_tag) { - (Some(v), None) => Ok(Ref::Version(None, Some(v))), - (None, Some(tag)) => Ok(Ref::Tag(tag)), - (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), - _ => Err(Error::InvalidInput { - message: "Cannot specify both source_version and source_tag".to_string(), - }), - }?; - - source_dataset - .shallow_clone(&target_uri, version_ref, Some(storage_params)) - .await - .map_err(|e| -> Error { e.into() })?; - let cloned_table = NativeTable::open_with_params( &target_uri, &request.target_table_name, @@ -2252,6 +2259,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_table".to_string(), target_namespace_path: vec![], source_uri: source_uri.clone(), @@ -2313,6 +2321,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_with_data".to_string(), target_namespace_path: vec![], source_uri, @@ -2375,6 +2384,7 @@ mod tests { // Clone should work with storage options let cloned = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2412,6 +2422,7 @@ mod tests { // Try deep clone (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2453,6 +2464,7 @@ mod tests { // Try clone with namespace (should fail for listing database) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec!["namespace".to_string()], // Non-empty namespace source_uri, @@ -2494,6 +2506,7 @@ mod tests { // Try clone with invalid target name let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "invalid/name".to_string(), // Invalid name with slash target_namespace_path: vec![], source_uri, @@ -2514,6 +2527,7 @@ mod tests { // Try to clone from non-existent source let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri: "/nonexistent/table.lance".to_string(), @@ -2551,6 +2565,7 @@ mod tests { // Try clone with both version and tag (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2625,6 +2640,7 @@ mod tests { // Clone from the initial version (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_version".to_string(), target_namespace_path: vec![], source_uri, @@ -2704,6 +2720,7 @@ mod tests { // Clone from the tag (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_tag".to_string(), target_namespace_path: vec![], source_uri, @@ -2756,6 +2773,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "independent_clone".to_string(), target_namespace_path: vec![], source_uri, @@ -2849,6 +2867,7 @@ mod tests { // Clone without specifying version or tag (should get latest) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_latest".to_string(), target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a05bb07b7..300cd6b09 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1612,10 +1612,13 @@ impl Database for RemoteDatabase { is_shallow: Some(request.is_shallow), }; - let req = self + let mut req = self .client .post(&format!("/v1/table/{}/clone", table_identifier.clone())) .json(&remote_request); + if request.exist_ok { + req = req.query(&[("exist_ok", true)]); + } let (request_id, rsp) = self.client.send(req).await?; @@ -3651,9 +3654,10 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { - let conn = Connection::new_with_handler(|request| { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { + let conn = Connection::new_with_handler(move |request| { assert_eq!(request.method(), &reqwest::Method::POST); assert_eq!(request.url().path(), "/v1/table/cloned_table/clone"); assert_eq!( @@ -3665,12 +3669,18 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(body).unwrap(); assert_eq!(body["source_location"], "s3://bucket/source_table"); assert_eq!(body["is_shallow"], true); + if exist_ok { + assert_eq!(request.url().query(), Some("exist_ok=true")); + } else { + assert!(request.url().query().is_none()); + } http::Response::builder().status(200).body("").unwrap() }); let table = conn .clone_table("cloned_table", "s3://bucket/source_table") + .exist_ok(exist_ok) .execute() .await .unwrap(); From 81d04b8c361b596b29f4f7988aab7df0eb9f84ca Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 19:21:29 -0800 Subject: [PATCH 45/75] feat(python): support exist_ok for materialized views (#4991) --- docs/web/sql/ddl/materialized-view.mdx | 10 +++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 25 ++++++ python/python/lancedb/namespace.py | 8 ++ python/python/lancedb/remote/db.py | 4 + .../tests/test_materialized_view_creation.py | 84 +++++++++++++++++++ .../python/tests/test_materialized_views.py | 2 + python/src/connection.rs | 10 ++- rust/lancedb/src/materialized_view.rs | 49 ++++++++++- rust/lancedb/src/remote/db.rs | 11 ++- .../src/remote/sql/materialized_view.rs | 15 ++++ rust/lancedb/src/remote/sql_test.rs | 60 +++++++++++++ rust/lancedb/src/remote/table.rs | 7 ++ 13 files changed, 281 insertions(+), 6 deletions(-) create mode 100644 python/python/tests/test_materialized_view_creation.py diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index 2f9173ecd..a2453ba01 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -27,6 +27,16 @@ CREATE MATERIALIZED VIEW AS SELECT ... ``` +{/* Draft for the materialized-view exist_ok release. + +`IF NOT EXISTS` preserves an existing materialized view's definition, data and +refresh settings without refreshing it. The Python equivalent is +`db.create_materialized_view("saved", "source", exist_ok=True)`. A skipped +asynchronous creation returns a completed job without submitting a refresh job. +Existing names are errors by default. + +*/} + Once created, a materialized view can be queried like a table. Use the statements below to list, refresh and drop it. For SDK methods, see [Materialized views](/management/materialized-view#create). diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index d5c024959..e3f00557c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -369,6 +369,7 @@ class Connection(object): auto_refresh_interval_seconds: Optional[float] = None, *, query: Optional[str] = None, + exist_ok: bool = False, ) -> Table: ... async def create_materialized_view_async( self, @@ -382,6 +383,7 @@ class Connection(object): auto_refresh_interval_seconds: Optional[float] = None, *, query: Optional[str] = None, + exist_ok: bool = False, ) -> Job: ... def list_materialized_views( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 18ca9cf6f..b84e4d581 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -710,11 +710,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -780,11 +784,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: """Submit materialized-view creation and return its job. + ``exist_ok=True`` preserves an existing view without refreshing it. + A skipped creation returns a completed job without a registry job ID. + The job may already be complete in LanceDB Embedded. In LanceDB Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL server and the returned ``id`` is the registry job ID. That ID can be @@ -2150,11 +2158,15 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -2185,6 +2197,7 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -2202,6 +2215,7 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: @@ -2214,6 +2228,7 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -3453,11 +3468,15 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncMaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -3480,6 +3499,7 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, @@ -3496,11 +3516,15 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job. + ``exist_ok=True`` preserves an existing view without refreshing it. + A skipped creation returns a completed job without a registry job ID. + Wait for the returned job before opening or querying the view. In LanceDB Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. @@ -3521,6 +3545,7 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 72dc78c8b..67fcc61f7 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -705,6 +705,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> "MaterializedView": """Define a materialized view over a table in the root namespace. See @@ -723,6 +724,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) ).name ) @@ -741,6 +743,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> Job[None]: job = LOOP.run( self._inner.create_materialized_view_async( @@ -753,6 +756,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) ) return Job(job) @@ -1352,6 +1356,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> "AsyncMaterializedView": """Define a materialized view over a table in the root namespace.""" view = await self._inner.create_materialized_view( @@ -1364,6 +1369,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) # Reopen through the namespace so the view's table carries the # namespace client and pushdown configuration a bare inner table lacks. @@ -1381,6 +1387,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job.""" return await self._inner.create_materialized_view_async( @@ -1393,6 +1400,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) async def open_materialized_view(self, name: str) -> "AsyncMaterializedView": diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 69b691004..b9928d278 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -803,6 +803,7 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: @@ -817,6 +818,7 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -841,6 +843,7 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: @@ -853,6 +856,7 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) diff --git a/python/python/tests/test_materialized_view_creation.py b/python/python/tests/test_materialized_view_creation.py new file mode 100644 index 000000000..0d9a4c2b4 --- /dev/null +++ b/python/python/tests/test_materialized_view_creation.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +import lancedb + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("namespace", [False, True]) +@pytest.mark.parametrize("defining_query", [False, True]) +async def test_exist_ok_preserves_materialized_data( + tmp_path, asynchronous, background, namespace, defining_query +): + source_args = ( + {"query": "SELECT * FROM source"} if defining_query else {"source": "source"} + ) + replacement_args = { + **( + {"query": "SELECT * FROM missing"} + if defining_query + else {"source": "missing"} + ), + "auto_refresh_enabled": True, + "auto_refresh_interval_seconds": 1, + } + options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}} + if asynchronous: + db = ( + lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options) + if namespace + else await lancedb.connect_async(tmp_path, **options) + ) + source = await db.create_table("source", [{"id": 1}]) + original = await db.create_materialized_view( + "saved", **source_args, exist_ok=True + ) + definition = await original.definition() + version = await original.table.version() + await source.add([{"id": 2}]) + if background: + job = await db.create_materialized_view_async( + "saved", **replacement_args, exist_ok=True + ) + await job.wait() + kept = await db.open_materialized_view("saved") + else: + kept = await db.create_materialized_view( + "saved", **replacement_args, exist_ok=True + ) + assert (await kept.definition()).query == definition.query + assert await kept.table.version() == version + assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}] + with pytest.raises(ValueError, match="already exists"): + await db.create_materialized_view("saved", **source_args) + else: + db = ( + lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options) + if namespace + else lancedb.connect(tmp_path, **options) + ) + source = db.create_table("source", [{"id": 1}]) + original = db.create_materialized_view("saved", **source_args, exist_ok=True) + definition = original.definition + version = original.table.version + source.add([{"id": 2}]) + if background: + job = db.create_materialized_view_async( + "saved", **replacement_args, exist_ok=True + ) + job.wait() + kept = db.open_materialized_view("saved") + else: + kept = db.create_materialized_view( + "saved", **replacement_args, exist_ok=True + ) + assert kept.definition.query == definition.query + assert kept.table.version == version + assert kept.table.to_arrow().to_pylist() == [{"id": 1}] + with pytest.raises(ValueError, match="already exists"): + db.create_materialized_view("saved", **source_args) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 1ea0c1cb9..13950a39c 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -197,6 +197,7 @@ def test_sync_remote_create_uses_public_async_connection(query): where=None, limit=None, with_no_data=False, + exist_ok=False, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, ): @@ -729,6 +730,7 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options "filter": None, "limit": None, "with_no_data": False, + "exist_ok": False, "auto_refresh_enabled": options.get("auto_refresh_enabled"), "auto_refresh_interval_seconds": options.get( "auto_refresh_interval_seconds" diff --git a/python/src/connection.rs b/python/src/connection.rs index 8763822cc..1a171032c 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -507,7 +507,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, @@ -519,6 +519,7 @@ impl Connection { auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let builder = materialized_view_builder( @@ -529,7 +530,7 @@ impl Connection { projections.is_some() || filter.is_some() || limit.is_some(), )?; future_into_py(self_.py(), async move { - let mut builder = builder; + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -552,7 +553,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, @@ -564,6 +565,7 @@ impl Connection { auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let builder = materialized_view_builder( @@ -574,7 +576,7 @@ impl Connection { projections.is_some() || filter.is_some() || limit.is_some(), )?; future_into_py(self_.py(), async move { - let mut builder = builder; + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 9920cd893..4b2a61f2c 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -287,6 +287,8 @@ pub struct MaterializedViewInfo { #[doc(hidden)] #[derive(Debug, Clone, PartialEq)] pub struct CreateMaterializedViewRequest { + /// Preserve an existing materialized view without refreshing it. + pub exist_ok: bool, /// Name of the new view. pub name: String, /// Namespace in which to create the view. @@ -1586,6 +1588,7 @@ pub struct CreateMaterializedViewBuilder { filter: Option, limit: Option, with_no_data: bool, + exist_ok: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, } @@ -1626,6 +1629,7 @@ impl CreateMaterializedViewBuilder { filter: None, limit: None, with_no_data: false, + exist_ok: false, auto_refresh_enabled: None, auto_refresh_interval_seconds: None, } @@ -1678,6 +1682,35 @@ impl CreateMaterializedViewBuilder { self } + /// Preserve an existing view's definition, data and refresh settings. + /// Defaults to false. A skipped creation does not refresh the view. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// db.create_materialized_view("saved", "source").exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + async fn existing_view(&self) -> Result> { + match self + .connection + .open_table(&self.name) + .namespace(self.namespace.clone()) + .execute() + .await + { + Ok(table) => MaterializedView::from_table(table).await.map(Some), + Err(Error::TableNotFound { .. }) => Ok(None), + Err(error) => Err(error), + } + } + /// Enable or disable automatic refresh in LanceDB Enterprise. /// When omitted, the server determines whether automatic refresh is enabled. /// LanceDB Embedded does not support automatic refresh. @@ -1759,6 +1792,7 @@ impl CreateMaterializedViewBuilder { .connection .database() .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: self.exist_ok, name: self.name.clone(), namespace_path: self.namespace.clone(), query: self.query()?, @@ -1793,6 +1827,11 @@ impl CreateMaterializedViewBuilder { async fn execute_native(self) -> Result { crate::require_experimental_functions()?; + if self.exist_ok + && let Some(view) = self.existing_view().await? + { + return Ok(view); + } if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { return Err(Error::NotSupported { message: "automatic materialized-view refresh requires LanceDB Enterprise" @@ -1826,7 +1865,15 @@ impl CreateMaterializedViewBuilder { prepare_definition(&source, definition).await? } }; - let view = prepared.create_in(&self.namespace, &self.name).await?; + let view = match prepared.create_in(&self.namespace, &self.name).await { + Ok(view) => view, + Err(Error::TableAlreadyExists { .. }) if self.exist_ok => { + return self.existing_view().await?.ok_or_else(|| Error::Runtime { + message: "materialized view disappeared after concurrent creation".into(), + }); + } + Err(error) => return Err(error), + }; if !self.with_no_data { view.refresh().execute().await?; } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 300cd6b09..7100e1b04 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -803,16 +803,24 @@ impl Database for RemoteDatabase { } else { format!(" WITH ({})", options.join(", ")) }; + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let submission = client .submit_materialized_view_job( format!( - "CREATE MATERIALIZED VIEW \"{name}\"{options} AS {}", + "CREATE MATERIALIZED VIEW{if_not_exists} \"{name}\"{options} AS {}", request.query ), request.namespace_path, ) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Ok(Job::new_done()) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new(Box::new(RemoteJob::new( @@ -4865,6 +4873,7 @@ mod tests { for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { let result = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec![], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index 4eaad5156..e982afac7 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -39,6 +39,7 @@ fn strings(batch: &RecordBatch, name: &str) -> Result> { } pub(in crate::remote) enum MaterializedViewJobSubmission { + AlreadyExists, Registry { job_id: String }, Query(Arc), } @@ -66,6 +67,7 @@ impl SqlClient { let mut reader: SendableRecordBatchStream = query.reader().await?; let mut rows = 0; let mut registry_job_id = None; + let mut already_exists = false; while let Some(batch) = reader.try_next().await? { rows += batch.num_rows(); if rows > 1 { @@ -74,6 +76,16 @@ impl SqlClient { .into(), }); } + if let Some(column) = batch.column_by_name("status") { + let values = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "materialized-view submission status is not UTF-8".into(), + })?; + already_exists = + values.len() == 1 && !values.is_null(0) && values.value(0) == "already_exists"; + } if let Some(column) = batch.column_by_name("job_id") { let values = column .as_any() @@ -100,6 +112,9 @@ impl SqlClient { message: "materialized-view submission must return exactly one status row".into(), }); } + if already_exists && registry_job_id.is_none() { + return Ok(MaterializedViewJobSubmission::AlreadyExists); + } let job_id = registry_job_id.ok_or_else(|| Error::Runtime { message: "server acknowledged an early materialized-view handle but returned no job_id" .into(), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index e1780f118..1c39eda19 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1220,6 +1220,7 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { ] { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1302,6 +1303,7 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1329,6 +1331,63 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry_job() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + materialized_view_job_handle_supported: true, + ..Default::default() + }; + let statement = "CREATE MATERIALIZED VIEW IF NOT EXISTS \"adults\" AS SELECT * FROM people"; + service.result_overrides.lock().unwrap().insert( + statement.into(), + RecordBatch::try_from_iter([ + ( + "status", + Arc::new(StringArray::from(vec!["already_exists"])) as arrow_array::ArrayRef, + ), + ( + "job_id", + Arc::new(StringArray::from(vec![""])) as arrow_array::ArrayRef, + ), + ]) + .unwrap(), + ); + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!( + "a skipped creation must not poll a registry job: {}", + request.url() + ); + }) + .with_sql_client(client); + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: true, + name: "adults".into(), + namespace_path: vec!["team".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + }) + .await + .unwrap(); + if defer { + assert!(job.id().is_none()); + } else { + assert_eq!(job.job_type().as_deref(), Some("query")); + } + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert_eq!(*statements.lock().unwrap(), [statement]); + shutdown.send(()).unwrap(); + } +} + #[tokio::test] async fn remote_create_registry_handle_reopens_describes_and_cancels() { let service = TestSqlService { @@ -1394,6 +1453,7 @@ async fn remote_create_registry_handle_reopens_describes_and_cancels() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 9b64ab56d..f4e5c1e4a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2658,6 +2658,13 @@ impl BaseTable for RemoteTable { .submit_materialized_view_job(statement, self.namespace.clone()) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Err(Error::Runtime { + message: + "REFRESH MATERIALIZED VIEW returned a create-only already_exists status" + .into(), + }) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new_typed(Box::new(MaterializedViewRefreshJob { From f6311ae7e9c34ab8fc5067282fec864bd9f3a558 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 19:21:50 -0800 Subject: [PATCH 46/75] feat: support exist_ok for index creation (#4993) --- docs/web/sql/ddl/index.mdx | 40 +++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/remote/table.py | 10 ++ python/python/lancedb/table.py | 71 ++++++++- python/python/tests/test_index.py | 42 ++++++ python/python/tests/test_remote_db.py | 52 +++++++ python/python/tests/test_table.py | 96 ++++++++++++ python/python/tests/test_table_signatures.py | 6 +- python/src/table.rs | 10 +- rust/lancedb/src/index.rs | 17 +++ rust/lancedb/src/remote/table.rs | 42 +++++- rust/lancedb/src/table.rs | 8 +- rust/lancedb/src/table/create_index.rs | 146 ++++++++++++++++++- 13 files changed, 525 insertions(+), 17 deletions(-) diff --git a/docs/web/sql/ddl/index.mdx b/docs/web/sql/ddl/index.mdx index 425af7376..035424b5f 100644 --- a/docs/web/sql/ddl/index.mdx +++ b/docs/web/sql/ddl/index.mdx @@ -38,6 +38,46 @@ runs as `create_` followed by the algorithm instead. See [Incremental Indexing](/indexing/incremental-indexing). +{/* Draft for the index exist_ok release. + +```sql +CREATE INDEX IF NOT EXISTS text_search ON documents USING fts (text) +``` + +Use `IF NOT EXISTS` to preserve the existing index with the same name. Without an +explicit name, the name is derived from the column (`title_idx`, or +`title_list_element_idx` for list-element FTS). Existing definitions and builds +are kept, even when the new request specifies different settings. + +The Python SDK exposes the same behavior through `exist_ok=True` on +`create_index` and `create_index_async`, including scalar and FTS wrappers. +This option takes precedence over `replace`, whose default behavior is unchanged. + +```python +from lancedb.index import BTree + +table.create_index("title", config=BTree(), name="title_idx", exist_ok=True) +``` + +```rust +use lancedb::index::Index; + +table.create_index(&["title"], Index::BTree(Default::default())) + .name("title_idx".to_string()) + .exist_ok(true) + .execute() + .await?; +``` + +The SDK option is available in Python and Rust. TypeScript support is a separate +follow-up. Remote use requires a server that supports the option. + +An existing background build continues running. A completed submission handle +for a skipped creation does not wait for that build; use `wait_for_index` when +its completion is required. + +*/} + ## DROP INDEX {#drop} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index e3f00557c..cbc62f772 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -591,6 +591,7 @@ class Table: *, name: Optional[str], train: Optional[bool], + exist_ok: bool = False, ): ... async def create_index_async( self, @@ -615,6 +616,7 @@ class Table: *, name: Optional[str], train: Optional[bool], + exist_ok: bool = False, ) -> Job: ... async def list_versions(self) -> List[Dict[str, Any]]: ... async def version(self) -> int: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 6730e6694..dbfd127ee 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -369,6 +369,7 @@ class RemoteTable(Table): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -395,6 +396,7 @@ class RemoteTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -433,6 +435,7 @@ class RemoteTable(Table): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on a column. @@ -492,6 +495,7 @@ class RemoteTable(Table): self._table.create_index( field_names, replace=replace, + exist_ok=exist_ok, config=config, name=name, wait_timeout=wait_timeout, @@ -516,6 +520,7 @@ class RemoteTable(Table): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -541,6 +546,7 @@ class RemoteTable(Table): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -572,6 +578,7 @@ class RemoteTable(Table): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -675,6 +682,7 @@ class RemoteTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -690,6 +698,7 @@ class RemoteTable(Table): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -702,6 +711,7 @@ class RemoteTable(Table): self._table.create_index_async( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 5f0af7a66..e0b96e476 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -168,6 +168,36 @@ def _validate_index_accelerator(accelerator: Any) -> None: raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err +def _create_accelerated_index(dataset, *, exist_ok=False, name=None, **options): + if exist_ok: + parts = _parse_field_path(options["column"]) + default_name = ".".join(parts) + if any("." in part for part in parts): + default_name = ".".join( + "`" + part.replace("`", "``") + "`" + if any( + not character.isalnum() and character != "_" for character in part + ) + else part + for part in parts + ) + name = name or f"{default_name}_idx" + dataset.checkout_latest() + if any(index["name"] == name for index in dataset.list_indices()): + return + options["replace"] = False + options["name"] = name + _validate_index_accelerator(options.get("accelerator")) + try: + dataset.create_index(**options) + except Exception: + if exist_ok: + dataset.checkout_latest() + if any(index["name"] == name for index in dataset.list_indices()): + return + raise + + def _polars_predicate_pushdown_barrier(frame: Any) -> Any: """Return a Polars frame unchanged while blocking predicate pushdown.""" return frame @@ -1834,6 +1864,7 @@ class Table(ABC): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -1859,6 +1890,7 @@ class Table(ABC): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -1890,6 +1922,7 @@ class Table(ABC): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -1913,6 +1946,9 @@ class Table(ABC): BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. + exist_ok : bool, default False + Preserve the existing index with the requested or derived name. + Takes precedence over replace and keeps its definition and build. wait_timeout : timedelta, optional LanceDB Enterprise only: how long to wait for the index build to finish. If not set, the call returns once the build is scheduled. @@ -1968,6 +2004,7 @@ class Table(ABC): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -2060,6 +2097,7 @@ class Table(ABC): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -2144,6 +2182,7 @@ class Table(ABC): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on the table. @@ -4318,6 +4357,7 @@ class LanceTable(Table): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -4343,6 +4383,7 @@ class LanceTable(Table): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -4374,6 +4415,7 @@ class LanceTable(Table): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -4397,6 +4439,9 @@ class LanceTable(Table): BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. + exist_ok : bool, default False + Preserve the existing index with the requested or derived name. + Takes precedence over replace and keeps its definition and build. wait_timeout : timedelta, optional Timeout to wait for async indexing to complete. name : str, optional @@ -4465,8 +4510,10 @@ class LanceTable(Table): # Handle accelerator through pylance if accelerator is not None: dataset = self.to_lance() - _validate_index_accelerator(accelerator) - dataset.create_index( + _create_accelerated_index( + dataset, + exist_ok=exist_ok, + name=name, column=column, index_type=index_type, metric=metric, @@ -4492,7 +4539,6 @@ class LanceTable(Table): if acc is not None: # Dispatch to pylance for GPU acceleration dataset = self.to_lance() - _validate_index_accelerator(acc) index_type_map = { "IvfFlat": "IVF_FLAT", "IvfSq": "IVF_SQ", @@ -4509,7 +4555,10 @@ class LanceTable(Table): if num_bits is not None: quantization_kwargs["num_bits"] = num_bits - dataset.create_index( + _create_accelerated_index( + dataset, + exist_ok=exist_ok, + name=name, column=column, index_type=lance_index_type, metric=getattr(config, "distance_type", "l2"), @@ -4531,6 +4580,7 @@ class LanceTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4546,6 +4596,7 @@ class LanceTable(Table): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -4564,6 +4615,7 @@ class LanceTable(Table): self._table.create_index_async( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4684,6 +4736,7 @@ class LanceTable(Table): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -4710,6 +4763,7 @@ class LanceTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4747,6 +4801,7 @@ class LanceTable(Table): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on a column. @@ -4808,6 +4863,7 @@ class LanceTable(Table): self._table.create_index( field_names, replace=replace, + exist_ok=exist_ok, config=config, name=name, wait_timeout=wait_timeout, @@ -6806,6 +6862,7 @@ class AsyncTable: ] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ): """Create an index to speed up queries @@ -6836,6 +6893,9 @@ class AsyncTable: If not set, the call returns once the build is scheduled. name: str, optional The name of the index. If not provided, a default name will be generated. + exist_ok: bool, default False + Preserve an existing index with the requested or derived name. This + takes precedence over replace and keeps its definition and build. train: bool, default True Whether to train the index with existing data. Vector indices always train with existing data. @@ -6891,6 +6951,7 @@ class AsyncTable: column, index=config, replace=replace, + exist_ok=exist_ok, wait_timeout=wait_timeout, name=name, train=train, @@ -6928,6 +6989,7 @@ class AsyncTable: ] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> AsyncJob: """Create an index, returning a handle to the indexing job. @@ -6946,6 +7008,7 @@ class AsyncTable: column, index=config, replace=replace, + exist_ok=exist_ok, wait_timeout=wait_timeout, name=name, train=train, diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 738a791ad..e658d18e1 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -621,3 +621,45 @@ def test_index_statistics_index_type_lists_all_supported_values(): set(get_args(get_type_hints(IndexStatistics)["index_type"])) == expected_index_types ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))] +) +async def test_index_exist_ok_preserves_existing_index( + some_table, background, column, config +): + await some_table.create_index(column, config=config, exist_ok=True) + version = await some_table.version() + original = await some_table.list_indices() + if background: + job = await some_table.create_index_async( + column, config=config, replace=True, exist_ok=True + ) + await job.wait() + else: + await some_table.create_index( + column, config=config, replace=True, exist_ok=True + ) + assert await some_table.version() == version + assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [ + (i.name, i.index_type) for i in original + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("background", [False, True]) +async def test_named_index_exist_ok_checks_before_column_validation( + some_table, background +): + await some_table.create_index("id", config=BTree(), name="kept") + version = await some_table.version() + method = some_table.create_index_async if background else some_table.create_index + result = await method("missing", config=BTree(), name="kept", exist_ok=True) + if background: + assert result.id is None + await result.wait() + assert await some_table.version() == version + assert [index.name for index in await some_table.list_indices()] == ["kept"] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ca2516fda..ea7f73c71 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -45,6 +45,7 @@ from lancedb.query import ( LanceVectorQueryBuilder, MatchQuery, ) +from lancedb.index import BTree from lancedb.remote import ClientConfig from lancedb.remote.errors import ( AlreadyExistsError, @@ -7420,3 +7421,54 @@ async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnati if use_async: await result assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("kwargs", [{}, {"exist_ok": False}, {"exist_ok": True}]) +async def test_remote_index_exist_ok_wire(is_async, background, kwargs): + received = [] + + def handler(request): + parsed = urlparse(request.path) + body = request.rfile.read(int(request.headers.get("Content-Length", 0))) + if parsed.path.endswith("/create_index/"): + received.append((parse_qs(parsed.query), json.loads(body))) + payload = {} + elif parsed.path.endswith("/describe/"): + payload = dict( + version=1, + schema=dict( + fields=[dict(name="id", type={"type": "int64"}, nullable=False)] + ), + ) + elif parsed.path.endswith("/create/"): + payload = {} + else: + raise AssertionError(request.path) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + + method = "create_index_async" if background else "create_index" + if is_async: + async with mock_lancedb_connection_async(handler) as db: + table = await db.create_table("test", [{"id": 1}]) + result = await getattr(table, method)("id", config=BTree(), **kwargs) + if background: + await result.wait() + else: + with mock_lancedb_connection(handler) as db: + table = db.create_table("test", [{"id": 1}]) + result = getattr(table, method)("id", config=BTree(), **kwargs) + if background: + result.wait() + query, body = received[0] + assert query == ({"exist_ok": ["true"]} if kwargs.get("exist_ok") else {}) + assert "exist_ok" not in body + if kwargs.get("exist_ok"): + assert body["replace"] is False + else: + assert "replace" not in body diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e3b69ced1..604d6afb3 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1837,6 +1837,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # Test with target_partition_size @@ -1862,6 +1863,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # target_partition_size has a default value, @@ -1886,6 +1888,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1902,6 +1905,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1922,6 +1926,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1942,6 +1947,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) @@ -2073,6 +2079,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name="my_custom_index", train=True, + exist_ok=False, ) # Test with train=False @@ -2084,6 +2091,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name=None, train=False, + exist_ok=False, ) # Test with both name and train @@ -2095,6 +2103,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name="my_index_name", train=True, + exist_ok=False, ) @@ -2132,6 +2141,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # Scalar index via new API @@ -2143,6 +2153,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # FTS index via new API @@ -2154,6 +2165,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) @@ -6292,3 +6304,87 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path): metadata = (await table.schema()).field("doubled").metadata assert metadata[b"computed_column.auto_refresh_enabled"] == b"true" assert b"computed_column.auto_refresh_interval_seconds" not in metadata + + +@pytest.mark.parametrize( + "method", + ["create_index", "create_index_async", "create_scalar_index", "create_fts_index"], +) +@pytest.mark.parametrize("name", [None, "kept_index"]) +def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name): + table = mem_db.create_table( + "keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)] + ) + column = "text" if method == "create_fts_index" else "id" + config = FTS() if column == "text" else BTree() + table.create_index(column, config=config, name=name, exist_ok=True) + before = table.version + original = table.list_indices() + kwargs = dict(name=name, exist_ok=True) + if method in ("create_index", "create_index_async"): + kwargs["config"] = config + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + result = getattr(table, method)(column, **kwargs) + if method == "create_index_async": + result.wait() + assert table.version == before + assert [(index.name, index.index_type) for index in table.list_indices()] == [ + (index.name, index.index_type) for index in original + ] + with pytest.raises((ValueError, RuntimeError), match="already exists"): + table.create_index(column, config=config, name=name, replace=False) + table.create_index(column, config=config, name=name) + assert table.version > before + + +@pytest.mark.parametrize( + "column,name,existing", + [ + ("vector", "kept", "kept"), + ("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"), + ], +) +def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing): + dataset = MagicMock() + dataset.list_indices.return_value = [{"name": existing}] + with patch("lancedb.table._validate_index_accelerator") as validate: + table_module._create_accelerated_index( + dataset, column=column, accelerator="cuda", name=name, exist_ok=True + ) + validate.assert_not_called() + dataset.create_index.assert_not_called() + + +def test_accelerated_index_exist_ok_preserves_concurrent_winner(): + dataset = MagicMock() + dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]] + dataset.create_index.side_effect = RuntimeError("concurrent create") + with patch("lancedb.table._validate_index_accelerator"): + table_module._create_accelerated_index( + dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True + ) + assert dataset.create_index.call_args.kwargs["replace"] is False + assert dataset.create_index.call_args.kwargs["name"] == "vector_idx" + + +@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"]) +def test_index_exist_ok_matches_lance_default_name(mem_db, column): + table = mem_db.create_table( + "quoted_index", + [{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}], + ) + table.create_index(column, config=BTree()) + before = table.version + table.create_index(column, config=BTree(), exist_ok=True) + assert table.version == before + assert len(table.list_indices()) == 1 + + +def test_fts_exist_ok_matches_quoted_default_name(mem_db): + table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}]) + table.create_index("`body-text`", config=FTS()) + before = table.version + table.create_index("`body-text`", config=FTS(), exist_ok=True) + assert table.version == before + assert len(table.list_indices()) == 1 diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py index 387a89f31..41a688068 100644 --- a/python/python/tests/test_table_signatures.py +++ b/python/python/tests/test_table_signatures.py @@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table): }.items(): assert getattr(config, name) == value assert kwargs == dict( - wait_timeout=timeout, name="custom_idx", replace=False, train=False + wait_timeout=timeout, + name="custom_idx", + replace=False, + train=False, + exist_ok=False, ) diff --git a/python/src/table.rs b/python/src/table.rs index 31cf8d25c..f77ff5a7f 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1628,7 +1628,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index<'a>( self_: PyRef<'a, Self>, column: String, @@ -1637,6 +1638,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1645,6 +1647,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } @@ -1661,7 +1664,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index_async<'a>( self_: PyRef<'a, Self>, column: String, @@ -1670,6 +1674,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1678,6 +1683,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 87eff864d..91c941154 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -220,6 +220,7 @@ pub struct IndexBuilder { pub(crate) index: Index, pub(crate) columns: Vec, pub(crate) replace: bool, + pub(crate) exist_ok: bool, pub(crate) wait_timeout: Option, pub(crate) train: bool, pub(crate) name: Option, @@ -232,6 +233,7 @@ impl IndexBuilder { index, columns, replace: true, + exist_ok: false, train: true, wait_timeout: None, name: None, @@ -324,6 +326,21 @@ impl IndexBuilder { self } + /// Preserve an existing index with the requested name. Defaults to false. + /// This takes precedence over `replace`; a skipped creation does not rebuild. + /// + /// ```no_run + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// table.create_index(&["id"], lancedb::index::Index::Auto) + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Duration of time to wait for asynchronous indexing to complete. If not set, /// `create_index()` will not wait. /// diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f4e5c1e4a..a7cf3f80d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -701,9 +701,13 @@ impl RemoteTable { async fn submit_create_index(&self, mut index: IndexBuilder) -> Result> { self.check_mutable().await?; - let request = self + let mut request = self .client .post(&format!("/v1/table/{}/create_index/", self.identifier)); + if index.exist_ok { + request = request.query(&[("exist_ok", true)]); + index.replace = false; + } let column = match index.columns.len() { 0 => { @@ -18101,6 +18105,42 @@ mod tests { branch.restore().await.unwrap(); } + #[tokio::test] + async fn test_index_exist_ok_query_and_replacement_policy() { + for exist_ok in [false, true] { + for background in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/create_index/" => { + assert_eq!(request.url().query(), exist_ok.then_some("exist_ok=true")); + let body = request_body_json(&request); + assert_eq!( + body.get("replace"), + exist_ok.then_some(&serde_json::Value::Bool(false)) + ); + assert!(body.get("exist_ok").is_none()); + http::Response::builder() + .status(200) + .body("{}".into()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let builder = table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(exist_ok); + if background { + builder.execute_async().await.unwrap().wait().await.unwrap(); + } else { + builder.execute().await.unwrap(); + } + } + } + } + #[tokio::test] async fn test_branch_create_index_carries_branch_in_body() { use lance::dataset::refs::Ref; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4959b2842..ff0ab8b94 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4145,14 +4145,18 @@ impl BaseTable for NativeTable { } async fn create_index(&self, opts: IndexBuilder) -> Result<()> { - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(()); + }; self.build_index(opts, prepared).await } async fn create_index_async(&self, opts: IndexBuilder) -> Result { // Prepare before spawning so bad input is reported by this call rather // than only by the job. - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(Job::new_done()); + }; let table = self.clone(); Ok(Job::spawned(tokio::spawn(async move { table.build_index(opts, prepared).await diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 5f9ae13b4..e0da64029 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -115,14 +115,24 @@ impl NativeTable { pub(super) async fn prepare_index( &self, opts: &crate::index::IndexBuilder, - ) -> Result { + ) -> Result> { + self.dataset.ensure_mutable()?; + let dataset = self.dataset.get().await?; + if opts.exist_ok + && let Some(name) = &opts.name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(None); + } if opts.columns.len() != 1 { return Err(Error::Schema { message: "Multi-column (composite) indices are not yet supported".to_string(), }); } - self.dataset.ensure_mutable()?; - let dataset = self.dataset.get().await?; let (column, field) = if let Index::FTS(params) = &opts.index { let resolved = resolve_lance_fts_field_path(dataset.schema(), &opts.columns[0])?; if params.get_document_granularity().is_list_element() && resolved.list_depth == 0 { @@ -137,9 +147,48 @@ impl NativeTable { } else { Self::resolve_index_field(dataset.schema(), &opts.columns[0])? }; + if let Some(name) = Self::guarded_index_name(opts, &column)? + && dataset + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(None); + } let params = self.make_index_params(&field, opts.index.clone()).await?; let index_type = self.get_index_type_for_field(&field, &opts.index); - Ok((column, params, index_type)) + Ok(Some((column, params, index_type))) + } + + fn guarded_index_name( + opts: &crate::index::IndexBuilder, + column: &str, + ) -> Result> { + let name = if opts.exist_ok { + Some(if let Some(name) = &opts.name { + name.clone() + } else { + let names = lance_core::datatypes::parse_field_path(column)?; + let default_name = if matches!(&opts.index, Index::FTS(_)) + || names.iter().any(|name| name.contains('.')) + { + column.to_string() + } else { + names.join(".") + }; + let suffix = if matches!(&opts.index, Index::FTS(params) if params.get_document_granularity().is_list_element()) + { + "_list_element_idx" + } else { + "_idx" + }; + format!("{default_name}{suffix}") + }) + } else { + None + }; + Ok(name) } /// Builds a prepared index and publishes the new dataset version. @@ -150,16 +199,42 @@ impl NativeTable { ) -> Result<()> { let (column, lance_idx_params, index_type) = prepared; let mut dataset = (*self.dataset.get().await?).clone(); + let guarded_name = Self::guarded_index_name(&opts, &column)?; + if let Some(name) = &guarded_name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(()); + } let columns = [column.as_str()]; let mut builder = dataset .create_index_builder(&columns, index_type, lance_idx_params.as_ref()) .train(opts.train) - .replace(opts.replace); + .replace(opts.replace && !opts.exist_ok); - if let Some(name) = opts.name { + if let Some(name) = guarded_name.clone().or(opts.name) { builder = builder.name(name); } - builder.await?; + if let Err(error) = builder.await { + if let Some(name) = guarded_name { + self.dataset.reload().await?; + if self + .dataset + .get() + .await? + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(()); + } + } + return Err(error.into()); + } // A writer already open was built before this index existed, so it has // to pick it up here or a read needing it is refused until it reopens. self.dataset @@ -568,6 +643,63 @@ mod tests { Ok(FixedSizeListArray::from(data)) } + #[tokio::test] + async fn test_concurrent_index_exist_ok_preserves_single_identity() { + let dir = tempdir().unwrap(); + let db = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("id", Int32, (0..512).collect::>())).unwrap(); + let table = db.create_table("t", batch).execute().await.unwrap(); + let second = db.open_table("t").execute().await.unwrap(); + let (left, right) = tokio::join!( + table + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute(), + second + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute() + ); + left.unwrap(); + right.unwrap(); + table.checkout_latest().await.unwrap(); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices.len(), 1); + let original_uuid = indices[0].uuid; + let version = table.version().await.unwrap(); + table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), version); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices[0].uuid, original_uuid); + } + #[tokio::test] async fn test_create_index() { use std::iter::repeat_with; From d67ec47921ba0b761405b898703725864adb15a2 Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:23:41 -0800 Subject: [PATCH 47/75] docs: make the landing page concise (#4898) Shortens the docs landing page and organizes its overview around database features, with the multimodal data model, ML workflow, SDKs, and PyTorch loader explained in prose. Keeps versioning visible, branching in draft, and the existing `{#architecture}` anchor. Validation: added documentation links and anchors verified; `git diff --check` passes. `mint validate` reports the same four pre-existing missing snippet-export warnings in the reranking and vector-search pages, also reproduced on the unchanged revision. Closes https://linear.app/lancedb/issue/DOC-80/strengthen-what-is-lancedb --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brendan Clement --- docs/web/basics/lance.mdx | 2 +- docs/web/docs.json | 2 +- docs/web/enterprise/deployment/kubernetes.mdx | 2 +- docs/web/enterprise/security.mdx | 2 +- docs/web/index.mdx | 157 +++++------------- docs/web/quickstart.mdx | 6 +- 6 files changed, 51 insertions(+), 120 deletions(-) diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index 84996ffe9..341d36cde 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -76,4 +76,4 @@ boundaries). - [Multimodal data and blobs](/management/table#multimodal): declare `lancedb.blob()` columns and read blobs on demand. - [Table versioning](/management/table#versioning): read and manage table versions. - [Computed columns](/feature-engineering/add-computed-column): add derived features to your data. -- [Architecture](/index#architecture): how LanceDB Embedded and Enterprise build on Lance. +- [Embedded vs Enterprise](/basics/embedded-vs-enterprise): how LanceDB Embedded and Enterprise build on Lance. diff --git a/docs/web/docs.json b/docs/web/docs.json index c20341793..3414fd121 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -81,7 +81,7 @@ }, { "source": "/basics/offerings", - "destination": "/#architecture" + "destination": "/basics/embedded-vs-enterprise" }, { "source": "/enterprise/deployment", diff --git a/docs/web/enterprise/deployment/kubernetes.mdx b/docs/web/enterprise/deployment/kubernetes.mdx index 0133cf065..0c09d7f90 100644 --- a/docs/web/enterprise/deployment/kubernetes.mdx +++ b/docs/web/enterprise/deployment/kubernetes.mdx @@ -10,7 +10,7 @@ keywords: ["kubernetes", "k8s", "aks", "deployment", "helm"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/index#architecture) for what differs between the two. +[Embedded vs Enterprise](/basics/embedded-vs-enterprise) for what differs between the two. The Kubernetes deployment procedure is published with LanceDB Enterprise. See [LanceDB Enterprise](/enterprise#deployment) for the general shape, and diff --git a/docs/web/enterprise/security.mdx b/docs/web/enterprise/security.mdx index 367e71b51..25af04656 100644 --- a/docs/web/enterprise/security.mdx +++ b/docs/web/enterprise/security.mdx @@ -10,7 +10,7 @@ keywords: ["compliance", "security", "soc2", "encryption", "audit"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/index#architecture) for what differs between the two. +[Embedded vs Enterprise](/basics/embedded-vs-enterprise) for what differs between the two. Compliance posture (certifications, data residency, encryption at rest and in transit, audit logging) is a property of a deployment, so it is documented diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 7b6bc6eed..1d451c246 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -6,130 +6,59 @@ icon: "/static/assets/logo/lancedb-icon-gray.svg" keywords: ["multimodal lakehouse", "training", "feature engineering", "search", "open source", "oss"] --- -**LanceDB** is a [multimodal lakehouse](https://lancedb.com/blog/multimodal-lakehouse/) for AI teams that need -one data layer for curation, feature engineering, search and retrieval, and model training. -It is built on top of [Lance](/basics/lance), an open-source lakehouse format designed for multimodal AI data. +LanceDB Enterprise is a distributed multimodal lakehouse for AI. It gives you one data layer for search and +retrieval, curation, feature engineering, and model training. It is built on [Lance](/basics/lance), an open-source +columnar format for multimodal AI data. For the open-source retrieval library that runs inside your application, +see [LanceDB Embedded](/basics/lancedb-embedded). -Move from data exploration to model training on one unified platform without needing to manage a -fragmented stack of storage, feature, retrieval, and training systems. +LanceDB Enterprise depends only on object storage for its primary state, and NVMe/memory for caching in the serving +layer, giving it the latency profile of an in-memory database with the petabyte scalability and cost profile of S3. +It brings these workloads into one system, giving your team one system to become expert in and removing the need +for multiple database systems and synchronization pipelines between them. -## Train on the right data faster {#train-on-the-right-data-faster} +Core features include: -Search, curate, and train at petabyte scale, with all your multimodal data in one table. +- [**SQL**](/basics/sql) powered by Apache DataFusion +- [**Secondary indexes**](/indexing) for vector search, full-text search, and scalar filters +- [**Computed columns**](/feature-engineering/add-computed-column) with on-demand or scheduled refresh +- [**Materialized views**](/feature-engineering/materialized-views) with on-demand or scheduled refresh +- [**Time travel and versioning**](/management/table#versioning) to pin and revisit datasets +- **Search**: [vector](/search/vector-search), [full-text](/search/full-text-search), and + [hybrid](/search/hybrid-search), with [filters](/search/filtering) and [reranking](/reranking) +- [**Functions**](/curation/create-function) for custom transformations and model inference (early access) +- [**Row-level random access**](/basics/lance#capabilities) for retrieval and training +- [**Column additions**](/management/table#schema-add-new-columns) without rewriting existing columns -Preparing training data and running experiments slow down when raw data, metadata, embeddings, features, and governance -artifacts live in separate systems. LanceDB keeps them together in one versioned multimodal table, so AI teams spend less -time stitching infrastructure together and more time improving datasets, testing features, and keeping GPUs fed. +{/* +Draft until branching reaches early access. Add this item to the list above, after Time travel and versioning: +- [**Copy-on-write branching**](/tables/branching) that gives each experiment or agent a writable fork of a table to review before it reaches `main` +*/} -## Accelerate the data flywheel for model research {#accelerate-the-data-flywheel-for-model-research} +LanceDB Enterprise stores images, video, audio, text, embeddings, and metadata in +[schema-enforced tables](/management/table#multimodal). These features let you build +declarative ML data pipelines: ingest raw data and metadata, enrich it incrementally with computed columns and +Functions, and organize it into [curated datasets](/curation) with materialized views. Add features without +rewriting existing columns, then train from those datasets using row-level random access and sampling. -Keep your AI data in one table.{/* Draft until branching reaches early access: restore ", and give each agent-driven experiment its own isolated branch" before the period. */} -Find the failure, fix the data, and retrain. +Connect through [SDKs](/basics/sdk) for Python, TypeScript, and Rust, and use the +[PyTorch data loader](/training/data-loading) for reproducible shuffling and streaming batches. - - - Start from one failed grasp or evaluation example. [Search](/search/) multimodal data, metadata, and embeddings - together, retrieve similar examples, and [curate](/curation) them into a targeted training subset. - - {/* - Draft until branching reaches early access. +## Architecture {#architecture} - - Don't let an agent silently corrupt your data and ruin a training run. Give each agent its own - [branch](/tables/branching), a writable fork of the table, to experiment on, and review the changes before - they reach `main`. See [Run experiments on branches](/agent-branch-experiments). - - */} - - Keep episodes, frames, metadata, features, and embeddings together in one schema-enforced table, without - pipelines to keep them in sync. Table [versions](/management/table#versioning) let you trace each training - run back to the exact data it used. - - - Define the [computed columns](/feature-engineering/add-computed-column) and - [materialized views](/feature-engineering/materialized-views) your experiment needs, such as extracted features - or embeddings, and refresh them as your data changes. On LanceDB Enterprise, column refreshes run as background - jobs on the cluster instead of in your code. - - - Keep GPUs fed. [`StreamingDataset`](/training/data-loading) streams multimodal training data into PyTorch with - globally shuffled, deterministic batches, combining fast random access with high-throughput scans. - - +Queries and feature engineering run across a cluster, with background indexing and maintenance. Deploy +LanceDB Enterprise in your cloud or use a LanceDB-managed deployment. -Use the same table to curate training data, add derived features, retrieve examples, and feed training jobs that rely on expensive GPUs. -Training workloads can sample, shuffle, and scan projected columns from local storage or object storage, then assemble -GPU-ready batches from a tagged dataset version. Training pipelines need curation, derived features, reproducible -splits, fast random access, and a clean path into frameworks such as PyTorch -- LanceDB keeps all of it connected -through the same table model, whether a workflow uses one table or several related ones. - -## Architecture: Embedded and Enterprise {#architecture} - -LanceDB ships as two offerings on the same [Lance](/basics/lance) format and table model, which stores table data, -versions, and indexes in open, columnar files. What changes between them is how storage and compute are organized -around that format: start locally with Embedded, then move to Enterprise when your team needs distributed scale, -managed infrastructure, private deployment, or higher-throughput curation, feature engineering, search and -retrieval, and training workflows. - - - - An open-source, embedded retrieval library that runs inside your application process, with no separate - database server to deploy. - - - A distributed multimodal lakehouse service for production workloads that need managed infrastructure and - higher-throughput workflows. - - - -See [Embedded vs Enterprise](/basics/embedded-vs-enterprise) for a feature-by-feature comparison, including -architecture, latency, throughput, and day-to-day usage differences. +Your application connects to the service through an SDK or [SQL client](/basics/sql). The cluster executes queries, +refreshes derived data, and maintains tables and indexes outside your application. ## Projects using LanceDB {#projects-using-lancedb} -### Training {#training} - -- [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) -- a platform for reproducible world-model - research built on a LanceDB data layer, reporting 3-4x faster data loading on Push-T versus HDF5 / MP4 at a - fraction of the disk footprint. -- [le-wm](https://github.com/lucas-maes/le-wm) -- a joint-embedding predictive world model from pixels, trained on - the stable-worldmodel platform and its LanceDB data layer. -- [lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb) -- a drop-in LanceDB backend for HuggingFace - LeRobot datasets with faster loading across robotics datasets. - -### Agentic applications {#agentic-applications} - -- [OpenClaw LanceDB Plugin](https://docs.openclaw.ai/plugins/memory-lancedb) -- stores an agent's long-term memory - in LanceDB, automatically recalling relevant memories before a model turn and capturing new facts afterward. -- [Cognee](https://github.com/topoteretes/cognee) -- an open-source AI memory platform that gives agents persistent - memory across sessions, using LanceDB as one of its vector store backends. -- [CrewAI](https://github.com/crewAIInc/crewAI) -- a multi-agent framework that - [rebuilt its agent memory on LanceDB](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb). - -Across these projects, LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations, -features, and training or memory access patterns in one format instead of scattering them across task-specific -stores. - -## Start with your workload {#start-with-your-workload} - - - - Create tables, append records, and update or delete rows as your data changes. - - - Use vector search, full-text search, hybrid search, reranking, filtering, and SQL. - - - Profile, sample, chunk, join, and deduplicate records before training on them. - - - Derive computed columns and materialized views without moving data elsewhere. - - - Use LanceDB tables and permutations for projected, shuffled, random-access training reads. - - - Create, list, and drop tables, namespaces, and views from Python, TypeScript, or SQL. - - +Teams use LanceDB for world-model and robotics training, as in +[stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) and +[lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb), and for agent memory, as in +[CrewAI](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb), +[Cognee](https://github.com/topoteretes/cognee), and +[OpenClaw](https://docs.openclaw.ai/plugins/memory-lancedb). +Try out LanceDB using our [quickstart](/quickstart). For help planning an Enterprise deployment +that meets your scale and performance needs, [contact the LanceDB team](https://www.lancedb.com/contact). diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index ef462cbf7..12c9f87ca 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -7,8 +7,10 @@ icon: rocket import { PyConnect, TsConnect, RsConnect, PyConnectObjectStorage, TsConnectObjectStorage, RsConnectObjectStorage, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartCurateSample, PyQuickstartCurateDedupeSetup, PyQuickstartCurateDedupe, PyQuickstartCurateDedupeQuery, PyQuickstartFlattenStats, PyQuickstartAddFeature, PyQuickstartAddFeatureEnterprise, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, RsQuickstartMultimodalBytes } from '/snippets/quickstart.mdx'; -This quickstart uses LanceDB Embedded with a local database and works without an account or API key. -LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. +This quickstart walks you through creating a table, searching your data, and preparing it for training. +By default, it uses LanceDB Embedded with a local database, so no account or API key is required. +To follow along with an existing LanceDB Enterprise deployment, use the +[Enterprise connection instructions](#connect-to-lancedb-enterprise). ## 1\. Install LanceDB {#1-install-lancedb} From 97e62dc11b561db29df24260d158ec9dba1f9a0d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 15:41:33 +0800 Subject: [PATCH 48/75] feat(remote): expose canonical job statistics reports (#5016) Expose `Job::stats()` in Rust and synchronous/asynchronous Python jobs. It reads `POST /v1/jobs/stats` and returns the canonical server-rendered report verbatim, or `None` for a running job or one without a readable durable profile. It does not wait for completion or recompute measurements. On `cc25005525671756b5cf5ebd96492b792e9aa1cb`, all three Rust transport tests and six Python tests passed against the matching rebuilt native extension; strict SDK Clippy also passed. These tests cover optional reports, exact text preservation, fresh reads, errors, and the HTTP boundary with a controlled server. Against the actual Phalanx HTTP route from [Sophon #10247](https://github.com/lancedb/sophon/pull/10247) (`5be3236`), the same native extension also completed two sync and two async reads after durable registry archival, preserving the exact canonical report. This is an HTTP/registry integration fixture, not a Function workload or shared-cluster acceptance. The private runner's JSON field-order collector failed after the successful probe; all raw evidence was retained and hash-verified, and the original receipt was recovered with the corrected parser without rerunning the probe. The follow-up `ad36f66` only corrects the synchronous Python API-reference link to the asynchronous method. Ruff checks and formatting passed; runtime evidence above remains applicable. The actual Phalanx/native-SDK probe covers archived reports; running-job null availability is covered by separate backend and SDK transport tests, not that end-to-end probe. Part of ENT-3501. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/job.py | 41 +++++++++++ python/python/tests/test_job.py | 40 +++++++++++ python/python/tests/test_remote_db.py | 44 ++++++++++++ python/src/job.rs | 5 ++ rust/lancedb/src/job.rs | 28 ++++++++ rust/lancedb/src/remote/job.rs | 97 +++++++++++++++++++++++++++ 7 files changed, 256 insertions(+) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index cbc62f772..1e811d865 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -437,6 +437,7 @@ class Job: async def cancel(self) -> None: ... async def refresh(self) -> None: ... async def timeline(self) -> str: ... + async def stats(self) -> Optional[str]: ... async def events( self, *, diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index bf9605567..9195e01ae 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -425,6 +425,32 @@ class AsyncJob(Generic[T]): description = self._inner._description if self._inner is not None else None return getattr(description, name) if description is not None else None + async def stats(self) -> Optional[str]: + """Return a printable run report for this Function job. + + The report includes recorded phase timings, finishing-supervisor slot + occupancy, all-attempt split execution and batch latency, and accepted-row + throughput. Each call reads the current server report. + Returns ``None`` while the job is running or if no recorded profile is + available, without waiting for completion. Missing measurements remain + unavailable rather than becoming zero. The server formats the report; + the SDK returns it verbatim. + + Requires a server-side Function job and a server supporting run reports. + Local operations and SQL query handles do not support this operation. + Unsupported operations raise ``NotImplementedError`` or a server error. + This method returns text; use ``print`` to display it. + + Examples + -------- + >>> print(await job.stats()) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job statistics require a server-side Function job" + ) + return await self._inner.stats() + async def export_timeline(self, path: str | PathLike[str]) -> None: """Write a fresh recorded Function job timeline as Chrome trace JSON. @@ -649,6 +675,21 @@ class Job(Generic[T]): def _field(self, name: str) -> Optional[Any]: return getattr(self._inner, name) if self._inner is not None else None + def stats(self) -> Optional[str]: + """Return a printable Function job run report. + + See [AsyncJob.stats][lancedb.job.AsyncJob.stats] for metrics and availability. + + Examples + -------- + >>> print(job.stats()) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job statistics require a server-side Function job" + ) + return LOOP.run(self._inner.stats()) + def export_timeline(self, path: str | PathLike[str]) -> None: """Write Chrome trace JSON for this Function job. diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 690f6414b..9897d97b5 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -754,6 +754,46 @@ async def test_query_wait_timeout_requires_keeping_original_handle(): assert "db.open_job" not in message +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stats_returns_fresh_report_without_waiting_or_printing(sync, capsys): + reports = [ + None, + "Function job: finished\nWorker utilization: unavailable\n", + "Function job: finished\nWorker utilization: 25.0%\n", + ] + inner = SimpleNamespace( + stats=AsyncMock(side_effect=reports), + wait=AsyncMock(), + cancel=AsyncMock(), + ) + job = AsyncJob(inner) + for expected in reports: + actual = await asyncio.to_thread(Job(job).stats) if sync else await job.stats() + assert actual == expected + inner.wait.assert_not_awaited() + inner.cancel.assert_not_awaited() + assert capsys.readouterr().out == "" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stats_preserves_errors_and_rejects_untracked_jobs(sync): + error = RuntimeError("run reports are unavailable on this server") + job = AsyncJob(SimpleNamespace(stats=AsyncMock(side_effect=error))) + with pytest.raises(RuntimeError) as exc: + if sync: + await asyncio.to_thread(Job(job).stats) + else: + await job.stats() + assert exc.value is error + with pytest.raises(NotImplementedError, match="server-side Function job"): + if sync: + Job(None).stats() + else: + await AsyncJob(None).stats() + + @pytest.mark.asyncio @pytest.mark.parametrize("sync", [False, True]) async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ea7f73c71..b38ae4a5b 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2732,6 +2732,50 @@ async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync): assert exc.value.__cause__.is_transport_error is True +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_remote_job_stats_returns_native_optional_report(sync): + report = "Function job: finished\nWorker utilization: unavailable\n" + paths = [] + + def handler(request): + payload = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert payload == {"job_id": "refresh-1"} + paths.append(request.path) + if request.path == "/v1/jobs/describe": + response = { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "IN_PROGRESS", + "creation_ms": 1000, + } + elif request.path == "/v1/jobs/stats": + available = paths.count("/v1/jobs/stats") > 1 + response = { + "job_id": "refresh-1", + "profile": {"future_field": True} if available else None, + "report": report if available else None, + } + else: + raise AssertionError(f"unexpected request: {request.path}") + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + assert job.stats() is None + assert job.stats() == report + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + assert await job.stats() is None + assert await job.stats() == report + assert paths == ["/v1/jobs/describe", "/v1/jobs/stats", "/v1/jobs/stats"] + + @pytest.mark.asyncio @pytest.mark.parametrize("sync", [False, True]) @pytest.mark.parametrize( diff --git a/python/src/job.rs b/python/src/job.rs index 0d411072f..08f6440ab 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -159,6 +159,11 @@ impl Job { }) } + pub fn stats(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { inner.stats().await.infer_error() }) + } + #[pyo3(signature = (*, limit=None, filter=None))] pub fn events( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 092ece8b5..b1e3c1bbf 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -90,6 +90,11 @@ pub(crate) trait JobHandle: Send + Sync { job_detail_not_supported("job timeline export") } + /// A printable report of recorded Function job metrics. + async fn stats(&self) -> Result> { + job_detail_not_supported("job statistics") + } + /// The job's recorded lifecycle events. async fn events(&self, _request: JobEventsRequest) -> Result> { job_detail_not_supported("job event history") @@ -531,6 +536,29 @@ where } } + /// Fetch a printable run report for a server-side Function job. + /// + /// The server report includes recorded phase timings, finishing-supervisor + /// slot occupancy, all-attempt split execution and batch latency, and + /// accepted-row throughput. Returns `None` for running jobs or when no recorded + /// profile is available, without waiting for completion. Requires server + /// support; local operations and SQL query handles do not support reports. + /// + /// ```no_run + /// # async fn report(job: &lancedb::job::Job) -> Result<(), Box> { + /// if let Some(report) = job.stats().await? { + /// println!("{report}"); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn stats(&self) -> Result> { + match &self.inner { + JobInner::Handle { handle, .. } => handle.stats().await, + JobInner::Completed(_) => job_detail_not_supported("job statistics"), + } + } + /// Waits until the operation reaches a terminal state. /// /// Returns the endpoint's typed result. Unit-result jobs return `()`. diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 5a0afa7e8..c546ce4d1 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -261,6 +261,35 @@ impl JobHandle for RemoteJob { Ok(trace) } + async fn stats(&self) -> Result> { + let request = self + .client + .post("/v1/jobs/stats") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let response: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse job statistics: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if response.get("job_id").and_then(serde_json::Value::as_str) == Some(self.job_id.as_str()) + { + match response.get("report") { + Some(serde_json::Value::Null) => return Ok(None), + Some(serde_json::Value::String(report)) => return Ok(Some(report.clone())), + _ => {} + } + } + Err(Error::Http { + source: "server response is not a Function job run report; job statistics require server support".into(), + request_id, + status_code: None, + }) + } + async fn events(&self, request: JobEventsRequest) -> Result> { let mut body = serde_json::json!({ "job_id": self.job_id }); if let Some(limit) = request.limit { @@ -354,6 +383,74 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + #[tokio::test] + async fn stats_reads_report_verbatim_and_preserves_unavailable_without_waiting() { + let requests = Arc::new(AtomicUsize::new(0)); + let seen = requests.clone(); + let report = "Function job: finished\nWorker utilization: unavailable\n"; + let client = client_with_handler(move |request| { + assert_eq!(request.method(), reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/jobs/stats"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body, serde_json::json!({"job_id":"job-1"})); + let response = if seen.fetch_add(1, Ordering::SeqCst) == 0 { + serde_json::json!({"job_id":"job-1","profile":null,"report":null}) + } else { + serde_json::json!({"job_id":"job-1","profile":{"future_field":17},"report":report}) + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".to_string()))); + assert_eq!(job.stats().await.unwrap(), None); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert_eq!(job.stats().await.unwrap().as_deref(), Some(report)); + assert_eq!(requests.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn stats_rejects_malformed_or_unrelated_responses() { + for body in [ + "{", + r#"{"job_id":"job-1"}"#, + r#"{"job_id":"job-1","report":7}"#, + r#"{"job_id":"another-job","report":"a report"}"#, + ] { + let client = client_with_handler(move |_| { + http::Response::builder().status(200).body(body).unwrap() + }); + let error = RemoteJob::new(client, "job-1".to_string()) + .stats() + .await + .unwrap_err(); + assert!(matches!(error, crate::Error::Http { .. })); + assert!(error.to_string().contains("job statistics")); + } + } + + #[tokio::test] + async fn stats_preserves_not_found_errors() { + let client = client_with_handler(|_| { + http::Response::builder() + .status(404) + .body("job not found") + .unwrap() + }); + let error = RemoteJob::new(client, "missing".to_string()) + .stats() + .await + .unwrap_err(); + match error { + crate::Error::Http { status_code, .. } => { + assert_eq!(status_code, Some(reqwest::StatusCode::NOT_FOUND)); + } + other => panic!("expected HTTP 404, got {other:?}"), + } + } + struct FixtureRemoteJob(&'static str); #[async_trait] From dd449978d9c43a286ae7bf739301be34827125c4 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 14 Nov 2026 01:09:40 -0800 Subject: [PATCH 49/75] docs: clarify Function workflows and search contracts Clarify Function signatures, refresh and recovery workflows, job snapshots, FTS operators, and IVF deduplication limits. --- .agents/skills/lancedb-vector-dedup/SKILL.md | 63 ++++++++ docs/web/basics/jobs.mdx | 73 +++++++++ docs/web/curation/create-function.mdx | 61 ++++++- docs/web/curation/dedupe.mdx | 58 ++++++- docs/web/docs.json | 1 + .../add-computed-column.mdx | 7 + .../materialized-views.mdx | 24 +++ .../feature-engineering/refresh-column.mdx | 119 ++++++++++++++ docs/web/management/function-failures.mdx | 151 ++++++++++++++++++ docs/web/management/function.mdx | 44 +++++ docs/web/search/full-text-search.mdx | 57 +++++++ docs/web/sql/dql/dedupe.mdx | 9 ++ docs/web/sql/dql/duplicate-pairs.mdx | 6 + docs/web/sql/dql/fts.mdx | 63 +++++++- 14 files changed, 725 insertions(+), 11 deletions(-) create mode 100644 .agents/skills/lancedb-vector-dedup/SKILL.md create mode 100644 docs/web/management/function-failures.mdx diff --git a/.agents/skills/lancedb-vector-dedup/SKILL.md b/.agents/skills/lancedb-vector-dedup/SKILL.md new file mode 100644 index 000000000..1221e4061 --- /dev/null +++ b/.agents/skills/lancedb-vector-dedup/SKILL.md @@ -0,0 +1,63 @@ +--- +name: lancedb-vector-dedup +description: Plan and run Enterprise IVF vector deduplication with dedupe and duplicate_pairs, including sampling, index coverage, recall and resource limits. Use for near-duplicate embedding or perceptual-hash records; use MinHash guidance for text shingles. +--- + +# Vector deduplication + +Read the maintained [workflow](../../../docs/web/curation/dedupe.mdx), +[DEDUPE reference](../../../docs/web/sql/dql/dedupe.mdx) and +[DUPLICATE_PAIRS reference](../../../docs/web/sql/dql/duplicate-pairs.mdx) +before constructing SQL. In a source checkout these paths are relative to this +skill directory. When using an installed copy without the docs, read +`https://docs.lancedb.com/curation/dedupe` and the linked SQL references. + +## Establish the comparison contract + +- Confirm an Enterprise deployment that supports these table functions. Use + `dedupe` and `duplicate_pairs`; legacy `vector_dedup` names are rejected. +- Inspect the vector type, metric, compatible index, indexed fragments and + source version. Wait for index coverage after writes. Do not run a full + scan over unindexed fragments or silently change the index to make it run. +- Explain that candidates are compared only within physical IVF partitions + and segments. Encoded/quantized distances are not an exact raw-vector + comparison. L2 thresholds are squared distances; Hamming counts bits. +- Use `id_column` on pair queries for business IDs. Retain `dataset_version`, + segment and partition identities. Do not decode internal row IDs or assume + that representatives stay the same after later data/index changes. + +## Bound the first experiment + +Use a reproducible partition sample before a full scan: + +```sql +SELECT id_a, id_b, distance, dataset_version, segment_id, partition_id +FROM duplicate_pairs( + 'frames', 'embedding', + distance_threshold => 0.02, + id_column => 'frame_id', + selection => 'random', count => 10, seed => 42 +) +``` + +Adapt the threshold and sample size to the metric and actual partition count. +Sampling partitions is not uniform sampling of rows. Inspect known duplicate +and distinct examples, pair density, partition skew, memory, spill space and +elapsed time. Do not infer global recall or ten-billion-row qualification +from a small or unversioned benchmark. Pair work and output can be quadratic +within a partition; an outer SQL `LIMIT` is not an upstream work budget. + +## Choose the result + +`dedupe` returns original representative rows and always scans all partitions. +Use its default `connected_components` for transitive groups; choose +`direct_representative` when chains should not merge transitively. It does not +accept `id_column`, `selection`, `count` or `seed`; `duplicate_pairs` does not +accept `resolution`. + +Keep pair data on the server when possible; avoid collecting an unbounded +edge set in client memory. Persist a new table/view only within the user's +authorized scope, preserving source rows unless deletion was requested. +Do not register a Python Function or fetch/rewrite Blob payloads to invoke +these built-in table functions. For MinHash/text deduplication, follow the +separate `https://docs.lancedb.com/enterprise/sql-minhash` workflow. diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 47285f5d0..264acd728 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -33,6 +33,46 @@ print(job.status()) ``` +## Cached properties and live calls {#snapshots} + +Python job properties describe the last observation; reading them does not +contact the server. Submission need not fetch the full registry record, so +some properties can initially be `None`. + +| Surface | Contract | +| --- | --- | +| `state` | Last observed lifecycle state. It does not update on its own. | +| `job_type`, `creation_ms` | Cached job kind and creation time in epoch milliseconds. | +| `spec` | Complete, job-specific submitted specification. Read this separately from the bounded `repr(job)` display. | +| `result` | Cached, job-specific reported data; it is not necessarily the typed object returned by `wait()`. | +| `failure` | Cached `JobFailureInfo`, when the server reports a terminal failure. | +| `status()` | Live lifecycle request. For registry jobs it also caches the full record. A failed state is returned without raising a job-failure exception; request errors can still raise. | +| `refresh()` | Fetch and cache the current record without waiting for completion. | +| `events(...)` | Separate live request returning a `pyarrow.Table` of recorded events; it does not refresh the properties. | +| `wait(...)` | Poll until completion and return the operation's typed result, or raise on failure/cancellation. Refresh afterward when you need the complete final registry record. | + +For example, poll a registry handle and then retrieve its final details: + +```python +import time + +state = job.status() +while state == "running": + print(job.state) + time.sleep(2) + state = job.status() + +result = job.wait() +job.refresh() +print(result) +print(job.spec) +``` + +The four lifecycle strings below are the usual SDK contract; newer server +states may pass through an older client. Do not infer execution progress from +`state` alone. Structured progress methods and queue fields require matching +SDK/server support; see [refresh admission](/feature-engineering/refresh-column#admission). + ## Submit and wait for a job {#waiting} 1. **Submit the operation.** Keep the returned job handle. For an Enterprise @@ -133,6 +173,39 @@ for info in db.list_jobs(page_limit=50): ``` +`list_jobs` yields `JobInfo` summaries, newest creation time first, rather than +live `Job` handles. Open an ID to inspect its full record. `page_limit` bounds +each server request, not the total yielded items, and `page_token` resumes a +listing. It is a lazy iterator: iteration performs requests and can raise +request errors. To materialize it, use `list(db.list_jobs(...))`; it does not +support list indexing, `len()`, or a `.to_list()` method. + +`Listing.num_page_results()` reports cached items remaining in the current +page and `Listing.page_token()` reports the next request's token. Drain the +cached items before saving that token, or resuming can skip them. A `None` +token after the final page can coexist with unread cached items. A resumed +listing is not a transactionally frozen view of jobs submitted in the meantime. + +`events.schema` describes the Arrow response. Use `events.to_pylist()` for +Python row dictionaries. Common event columns are `event_seq` (int64), `state` +(string), `updated_at_millis` (int64), `updated_by` (string), and nullable +`emitted_from`, `emitted_by` and `claim_entity` strings. Optional uint64 work +counters such as `rows_processed` and diagnostic details depend on job type +and server version. If a `payload` column is returned, its value is a nullable +JSON string, not an already decoded Python dictionary. +Empty results retain their schema. Events are newest first and belong to the +requested job; child events are separate. An event count is not a completed-row +count, and a running job can have no terminal `result` while producing events. + +For a Function refresh, `wait()` returns a `RefreshColumnResult` such as +`rows_assigned`, `rows_failed`, `rows_remaining`, `source_version` and optional +`published_version`. Other job types have different results. Do not parse the +printed representation to recover a spec, result or progress measurement. +For object-shaped registry data, `job.spec` and `job.result` are decoded Python +dictionaries: access fields with keys, such as `job.result.get("summary")` +after refreshing a successful Function job. The separate typed object from +`wait()` uses attributes, such as `result.rows_assigned`. + Event responses have [row limits](/basics/limits#jobs). An explicit limit can request more than the default, but it does not guarantee a complete event history. diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 111eaf13f..9ee7d572a 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -44,6 +44,58 @@ table.add_columns({"doubled": version(value=col("value"))}) immutable version, so changing one produces a new version rather than altering rows a previous version already filled. +## Supported Function signatures {#signature-types} + +A table's [Arrow schema](/sql/data-types#supported) can contain types that a +Function cannot accept or return. The matrix below describes the Python SDK +`0.42.0-beta.12` source contract. Nested schemas and list-Blob outputs require +a matching Enterprise server; an SDK upgrade alone does not enable them. + +| Arrow type | Function input/output support | +| --- | --- | +| Boolean; signed/unsigned 8, 16, 32, 64-bit integers; float16/32/64 | Supported. Ordinary `int` and `float` annotations infer int64 and float64. | +| utf8 / large_utf8; binary / large_binary | Supported. `str` and `bytes` infer utf8 and binary. Plain binary does not carry Blob semantics. | +| date32 / date64 | Supported; Python `date` infers date32. | +| timestamp, with or without timezone; time32/64; duration; interval | Unsupported by the Function signature grammar. A Python `datetime` annotation can resolve to an Arrow timestamp but registration still rejects it. | +| decimal; map; dictionary; union; fixed-size binary | Unsupported. Decode dictionary values and use supported scalar/list/struct representations. | +| struct; list / large_list; positive-length fixed-size list | Supported with supported children. Explicit schemas preserve child nullability; annotation-only `list[T]` uses non-nullable elements. Struct fields must be nonempty and uniquely named. | +| Blob v2 at top level or in a struct | Supported in inputs and outputs; use `lancedb.blob(...)` in the schema. | +| Blob v2 under list / large_list | Output only on supporting SDK/server versions. Inputs are rejected. | +| Blob v2 under fixed-size list or map | Unsupported in both directions. | + +For times, pass an int64 epoch value with an explicit unit such as microseconds, +or a UTF-8 ISO 8601 string with its timezone. Convert inside the Function and +cast the result in SQL if needed. Use scaled integers with a declared scale +when exact decimal values matter; converting to float can lose precision. +Represent a map as a list of key/value structs when that fits the calculation. + +A scalar output is non-nullable because physical NULL represents an unfilled +computed output. For an optional value, return a named struct with a nullable +field, for example: + +```python +import pyarrow as pa +from lancedb import function + +@function( + input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]), + output_schema=pa.schema([pa.field("score", pa.float64(), nullable=True)]), +) +def optional_score(text: str): + return {"score": float(len(text)) if text else None} +``` + +Return a dictionary by field name. A successfully computed nullable field can +be NULL; `score IS NULL` alone cannot distinguish it from pending work or a +skipped failure. Use the job result and error diagnostics. Do not assume an +explicit assignment-state flag is available on every deployment. + +List-nested Blob outputs are queryable as descriptors, but row-ID blob fetch +APIs and `blob_mode="bytes"` do not fetch payloads inside lists. Prefer a +separate row per media item when you need independent reads, retries or +re-scoring. A plain struct shaped like a Blob without its extension metadata +is not a substitute for `lancedb.blob`. + ## Batch: once per call, many rows at a time {#batch} A function is called once per batch instead of once per row when its @@ -170,9 +222,12 @@ in the function's source. A Secret is a database-scoped named credential: puts it in the environment variable the function reads, without ever returning it from any API or recording it in the function's own definition. Combine it with the stateful form so the HTTP client -- and any rate limiter -around it -- is built once, not reopened on every row. There is no built-in -retry or per-row error-skip policy -- a function that calls a flaky service -should handle timeouts and retries itself, inside `__call__`. +around it -- is built once, not reopened on every row. Configure HTTP timeouts +inside `__call__`. Refresh-level `error_policy='skip'` can record row failures; +see [handling failures](/management/function#failures). Native retry policies +need matching SDK, server and Function-image support; on other deployments, +handle bounded retries inside the Function only when repeating the request is +safe. See [Vend a Secret to a Function](/curation/vend-secret#specify) for the full worked example, how the bound value actually reaches a running diff --git a/docs/web/curation/dedupe.mdx b/docs/web/curation/dedupe.mdx index 470e170c2..2e90bc231 100644 --- a/docs/web/curation/dedupe.mdx +++ b/docs/web/curation/dedupe.mdx @@ -136,12 +136,60 @@ SELECT * FROM dedupe( See [Refresh a materialized view](/feature-engineering/refresh-materialized-view) for manual and automatic refresh options to keep it current as new records land. -## At production scale {#production} +## Index, snapshot and recall limits {#limits} -[LeRobotDataset](/integrations/lerobotdataset) runs the same `dedupe` -call over 27.6 million real embedding rows to remove near-static frames from a -robotics training set in under 30 seconds -- the mechanism does not change -with scale, only the table it runs against. +These are Enterprise SQL table functions, not standard SQL or a registered +Python Function. They require one compatible current vector index covering +the scanned snapshot. Wait for indexing to finish after ingestion and inspect +index coverage before running a full scan. Unindexed fragments are rejected; +deleted rows are excluded at the pinned dataset version. + +The scan compares candidates **within each physical IVF partition and index +segment**. It does not compare across partitions or segments. Scanning every +partition therefore does not establish global all-pairs recall. Quantized +indexes compare their encoded vector representations; `IVF_FLAT` compares the +stored vectors. Thresholds must match the index's metric: L2 is squared L2, +cosine is `1 - cosine`, dot distance is `1 - dot`, and Hamming counts differing +bits. Inspect close examples and known duplicates before choosing a threshold. + +`duplicate_pairs` reports `dataset_version`, `segment_id` and `partition_id`. +Retain those with the index configuration and source version when comparing +runs. Pass `id_column` for application IDs, rather than treating physical row +addresses as durable identifiers. A new append, index change or bridge between +components can change groups and representatives. + +## Efficient use and scale qualification {#production} + +Start with [`duplicate_pairs` partition sampling](/sql/dql/duplicate-pairs#sampling), +using a recorded seed and a bounded partition count. Inspect pair density and +threshold quality before running `dedupe`, which always scans every partition. +Sampling partitions is not uniform row sampling and can miss rare groups. +`resolution='connected_components'` merges transitive chains; +`direct_representative` uses direct representative relationships instead. + +Pair work grows quadratically within dense partitions, and a loose threshold +can emit a quadratic number of edges. An outer `LIMIT` is not a resource +budget for upstream pair finding or group resolution. Avoid repeatedly +materializing all pairs in a Python list; select needed columns, aggregate on +the server, and persist a reviewed result when repeated reads justify it. +Measure peak memory, spill storage, elapsed time and pair count on +representative partitions before increasing scope. + +The [LeRobotDataset integration](/integrations/lerobotdataset) illustrates a +27.6-million-row data workflow. Its timings are not a versioned qualification +of this deduplication path on arbitrary indexes or hardware. A 10-billion-row +run is not qualified by that example. Qualify source/index versions, partition +sizes, metric, threshold, worker resources, spill limits and correctness on your +deployment before extrapolating. There is no universal row-count or latency +guarantee in this guide. + +For text shingles and MinHash signatures, use the distinct +[MinHash workflow](/enterprise/sql-minhash). Vector distance deduplication and +MinHash/Jaccard text deduplication have different indexes and thresholds. + +Agents can follow the repository's +[vector deduplication skill](https://github.com/lancedb/lancedb/blob/main/.agents/skills/lancedb-vector-dedup/SKILL.md) +to apply these checks without inventing Function options or scale guarantees. ## Continue with the curated data {#next} diff --git a/docs/web/docs.json b/docs/web/docs.json index 3414fd121..c586d4f62 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -496,6 +496,7 @@ "management/materialized-view", "management/secret", "management/function", + "management/function-failures", "management/storage-integration" ] }, diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 851b37d9b..7cc9f6988 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -13,6 +13,13 @@ import { PySchemaAddSetup, } from '/snippets/tables.mdx'; + +Declare computed columns on ordinary tables. A materialized view derives its +schema from its query; include the calculation in the view's `SELECT` instead +of attaching a Function with `add_columns`. See +[materialized-view schema changes](/feature-engineering/materialized-views#schema-changes). + + Lance can write a new column without rewriting the columns already in the table. That matters most on a table that also holds large images, video or embeddings, where rewriting everything just to add one small derived field diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 617eb7525..ccfd8429d 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -176,6 +176,30 @@ definition is read with `await view.definition()`. Creation, refresh and drop also have async, job-returning SDK methods; see [Materialized view](/management/materialized-view#manage). +## Add derived values to a view {#schema-changes} + +A materialized view's output schema belongs to its defining `SELECT`. Do not +use `view.table.add_columns(...)` to attach another computed or Function column +to that output. In particular, adding a Function binding is rejected: the +column would not be produced by the next view refresh. + +Choose where the calculation belongs: + +- Include the expression or Function call in the view's `SELECT`, as in the + [caption example](#functions). To change an existing definition, create a + replacement view under a new name, check its results, indexes and grants, + and move readers to it before dropping the old view. +- Add a Function column to the ordinary source table, refresh it, then select + that stored column in a view. This lets you manage column refresh separately + from view refresh. +- Create an ordinary table from a query when you need independently editable + outputs. That table is a snapshot; it does not inherit the view's refresh + relationship to the source. + +Opening the underlying table gives access to reads and indexes; it does not +make independent schema changes part of the materialized-view definition. +Changing automatic-refresh settings also does not change that definition. + ## Related guides {#next} diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 1b809b91d..d82fb1eef 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -77,6 +77,11 @@ catch-up works when it's re-enabled after being off. ## Refreshing part of a table {#partial} +Python `where=` requires a supporting SDK, such as `0.42.0b9`, and an +Enterprise server with filtered refresh support. Stable `0.41.0` does not +accept this argument. The SQL form is available independently of that Python +argument on supporting servers. + Enterprise A refresh can be scoped to a predicate, with `where=` in Python or `WHERE` in SQL, which is useful for filling a slice first and checking it before committing to the whole table: @@ -123,6 +128,89 @@ to let LanceDB track which outputs need updating. `function_refresh` for one filled by a registered [function](/management/function). +### Re-score selected list elements {#list-elements} + +`WHERE` selects **rows**, not elements within a list. Refreshing a row that +contains ten answers passes the whole list to the Function. A mask can control +which elements your code computes, but the Function still returns one complete +list for that row. There is no element-level refresh or partial-list write API. + +This example keeps `sample_id` as the link to an existing `samples` table with +a Blob column named `media`. It creates only answer metadata and scores; it +neither reads nor copies Blob payloads. Run it on a deployment supporting +`@function`, list signatures and Python `where=`, with `samples` already +containing sample IDs `s1` and `s2`. + +```python +from lancedb import col, function + +media_before = db.execute_query( + "SELECT sample_id, media FROM samples " + "WHERE sample_id IN ('s1', 's2') ORDER BY sample_id" +).read_all().to_pylist() + +answers = db.create_table("answer_rescore_demo", [ + {"group_id": "g1", "sample_id": "s1", + "answers": ["yes", "maybe", "no"], + "selected": [False, True, False], "previous": [0.1, 0.2, 0.3]}, + {"group_id": "g1", "sample_id": "s2", + "answers": ["other"], "selected": [False], "previous": [0.4]}, +]) + +@function +def rescore_masked( + answers: list[str], selected: list[bool], previous: list[float] +) -> list[float]: + if not (len(answers) == len(selected) == len(previous)): + raise ValueError("answers, selected and previous must have equal lengths") + return [ + float(len(answer)) if choose else old + for answer, choose, old in zip(answers, selected, previous) + ] + +version = db.create_function(rescore_masked) +answers.add_columns( + {"rescored": version( + answers=col("answers"), selected=col("selected"), previous=col("previous") + )}, + auto_refresh_enabled=False, +) +job = answers.refresh_column_async("rescored", where="sample_id = 's1'") +job.wait() + +rows = answers.search().select( + ["group_id", "sample_id", "previous", "rescored"] +).to_list() +by_sample = {row["sample_id"]: row for row in rows} +assert by_sample["s1"]["group_id"] == "g1" +assert by_sample["s1"]["rescored"] == [0.1, 5.0, 0.3] +assert by_sample["s1"]["previous"] == [0.1, 0.2, 0.3] +assert by_sample["s2"]["rescored"] is None +assert by_sample["s2"]["previous"] == [0.4] + +media_after = db.execute_query( + "SELECT sample_id, media FROM samples " + "WHERE sample_id IN ('s1', 's2') ORDER BY sample_id" +).read_all().to_pylist() +assert media_after == media_before +``` + +Here length is a deterministic stand-in for a scorer. Only `"maybe"` is scored; +the other scores are copied from `previous`. The final equality checks Blob +descriptors on an otherwise unchanged source table, without fetching payloads. +Keep the source table unchanged during this comparison. Use the same model, +normalization and score type as the original computation in a real re-scoring +pass. For another pass, explicitly supply the intended prior scores and mask; +refresh does not merge the previous output into your Function's inputs. + +If answers need independent retries or versions, prefer one ordinary table row +per answer, with `group_id`, `sample_id`, a stable application `answer_id`, +answer text and score. Keep media in `samples` and join by `sample_id` when +needed. A row predicate can then select exact answer IDs, and Blob storage +stays in the source table. Do not use `UNNEST` to assume that nested Blob values +become supported Function inputs; see the +[nested-Blob limits](/curation/create-function#signature-types). + ## Run a refresh on Enterprise {#async} Enterprise @@ -212,6 +300,31 @@ The wait helpers do not submit or cancel a refresh. They retry only the typed finalization-pending response and propagate other errors. */} +### Admission and waiting {#admission} + +Submission does not reserve a supervisor or GPU immediately. A refresh can wait +for source preparation/compaction, an earlier refresh, executor admission or +worker capacity. A lifecycle `running` value from `status()` alone does not +prove that Python code has begun executing. + +Use [`SHOW JOBS`](/sql/ddl/job#show) and the Console's job detail to inspect +available phase and row progress. On SDK/server versions with `job.progress()`, +the snapshot can also include `phase`, `queue_reason`, timestamps and row +counters. These optional fields are version-dependent; missing values are +unknown, not zero progress or an ETA. `creation_ms` is submission time, not +worker start time. `DESCRIBE JOB` provides the finished run report, rather than +a live queue-position API. + +Limits are deployment settings: the Agent dispatcher concurrency, executor +capacity, per-table automatic-refresh limit and Function-call +`max_concurrency` control different things. There is no universal five-refresh +limit per database. Ask your administrator for the effective settings and use +the [Enterprise operations guide](/enterprise/function-operations#admission) +for their configuration names. Repeated cancellation and resubmission does not +bypass those limits. Cancellation requests a stop, including while queued; +observe a terminal state before submitting replacement work. Committed work +is not rolled back. + ### Configure workers and resources {#resources} SQL exposes the worker budget directly, which is the lever when a backfill is @@ -229,6 +342,12 @@ up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not per-worker allocations or a guaranteed worker count. `num_workers` is only accepted for SQL-expression columns; registered Function columns reject it. +In particular, `gpu_count = 2` does not request two devices inside one Python +process or enable tensor parallelism. Inspect configured GPU classes and their +per-worker limits with `db.list_gpu_classes()` or `SHOW GPU CLASSES`. Choose a +model that fits the worker shape supported by your deployment; see +[GPU placement and budgets](/enterprise/function-operations#gpu). + The SDKs accept the same nested budget. CPU and memory are required; the GPU count inside the budget defaults to zero, so a CPU-only Function can omit it: diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx new file mode 100644 index 000000000..4546129fa --- /dev/null +++ b/docs/web/management/function-failures.mdx @@ -0,0 +1,151 @@ +--- +title: "Handle Function failures" +sidebarTitle: "Function Failures" +description: "Keep usable outputs, inspect row errors, retry by stable identity and isolate inputs that need attention." +tag: "Early access" +availability: + embedded: unavailable + enterprise: available +--- + +A Function refresh can encounter a bad row, fail to initialize a model, lose +a worker, or fail while publishing results. These need different remedies. +This guide uses the existing [refresh error policy](/sql/dml/refresh-column#options) +and Python error records; it does not require a new retry or quarantine API. + +## Choose a row-error policy {#policy} + +The default `fail` stops the job on a row error. `skip` writes null outputs for +failed rows and records errors, subject to the refresh's failure limits: + +```python +job = table.refresh_column_async( + "embedding", + error_policy="skip", + max_failed_rows=100, + max_failed_fraction=0.1, +) +result = job.wait() +print(result.rows_assigned, result.rows_failed, result.rows_remaining) +``` + +Choose limits for your workload; these example limits stop work when more +than 100 rows or more than 10% fail. `skip` does not make initialization, +infrastructure or publication failures successful. If `wait()` raises, +[refresh the job record](/basics/jobs#snapshots), inspect `job.failure`, and +inspect any recorded row errors. A failed/cancelled job can have committed +some output, but retention of every successful call is not guaranteed. +External effects are not rolled back and can be repeated during recovery. + +## Inspect and group recorded errors {#inspect} + +Scope diagnostics to the job you are investigating: + +```python +from collections import Counter + +errors = table.function_errors(job_id=job.id, column="embedding", limit=10000) +groups = Counter((r.error_type, r.error_message) for r in errors.records) +for cause, count in groups.most_common(): + print(count, cause) +for fragment in errors.fragments: + print(fragment.fragment_id, fragment.rows_skipped, fragment.rows_recorded) +print("listing truncated:", errors.truncated) +``` + +Each record includes the Function name/version, table version, error type and +message, creation time, and available row identities. `attempts` and traceback +details depend on the server/image version. This client-side grouping counts +only returned detail records. `truncated=True` or fragment summaries with +more skipped than recorded rows mean it is incomplete; do not label it a full +error census. See [`SHOW ERRORS`](/sql/ddl/job#errors) for SQL and its limits. + +Records are historical observations, not a deduplicated list of currently +failed rows. Reading errors without `job_id` can include older attempts that +have since succeeded. A null output can mean unfilled, skipped, or a computed +nullable field; output nullness alone is not a current-error test. + +## Retry exactly identified rows {#retry} + +On tables with stable row IDs, supporting server/SDK versions return +`record.row_id` from the refresh's pinned source version. Keep that table and +branch identity with the records. Compaction can move physical addresses, so +do not derive a row ID from fragment numbers or offsets. + +The following deliberately refuses incomplete or unidentified error sets. +Review historical records against the current inputs before using them as a +retry selection. Keep this selection small enough for a SQL predicate. + +```python +if errors.truncated or any(f.rows_skipped > f.rows_recorded for f in errors.fragments): + raise RuntimeError("Inspect a narrower job/error set before selecting retries") +if any(r.row_id is None for r in errors.records): + raise RuntimeError("This workflow requires stable row IDs in every error record") + +row_ids = sorted({int(r.row_id) for r in errors.records}) +if row_ids: + predicate = "_rowid IN (" + ", ".join(map(str, row_ids)) + ")" + retry_job = table.refresh_column_async("embedding", where=predicate) + retry_job.wait() +``` + +This recomputes every selected live row with the existing binding. It can +repeat a row already repaired since the error was recorded. Inspect the retry +job and its errors afterward; an older record need not disappear. On tables +without stable row IDs, resolve errors to application keys at the recorded +snapshot before retrying. Do not substitute `_rowaddr` after a rewrite. +Python `where=` requires a supporting SDK such as `0.42.0b9`, not stable +`0.41.0`, plus a matching server. + +## Repair with a newer Function {#new-version} + +Registering a new version does not change an existing column's immutable +binding. To evaluate a fix while retaining old outputs, register the corrected +callable and declare a separate output column. For example, with a corrected +`embed_fixed` callable already defined and a `text` input column: + +```python +from lancedb import col + +fixed = db.create_function(embed_fixed) +table.add_columns( + {"embedding_repaired": fixed(text=col("text"))}, + auto_refresh_enabled=False, +) +if row_ids: + repair_job = table.refresh_column_async("embedding_repaired", where=predicate) + repair_job.wait() +``` + +Only the reviewed failed-row selection is populated in the new column; other +rows remain unfilled. Compare those outputs before deciding how readers +should use them. This does not promise an in-place upgrade/retry operation or +per-row producing-version lookup for a column containing mixed executions. +Error records' Function versions describe failures, not the provenance of +every successful row. + +## Quarantine inputs for review {#quarantine} + +Use an application-owned table of source table/branch, recorded table version, +stable row ID or business key, Function version, cause and review disposition. +Keep Blob payloads in the source table; a quarantine entry can refer to their +source identity. Choose an ordinary table name such as `function_quarantine`, +and explicitly exclude its reviewed IDs in subsequent input selections. + +Quarantine is an application workflow here: there is no implied built-in +quarantine lifecycle, automatic current-error clearing or exactly-once retry. +Do not delete source rows merely to hide an error. For very large failure sets, +bounded error listings cannot select every row; use a smaller reviewed scope +or wait for a deployment with the required complete selection support. + +Native retry policies, full current-error summaries, in-place version upgrades +and materialized-view row-error handling have separate server/SDK prerequisites. +Do not apply `REFRESH COLUMN` options to a materialized view and assume the +same policy; consult the [MV refresh reference](/sql/dml/refresh-materialized-view) +for your deployment's accepted options. + +## Continue {#next} + +- [Function lifecycle and failures](/management/function#failures) +- [Conditional and list-element refresh](/feature-engineering/refresh-column#partial) +- [Job results and events](/basics/jobs#snapshots) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index aae67ceb9..27f45cb6a 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -420,6 +420,9 @@ full worked example. ## Failure handling {#failures} +For the full skip, inspect, grouped-error, stable-row-ID retry and quarantine +workflow, see [Handle Function failures](/management/function-failures). + By default, a Function that raises fails the refresh job. Choose how the refresh handles row errors with its error policy: @@ -495,6 +498,47 @@ In practice this means a function should be self-contained: take its inputs as arguments, import what it needs at module level, and avoid capturing state from the surrounding scope. +### Supported global captures {#captures} + +The Python SDK's source packager captures only these literal values: + +| Module-level value | Packaging behavior | +| --- | --- | +| `None`, exact `bool`, `int`, `str`, `bytes`, finite `float` | Inlined as a snapshot at registration. | +| Tuples containing only those values, including nested tuples | Recursively inlined. | +| Imported modules, importable functions/classes | Reconstructed as imports; declare their packages in `pip` or `conda`, or ship local source with `code`. | +| Arrow types/schemas, lists, dictionaries, sets, NumPy arrays, non-finite floats, other objects | Not captured as literals. Construct them inside the Function or class. | + +For example, a module-level `OUT_TYPE = pa.list_(pa.float32(), 3)` referenced +from the Function body is unsupported. Construct the type where it is used: + +```python +import pyarrow as pa +from lancedb import function + +@function( + input_schema=pa.schema([pa.field("value", pa.float32(), nullable=False)]), + output_schema=pa.list_(pa.float32(), 3), +) +def make_vector(value: pa.Array) -> pa.Array: + out_type = pa.list_(pa.float32(), 3) + return pa.array([[v, v, v] for v in value.to_pylist()], type=out_type) +``` + +Decorator schema arguments are serialized as the signature; this restriction +concerns values referenced by the packaged body. For an expensive constant or +model, build it in a class Function's `__init__` and keep it on `self`. + +Later mutations of a client global do not update a registered version. Register +a new version to change captured literals or source. The diagnostic fix in +[SDK #4938](https://github.com/lancedb/lancedb/pull/4938) names the unsupported +global and its type; it does not add Arrow/container capture support. There is +no supported arbitrary-object serialization or documented container-size limit +to rely on for those rejected types. + +See the [Function type matrix](/curation/create-function#signature-types) for +what can travel as row inputs and outputs rather than captured globals. + Pass `code=[module, ...]` to ship additional helper modules into the same image, for logic the function imports but that does not belong inlined into it -- a model-loading helper shared by several Functions, for example. diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index 9c17fc50b..b7ceb15ad 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -182,6 +182,56 @@ BM25 scores depend on the indexed corpus and its term statistics. Compare rankings on the dataset you will search; treat scores as relative relevance values rather than probabilities. +### Match any word or every word {#term-operators} + +A multi-word string such as `"happy puppy"` uses **OR**: a row can match either +term. Writing `"happy AND puppy"` does not select an AND operator; the string +is analyzed as search text. To require both terms, construct a match query: + + +```python Python icon="python" +from lancedb.query import FullTextOperator, MatchQuery + +query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND) +results = table.search(query, query_type="fts").limit(10).to_list() +``` + +```typescript TypeScript icon="square-js" +import { MatchQuery, Operator } from "@lancedb/lancedb"; + +const query = new MatchQuery("happy puppy", "text", { operator: Operator.And }); +const results = await tbl.query().fullTextSearch(query).limit(10).toArray(); +``` + +```rust Rust icon="rust" +use lance_index::scalar::{ + FullTextSearchQuery, + inverted::query::{MatchQuery, Operator}, +}; +use lancedb::query::{ExecutableQuery, QueryBase}; + +let query = MatchQuery::new("happy puppy".to_owned()) + .with_column(Some("text".to_owned())) + .with_operator(Operator::And); +let results = tbl + .query() + .full_text_search(FullTextSearchQuery::new_query(query.into())) + .limit(10) + .execute() + .await?; +``` + + +AND requires all analyzed terms, without requiring adjacency or order. Use +[`PhraseQuery`](#phrase-vs-terms-queries) for an ordered phrase, or combine +separate queries with [`&` and `|`](#boolean-queries). Python `and` and `or` +do not build queries. + +On Enterprise, the existing [`fts()` SQL reference](/sql/dql/fts#term-operators) +shows the equivalent JSON (`"operator":"And"`), `_score`, and a +[`COUNT(*)` workaround](/sql/dql/fts#count) for counting matches without a +top-k limit. `len(results)` counts only the returned result page. + ### Keeping the index up to date {#keeping-the-index-up-to-date} In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table. @@ -395,6 +445,13 @@ table.create_index("text", config=FTS(with_position=True, remove_stop_words=Fals Storing token positions increases the index size and adds indexing work. +On Enterprise, wait for the replacement index to finish before issuing the +phrase query, using `table.wait_for_index(["text_idx"])` with your actual +index name. An existing index without positions must be rebuilt; changing the +query does not add positions. A phrase query against such an index is rejected +with an error asking you to recreate it with positions, rather than returning +an empty match set. See [FTS index options](/indexing/fts-index#fts-parameters) +and the [SQL phrase reference](/sql/dql/fts#phrase). ### Fuzzy Search {#fuzzy-search} diff --git a/docs/web/sql/dql/dedupe.mdx b/docs/web/sql/dql/dedupe.mdx index dbb6717b4..452638ea3 100644 --- a/docs/web/sql/dql/dedupe.mdx +++ b/docs/web/sql/dql/dedupe.mdx @@ -55,6 +55,15 @@ current deployments. a subset of partitions and `id_column` are pair-query-only options, accepted by [`duplicate_pairs`](/sql/dql/duplicate-pairs#input) but refused here. +## Index and snapshot requirements {#requirements} + +Use one compatible, current vector index covering the source snapshot. +Full scans reject unindexed fragments. Comparisons stay within physical IVF +partitions and index segments; this does not enumerate cross-partition or +cross-segment duplicates. Quantized-index distances use encoded vector +representations. See [recall and scale limits](/curation/dedupe#limits) before +treating the result as globally exact deduplication. + ## Output {#output} One row per duplicate group, **in the table's own schema** -- every column of diff --git a/docs/web/sql/dql/duplicate-pairs.mdx b/docs/web/sql/dql/duplicate-pairs.mdx index daa078955..dc93d5180 100644 --- a/docs/web/sql/dql/duplicate-pairs.mdx +++ b/docs/web/sql/dql/duplicate-pairs.mdx @@ -60,6 +60,12 @@ only [`dedupe`](/sql/dql/dedupe#input) accepts it. ## Output {#output} +See [`dedupe` index prerequisites](/sql/dql/dedupe#requirements) and the +[recall limits](/curation/dedupe#limits). Pairs are found within each physical +partition and index segment, not across them. A full scan requires complete +index coverage; sampling is a diagnostic view of the selected indexed +partitions and does not prove coverage or recall for the rest of the table. + One row per close pair found, in a fixed schema independent of the source table: diff --git a/docs/web/sql/dql/fts.mdx b/docs/web/sql/dql/fts.mdx index 7b52f5e17..667d92cd6 100644 --- a/docs/web/sql/dql/fts.mdx +++ b/docs/web/sql/dql/fts.mdx @@ -30,14 +30,16 @@ INSERT INTO my_docs VALUES (3, 'The puppy catches a ball with great enthusiasm', 'sports', 'Alice'), (5, 'Puppy training requires patience and dedication', 'training', 'Alice'); -CREATE INDEX ON my_docs USING fts (text); +CREATE INDEX ON my_docs USING fts (text) WITH (with_position = true); ``` Phrase queries need position information, which costs extra index size. -Add `WITH (with_position = true)` to `CREATE INDEX`. Without it, -[phrase queries](#phrase) find nothing. See +The setup above enables it with `WITH (with_position = true)`. An existing +index without positions must be rebuilt before running a phrase query; the +server rejects the query and asks you to recreate the index with positions. +It does not silently return no matches. See [FTS parameters](/indexing/fts-index#fts-parameters). @@ -86,6 +88,44 @@ LIMIT 5 it behaves like any other column, but exists only in a relation that came from `fts()`. See [Data types](/sql/data-types#pseudo-columns). +## Match any term or every term {#term-operators} + +The default match operator is OR. `"happy puppy"` matches either analyzed +term. SQL JSON uses `"Or"` and `"And"`, with this casing; Python uses the +`FullTextOperator.OR` and `FullTextOperator.AND` enum members: + +```python +from lancedb.query import FullTextOperator, MatchQuery + +query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND) +json_query = query.to_json() +``` + +```sql +SELECT id, text, _score +FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}') +ORDER BY _score DESC +``` + +Both terms must occur, but they need not be adjacent. Do not embed `AND` or +`OR` in `terms` to select an operator. + +## Count matches {#count} + +Count the `fts()` relation before applying a top-k limit: + +```sql +SELECT COUNT(*) AS matching_rows +FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}') +``` + +This is an Enterprise SQL workaround when the SDK's FTS query builder does +not expose a match-count operation. `table.count_rows()` without an FTS +relation counts table rows, and taking the length of a limited search counts +only that result page. For list-element indexes, multiple matching elements +can produce multiple rows; use `COUNT(DISTINCT id)` when you need unique +application records. + ## Fuzzy {#fuzzy} Tolerates typos, up to a character-edit budget: @@ -109,6 +149,12 @@ PhraseQuery("puppy park", "text", slop=2) # up to 2 words between them ``` +```sql +SELECT id, text, _score +FROM fts('my_docs', '{"phrase":{"column":"text","terms":"happy puppy","slop":0}}') +ORDER BY _score DESC +``` + ## Boolean {#boolean} Combine queries with `&` (AND) or `|` (OR): @@ -120,6 +166,17 @@ MatchQuery("puppy", "text") | MatchQuery("kitten", "text") ``` +For SQL, serialize the composed query rather than writing occurrence enums +by hand: + +```python +query = MatchQuery("puppy", "text") & MatchQuery("happy", "text") +json_query = query.to_json() +``` + +Use that string as the second `fts()` argument. `.to_json()` supplies the +serialized Boolean field names for the SDK version you use. + ## Boost {#boost} Weight a query up or down relative to another: From e1a10eaa66c68aa87d40056f73f0bf97c95091c3 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Sat, 14 Nov 2026 20:22:13 +0800 Subject: [PATCH 50/75] chore(deps): upgrade Lance to v15.0.0-beta.21 (#5046) Upgrade the Rust Lance family from beta.18 to the published v15.0.0-beta.21 tag, and align Python test wheels and Java artifacts. This includes the explicit-empty-segment FTS fix in lance-format/lance#11063 needed by lancedb/sophon#10314. Enable Windows Git long paths so Cargo can check out Lance fixtures in the Rust, NPM and Python wheel builds. Beta.21 also contains lance-format/lance#9858: new NGram, RTree and MinHash LSH indexes use row addresses. Legacy row-ID segments remain readable, but index maintenance on stable-row-ID tables can require a rebuild. The NGram documentation now explains the consolidation requirement; NGram/RTree tables without stable row IDs retain their earlier format. The Python lock revision and unrelated dependency entries are unchanged. Validation: - The official Lance release and internal mirror match 80bc45a195279befdec42853dac8d15a37e0504d. The seven official Fury wheels and Maven POM/JAR were verified. - Exact executable/dependency state 7846a15e completed the full Rust, Python, Node, Java and CLI CI, including platform builds and package publication dry runs. Xuanwo approved that head; Gatekeeper recommended approve with a non-blocking qualification risk. - Follow-up a289cb2c only adds the requested seven-line NGram upgrade note. Static whitespace checks passed; new-head CI is running. No local correctness tests or test builds were run by this task owner. - Broader IVF/encoding/Blob/cache workload performance and the beta.21 Sophon composition remain separately qualified. Earlier Blob cancellation and DynamoDB failures on #4967 are retained in their original evidence; this PR does not count those historical failures as fixed. Current-head CI, full feedback and required review still gate merge. SDK publication is a separate action. Sophon adoption follows a published SDK release and mirror through its own dependency PR; its distributed performance acceptance remains in #10314. --- .../workflows/build_windows_wheel/action.yml | 3 + .github/workflows/npm-publish.yml | 4 + .github/workflows/rust.yml | 4 + Cargo.lock | 97 ++++++++++--------- Cargo.toml | 30 +++--- docs/web/indexing/scalar-index.mdx | 7 ++ java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 17 ++-- 9 files changed, 93 insertions(+), 73 deletions(-) diff --git a/.github/workflows/build_windows_wheel/action.yml b/.github/workflows/build_windows_wheel/action.yml index 954ee7d35..3d92d818a 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -12,6 +12,9 @@ inputs: runs: using: "composite" steps: + - name: Enable long paths for Lance dependencies + shell: bash + run: git config --global core.longpaths true - uses: ./.github/actions/setup-protoc - name: Build wheel uses: PyO3/maturin-action@v1 diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 1b7d3dcbc..ac95b5a47 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -162,6 +162,10 @@ jobs: working-directory: nodejs steps: - uses: actions/checkout@v6 + - name: Enable long paths for Windows dependencies + if: runner.os == 'Windows' + # Cargo also checks out Lance test fixtures below its git cache path. + run: git config --global core.longpaths true - name: Setup pnpm uses: pnpm/action-setup@v6 with: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a5e5c9c30..4c275240f 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -349,6 +349,8 @@ jobs: working-directory: rust/lancedb steps: - uses: actions/checkout@v6 + - name: Enable long paths for Lance dependencies + run: git config --global core.longpaths true - name: Set target run: rustup target add ${{ matrix.target }} - uses: Swatinem/rust-cache@v2 @@ -386,6 +388,8 @@ jobs: working-directory: rust/lancedb steps: - uses: actions/checkout@v6 + - name: Enable long paths for Lance dependencies + run: git config --global core.longpaths true - name: Set target run: rustup target add aarch64-pc-windows-msvc - uses: Swatinem/rust-cache@v2 diff --git a/Cargo.lock b/Cargo.lock index 22b0f1e6f..d1624f941 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3824,8 +3824,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5303,8 +5303,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5379,8 +5379,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5416,7 +5416,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5425,8 +5425,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrayref", "crunchy", @@ -5436,8 +5436,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5475,8 +5475,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5507,8 +5507,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5533,8 +5533,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5551,8 +5551,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "proc-macro2", "quote", @@ -5561,8 +5561,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-arith", "arrow-array", @@ -5595,8 +5595,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-arith", "arrow-array", @@ -5627,8 +5627,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5659,8 +5659,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5696,6 +5696,7 @@ dependencies = [ "lance-arrow-stats", "lance-bitpacking", "lance-core", + "lance-datafusion", "lance-datafusion-exec", "lance-encoding", "lance-file", @@ -5732,8 +5733,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5756,8 +5757,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5802,8 +5803,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "byteorder", "ethnum", @@ -5820,8 +5821,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5836,8 +5837,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "async-trait", @@ -5851,8 +5852,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5906,8 +5907,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5921,8 +5922,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5963,8 +5964,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5977,8 +5978,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index c45eef6da..bc9d85c72 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index f674a988d..fbd818b64 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -210,6 +210,13 @@ table.search().where("contains(text, 'needle')").limit(10).to_pandas() `list_indices()` reports the index type as `"NGram"`. + +Lance 15.0.0-beta.21 writes new NGram indexes using physical row addresses. On +tables with stable row IDs, rebuild legacy NGram indexes that store row IDs +before consolidating their segments. Consolidation rejects these legacy +row-ID segments. Tables without stable row IDs retain the earlier index format. + + ## Index UUID Columns LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys. diff --git a/java/pom.xml b/java/pom.xml index fc89ebe4c..196e6db9a 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.18 + 15.0.0-beta.21 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 6940dce4f..d464424c7 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b18", + "pylance==15.0.0b21", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 369d558d2..31ac68b4d 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b18" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b21" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b18" +version = "15.0.0b21" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_Rs8tZ/pylance-15.0.0b18-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:255e782b016555c3f8072bb3d2a33dfdb3cb67b5ccf10a6a999fd007c58b16ab" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1D7wV0/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11adaf98d8e2960bb25d30315720cb93a2ac291d3fec29cd9726e1085cd9e40f" }, - { url = "https://pypi.fury.io/lance-format/-/ver_pK9DO/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aea39d714821d561b655f2d046129700a5ff95c3352813edd6af15ec6d9d29e2" }, - { url = "https://pypi.fury.io/lance-format/-/ver_28PrEd/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c19b3293be41ae4a87a67123e8d7233b0c5508aa39012c26525ab9d19884386d" }, - { url = "https://pypi.fury.io/lance-format/-/ver_kV8Di/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7a48686ab4777b58fe9f0e17a68048b779c071879d48035afb3e79b81b9d47a1" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1pAhhP/pylance-15.0.0b18-cp310-abi3-win_amd64.whl", hash = "sha256:dc32e4731b78c8325d1bd0f0e23f13f7dab7ed1f0fcda47d52661d44c8bfc83a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_mzSgZ/pylance-15.0.0b21-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:251682fe543131c371a6af45d8c672ea53b6ee83b5f777885f15ce383144d820" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1UfHMZ/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cbc92a2bac73f179a382e1bdb495fa3631a17e35687c2f00721af073eeb445a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Ugv8b/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59bd56971aa41a21783e938e18a752fdaa97a37cfdd8940ed2f37d0c665d0fdd" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1mO0GG/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a0da124e95240e448daa981664a5e64e87bc99411eb4c408cbd50147096654f4" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1n5aaN/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:341a1abcd62e6134982968a5236f8128d88211ab288d329924a812d87e555555" }, + { url = "https://pypi.fury.io/lance-format/-/ver_RVDDc/pylance-15.0.0b21-cp310-abi3-win_amd64.whl", hash = "sha256:f5dbd51b2553d70b927c537672bad41075cd8615f5e951008d7cd59c7365e587" }, + { url = "https://pypi.fury.io/lance-format/-/ver_GJeqW/pylance-15.0.0b21-cp310-abi3-win_arm64.whl", hash = "sha256:ddd517d555c6674c94b0eeee78ed6c3c3ac7b32319e27c47dd6f78a2639d6837" }, ] [[package]] From 5de76bd8edebb1aae915591683bdcfa642807032 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sat, 14 Nov 2026 12:33:00 +0000 Subject: [PATCH 51/75] =?UTF-8?q?Bump=20version:=200.42.0-beta.12=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index e4989d1eb..04ce71470 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.12" +current_version = "0.42.0-beta.13" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index d1624f941..a84f1d6fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5992,7 +5992,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "ahash", "anyhow", @@ -6103,7 +6103,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "anyhow", "arrow-array", @@ -6146,7 +6146,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "arrow-array", "arrow-buffer", @@ -6171,7 +6171,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index ca77b251c..1aadbe68f 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.12 + 0.42.0-beta.13 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 792b434a1..e8a9a76ec 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.12 + 0.42.0-beta.13 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 196e6db9a..9b062f4e8 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.12 + 0.42.0-beta.13 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 22cfe6ecc..7f8468eb5 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 283a32fdc..0fb6fde09 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 5fd392245..24e779721 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index ec5103284..8ee7bd66b 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 1d45a2ed2..3c7c63b86 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index d17a3b4e7..75e68cacd 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index a7c4a74b6..3422e095c 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 0e3a4a626..e9ceb4dfb 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index b0d99fb60..512e390aa 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 5a2923216..0f7667320 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index ef5da44c5..2dac7bda3 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index b22a3b8d8..581504423 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" edition = "2021" license.workspace = true repository.workspace = true From 2f496322ef23bdb27d57e7aea9d151336ab570a4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:51:25 +0800 Subject: [PATCH 52/75] 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 53/75] 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 54/75] 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 55/75] 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 56/75] 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 57/75] 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 58/75] 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 59/75] 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 60/75] 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 61/75] 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) From ea59f8acb61a6ac93fc940d055efe3c8f823991c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 21:49:45 +0800 Subject: [PATCH 62/75] feat(python): preserve Function timestamp and duration types (#5032) Function declarations currently reject exact timestamp and duration types. Preserve their Arrow units and timezones in canonical signature JSON, including fixed-offset timezones and nested fields. Bare `datetime` and microsecond/no-timezone declarations keep their existing representation; `timedelta` requires an explicit unit. Compound temporal signatures require the Lance Namespace decoder in https://github.com/lance-format/lance/pull/11059 and corresponding server validation support. Older readers reject these signatures; this change does not upgrade server support or dependency pins. Validation: 128 Python signature tests and 30 documentation tests passed (one skipped), using the changed Python source with an existing native extension. No Rust rebuild or end-to-end Function registration/refresh was performed. --- docs/web/management/function.mdx | 35 ++++ python/python/lancedb/functions.py | 48 +++++- .../tests/test_first_class_function_slice2.py | 156 +++++++++++++++++- 3 files changed, 227 insertions(+), 12 deletions(-) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 41e64d482..f6264edbf 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -104,6 +104,41 @@ 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. +### Timestamps and durations {#timestamps-durations} + +Bare `datetime` keeps its existing `timestamp[us]` default without a timezone. +For any other unit or a timezone, declare the Arrow type explicitly: + +```python +from datetime import datetime +from typing import Annotated + +import pyarrow as pa + + +@function +def normalize( + ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")], +) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]: + ... +``` + +`pa.timestamp` accepts `s`, `ms`, `us`, and `ns`, and a timezone such as +`UTC`, `America/New_York`, or `+08:00`. The canonical signature uses +`{"type":"timestamp::"}`, with `-` for no timezone; the +microsecond/no-timezone case keeps the legacy `{"type":"timestamp"}` shape. +A timezone string of `-` is reserved for "no timezone" and is rejected. + +`pa.duration` accepts the same four units and uses +`{"type":"duration:"}`; the microsecond case keeps the legacy +`{"type":"duration"}` shape. A bare `timedelta` has no unit and is rejected; +use `Annotated[timedelta, pa.duration("s")]` or an explicit schema. + +Other units are never downgraded to microseconds. A reader that predates the +compound temporal representation cannot read those signatures. A deployment +must include the corresponding Lance Namespace and Sophon support; this +client-side declaration does not add server support. + ## Connect and create a table {#table} The remaining steps run against your Enterprise deployment. Replace the database diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 471fc2437..18c504a8f 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -29,7 +29,7 @@ import textwrap import types import warnings from collections.abc import Mapping, Sequence -from datetime import date, datetime +from datetime import date, datetime, timedelta from pathlib import Path from typing import ( Annotated, @@ -1043,6 +1043,7 @@ _GRAMMAR_PRIMITIVES = ( (pa.date32(), "date32"), (pa.date64(), "date64"), ) +_FUNCTION_TIMEUNITS = ("s", "ms", "us", "ns") def _canonical_arrow_type( @@ -1259,6 +1260,26 @@ def _exact_arrow_type( for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: return {"type": name} + if pa.types.is_timestamp(data_type): + unit = data_type.unit + if unit not in _FUNCTION_TIMEUNITS: + raise TypeError(f"unsupported Function timestamp unit: {unit!r}") + timezone = data_type.tz + if timezone == "-": + raise TypeError( + "unsupported Function timestamp timezone: '-' is reserved for " + "no timezone" + ) + if unit == "us" and timezone is None: + return {"type": "timestamp"} + return {"type": f"timestamp:{unit}:{timezone if timezone is not None else '-'}"} + if pa.types.is_duration(data_type): + unit = data_type.unit + if unit not in _FUNCTION_TIMEUNITS: + raise TypeError(f"unsupported Function duration unit: {unit!r}") + if unit == "us": + return {"type": "duration"} + return {"type": f"duration:{unit}"} if pa.types.is_struct(data_type): fields = list(data_type) names = [field.name for field in fields] @@ -1344,9 +1365,9 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: raise TypeError( "Annotated Function types require exactly one PyArrow DataType" ) - # A struct value is written as a dict, which has no Arrow type of its - # own; the Annotated metadata supplies it. - if base is dict or get_origin(base) is dict: + # A struct value is written as a dict, and timedelta has no unit of + # its own; the Annotated metadata supplies those types. + if base is dict or get_origin(base) is dict or base is timedelta: base_nullable = False else: _, base_nullable = _annotation_type(base) @@ -1372,7 +1393,14 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: if annotation is date: return pa.date32(), nullable if annotation is datetime: + # Existing default: microsecond precision, no timezone. Other units + # and timezones require Annotated or an explicit schema. return pa.timestamp("us"), nullable + if annotation is timedelta: + raise TypeError( + "timedelta Function annotations require an explicit unit; use " + "Annotated[timedelta, pyarrow.duration(unit)] or an explicit schema" + ) if get_origin(annotation) is list: arguments = get_args(annotation) if len(arguments) != 1: @@ -2701,7 +2729,11 @@ def function( 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. + columns. Bare ``datetime`` keeps its existing ``timestamp[us]`` default + without a timezone; other units and timezones require + ``Annotated[datetime, pyarrow.timestamp(unit, tz=...)]`` or an explicit + schema. A bare ``timedelta`` has no unit and is rejected; use + ``Annotated[timedelta, pyarrow.duration(unit)]`` or an explicit schema. **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 @@ -2808,8 +2840,10 @@ def function( output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional 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. + must be non-nullable. Temporal fields use canonical Arrow JSON; the + microsecond/no-timezone case keeps the legacy timestamp/duration + shape. 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 7e089a96d..1e896f780 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -9,7 +9,7 @@ import functools import importlib.util import inspect import types -from datetime import date +from datetime import date, datetime, timedelta import http.server import json import os @@ -19,7 +19,7 @@ import sys import typing import urllib.parse import warnings -from typing import Optional +from typing import Annotated, Optional import pyarrow as pa import pytest @@ -884,12 +884,11 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): == "large_list" ) for outside in [ - pa.timestamp("us"), pa.decimal128(10, 2), pa.binary(4), - pa.duration("s"), + pa.time32("s"), + pa.time64("us"), pa.list_(pa.float32(), 0), - pa.list_(pa.timestamp("us")), ]: with pytest.raises(TypeError, match="unsupported Arrow type"): _canonical_arrow_type(outside) @@ -1215,6 +1214,153 @@ def test_explicit_arrow_schema_is_deterministic(): assert signature.output.nullable is False +def test_timestamp_annotation_and_explicit_schema_serialization(): + for unit in ("s", "ms", "us", "ns"): + for timezone in (None, "UTC", "America/New_York", "+08:00", "-05:00"): + encoded = json.loads(_canonical_arrow_type(pa.timestamp(unit, tz=timezone))) + if unit == "us" and timezone is None: + assert encoded == {"type": "timestamp"} + else: + suffix = timezone if timezone is not None else "-" + assert encoded == {"type": f"timestamp:{unit}:{suffix}"} + + with pytest.raises(TypeError, match="reserved for no timezone"): + _canonical_arrow_type(pa.timestamp("us", tz="-")) + + @function + def normalize( + ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")], + ) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]: + return ts + + signature = normalize.registration_request.signature + assert json.loads(signature.inputs[0].arrow_type) == {"type": "timestamp:ns:UTC"} + assert json.loads(signature.output.arrow_type) == {"type": "timestamp:ns:UTC"} + round_trip = FunctionSignature.from_json(signature.to_canonical_json()) + assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type + assert round_trip.output.arrow_type == signature.output.arrow_type + + @function + def optional_timestamp( + ts: Optional[Annotated[datetime, pa.timestamp("ms", tz="UTC")]], + ) -> int: + return 0 + + optional_input = optional_timestamp.registration_request.signature.inputs[0] + assert optional_input.nullable is True + assert json.loads(optional_input.arrow_type) == {"type": "timestamp:ms:UTC"} + + @function + def legacy(ts: datetime) -> datetime: + return ts + + legacy_signature = legacy.registration_request.signature + assert json.loads(legacy_signature.inputs[0].arrow_type) == {"type": "timestamp"} + assert json.loads(legacy_signature.output.arrow_type) == {"type": "timestamp"} + legacy_round_trip = FunctionSignature.from_json( + legacy_signature.to_canonical_json() + ) + assert legacy_round_trip.inputs[0].arrow_type == '{"type":"timestamp"}' + + input_schema = pa.schema( + [pa.field("ts", pa.timestamp("ms", tz="America/New_York"), nullable=True)] + ) + output_schema = pa.schema( + [ + pa.field("ts", pa.timestamp("ns", tz="+08:00"), nullable=True), + pa.field("elapsed", pa.duration("ms"), nullable=False), + ] + ) + + @function(input_schema=input_schema, output_schema=output_schema) + def nested(ts): + return {"ts": ts, "elapsed": None} + + nested_signature = nested.registration_request.signature + assert nested_signature.inputs[0].nullable is True + assert json.loads(nested_signature.inputs[0].arrow_type) == { + "type": "timestamp:ms:America/New_York" + } + assert nested_signature.output.kind == "named_struct" + assert nested_signature.output.fields[0].nullable is True + assert json.loads(nested_signature.output.fields[0].arrow_type) == { + "type": "timestamp:ns:+08:00" + } + assert json.loads(nested_signature.output.fields[1].arrow_type) == { + "type": "duration:ms" + } + + list_type = pa.list_(pa.field("item", pa.timestamp("ms", tz="UTC"), nullable=False)) + assert json.loads(_canonical_arrow_type(list_type)) == { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": False, + "type": {"type": "timestamp:ms:UTC"}, + } + ], + } + + +def test_duration_annotation_and_explicit_schema_serialization(): + for unit in ("s", "ms", "us", "ns"): + encoded = json.loads(_canonical_arrow_type(pa.duration(unit))) + expected = ( + {"type": "duration"} if unit == "us" else {"type": f"duration:{unit}"} + ) + assert encoded == expected + + @function + def elapsed( + value: Annotated[timedelta, pa.duration("s")], + ) -> Annotated[timedelta, pa.duration("ns")]: + return value + + signature = elapsed.registration_request.signature + assert json.loads(signature.inputs[0].arrow_type) == {"type": "duration:s"} + assert json.loads(signature.output.arrow_type) == {"type": "duration:ns"} + round_trip = FunctionSignature.from_json(signature.to_canonical_json()) + assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type + assert round_trip.output.arrow_type == signature.output.arrow_type + + @function + def optional_elapsed( + value: Optional[Annotated[timedelta, pa.duration("ms")]], + ) -> int: + return 0 + + optional_input = optional_elapsed.registration_request.signature.inputs[0] + assert optional_input.nullable is True + assert json.loads(optional_input.arrow_type) == {"type": "duration:ms"} + + with pytest.raises( + TypeError, match="timedelta Function annotations require an explicit unit" + ): + + @function + def missing(value: timedelta) -> timedelta: + return value + + input_schema = pa.schema([pa.field("elapsed", pa.duration("ms"), nullable=True)]) + output_schema = pa.field("result", pa.duration("us"), nullable=False) + + @function(input_schema=input_schema, output_schema=output_schema) + def explicit(elapsed: timedelta) -> timedelta: + return elapsed + + explicit_signature = explicit.registration_request.signature + assert explicit_signature.inputs[0].nullable is True + assert json.loads(explicit_signature.inputs[0].arrow_type) == { + "type": "duration:ms" + } + assert json.loads(explicit_signature.output.arrow_type) == {"type": "duration"} + explicit_round_trip = FunctionSignature.from_json( + explicit_signature.to_canonical_json() + ) + assert explicit_round_trip.output.arrow_type == '{"type":"duration"}' + + def test_nullable_scalar_output_annotation_and_explicit_schema(): input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)]) From 2499342fa1bccdaafdf4c38a8da35459b25b247d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:30:28 +0800 Subject: [PATCH 63/75] feat(function): expose resolved environments and fresh lock requests (#5034) Function registration clients cannot request fresh dependency resolution or inspect the measured environment returned by the server. Add `refresh_lock=True` to Python registration and preserve the requested runtime and measured environments in Rust/Python Function version readback. Registration forwards both `exist_ok` and `refresh_lock`; defaults remain unchanged. Single-platform versions retain `resolved_environment`. Multiarchitecture versions expose `resolved_environments`, keyed by OCI `os/architecture`, and the Python `environment_report` alias. Platforms are never flattened: absent entries mean unknown measurements, while measured empty package lists remain present. Registration waits emit scalar and per-platform server warnings once per Job; catalog reads do not repeat them. Requires matching server support, including Sophon #10344 for per-platform publication. Nine focused Python source-overlay tests and 29 documentation tests passed for the additive map change; one documentation test requiring a newer native `exist_ok` binding was excluded. These checks reuse a prebuilt extension and do not establish current native integration. PR CI exercises the Rust transport/readback and Python bindings. Live multiarchitecture registration and GPU acceptance remain separate. --- docs/src/python/python.md | 8 + docs/web/management/function.mdx | 118 ++++++ python/python/lancedb/__init__.py | 4 + python/python/lancedb/db.py | 56 ++- python/python/lancedb/functions.py | 122 ++++++ python/python/lancedb/remote/db.py | 2 + .../tests/test_first_class_function_slice2.py | 371 +++++++++++++++++- rust/lancedb/src/function.rs | 279 ++++++++++++- rust/lancedb/src/remote/sql_test.rs | 135 +++++++ 9 files changed, 1087 insertions(+), 8 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 5aa21f691..b7eb1704a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -564,6 +564,14 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.FunctionVersion +::: lancedb.functions.FunctionEnvironment + +::: lancedb.functions.ResolvedEnvironment + +::: lancedb.functions.ResolvedPackage + +::: lancedb.functions.ResolvedEnvironmentProvenance + ::: lancedb.functions.HuggingFaceModel ::: lancedb.functions.PythonRuntimeSpec diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index f6264edbf..efcbcc799 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -178,6 +178,13 @@ with `db.get_function(name, version=...)`. The version may be an integer or its string form. Omit `version` to resolve and return the latest currently visible revision. +Re-registering unchanged code reuses the published version and its resolved +environment lock. Pass `refresh_lock=True` to `create_function` or +`create_function_async` to request a fresh lock for this registration. It is a +registration action, not part of the Function's source or runtime identity. +A deployment must support the field; an older server rejects the unknown +field rather than silently reusing the old lock. + {/* Draft for the function exist_ok release. Use `exist_ok=True` on `create_function` or `create_function_async` to return @@ -246,6 +253,117 @@ are not included; list each namespace separately. A version's `created_at_millis`, `metadata`, `disabled` flag, and `secret_bindings` are all readable this way without applying or calling the function. +### Inspect the resolved environment {#resolved-environment} + +The version keeps the requested runtime separate from what the server actually +installed. The typed catalog API is available in Python and Rust; TypeScript +does not yet expose this readback API. `version.runtime` is the specification +sent at registration. `version.resolved_environment` is measured data from the +built image: + + +```python +version = db.get_function("double") +print(version.runtime) # requested runtime, or None for legacy +print(version.environment.resolved) # measured environment, or None for legacy +print(version.environment_report) # platform -> measured environment map + +if version.environment.resolved is not None: + for package in version.environment.resolved.packages: + print(package.name, package.version) # versions keep labels such as +cu130 +``` + +{/* Draft for the typed Rust environment inspection release. +```rust +# async fn inspect_environment(connection: &lancedb::Connection) -> Result<(), Box> { +let version = connection.get_function_latest("double", &[]).await?; +println!("Requested runtime: {:?}", version.runtime()); + +if let Some(environment) = version.resolved_environment() { + for package in &environment.packages { + println!("{} {}", package.name, package.version); + } +} + +for (platform, environment) in version.resolved_environments() { + println!("{platform}: {} measured packages", environment.packages.len()); + for package in &environment.packages { + println!("{} {}", package.name, package.version); + } +} +# Ok(()) +# } +``` +*/} + + +`version.environment.requested` and `version.environment.resolved` are +convenience members over the same canonical fields; they do not add another +wire shape. The canonical JSON exposes top-level `runtime` and +`resolved_environment`. A missing `resolved_environment` means the version or +environment cache predates measurement; it is unknown, not an empty installed +package list. A package's `source` is present only when the submitted lock +retained it, and provenance fields are reported without client-side guessing. + +For a multiarchitecture image, the scalar field is absent and +`version.resolved_environments` (also available as +`version.environment_report`) maps OCI `os/architecture` keys to the measured +environment for that platform. A missing platform key means its measurement is +unknown; an empty `packages` list inside a key is a measured empty environment +and is retained. The SDK never merges platforms or fabricates an aggregate +package list. + +The corresponding canonical payload has this shape: + +```json +{ + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": {"kind": "pip", "packages": ["vllm==0.11.0"]} + }, + "resolved_environment": { + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "torch resolved to torch==2.9.0+cu130 but is not pinned exactly; add torch==2.9.0+cu130 to pin it." + ] + } +} +``` + +The multiarchitecture form has the same package shape per platform: + +```json +{ + "resolved_environments": { + "linux/amd64": { + "packages": [{"name": "torch", "version": "2.9.0+cu130"}] + }, + "linux/arm64": { + "packages": [] + } + } +} +``` + +Environment warnings are part of the registration result. Waiting on +`create_function_async(...)` (or calling `create_function`) emits each server +warning from the scalar or per-platform measurements as a Python `UserWarning`; +`get_function` and `list_functions` read the same version but do not +replay those registration warnings. + ## Try it in SQL {#try-sql} A registered function is callable in SQL by its name, the same as any other diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 31285d100..acf25d35c 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -51,11 +51,15 @@ from .functions import ( FunctionApplication as FunctionApplication, FunctionBinding as FunctionBinding, FunctionDefinition as FunctionDefinition, + FunctionEnvironment as FunctionEnvironment, FunctionRegistrationRequest as FunctionRegistrationRequest, FunctionRetryPolicy as FunctionRetryPolicy, FunctionVersion as FunctionVersion, HuggingFaceModel as HuggingFaceModel, PythonRuntimeSpec as PythonRuntimeSpec, + ResolvedEnvironment as ResolvedEnvironment, + ResolvedEnvironmentProvenance as ResolvedEnvironmentProvenance, + ResolvedPackage as ResolvedPackage, RefreshColumnResult as RefreshColumnResult, function as function, udf as udf, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b84e4d581..12c7edd5c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -154,6 +154,38 @@ def _normalize_function_version(version: Optional[Union[int, str]]) -> Optional[ raise TypeError("version must be an int, str, or None") +def _function_registration_decoder(): + """Parse a registration result and emit its server warnings once. + + The warnings come from the scalar environment or, for a multiarchitecture + image, each measured platform entry. They are part of the registration job + result, not a new client-side package policy. Catalog get/list readbacks + use ``FunctionVersion.from_json`` directly and therefore do not replay + them. + """ + warned = False + + def decode(payload: str) -> FunctionVersion: + nonlocal warned + version = FunctionVersion.from_json(payload) + if not warned: + environments = [ + environment + for environment in ( + version.resolved_environment, + *version.resolved_environments.values(), + ) + if environment is not None + ] + for environment in environments: + for message in environment.warnings: + warnings.warn(message, UserWarning, stacklevel=3) + warned = True + return version + + return decode + + class DBConnection(EnforceOverrides): """An active LanceDB connection interface. @@ -1018,6 +1050,7 @@ class DBConnection(EnforceOverrides): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. @@ -1040,6 +1073,13 @@ class DBConnection(EnforceOverrides): namespace_path : list of str, optional The namespace holding the Function. None or an empty list is the root namespace. + refresh_lock : bool, default False + Ask the server to resolve a fresh environment lock instead of + reusing the published version's lock. + + When the registration job resolves, each resolved-environment warning + reported by the server is emitted as a Python ``UserWarning``. Catalog + reads do not replay those registration warnings. Examples -------- @@ -1060,6 +1100,7 @@ class DBConnection(EnforceOverrides): secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, + refresh_lock=refresh_lock, ).wait() def create_function_async( @@ -1069,6 +1110,7 @@ class DBConnection(EnforceOverrides): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> Job[FunctionVersion]: """Submit a scalar Python function for building and registration. @@ -1079,6 +1121,11 @@ class DBConnection(EnforceOverrides): artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. LanceDB Embedded connections raise ``NotImplementedError``. + + ``refresh_lock`` asks the server to resolve a fresh environment lock + instead of reusing the published version's lock. Waiting on the job + emits the server's resolved-environment warnings as Python warnings; + reading the same version later does not repeat them. """ raise NotImplementedError( _append_doc_url( @@ -2432,6 +2479,7 @@ class LanceDBConnection(DBConnection): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( @@ -2439,6 +2487,7 @@ class LanceDBConnection(DBConnection): secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, + refresh_lock=refresh_lock, ) ) return Job(job) @@ -3788,6 +3837,7 @@ class AsyncConnection(object): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> AsyncJob[FunctionVersion]: """Submit a scalar Python function for building and registration. @@ -3802,14 +3852,16 @@ class AsyncConnection(object): the environment variable its value arrives in. ``namespace_path`` is the namespace the Function is registered in; None or an empty list is the root. LanceDB Embedded connections raise ``NotImplementedError``. + ``refresh_lock`` asks the server to resolve a fresh environment lock + instead of reusing the published version's lock. """ if not isinstance(definition, FunctionDefinition): raise TypeError("create_function_async requires a @function definition") - request = definition.bind_secrets(secrets) + request = definition.bind_secrets(secrets).with_refresh_lock(refresh_lock) inner = await self._inner.create_function_async( request.to_canonical_json(), namespace_path, exist_ok=exist_ok ) - return _typed_job(inner, FunctionVersion.from_json) + return _typed_job(inner, _function_registration_decoder()) async def get_function( self, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 18c504a8f..ecbc697d1 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -36,6 +36,7 @@ from typing import ( Any, Callable, Literal, + NamedTuple, Optional, TYPE_CHECKING, Union, @@ -101,6 +102,12 @@ def _validate_batch_size(value: Any) -> Optional[int]: return value +def _validate_refresh_lock(value: Any) -> bool: + if not isinstance(value, bool): + raise ValueError("refresh_lock must be a boolean") + return value + + def _validate_max_concurrency(value: Any) -> Optional[int]: if value is None: return None @@ -544,6 +551,67 @@ class FunctionImage(_RemoteValue): models: tuple[HuggingFaceModel, ...] = () +class ResolvedPackage(_RemoteValue): + """One installed Python distribution measured from a baked environment. + + ``version`` is the complete version reported by package metadata, + including local labels such as ``+cu130``. ``source`` is present only when + the submitted lock retained a per-package source; absent means unknown, not + an inferred index. + """ + + name: str + version: str + source: Optional[str] = None + + +class ResolvedEnvironmentProvenance(_RemoteValue): + """Sanitized source and accelerator provenance for a resolved environment. + + ``configured_index_urls`` and ``configured_find_links`` record build + inputs. ``resolved_indexes`` records indexes visible in the submitted lock, + so a configured source is not by itself evidence that a package came from + it. Empty lists and absent fields remain absent; the client does not + synthesize them. + """ + + configured_index_urls: tuple[str, ...] = () + configured_find_links: tuple[str, ...] = () + resolved_indexes: tuple[str, ...] = () + cuda_toolkit: Optional[str] = None + torch_version: Optional[str] = None + + +class ResolvedEnvironment(_RemoteValue): + """Actual installed distributions and registration warnings for one platform. + + A missing value means its measurement is unknown, not an empty + installed-package list. Versions are retained verbatim, including local + labels; package ``source`` is retained only when the producer recorded it. + """ + + packages: tuple[ResolvedPackage, ...] + provenance: Optional[ResolvedEnvironmentProvenance] = None + warnings: tuple[str, ...] = () + + +class FunctionEnvironment(NamedTuple): + """Requested and measured environment view for a Function version. + + This is a view over + [FunctionVersion.runtime][lancedb.functions.FunctionVersion.runtime] + and + [FunctionVersion.resolved_environment][lancedb.functions.FunctionVersion.resolved_environment]. + It adds no wire field and performs no second parse. ``requested`` is the + runtime specification supplied at registration; ``resolved`` is measured + data and is ``None`` when unknown. For per-platform multiarchitecture + measurements, use ``FunctionVersion.environment_report``. + """ + + requested: Optional[PythonRuntimeSpec] + resolved: Optional[ResolvedEnvironment] + + def _validate_object_version(value: str) -> str: if int(value) > 2**64 - 1: raise ValueError("Function version exceeds uint64") @@ -593,6 +661,17 @@ class FunctionVersion(_RemoteValue): ``result_stability`` retain the execution controls reported by the catalog. They are ``None`` for versions registered before the corresponding declaration. + + ``runtime`` is the runtime specification requested at registration. It is + not evidence of what was installed. ``resolved_environment`` is measured + data for a single-platform image: actual package names and complete + versions, optional per-package source, provenance, and registration + warnings. ``resolved_environments`` is the corresponding map for a + multiarchitecture image, keyed by OCI ``os/architecture``. It is never + flattened into an aggregate package list. ``None`` or an empty map means + unknown data, not an empty installed environment. ``environment`` is a + convenience view with ``requested`` and ``resolved`` members over the same + fields. """ name: str @@ -613,6 +692,11 @@ class FunctionVersion(_RemoteValue): max_concurrency: Optional[int] = None row_timeout_seconds: Optional[float] = None result_stability: Optional[str] = None + runtime: Optional[PythonRuntimeSpec] = None + resolved_environment: Optional[ResolvedEnvironment] = None + resolved_environments: Mapping[str, ResolvedEnvironment] = Field( + default_factory=dict + ) @field_validator("batch_size", mode="before") @classmethod @@ -629,6 +713,24 @@ class FunctionVersion(_RemoteValue): def _validate_row_timeout(cls, value): return _validate_row_timeout(value) + @property + def environment(self) -> FunctionEnvironment: + """Requested and measured environment without adding a second parser.""" + return FunctionEnvironment( + requested=self.runtime, + resolved=self.resolved_environment, + ) + + @property + def environment_report(self) -> Mapping[str, ResolvedEnvironment]: + """Per-platform measured reports, keyed by OCI ``os/architecture``. + + This is the same map as ``resolved_environments`` and is never + flattened. Single-platform images use ``resolved_environment`` instead; + an absent platform means its measurement is unknown. + """ + return self.resolved_environments + def __call__(self, **arguments: Any) -> FunctionApplication: """Bind this exact version to named table columns and constant inputs. @@ -769,6 +871,9 @@ class FunctionRegistrationRequest(_RemoteValue): Credential values deliberately have no field here. The only secret-shaped thing a client sends is ``secret_bindings``: the name of a Secret the database already holds, which the remote service resolves at execution. + ``refresh_lock`` is a per-registration action, not part of the Function's + source or runtime identity; its false default is omitted from canonical + JSON. """ name: str @@ -781,6 +886,7 @@ class FunctionRegistrationRequest(_RemoteValue): retry_policy: Optional[FunctionRetryPolicy] = None secret_bindings: tuple[SecretBinding, ...] = () models: tuple[HuggingFaceModel, ...] = () + refresh_lock: bool = False @field_validator("batch_size", mode="before") @classmethod @@ -797,6 +903,18 @@ class FunctionRegistrationRequest(_RemoteValue): def _validate_row_timeout(cls, value): return _validate_row_timeout(value) + @field_validator("refresh_lock", mode="before") + @classmethod + def _validate_refresh_lock(cls, value): + return _validate_refresh_lock(value) + + def with_refresh_lock(self, refresh_lock: bool) -> FunctionRegistrationRequest: + """Return this request with the registration-time refresh action set.""" + refresh_lock = _validate_refresh_lock(refresh_lock) + if self.refresh_lock == refresh_lock: + return self + return self._copy(update={"refresh_lock": refresh_lock}) + class FunctionVersionRef(_OpenRemoteValue): name: str @@ -3043,6 +3161,7 @@ __all__ = [ "FunctionArtifactContent", "FunctionArtifactRequest", "FunctionBinding", + "FunctionEnvironment", "FunctionOutput", "FunctionParameter", "FunctionRegistrationRequest", @@ -3059,6 +3178,9 @@ __all__ = [ "PythonEnvironmentSpec", "PythonAdapterSpec", "PythonRuntimeSpec", + "ResolvedEnvironment", + "ResolvedEnvironmentProvenance", + "ResolvedPackage", "RefreshColumnResult", "FunctionDefinition", ] diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index b9928d278..913c8fc2c 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1002,6 +1002,7 @@ class RemoteDBConnection(DBConnection): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( @@ -1009,6 +1010,7 @@ class RemoteDBConnection(DBConnection): secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, + refresh_lock=refresh_lock, ) ) return Job(job) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 1e896f780..6dcc0bbbe 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -26,8 +26,9 @@ import pytest import lancedb from lancedb import BlobReader -from lancedb.db import AsyncConnection +from lancedb.db import AsyncConnection, DBConnection, LanceDBConnection from lancedb.functions import ( + FunctionRegistrationRequest, FunctionSignature, FunctionVersion, HuggingFaceModel, @@ -82,6 +83,63 @@ def analyze_caption(caption: str) -> str: return caption.strip() +def _function_version_with_resolved_environment(): + version = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + version["runtime"] = json.loads( + normalize_score.registration_request.runtime.to_canonical_json() + ) + version["resolved_environment"] = { + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple", + }, + {"name": "transformers", "version": "4.57.1"}, + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "configured_find_links": ["https://downloads.example/wheels"], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130", + }, + "warnings": [ + "transformers resolved to transformers==4.57.1 but is not pinned " + "exactly; add transformers==4.57.1 to pin it." + ], + } + return version + + +def _function_version_with_resolved_environments(): + version = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + version["runtime"] = json.loads( + normalize_score.registration_request.runtime.to_canonical_json() + ) + version["resolved_environments"] = { + "linux/amd64": { + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple", + } + ], + "warnings": ["amd64 environment warning"], + }, + "linux/arm64": { + "packages": [], + "warnings": ["arm64 environment warning"], + }, + } + return version + + def test_scalar_function_matches_shared_registration_golden_and_remains_callable(): assert isinstance(normalize_score, FunctionDefinition) assert normalize_score(25.0) == 0.25 @@ -98,6 +156,118 @@ def test_scalar_function_matches_shared_registration_golden_and_remains_callable } +def test_refresh_lock_is_a_registration_option_not_part_of_identity(): + default = normalize_score.registration_request + old_json = default.to_canonical_json() + assert "refresh_lock" not in json.loads(old_json) + + refreshed = default.with_refresh_lock(True) + payload = json.loads(refreshed.to_canonical_json()) + assert payload["refresh_lock"] is True + assert ( + FunctionRegistrationRequest.from_json( + refreshed.to_canonical_json() + ).refresh_lock + is True + ) + assert refreshed.artifact.digest == default.artifact.digest + assert refreshed.runtime.digest == default.runtime.digest + assert default.with_refresh_lock(False).to_canonical_json() == old_json + with pytest.raises(ValueError, match="refresh_lock must be a boolean"): + default.with_refresh_lock(1) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("exist_ok", [False, True]) +async def test_async_create_function_forwards_refresh_lock(exist_ok): + calls = [] + + class Inner: + async def create_function_async( + self, request_json, namespace_path=None, *, exist_ok=False + ): + calls.append((json.loads(request_json), namespace_path, exist_ok)) + return object() + + connection = object.__new__(AsyncConnection) + connection._inner = Inner() + await connection.create_function_async(normalize_score) + await connection.create_function_async( + normalize_score, refresh_lock=True, exist_ok=exist_ok, namespace_path=["team"] + ) + with pytest.raises(ValueError, match="refresh_lock must be a boolean"): + await connection.create_function_async(normalize_score, refresh_lock=1) + + assert len(calls) == 2 + assert "refresh_lock" not in calls[0][0] + assert calls[0][1:] == (None, False) + assert calls[1][0]["refresh_lock"] is True + assert calls[1][1:] == (["team"], exist_ok) + + +@pytest.mark.parametrize("exist_ok", [False, True]) +def test_sync_create_function_paths_forward_refresh_lock(exist_ok): + calls = [] + + class AsyncInner: + async def create_function_async( + self, + definition, + *, + secrets=None, + exist_ok=False, + namespace_path=None, + refresh_lock=False, + ): + calls.append(("wrapped", refresh_lock, namespace_path, exist_ok)) + return object() + + for connection_type in (LanceDBConnection, RemoteDBConnection): + connection = object.__new__(connection_type) + connection._conn = AsyncInner() + connection.create_function_async( + normalize_score, + refresh_lock=True, + exist_ok=exist_ok, + namespace_path=["team"], + ) + + class BlockingConnection: + def create_function_async( + self, + definition, + *, + secrets=None, + exist_ok=False, + namespace_path=None, + refresh_lock=False, + ): + calls.append(("blocking", refresh_lock, namespace_path, exist_ok)) + + class ImmediateJob: + def wait(self): + return "version" + + return ImmediateJob() + + blocking = BlockingConnection() + assert ( + DBConnection.create_function( + blocking, + normalize_score, + refresh_lock=True, + exist_ok=exist_ok, + namespace_path=["team"], + ) + == "version" + ) + assert calls == [ + ("wrapped", True, ["team"], exist_ok), + ("wrapped", True, ["team"], exist_ok), + ("blocking", True, ["team"], exist_ok), + ] + + def test_function_declares_pinned_hugging_face_models(): model = HuggingFaceModel( repo="sentence-transformers/all-MiniLM-L6-v2", @@ -2205,6 +2375,205 @@ class _RawFunctionCatalog: return None +def test_function_version_reads_requested_and_resolved_environments(): + legacy = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + legacy_version = FunctionVersion.from_json(json.dumps(legacy)) + assert legacy_version.runtime is None + assert legacy_version.resolved_environment is None + assert legacy_version.environment.requested is None + assert legacy_version.environment.resolved is None + + payload = _function_version_with_resolved_environment() + version = FunctionVersion.from_json(json.dumps(payload)) + assert version.environment.requested is version.runtime + assert version.environment.resolved is version.resolved_environment + assert version.runtime.kind == "python" + resolved = version.resolved_environment + assert resolved.packages[0].version == "2.9.0+cu130" + assert resolved.packages[0].source == "https://packages.example/simple" + assert resolved.packages[1].source is None + assert resolved.provenance.torch_version == "torch==2.9.0+cu130" + assert resolved.warnings == tuple(payload["resolved_environment"]["warnings"]) + + encoded = json.loads(version.to_canonical_json()) + assert encoded["runtime"]["kind"] == "python" + assert encoded["resolved_environment"]["packages"][0]["version"] == "2.9.0+cu130" + assert "source" not in encoded["resolved_environment"]["packages"][1] + assert ( + encoded["resolved_environment"]["provenance"]["torch_version"] + == "torch==2.9.0+cu130" + ) + assert FunctionVersion.from_json(version.to_canonical_json()) == version + + invalid = json.loads(json.dumps(payload)) + del invalid["resolved_environment"]["packages"] + with pytest.raises(ValueError): + FunctionVersion.from_json(json.dumps(invalid)) + + +def test_function_version_reads_resolved_environments_by_platform(): + legacy = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + legacy_version = FunctionVersion.from_json(json.dumps(legacy)) + assert legacy_version.resolved_environment is None + assert legacy_version.resolved_environments == {} + assert legacy_version.environment_report == {} + + payload = _function_version_with_resolved_environments() + version = FunctionVersion.from_json(json.dumps(payload)) + assert version.resolved_environment is None + assert version.resolved_environments == version.environment_report + assert set(version.environment_report) == {"linux/amd64", "linux/arm64"} + assert ( + version.environment_report["linux/amd64"].packages[0].version == "2.9.0+cu130" + ) + assert version.environment_report["linux/arm64"].packages == () + assert version.environment_report["linux/arm64"].warnings == ( + "arm64 environment warning", + ) + + encoded = json.loads(version.to_canonical_json()) + assert "resolved_environment" not in encoded + assert ( + encoded["resolved_environments"]["linux/amd64"]["packages"][0]["version"] + == "2.9.0+cu130" + ) + assert encoded["resolved_environments"]["linux/arm64"]["packages"] == [] + assert FunctionVersion.from_json(version.to_canonical_json()) == version + + missing_platform = json.loads(json.dumps(payload)) + del missing_platform["resolved_environments"]["linux/arm64"] + missing_version = FunctionVersion.from_json(json.dumps(missing_platform)) + assert "linux/arm64" not in missing_version.environment_report + assert "linux/amd64" in missing_version.environment_report + + empty_map = json.loads(json.dumps(payload)) + empty_map["resolved_environments"] = {} + empty_version = FunctionVersion.from_json(json.dumps(empty_map)) + assert empty_version.resolved_environments == {} + assert "resolved_environments" not in json.loads(empty_version.to_canonical_json()) + + invalid = json.loads(json.dumps(payload)) + del invalid["resolved_environments"]["linux/amd64"]["packages"] + with pytest.raises(ValueError): + FunctionVersion.from_json(json.dumps(invalid)) + + +@pytest.mark.asyncio +async def test_registration_job_emits_server_environment_warnings_once(): + payload = _function_version_with_resolved_environment() + + class InnerJob: + async def wait(self): + return json.dumps(payload) + + class Inner: + async def create_function_async( + self, request_json, namespace_path=None, *, exist_ok=False + ): + assert "refresh_lock" not in json.loads(request_json) + return InnerJob() + + connection = object.__new__(AsyncConnection) + connection._inner = Inner() + job = await connection.create_function_async(normalize_score) + with pytest.warns(UserWarning) as recorded: + version = await job.wait() + assert [str(w.message) for w in recorded] == list( + payload["resolved_environment"]["warnings"] + ) + assert version.environment.resolved.warnings == tuple( + payload["resolved_environment"]["warnings"] + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert await job.wait() is not None + assert caught == [] + + +@pytest.mark.asyncio +async def test_registration_job_emits_per_platform_environment_warnings(): + payload = _function_version_with_resolved_environments() + + class InnerJob: + async def wait(self): + return json.dumps(payload) + + class Inner: + async def create_function_async( + self, request_json, namespace_path=None, *, exist_ok=False + ): + return InnerJob() + + connection = object.__new__(AsyncConnection) + connection._inner = Inner() + job = await connection.create_function_async(normalize_score) + with pytest.warns(UserWarning) as recorded: + version = await job.wait() + assert [str(w.message) for w in recorded] == [ + "amd64 environment warning", + "arm64 environment warning", + ] + assert version.environment_report["linux/arm64"].warnings == ( + "arm64 environment warning", + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert await job.wait() is not None + assert caught == [] + + +def test_blocking_create_function_emits_server_environment_warnings(): + payload = _function_version_with_resolved_environment() + + class InnerJob: + async def wait(self): + return json.dumps(payload) + + class Inner: + async def create_function_async( + self, request_json, namespace_path=None, *, exist_ok=False + ): + return InnerJob() + + connection = object.__new__(RemoteDBConnection) + connection._conn = AsyncConnection(Inner()) + with pytest.warns(UserWarning) as recorded: + version = DBConnection.create_function(connection, normalize_score) + assert [str(w.message) for w in recorded] == list( + payload["resolved_environment"]["warnings"] + ) + assert version.environment.resolved.packages[0].version == "2.9.0+cu130" + + +@pytest.mark.asyncio +async def test_catalog_readback_does_not_replay_registration_warnings(): + payload = _function_version_with_resolved_environment() + connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True)) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + version = await connection.get_function("embed") + listed = [item async for item in connection.list_functions()] + assert caught == [] + assert version.environment.resolved.packages[0].version == "2.9.0+cu130" + assert listed[0].environment.resolved == version.resolved_environment + + +@pytest.mark.asyncio +async def test_catalog_readback_does_not_replay_per_platform_warnings(): + payload = _function_version_with_resolved_environments() + connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True)) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + version = await connection.get_function("embed") + listed = [item async for item in connection.list_functions()] + assert caught == [] + assert version.environment_report == listed[0].environment_report + + def _assert_execution_control_encoding(version): encoded = json.loads(version.to_canonical_json()) assert type(encoded["batch_size"]) is int diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 582b5b08a..d0ef6570d 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -521,6 +521,59 @@ pub struct HuggingFaceModel { pub revision: String, } +/// One installed Python distribution as measured from a Function's baked +/// environment. +/// +/// `version` is the complete version string reported by the package metadata, +/// including local labels such as `+cu130`. `source` is present only when the +/// submitted lock retained a per-package source; a missing value is unknown and +/// must not be inferred from other package indexes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedPackage { + pub name: String, + pub version: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, +} + +/// Sanitized source and accelerator provenance retained with a resolved +/// environment. +/// +/// `configured_*` records what the build was asked to use. `resolved_indexes` +/// records indexes visible in the submitted lock, so a configured source is +/// not mistaken for evidence that a package came from it. Empty lists and +/// absent fields remain absent rather than being synthesized by the client. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedEnvironmentProvenance { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub configured_index_urls: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub configured_find_links: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub resolved_indexes: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cuda_toolkit: Option, + /// The fully resolved `torch==` when torch was installed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub torch_version: Option, +} + +/// Actual installed distributions and registration warnings for one native +/// Function environment. +/// +/// A missing environment means its measurement is unknown, not an empty +/// installed-package list. The field keeps the complete versions and only the +/// provenance the producer recorded; SDK readers do not recompute package +/// policy. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedEnvironment { + pub packages: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provenance: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, +} + /// A complete OCI Function image. Its digest is independent of catalog names. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionImage { @@ -578,7 +631,9 @@ impl<'de> Deserialize<'de> for RowTimeoutSeconds { /// decoding, but they are not part of this value and are omitted from /// canonical JSON. Known fields retain their complete values, while unknown /// fields inside the open [`FunctionImage::descriptor`] JSON object remain -/// available. +/// available. Single-platform measurements use `resolved_environment`; +/// multiarchitecture measurements use `resolved_environments`, keyed by OCI +/// `os/architecture`, without flattening the platforms. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionVersion { name: String, @@ -626,6 +681,28 @@ pub struct FunctionVersion { /// Result-stability value declared at registration. #[serde(default, skip_serializing_if = "Option::is_none")] result_stability: Option, + /// The runtime requested at registration, with submitted lock bytes omitted. + /// + /// This is a specification, not the measured installation. Compare it with + /// [`Self::resolved_environment`] when the caller needs actual package + /// versions. + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime: Option, + /// Actual installed distributions, provenance, and registration warnings. + /// + /// This is the single-platform compatibility field. `None` on a + /// multiarchitecture version is expected; use + /// [`Self::resolved_environments`] for its per-platform measurements. + #[serde(default, skip_serializing_if = "Option::is_none")] + resolved_environment: Option, + /// Measurements for a multiarchitecture image, keyed by OCI + /// `os/architecture`. + /// + /// Unmeasured platforms are absent. An empty map is unknown, not an + /// aggregate of packages from the available platforms. Single-platform + /// images use [`Self::resolved_environment`] instead. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + resolved_environments: BTreeMap, } impl FunctionVersion { @@ -716,6 +793,35 @@ impl FunctionVersion { self.result_stability.as_deref() } + /// The runtime specification requested at registration, when exposed by the + /// server. + /// + /// This is the requested configuration, not evidence of what was installed. + pub fn runtime(&self) -> Option<&PythonRuntimeSpec> { + self.runtime.as_ref() + } + + /// Actual installed distributions and registration warnings for a + /// single-platform image, when measured by the server. + /// + /// `None` is unknown, not an empty environment. Package versions are + /// retained verbatim, including local labels such as `+cu130`; `source` + /// remains absent when the producer did not retain it. + pub fn resolved_environment(&self) -> Option<&ResolvedEnvironment> { + self.resolved_environment.as_ref() + } + + /// Per-platform measurements for a multiarchitecture image, keyed by OCI + /// `os/architecture`. + /// + /// The map is returned without flattening or synthesis. A missing platform + /// means its measurement is unknown; an empty environment value is a + /// measured empty environment and is retained. Single-platform images use + /// [`Self::resolved_environment`] instead. + pub fn resolved_environments(&self) -> &BTreeMap { + &self.resolved_environments + } + pub fn signature(&self) -> &FunctionSignature { &self.signature } @@ -827,6 +933,10 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s Ok(()) } +fn is_false(value: &bool) -> bool { + !*value +} + /// Stable request envelope for remote immutable Function registration. /// /// Credential values deliberately have no field here. The only secret-shaped @@ -877,10 +987,10 @@ pub struct FunctionRegistrationRequest { /// Model snapshots prepared by the service before user code runs. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, -} - -fn is_false(value: &bool) -> bool { - !*value + /// Ask the service to resolve a fresh environment lock for this request + /// instead of reusing the published version's lock. Omitted when false. + #[serde(default, skip_serializing_if = "is_false")] + pub refresh_lock: bool, } impl FunctionRegistrationRequest { @@ -1465,6 +1575,165 @@ mod tests { assert!(FunctionVersion::from_json(&document.to_string()).is_err()); } + #[test] + fn function_version_preserves_requested_and_resolved_environments() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + let legacy = FunctionVersion::from_json(VERSION).unwrap(); + assert!(legacy.runtime().is_none()); + assert!(legacy.resolved_environment().is_none()); + assert!(legacy.resolved_environments().is_empty()); + + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": ["vllm==0.11.0"] + } + }); + document["resolved_environment"] = serde_json::json!({ + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + }, + { + "name": "transformers", + "version": "4.57.1" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "configured_find_links": ["https://downloads.example/wheels"], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "transformers resolved to transformers==4.57.1 but is not pinned exactly; add transformers==4.57.1 to pin it." + ] + }); + + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime().unwrap().kind(), "python"); + assert!(version.resolved_environments().is_empty()); + let resolved = version.resolved_environment().unwrap(); + assert_eq!(resolved.packages[0].version, "2.9.0+cu130"); + assert_eq!( + resolved.packages[0].source.as_deref(), + Some("https://packages.example/simple") + ); + assert_eq!(resolved.packages[1].source, None); + assert_eq!( + resolved + .provenance + .as_ref() + .unwrap() + .torch_version + .as_deref(), + Some("torch==2.9.0+cu130") + ); + assert_eq!(resolved.warnings.len(), 1); + + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + assert_eq!( + encoded_value["resolved_environment"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert!( + encoded_value["resolved_environment"]["packages"][1] + .get("source") + .is_none() + ); + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + + document["resolved_environment"] = serde_json::json!({"warnings": []}); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); + } + + #[test] + fn function_version_preserves_resolved_environments_by_platform() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": ["vllm==0.11.0"] + } + }); + document["resolved_environments"] = serde_json::json!({ + "linux/amd64": { + "packages": [ + {"name": "torch", "version": "2.9.0+cu130"} + ], + "warnings": ["amd64 measurement"] + }, + "linux/arm64": { + "packages": [], + "warnings": ["arm64 measurement"] + } + }); + + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!(version.resolved_environment().is_none()); + let environments = version.resolved_environments(); + assert_eq!(environments.len(), 2); + assert_eq!( + environments["linux/amd64"].packages[0].version, + "2.9.0+cu130" + ); + assert!(environments["linux/arm64"].packages.is_empty()); + assert_eq!(environments["linux/arm64"].warnings, ["arm64 measurement"]); + + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + assert!(encoded_value.get("resolved_environment").is_none()); + assert_eq!( + encoded_value["resolved_environments"]["linux/amd64"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert_eq!( + encoded_value["resolved_environments"]["linux/arm64"]["packages"], + serde_json::json!([]) + ); + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + + document["resolved_environments"] + .as_object_mut() + .unwrap() + .remove("linux/arm64"); + let missing_platform = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!( + !missing_platform + .resolved_environments() + .contains_key("linux/arm64") + ); + + document["resolved_environments"] = serde_json::json!({}); + let empty_map = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!(empty_map.resolved_environments().is_empty()); + assert!( + !empty_map + .to_canonical_json() + .unwrap() + .contains("resolved_environments") + ); + + document["resolved_environments"] = serde_json::json!({ + "linux/amd64": {"warnings": []} + }); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); + } + #[test] fn blob_reader_access_survives_signature_round_trip() { let parameter: FunctionParameter = serde_json::from_value(serde_json::json!({ diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 1c39eda19..5c7ae7673 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3171,6 +3171,38 @@ async fn function_creation_and_description_use_sql_query_handles() { version_json["max_concurrency"] = serde_json::json!(4); version_json["row_timeout_seconds"] = serde_json::json!(8.0); version_json["result_stability"] = serde_json::json!("input_and_context"); + version_json["runtime"] = request_json["runtime"].clone(); + version_json["resolved_environment"] = serde_json::json!({ + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + }, + { + "name": "transformers", + "version": "4.57.1" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "configured_find_links": [], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "transformers resolved to transformers==4.57.1 but is not pinned exactly; add transformers==4.57.1 to pin it." + ] + }); + version_json["resolved_environments"] = serde_json::json!({ + "linux/amd64": { + "packages": [{"name": "torch", "version": "2.9.0+cu130"}] + }, + "linux/arm64": { + "packages": [] + } + }); if with_models { let models = serde_json::json!([{ "repo": "sentence-transformers/all-MiniLM-L6-v2", @@ -3217,6 +3249,17 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(created.max_concurrency(), Some(4)); assert_eq!(created.row_timeout_seconds(), Some(8.0)); assert_eq!(created.result_stability(), Some("input_and_context")); + assert_eq!(created.runtime().unwrap().kind(), "python"); + assert_eq!( + created.resolved_environment().unwrap().packages[0].version, + "2.9.0+cu130" + ); + assert_eq!(created.resolved_environments().len(), 2); + assert!( + created.resolved_environments()["linux/arm64"] + .packages + .is_empty() + ); // Assert the actual SQL body, after the same native JSON decode used // by the Python binding, rather than only the Python declaration. { @@ -3240,6 +3283,23 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(created_json["max_concurrency"], 4); assert_eq!(created_json["row_timeout_seconds"], 8.0); assert_eq!(created_json["result_stability"], "input_and_context"); + assert_eq!( + created_json["resolved_environment"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert!( + created_json["resolved_environment"]["packages"][1] + .get("source") + .is_none() + ); + assert_eq!( + created_json["resolved_environments"]["linux/amd64"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert_eq!( + created_json["resolved_environments"]["linux/arm64"]["packages"], + serde_json::json!([]) + ); assert_eq!( client.describe(id).await.unwrap().status, QueryStatus::Finished @@ -3253,6 +3313,19 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(described.max_concurrency(), Some(4)); assert_eq!(described.row_timeout_seconds(), Some(8.0)); assert_eq!(described.result_stability(), Some("input_and_context")); + assert_eq!(described.runtime().unwrap().kind(), "python"); + assert_eq!( + described + .resolved_environment() + .unwrap() + .provenance + .as_ref() + .unwrap() + .torch_version + .as_deref(), + Some("torch==2.9.0+cu130") + ); + assert_eq!(described.resolved_environments().len(), 2); let described_json: serde_json::Value = serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap(); assert_eq!(described_json["image"].get("models"), expected_models); @@ -3279,6 +3352,16 @@ async fn function_creation_and_description_use_sql_query_handles() { listed.items[0].result_stability(), Some("input_and_context") ); + assert_eq!(listed.items[0].runtime().unwrap().kind(), "python"); + assert_eq!( + listed.items[0] + .resolved_environment() + .unwrap() + .warnings + .len(), + 1 + ); + assert_eq!(listed.items[0].resolved_environments().len(), 2); let listed_json: serde_json::Value = serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap(); assert_eq!(listed_json["image"].get("models"), expected_models); @@ -3293,6 +3376,58 @@ async fn function_creation_and_description_use_sql_query_handles() { } } +#[tokio::test] +async fn function_creation_refresh_lock_is_forwarded_only_when_true() { + const VERSION: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + const REQUEST: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" + ); + for (refresh_lock, expect_field) in [(false, false), (true, true)] { + let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); + if refresh_lock { + request_json["refresh_lock"] = serde_json::json!(true); + } + let request = + crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) + .unwrap(); + assert_eq!(request.refresh_lock, refresh_lock); + let result = RecordBatch::try_from_iter(vec![( + "definition", + Arc::new(StringArray::from(vec![VERSION.to_string()])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: false, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client.clone()); + let job = db.create_function_async(request, &[]).await.unwrap(); + job.wait().await.unwrap(); + let seen = statements.lock().unwrap(); + let encoded = seen[0] + .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .unwrap() + .strip_suffix('\'') + .unwrap(); + let sent: serde_json::Value = serde_json::from_str(&encoded.replace("''", "'")).unwrap(); + assert_eq!(sent.get("refresh_lock").is_some(), expect_field); + if expect_field { + assert_eq!(sent["refresh_lock"], serde_json::json!(true)); + } + drop(seen); + shutdown.send(()).unwrap(); + } +} + #[tokio::test] async fn function_creation_rejects_invalid_execution_controls_before_sql() { const REQUEST: &str = include_str!( From dc9eb269b15bae731e3d99ddcf67f61723fc703c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:30:47 +0800 Subject: [PATCH 64/75] feat(python): support map and decimal Function signatures (#5031) Python Function declarations reject Arrow map and decimal types before registration. Accept `dict[str, T]`, nullable map values, explicit Arrow maps, and `Annotated[Decimal, pa.decimal128/256(...)]` using the existing canonical JSON representation. Preserve map key/value nullability and decimal precision/scale; reject unsupported map keys, sorted maps, nested Blob values, and a bare Decimal without precision/scale. This is the SDK map/decimal portion of ENT-3414. Server validation and SQL support are separate changes; older servers can still reject these signatures. Nullable scalar output support remains separate in #5030. Validation: 129 Function signature tests passed; 30 documentation tests passed with one existing skip. Ruff format/lint and diff checks passed. Python tests used the existing Python 3.13 environment and prebuilt native extension with this Python source overlaid; no Rust build or remote-server execution was performed. --- docs/web/management/function.mdx | 40 +++++ python/python/lancedb/functions.py | 85 ++++++++-- .../tests/test_first_class_function_slice2.py | 153 +++++++++++++++++- 3 files changed, 267 insertions(+), 11 deletions(-) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index efcbcc799..41e47dee1 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -139,6 +139,46 @@ compound temporal representation cannot read those signatures. A deployment must include the corresponding Lance Namespace and Sophon support; this client-side declaration does not add server support. +### Maps and decimals {#maps-decimals} + +A `dict[str, T]` annotation declares an Arrow map with a non-nullable `utf8` +key. A plain `T` value is non-nullable; annotate `dict[str, Optional[T]]` for +nullable values. An explicit `pa.map_(...)` schema preserves the value field's +own `nullable` flag: + +```python +@function +def word_counts(text: str) -> dict[str, int]: + ... +``` + +Map keys must be non-nullable `utf8`; `keys_sorted=True` is not supported, and +Blob v2 values inside a map are not supported. + +`Decimal` carries no precision or scale by itself, so a bare `Decimal` +annotation is rejected. Declare both explicitly with `Annotated`, or use an +explicit Arrow schema: + +```python +from decimal import Decimal +from typing import Annotated + +import pyarrow as pa + + +@function +def add_tax( + amount: Annotated[Decimal, pa.decimal128(12, 2)], +) -> Annotated[Decimal, pa.decimal128(12, 2)]: + ... +``` + +`decimal128` and `decimal256` keep the declared precision and scale in the +canonical signature; no default is chosen. Map and decimal signatures are sent +as canonical Arrow JSON. A deployment must support those types; an older +Enterprise server may reject the registration, and this client-side +declaration does not add server support. + ## Connect and create a table {#table} The remaining steps run against your Enterprise deployment. Replace the database diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index ecbc697d1..548129211 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -30,6 +30,7 @@ import types import warnings from collections.abc import Mapping, Sequence from datetime import date, datetime, timedelta +from decimal import Decimal from pathlib import Path from typing import ( Annotated, @@ -1378,6 +1379,13 @@ def _exact_arrow_type( for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: return {"type": name} + if pa.types.is_decimal128(data_type) or pa.types.is_decimal256(data_type): + return { + "type": ( + "decimal128" if pa.types.is_decimal128(data_type) else "decimal256" + ), + "length": data_type.precision * 1000 + data_type.scale, + } if pa.types.is_timestamp(data_type): unit = data_type.unit if unit not in _FUNCTION_TIMEUNITS: @@ -1453,8 +1461,29 @@ def _exact_arrow_type( if pa.types.is_fixed_size_list(data_type): value["length"] = data_type.list_size return value - if pa.types.is_map(data_type) and _data_type_has_blob_v2(data_type): - raise TypeError(_NESTED_BLOB_COLLECTION_ERROR) + if pa.types.is_map(data_type): + if data_type.keys_sorted: + raise TypeError( + "unsupported Arrow type for Function signature: map keys_sorted=true " + "is not supported" + ) + key_field = data_type.key_field + if key_field.nullable or key_field.type != pa.string(): + raise TypeError( + "unsupported Arrow type for Function signature: map keys must be " + "non-nullable utf8" + ) + if _data_type_has_blob_v2(data_type): + raise TypeError(_NESTED_BLOB_COLLECTION_ERROR) + return { + "type": "map", + "fields": [ + _exact_arrow_field( + data_type.field(0), + inside_collection=True, + ) + ], + } raise TypeError(f"unsupported Arrow type for Function signature: {data_type}") @@ -1483,9 +1512,15 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: raise TypeError( "Annotated Function types require exactly one PyArrow DataType" ) - # A struct value is written as a dict, and timedelta has no unit of - # its own; the Annotated metadata supplies those types. - if base is dict or get_origin(base) is dict or base is timedelta: + # A struct value is written as a dict, while Decimal and timedelta + # carry no precision or unit of their own; the Annotated metadata + # supplies those types. + if ( + base is dict + or get_origin(base) is dict + or base is Decimal + or base is timedelta + ): base_nullable = False else: _, base_nullable = _annotation_type(base) @@ -1514,6 +1549,13 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: # Existing default: microsecond precision, no timezone. Other units # and timezones require Annotated or an explicit schema. return pa.timestamp("us"), nullable + if annotation is Decimal: + raise TypeError( + "Decimal Function annotations require precision and scale; use " + "Annotated[Decimal, pyarrow.decimal128(precision, scale)], " + "Annotated[Decimal, pyarrow.decimal256(precision, scale)], or an " + "explicit schema" + ) if annotation is timedelta: raise TypeError( "timedelta Function annotations require an explicit unit; use " @@ -1527,6 +1569,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: if value_nullable: raise TypeError("nullable Function list elements are not supported") return _list_of(value_type), nullable + if get_origin(annotation) is dict: + arguments = get_args(annotation) + if len(arguments) != 2: + raise TypeError(f"unsupported dict annotation: {annotation!r}") + key_type, value_annotation = arguments + if key_type is not str: + raise TypeError("Function map keys must be str") + value_type, value_nullable = _annotation_type(value_annotation) + return ( + pa.map_( + pa.string(), + pa.field("value", value_type, nullable=value_nullable), + ), + nullable, + ) raise TypeError(f"unsupported Function annotation: {annotation!r}") @@ -2847,7 +2904,13 @@ def function( 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. Bare ``datetime`` keeps its existing ``timestamp[us]`` default + columns. + ``dict[str, T]`` declares an Arrow map with a non-nullable utf8 key; the + value is non-nullable for ``T`` and nullable for ``Optional[T]``. A bare + ``Decimal`` has no precision or scale; use + ``Annotated[Decimal, pyarrow.decimal128(precision, scale)]``, + ``Annotated[Decimal, pyarrow.decimal256(precision, scale)]``, or an + explicit schema. Bare ``datetime`` keeps its existing ``timestamp[us]`` default without a timezone; other units and timezones require ``Annotated[datetime, pyarrow.timestamp(unit, tz=...)]`` or an explicit schema. A bare ``timedelta`` has no unit and is rejected; use @@ -2958,10 +3021,12 @@ def function( output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional 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. Temporal fields use canonical Arrow JSON; the - microsecond/no-timezone case keeps the legacy timestamp/duration - shape. Required for batch annotations. When omitted, the output is - inferred from the return annotation. + must be non-nullable. Map and decimal fields use canonical Arrow JSON; + a map key must be non-nullable utf8 and its value field keeps the + declared nullability. Temporal fields use canonical Arrow JSON; the + microsecond/no-timezone case keeps the legacy timestamp/duration shape. + 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 6dcc0bbbe..dbc574e88 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -19,6 +19,7 @@ import sys import typing import urllib.parse import warnings +from decimal import Decimal from typing import Annotated, Optional import pyarrow as pa @@ -1054,7 +1055,6 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): == "large_list" ) for outside in [ - pa.decimal128(10, 2), pa.binary(4), pa.time32("s"), pa.time64("us"), @@ -1531,6 +1531,157 @@ def test_duration_annotation_and_explicit_schema_serialization(): assert explicit_round_trip.output.arrow_type == '{"type":"duration"}' +def test_map_annotation_and_explicit_schema_serialization(): + @function + def map_round_trip(values: dict[str, int]) -> dict[str, int]: + return values + + signature = map_round_trip.registration_request.signature + expected = { + "type": "map", + "fields": [ + { + "name": "entries", + "nullable": False, + "type": { + "type": "struct", + "fields": [ + { + "name": "key", + "nullable": False, + "type": {"type": "utf8"}, + }, + { + "name": "value", + "nullable": False, + "type": {"type": "int64"}, + }, + ], + }, + } + ], + } + assert json.loads(signature.inputs[0].arrow_type) == expected + assert json.loads(signature.output.arrow_type) == expected + round_trip = FunctionSignature.from_json(signature.to_canonical_json()) + assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type + assert round_trip.output.arrow_type == signature.output.arrow_type + + @function + def nullable_values( + values: dict[str, Optional[int]], + ) -> dict[str, Optional[int]]: + return values + + nullable_signature = nullable_values.registration_request.signature + nullable_map = json.loads(nullable_signature.inputs[0].arrow_type) + assert nullable_map["fields"][0]["type"]["fields"][1] == { + "name": "value", + "nullable": True, + "type": {"type": "int64"}, + } + + input_schema = pa.schema( + [ + pa.field( + "values", + pa.map_(pa.string(), pa.field("custom", pa.int64(), nullable=True)), + nullable=False, + ) + ] + ) + output_schema = pa.field( + "result", + pa.map_(pa.string(), pa.field("value", pa.int64(), nullable=False)), + nullable=False, + ) + + @function(input_schema=input_schema, output_schema=output_schema) + def explicit(values): + return {} + + explicit_signature = explicit.registration_request.signature + explicit_input = json.loads(explicit_signature.inputs[0].arrow_type) + assert explicit_input["fields"][0]["type"]["fields"][1] == { + "name": "custom", + "nullable": True, + "type": {"type": "int64"}, + } + explicit_output = json.loads(explicit_signature.output.arrow_type) + assert explicit_output["fields"][0]["type"]["fields"][1]["nullable"] is False + + +def test_map_rejects_unsupported_boundaries(): + with pytest.raises(TypeError, match="map keys_sorted=true"): + _canonical_arrow_type(pa.map_(pa.string(), pa.int64(), keys_sorted=True)) + with pytest.raises(TypeError, match="map keys must be non-nullable utf8"): + _canonical_arrow_type(pa.map_(pa.int64(), pa.int64())) + with pytest.raises(TypeError, match="Blob v2 fields nested under"): + _canonical_arrow_type(pa.map_(pa.string(), lancedb.blob("image").type)) + with pytest.raises(TypeError, match="map keys must be str"): + + @function + def invalid_keys(values: dict[int, int]) -> int: + return 0 + + +def test_decimal_annotation_and_explicit_schema_serialization(): + @function + def price( + amount: Annotated[Decimal, pa.decimal128(10, 2)], + ) -> Annotated[Decimal, pa.decimal256(50, 4)]: + return Decimal("1.0000") + + signature = price.registration_request.signature + assert json.loads(signature.inputs[0].arrow_type) == { + "type": "decimal128", + "length": 10002, + } + assert json.loads(signature.output.arrow_type) == { + "type": "decimal256", + "length": 50004, + } + round_trip = FunctionSignature.from_json(signature.to_canonical_json()) + assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type + assert round_trip.output.arrow_type == signature.output.arrow_type + assert json.loads(_canonical_arrow_type(pa.decimal128(10, -2))) == { + "type": "decimal128", + "length": 9998, + } + decimal_map = json.loads( + _canonical_arrow_type(pa.map_(pa.string(), pa.decimal128(10, 2))) + ) + assert decimal_map["fields"][0]["type"]["fields"][1]["type"] == { + "type": "decimal128", + "length": 10002, + } + + input_schema = pa.schema([pa.field("amount", pa.decimal128(12, 2), nullable=False)]) + output_schema = pa.field("result", pa.decimal256(60, 6), nullable=False) + + @function(input_schema=input_schema, output_schema=output_schema) + def explicit(amount: Decimal) -> Decimal: + return amount + + explicit_signature = explicit.registration_request.signature + assert json.loads(explicit_signature.inputs[0].arrow_type) == { + "type": "decimal128", + "length": 12002, + } + assert json.loads(explicit_signature.output.arrow_type) == { + "type": "decimal256", + "length": 60006, + } + + with pytest.raises( + TypeError, match="Decimal Function annotations require precision and scale" + ): + + @function + def missing(amount: Decimal) -> Decimal: + return amount + + def test_nullable_scalar_output_annotation_and_explicit_schema(): input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)]) From e2f836da99deacb6b1a3a9ca7acc1222e7d39d3f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:43:56 +0800 Subject: [PATCH 65/75] feat: expose per-call merge retry controls in Python and Node (#5015) Python and Node callers could not disable precommit retries for one merge without changing the connection. Add `execute(..., retries=0)` for Python sync/async and `execute(data, { retries: 0 })` for TypeScript, forwarding into the existing Rust control without persisting the override. Ambiguous 5xx outcomes remain non-replayable; permitted merge retries now log status and attempt at WARN, and the API docs explain retry budgets and timeout boundaries. Validation at `6001300` passed 70 Python HTTP cases, 36 Node HTTP cases, 14 local merge regressions per binding, and 34 scoped Rust tests, with rebuilt native extensions, TypeScript compilation, Clippy, scoped formatting/lint, and generated API docs. The public API and feature diff are unchanged after integrating main and the reviewed ingestion guide; that binding evidence is retained. Focused merged-tree validation additionally passed 267 Rust merge/retry/provenance cases and the CI fixtures. Existing root Ruff issues in docs/web-tests remain; local fixtures do not establish live proxy/server cancellation behavior. Refs #4256 and OSS-2370. --- .../js/interfaces/WriteExecutionOptions.md | 23 +++ docs/web/ingestion/merge-insert.mdx | 7 + nodejs/__test__/remote.test.ts | 157 +++++++++++++++++ nodejs/__test__/table.test.ts | 3 +- nodejs/lancedb/merge.ts | 28 +++- nodejs/src/merge.rs | 9 +- python/python/lancedb/_lancedb.pyi | 6 + python/python/lancedb/merge.py | 23 ++- python/python/lancedb/remote/table.py | 3 +- python/python/lancedb/table.py | 6 +- python/python/tests/test_remote_db.py | 158 ++++++++++++++++++ python/python/tests/test_table.py | 5 +- python/src/table.rs | 5 + rust/lancedb/src/remote/table.rs | 10 ++ 14 files changed, 433 insertions(+), 10 deletions(-) diff --git a/docs/src/js/interfaces/WriteExecutionOptions.md b/docs/src/js/interfaces/WriteExecutionOptions.md index 0ca796b6b..9c9be4489 100644 --- a/docs/src/js/interfaces/WriteExecutionOptions.md +++ b/docs/src/js/interfaces/WriteExecutionOptions.md @@ -8,6 +8,26 @@ ## Properties +### retries? + +```ts +optional retries: number; +``` + +Override the remote retry budget for this execution only (an integer from +0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after +precommit conflicts (409) or rate limits (429). This does not change +connection-wide/read budgets or local transaction conflict retries. + +By default, remote calls use the connection's `clientConfig.retryConfig` +([RetryConfig](RetryConfig.md)). Its `statuses` (also set through +`LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget; +it never permits replay of ambiguous merge outcomes. In particular, 502, +ordinary 503, and 504 are never replayed, even if configured. Reconcile table +contents before manually repeating a merge whose commit outcome is unknown. + +*** + ### timeoutMs? ```ts @@ -24,3 +44,6 @@ the second attempt will be cancelled after 10 seconds, hitting the first attempt will not be cancelled. When this is set, the timeout is enforced on all attempts, including the first. +For remote tables this is sent as a server execution timeout. It does not +extend HTTP read or proxy idle timeouts, or prove that a failed request did +not commit. diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index 8106e7706..2d6fd8470 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -221,6 +221,13 @@ and check inserted or deleted counts when the SDK returns them. Repeating a merge is only safe when its keys, conditions and update values produce the intended result on retry. +To override the transport retry budget for one merge, pass `retries=0` to +Python's synchronous or asynchronous `builder.execute(data, retries=0)`, or +use TypeScript's `builder.execute(data, { retries: 0 })`. The override applies +only to that execution. A larger budget does not make an ambiguous 5xx result +safe to replay. See [write retry boundaries](/ingestion/insert#performance) +for the distinction between retryable failures and an unknown commit outcome. + ### Embeddings and expression predicates {#advanced} When a table uses an [embedding definition](/embedding), behavior depends on diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 3e8d5a79b..215df992d 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -542,6 +542,163 @@ describe("remote connection", () => { expect(attempts).toBe(scenario.attempts); }); + it.each( + [409, 429, 502, 503, 504].flatMap((status) => + [undefined, 0, 2].flatMap((retries) => + [[], ["analytics", "features"]].map((namespacePath) => ({ + status, + retries, + namespacePath, + })), + ), + ), + )("applies per-call merge retries: %j", async (scenario) => { + let attempts = 0; + const identifier = [...scenario.namespacePath, "items"].join("$"); + const succeeds = + [409, 429].includes(scenario.status) && scenario.retries !== 0; + await withMockDatabase( + (req, res) => { + const url = new URL(req.url ?? "", "http://localhost"); + if (url.pathname === `/v1/table/${identifier}/describe/`) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + try { + expect(url.pathname).toBe(`/v1/table/${identifier}/merge_insert/`); + expect(url.searchParams.get("use_index")).toBe("false"); + expect(req.headers["x-request-timeout-ms"]).toBe("10000"); + // Rust compresses the batches; Arrow JS can inspect the schema without a codec. + const reader = RecordBatchReader.from(Buffer.concat(chunks)).open(); + expect(reader.schema.fields.map((field) => field.name)).toEqual([ + "id", + ]); + } finally { + attempts++; + res + .writeHead(attempts === 1 ? scenario.status : 200) + .end('{"version":2}'); + } + }); + }, + async (db) => { + const table = await db.openTable("items", scenario.namespacePath); + const merge = table + .mergeInsert("id") + .whenNotMatchedInsertAll() + .useIndex(false); + const result = merge.execute([{ id: 1n }], { + timeoutMs: 10_000, + retries: scenario.retries, + }); + if (succeeds) { + await expect(result).resolves.toMatchObject({ version: 2 }); + } else { + await expect(result).rejects.toThrow(); + } + }, + { + clientConfig: { + retryConfig: { + retries: 3, + statuses: [409, 429, 502, 503, 504], + backoffFactor: 0, + backoffJitter: 0, + }, + }, + }, + ); + expect(attempts).toBe(succeeds ? 2 : 1); + }); + + it("isolates merge retry overrides across reused builders and reads", async () => { + let attempts = 0; + let readAttempts = 0; + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + req.resume(); + req.on("end", () => { + if (req.url?.endsWith("/count_rows/")) { + readAttempts++; + res.writeHead(readAttempts % 2 ? 429 : 200).end("1"); + } else { + attempts++; + res + .writeHead([1, 2, 4, 6].includes(attempts) ? 429 : 200) + .end('{"version":2}'); + expect(req.url).toContain("/merge_insert/"); + } + }); + }, + async (db) => { + const table = await db.openTable("items"); + const merge = table.mergeInsert("id").whenNotMatchedInsertAll(); + for (const retries of [ + -1, + 256, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + ]) { + await expect( + merge.execute([{ id: 1n }], { retries }), + ).rejects.toThrow("retries must be an integer between 0 and 255"); + } + expect(attempts).toBe(0); + await expect( + merge.execute([{ id: 1n }], { retries: 0 }), + ).rejects.toThrow(); + expect(attempts).toBe(1); + await expect(merge.execute([{ id: 1n }])).resolves.toMatchObject({ + version: 2, + }); + await expect( + merge.execute([{ id: 1n }], { retries: 255 }), + ).resolves.toMatchObject({ version: 2 }); + expect(attempts).toBe(5); + await expect(table.countRows()).resolves.toBe(1); + expect(readAttempts).toBe(2); + await expect( + table + .mergeInsert("id") + .whenNotMatchedInsertAll() + .execute([{ id: 1n }]), + ).resolves.toMatchObject({ version: 2 }); + expect(attempts).toBe(7); + }, + { + clientConfig: { + retryConfig: { retries: 3, backoffFactor: 0, backoffJitter: 0 }, + }, + }, + ); + }); + it("should accept partial connection options", async () => { await connect("db://test", { apiKey: "fake", diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index e97b32e78..99c58a8c9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -938,7 +938,8 @@ describe("merge insert", () => { .mergeInsert("a") .whenMatchedUpdateAll() .whenNotMatchedInsertAll() - .execute(newData, { timeoutMs: 10_000 }); + .useIndex(false) + .execute(newData, { timeoutMs: 10_000, retries: 0 }); expect(mergeInsertRes).toHaveProperty("version"); expect(mergeInsertRes.version).toBe(2); expect(mergeInsertRes.numInsertedRows).toBe(1); diff --git a/nodejs/lancedb/merge.ts b/nodejs/lancedb/merge.ts index 7bb36e678..7d95d4a36 100644 --- a/nodejs/lancedb/merge.ts +++ b/nodejs/lancedb/merge.ts @@ -127,6 +127,14 @@ export class MergeInsertBuilder { data: Data, execOptions?: Partial, ): Promise { + if ( + execOptions?.retries !== undefined && + (!Number.isInteger(execOptions.retries) || + execOptions.retries < 0 || + execOptions.retries > 255) + ) { + throw new Error("retries must be an integer between 0 and 255"); + } let schema: Schema; if (this.#schema instanceof Promise) { schema = await this.#schema; @@ -140,7 +148,7 @@ export class MergeInsertBuilder { } const buffer = await fromDataToBuffer(data, undefined, schema); - return await this.#native.execute(buffer); + return await this.#native.execute(buffer, execOptions?.retries); } } @@ -156,6 +164,24 @@ export interface WriteExecutionOptions { * first attempt will not be cancelled. * * When this is set, the timeout is enforced on all attempts, including the first. + * For remote tables this is sent as a server execution timeout. It does not + * extend HTTP read or proxy idle timeouts, or prove that a failed request did + * not commit. */ timeoutMs?: number; + + /** + * Override the remote retry budget for this execution only (an integer from + * 0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after + * precommit conflicts (409) or rate limits (429). This does not change + * connection-wide/read budgets or local transaction conflict retries. + * + * By default, remote calls use the connection's `clientConfig.retryConfig` + * ({@link RetryConfig}). Its `statuses` (also set through + * `LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget; + * it never permits replay of ambiguous merge outcomes. In particular, 502, + * ordinary 503, and 504 are never replayed, even if configured. Reconcile table + * contents before manually repeating a merge whose commit outcome is unknown. + */ + retries?: number; } diff --git a/nodejs/src/merge.rs b/nodejs/src/merge.rs index ccff2a689..86901c04f 100644 --- a/nodejs/src/merge.rs +++ b/nodejs/src/merge.rs @@ -65,12 +65,17 @@ impl NativeMergeInsertBuilder { } #[napi(catch_unwind)] - pub async fn execute(&self, buf: Buffer) -> napi::Result { + pub async fn execute(&self, buf: Buffer, retries: Option) -> napi::Result { let data = ipc_file_to_batches(buf.to_vec()).map_err(|e| { napi::Error::from_reason(format!("Failed to read IPC file: {}", convert_error(&e))) })?; - let this = self.clone(); + let mut this = self.clone(); + if let Some(retries) = retries { + let retries = u8::try_from(retries) + .map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?; + this.inner.retries(retries); + } let res = this.inner.execute(data).await.map_err(|e| { napi::Error::from_reason(format!( diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a87b82a21..a86bae9d5 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -565,6 +565,12 @@ class Table: allow_external_blob_outside_bases: bool = False, retries: Optional[int] = None, ) -> AddResult: ... + async def execute_merge_insert( + self, + data: pa.RecordBatchReader, + parameters: Dict[str, Any], + retries: Optional[int] = None, + ) -> MergeResult: ... async def update( self, updates: Dict[str, str], where: Optional[str] ) -> UpdateResult: ... diff --git a/python/python/lancedb/merge.py b/python/python/lancedb/merge.py index 49f4793ed..c861414aa 100644 --- a/python/python/lancedb/merge.py +++ b/python/python/lancedb/merge.py @@ -161,6 +161,8 @@ class LanceMergeInsertBuilder(object): on_bad_vectors: str = "error", fill_value: float = 0.0, timeout: Optional[timedelta] = None, + *, + retries: Optional[int] = None, ) -> MergeInsertResult: """ Executes the merge insert operation @@ -189,7 +191,22 @@ class LanceMergeInsertBuilder(object): first attempt will not be cancelled. When this is set, the timeout is enforced on all attempts, including - the first. + the first. For remote tables it is sent as a server execution timeout; + it does not extend HTTP read or proxy idle timeouts, or prove that a + failed request did not commit. + retries: int, optional + Override the remote retry budget for this execution only (0 to 255). + Use ``execute(new_data, retries=0)`` to disable even retries after + precommit conflicts (409) or rate limits (429). This does not change + connection-wide/read budgets or local transaction conflict retries. + + By default, remote calls use the connection's + [RetryConfig][lancedb.remote.RetryConfig]. Its ``statuses`` (also set + through ``LANCE_CLIENT_RETRY_STATUSES``) selects candidates within + the retry budget; it never permits replay of ambiguous merge outcomes. + In particular, 502, ordinary 503, and 504 are never replayed, even if + configured. Reconcile table contents before manually repeating a merge + whose commit outcome is unknown. Returns ------- @@ -198,4 +215,6 @@ class LanceMergeInsertBuilder(object): """ if timeout is not None: self._timeout = timeout - return self._table._do_merge(self, new_data, on_bad_vectors, fill_value) + return self._table._do_merge( + self, new_data, on_bad_vectors, fill_value, retries=retries + ) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index b5d97eb62..818d2a257 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -945,9 +945,10 @@ class RemoteTable(Table): new_data: DATA, on_bad_vectors: str, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: return LOOP.run( - self._table._do_merge(merge, new_data, on_bad_vectors, fill_value) + self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries) ) @_deprecated_keyword("predicate", "where") diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 45b2eb4f6..4a713da06 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2810,6 +2810,7 @@ class Table(ABC): new_data: DATA, on_bad_vectors: OnBadVectorsType, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: ... @abstractmethod @@ -5443,9 +5444,10 @@ class LanceTable(Table): new_data: DATA, on_bad_vectors: OnBadVectorsType, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: return LOOP.run( - self._table._do_merge(merge, new_data, on_bad_vectors, fill_value) + self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries) ) @property @@ -7777,6 +7779,7 @@ class AsyncTable: new_data: DATA, on_bad_vectors: OnBadVectorsType, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: schema = await self.schema() if on_bad_vectors is None: @@ -7808,6 +7811,7 @@ class AsyncTable: use_rte=merge._use_rte, validate_single_shard=merge._validate_single_shard, ), + retries=retries, ) async def delete(self, where: Union[str, Expr]) -> DeleteResult: diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index fc5b5df73..f404e36f7 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -310,6 +310,164 @@ async def test_add_retry_override(sync_api, retries, status): assert attempts == (2 if expected_success else 1) +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.parametrize("namespace_path", [[], ["analytics", "features"]]) +@pytest.mark.parametrize("retries", [None, 0, 2]) +@pytest.mark.parametrize("status", [409, 429, 502, 503, 504]) +@pytest.mark.asyncio +async def test_merge_retry_override(sync_api, namespace_path, retries, status, capfd): + attempts = 0 + identifier = "$".join(namespace_path + ["test"]) + + def handler(request): + nonlocal attempts + if request.path == f"/v1/table/{identifier}/describe/": + send_json( + request, + { + "version": 1, + "schema": { + "fields": [ + {"name": "id", "type": {"type": "int64"}, "nullable": True} + ] + }, + }, + ) + return + assert urlparse(request.path).path == f"/v1/table/{identifier}/merge_insert/" + query = parse_qs(urlparse(request.path).query) + assert query["use_index"] == ["false"] + assert request.headers["x-request-timeout-ms"] == "10000" + body = bytearray() + if request.headers.get("Transfer-Encoding") == "chunked": + while True: + size = int(request.rfile.readline().strip(), 16) + if size == 0: + request.rfile.readline() + break + body.extend(request.rfile.read(size)) + request.rfile.read(2) + else: + body.extend( + request.rfile.read(int(request.headers.get("Content-Length", 0))) + ) + assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}] + attempts += 1 + send_json(request, {"version": 2}, status if attempts == 1 else 200) + + config = { + "retry_config": { + "retries": 3, + "statuses": [409, 429, 502, 503, 504], + "backoff_factor": 0, + "backoff_jitter": 0, + } + } + expected_success = status in (409, 429) and retries != 0 + + async def check(table): + merge = table.merge_insert("id").when_not_matched_insert_all().use_index(False) + options = {"timeout": timedelta(seconds=10)} + if retries is not None: + options["retries"] = retries + if expected_success: + result = merge.execute([{"id": 1}], **options) + if not sync_api: + result = await result + assert result.version == 2 + else: + with pytest.raises((HttpError, RetryError)): + result = merge.execute([{"id": 1}], **options) + if not sync_api: + await result + + if sync_api: + with mock_lancedb_connection(handler, **config) as db: + await check(db.open_table("test", namespace_path=namespace_path)) + else: + async with mock_lancedb_connection_async(handler, **config) as db: + await check(await db.open_table("test", namespace_path=namespace_path)) + assert attempts == (2 if expected_success else 1) + warnings = [ + line + for line in capfd.readouterr().err.splitlines() + if "Retrying merge insert" in line + ] + assert len(warnings) == (1 if expected_success else 0) + if expected_success: + assert "WARN" in warnings[0] + assert f"status Some({status}); attempt 2" in warnings[0] + + +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.asyncio +async def test_merge_retry_override_isolation(sync_api): + attempts = 0 + read_attempts = 0 + + def handler(request): + nonlocal attempts, read_attempts + if request.path.endswith("/describe/"): + send_json( + request, + { + "version": 1, + "schema": { + "fields": [ + {"name": "id", "type": {"type": "int64"}, "nullable": True} + ] + }, + }, + ) + elif request.path.endswith("/count_rows/"): + read_attempts += 1 + send_json(request, 1, 429 if read_attempts % 2 else 200) + else: + assert urlparse(request.path).path.endswith("/merge_insert/") + attempts += 1 + send_json(request, {"version": 2}, 429 if attempts in (1, 2, 4, 6) else 200) + + async def check(table): + merge = table.merge_insert("id").when_not_matched_insert_all() + for retries in [-1, 256, 1.5, "1"]: + with pytest.raises((OverflowError, TypeError, ValueError)): + result = merge.execute([{"id": 1}], retries=retries) + if not sync_api: + await result + assert attempts == 0 + with pytest.raises((HttpError, RetryError)): + result = merge.execute([{"id": 1}], retries=0) + if not sync_api: + await result + assert attempts == 1 + for options in ({}, {"retries": 255}): + result = merge.execute([{"id": 1}], **options) + if not sync_api: + result = await result + assert result.version == 2 + assert attempts == 5 + result = table.count_rows() + if not sync_api: + result = await result + assert result == 1 + assert read_attempts == 2 + result = ( + table.merge_insert("id").when_not_matched_insert_all().execute([{"id": 1}]) + ) + if not sync_api: + result = await result + assert result.version == 2 + assert attempts == 7 + + config = {"retry_config": {"retries": 3, "backoff_factor": 0, "backoff_jitter": 0}} + if sync_api: + with mock_lancedb_connection(handler, **config) as db: + await check(db.open_table("test")) + else: + async with mock_lancedb_connection_async(handler, **config) as db: + await check(await db.open_table("test")) + + @pytest.fixture def missing_table_handler(cached, namespace_path): request_ids = [] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index ce4f57c48..4b26a9003 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3448,7 +3448,8 @@ def test_merge_insert(mem_db: DBConnection): table.merge_insert("a") .when_matched_update_all() .when_not_matched_insert_all() - .execute(new_data, timeout=timedelta(seconds=10)) + .use_index(False) + .execute(new_data, timeout=timedelta(seconds=10), retries=0) ) assert merge_insert_res.version == 2 assert merge_insert_res.num_inserted_rows == 1 @@ -3527,7 +3528,7 @@ def test_merge_insert(mem_db: DBConnection): # timeout with pytest.raises(Exception, match="merge insert timed out"): table.merge_insert("a").when_matched_update_all().execute( - new_data, timeout=timedelta(0) + new_data, timeout=timedelta(0), retries=255 ) diff --git a/python/src/table.rs b/python/src/table.rs index f5270a594..25a99e5db 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2269,10 +2269,12 @@ impl Table { }) } + #[pyo3(signature = (data, parameters, retries=None))] pub fn execute_merge_insert<'a>( self_: PyRef<'a, Self>, data: Bound<'a, PyAny>, parameters: MergeInsertParams, + retries: Option, ) -> PyResult> { let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; let on = parameters.on.iter().map(|s| s.as_str()).collect::>(); @@ -2295,6 +2297,9 @@ impl Table { if let Some(timeout) = parameters.timeout { builder.timeout(timeout); } + if let Some(retries) = retries { + builder.retries(retries); + } if let Some(use_index) = parameters.use_index { builder.use_index(use_index); } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 29f3ab50e..2224203cf 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3707,7 +3707,17 @@ impl BaseTable for RemoteTable { return Ok(merge_result); } Err(err) if rescannable && self.is_retryable_write_error(&err) => { + let status = err.status_code(); retry_counter.increment_from_error(err)?; + log::warn!( + "Retrying merge insert {} after status {:?}; attempt {}", + retry_counter.request_id, + status.map(|s| s.as_u16()), + u16::from(retry_counter.request_failures) + + u16::from(retry_counter.connect_failures) + + u16::from(retry_counter.read_failures) + + 1, + ); tokio::time::sleep(retry_counter.next_sleep_time()).await; merge = merge.reset_state()?; continue; From e8a8dd1b2a240646b39ecfc848b1c3dd4a0701fc Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 14 Nov 2026 16:55:42 -0800 Subject: [PATCH 66/75] feat(sql): use server-issued catalog listing tokens (#5026) Migrates SQL-backed catalog listing APIs to `LIMIT ... FROM ''` and server-issued Arrow continuation metadata. Namespace-specific APIs send an explicit `IN` schema clause, including `IN "public"` for root, so raw SQL can default to all namespaces. ```sql SHOW VIEWS LIMIT 100; SHOW VIEWS IN team$ml LIMIT 100; SHOW VIEWS IN team$ml LIMIT 100 FROM ''; SHOW VIEWS IN other_db.team$ml LIMIT 100; ``` SDK clients forward opaque tokens unchanged, preserve empty continuations, and decode identifier columns by name. Removes legacy cursor reconstruction and updates the SQL reference and Python Flight fixture. Public docs cover optional direct schema paths, all-namespace defaults, and the shared pagination syntax across every catalog listing. --- docs/web/docs.json | 1 + docs/web/management/function.mdx | 4 +- docs/web/management/index.mdx | 2 +- docs/web/sql/ddl/database.mdx | 20 +- docs/web/sql/ddl/function.mdx | 37 +- docs/web/sql/ddl/materialized-view.mdx | 25 +- docs/web/sql/ddl/namespace.mdx | 40 +- docs/web/sql/ddl/secret.mdx | 30 +- docs/web/sql/ddl/storage-integration.mdx | 25 +- docs/web/sql/ddl/table.mdx | 20 + docs/web/sql/ddl/view.mdx | 33 +- docs/web/sql/pagination.mdx | 68 +++ .../python/tests/test_storage_integration.py | 30 +- rust/lancedb/src/listing.rs | 8 +- rust/lancedb/src/remote/db.rs | 27 +- rust/lancedb/src/remote/sql/function.rs | 85 +-- .../src/remote/sql/materialized_view.rs | 58 +- rust/lancedb/src/remote/sql/objects.rs | 144 ++++- rust/lancedb/src/remote/sql/secret.rs | 62 +- rust/lancedb/src/remote/sql/view.rs | 62 +- rust/lancedb/src/remote/sql_test.rs | 554 +++++++++--------- .../lancedb/src/remote/storage_integration.rs | 23 - 22 files changed, 663 insertions(+), 695 deletions(-) create mode 100644 docs/web/sql/pagination.mdx diff --git a/docs/web/docs.json b/docs/web/docs.json index c586d4f62..0b26a7fc0 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -543,6 +543,7 @@ "group": "SQL Reference", "pages": [ "sql/index", + "sql/pagination", "sql/data-types", { "group": "DDL", diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 41e47dee1..562de05c6 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -280,7 +280,9 @@ let latest = connection.get_function_latest("double", &[]).await?; ```sql SQL icon="database" SHOW FUNCTIONS -SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100) +SHOW FUNCTIONS IN "analytics" LIMIT 100 +SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100 +SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100 FROM '' DESCRIBE FUNCTION double WITH (version = '1') DESCRIBE FUNCTION double diff --git a/docs/web/management/index.mdx b/docs/web/management/index.mdx index fbef65756..50f6e7507 100644 --- a/docs/web/management/index.mdx +++ b/docs/web/management/index.mdx @@ -85,7 +85,7 @@ enables them; the SDK methods send the view's SQL query to the deployment. See | --- | --- | --- | --- | | create | `create_function`, `create_function_async` | -- | `CREATE FUNCTION` | | get | `get_function` | -- | `DESCRIBE FUNCTION` | -| list | `list_functions` | -- | `SHOW FUNCTIONS` | +| list | `list_functions` | -- | `SHOW FUNCTIONS HISTORY` | | drop | `drop_function` | -- | `DROP FUNCTION` | Enterprise A function runs on the server, and only on diff --git a/docs/web/sql/ddl/database.mdx b/docs/web/sql/ddl/database.mdx index e8cdb55bc..f84d4cfb9 100644 --- a/docs/web/sql/ddl/database.mdx +++ b/docs/web/sql/ddl/database.mdx @@ -57,15 +57,21 @@ properties and requires system `USAGE`. ## SHOW DATABASES {#show} - -```sql SQL icon="database" -SHOW DATABASES +```sql +SHOW DATABASES LIMIT 100; +SHOW DATABASES LIMIT 100 FROM ''; ``` - -Returns a sorted `name` column containing the databases the caller has -`USAGE` on, including `system` when permitted. `LIKE` and `WHERE` filters -are unsupported. +Returns one non-null `name` column, sorted by database name and filtered to +databases the caller has `USAGE` on, including `system` when permitted. +Databases are above namespaces, so this command does not accept `IN` or +return a `namespace_path` column. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## ATTACH DATABASE {#attach} diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 55e2d6fe7..691118026 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -135,20 +135,33 @@ from it. ## SHOW FUNCTIONS {#show} - -```sql SQL icon="database" -SHOW FUNCTIONS -SHOW FUNCTIONS HISTORY IN "analytics" WITH (name = 'embed', limit = 100) -SHOW FUNCTIONS HISTORY WITH (after_name = 'embed', after_version = '1', limit = 100) +```sql +SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100; +SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -`SHOW FUNCTIONS` returns the highest published numeric revision for each name. -Add `HISTORY` to list every published revision, as Python's `list_functions()` -does. Rows are ordered by name and numeric revision, so `2` comes before `10`. -`after_name` and `after_version` must be supplied together for keyset pagination. -`limit` bounds -the response; `include_definition = false` omits the optional definition JSON. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +`SHOW FUNCTIONS` lists each function once. Add `HISTORY` to list every +published revision with its metadata and definition, as `list_functions()` +does. History uses the same pagination suffix; numeric revision order is +encoded in the token, so revision `2` precedes `10`. + +```sql +SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100; +SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100 FROM ''; +``` + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP FUNCTION {#drop} diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index a2453ba01..a2a5024f6 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -70,16 +70,25 @@ automatic execution needs the same server-side switch enabled. Omitting ## SHOW MATERIALIZED VIEWS {#show} - -```sql SQL icon="database" -SHOW MATERIALIZED VIEWS +```sql +SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100; +SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - - -This asks the server for its views, as the SDK's `list_materialized_views` does -on a `db://` connection. - +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +The listing contains identifiers; use `DESCRIBE MATERIALIZED VIEW` for its defining query and refresh metadata. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## Refreshing one {#refresh} diff --git a/docs/web/sql/ddl/namespace.mdx b/docs/web/sql/ddl/namespace.mdx index 8f446f1e7..14391ac18 100644 --- a/docs/web/sql/ddl/namespace.mdx +++ b/docs/web/sql/ddl/namespace.mdx @@ -17,7 +17,7 @@ backtick-quoted identifier with `$` between components, such as one path component, relative to an explicit parent schema or the session's current schema -- it cannot contain `$` or be qualified with a database. -`SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete +For single-object commands, `SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete schema identifier. Names are lowercased unless quoted. ## CREATE SCHEMA and CREATE NAMESPACE {#create} @@ -126,27 +126,30 @@ Requires `USAGE` on the database and the namespace. ## SHOW SCHEMAS and SHOW NAMESPACES {#show} - -```sql SQL icon="database" -SHOW SCHEMAS -SHOW NAMESPACES -SHOW NAMESPACES IN analytics.team +```sql +SHOW SCHEMAS LIMIT 100; +SHOW SCHEMAS LIMIT 100 FROM ''; +SHOW NAMESPACES IN analytics.team LIMIT 100; +SHOW NAMESPACES IN analytics.team LIMIT 100 FROM ''; ``` - -`SHOW SCHEMAS` returns complete paths in the current database, recursively, -including `public` when the caller can use it. It does not accept `IN`. +Both commands return two non-null string columns: `namespace_path`, the +parent path as a compact JSON array, and `name`, the unqualified child name. +Results are ordered by parent path components, then name, and omit namespaces +the caller cannot use. -`SHOW NAMESPACES` lists only immediate child names under the session's -current schema. `IN` selects a different parent schema, optionally in -another database -- use `IN public` for the current database's root, or -`IN analytics.public` for another database's root. A missing parent is an -error. +`SHOW SCHEMAS` and `SHOW NAMESPACES` are equivalent listings. Without `IN`, +both list recursively in the current database, include the implicit `public` +root, and ignore the session namespace. With `IN`, both list immediate children +of the selected parent. A schema path can appear directly: `IN team$features`; +a database qualifier is optional. `IN public` selects the current database root, +and `IN analytics.public` selects another database's root. -Both forms return a sorted `name` column and omit namespaces the caller -cannot use. Large listings that exceed 10,000 namespaces, or recursive -listings deeper than 32 levels, return an error suggesting a narrower -listing. +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP SCHEMA and DROP NAMESPACE {#drop} @@ -187,7 +190,6 @@ with `IF EXISTS`. Inspect a cascade drop's child jobs with | `CREATE SCHEMA child IN parent` | `CREATE NAMESPACE child IN parent` or `` CREATE SCHEMA `parent$child` `` | | `` DESCRIBE NAMESPACE `parent$child` `` | `` DESCRIBE SCHEMA `parent$child` `` or `DESCRIBE NAMESPACE child IN parent` | | `DROP NAMESPACE analytics.child` | `DROP NAMESPACE child IN analytics.public` | -| `SHOW SCHEMAS IN parent` | `SHOW NAMESPACES IN parent` | ## What to read next {#next} diff --git a/docs/web/sql/ddl/secret.mdx b/docs/web/sql/ddl/secret.mdx index 922dec247..15039c6c7 100644 --- a/docs/web/sql/ddl/secret.mdx +++ b/docs/web/sql/ddl/secret.mdx @@ -98,21 +98,25 @@ picked up by every Function still bound to that name. ## SHOW SECRETS {#show} - -```sql SQL icon="database" -SHOW SECRETS -SHOW SECRETS IN platform -SHOW SECRETS IN analytics.`ml$vision` -SHOW SECRETS IN public -SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50 +```sql +SHOW SECRETS IN analytics.`team$ml` LIMIT 100; +SHOW SECRETS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -Lists the Secret names in one namespace as a sorted `name` column. Without -`IN`, it lists the session's namespace; `IN public` lists the root. `WHERE -name > ''` pages past the last name already seen, and `LIMIT` -bounds the page size; `WHERE` must compare `name` with `>`. Requires -`USAGE` on the database and the namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +Secret listings contain no values or Secret metadata. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DESCRIBE SECRET {#describe} diff --git a/docs/web/sql/ddl/storage-integration.mdx b/docs/web/sql/ddl/storage-integration.mdx index 9444824ac..de64ba4e5 100644 --- a/docs/web/sql/ddl/storage-integration.mdx +++ b/docs/web/sql/ddl/storage-integration.mdx @@ -194,16 +194,25 @@ only the reference naming it. ## SHOW STORAGE INTEGRATIONS {#show} - -```sql SQL icon="database" -SHOW STORAGE INTEGRATIONS -SHOW STORAGE INTEGRATIONS IN platform -LIST STORAGE INTEGRATIONS +```sql +SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100; +SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -`LIST` is an alias for `SHOW` here. Returns one `name` column; `IN` -narrows the listing to one namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +`LIST STORAGE INTEGRATIONS` is an exact alias, including pagination. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP STORAGE INTEGRATION {#drop} diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index c8c42d4e0..d2196b93a 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -268,3 +268,23 @@ deployment stores its catalog. See Renaming, retyping and dropping columns from the SDK. + +## SHOW TABLES {#show} + +```sql +SHOW TABLES IN analytics.`team$ml` LIMIT 100; +SHOW TABLES IN analytics.`team$ml` LIMIT 100 FROM ''; +``` + +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index 3d94292ab..38fd37e30 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -81,29 +81,22 @@ was none to begin with. ## Listing {#listing} ```sql -SHOW VIEWS -SHOW VIEWS IN "analytics" WHERE name > 'previous_view' LIMIT 100 +SHOW VIEWS IN analytics.`team$ml` LIMIT 100; +SHOW VIEWS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` -`SHOW VIEWS` returns ascending `name` values. The `name` cursor is scoped to -the selected namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. -Object commands retain their small results in shared storage even when general -query-result copying is disabled, so asynchronous polling can use any query node. - -Views and tables share a namespace, and both are things you can query. The -catalog distinguishes them: - -| | | -| --- | --- | -| view names | the views in the database | -| table names | the tables | -| relation names | everything queryable (both) | - -Use the relation listing when the question is "what can I select from," and the -separate listings when the distinction matters: before dropping, for -instance, since dropping a view removes only the saved query while dropping a -table removes data. +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## Choosing between a view and a materialized view {#choosing} diff --git a/docs/web/sql/pagination.mdx b/docs/web/sql/pagination.mdx new file mode 100644 index 000000000..d6649ebfe --- /dev/null +++ b/docs/web/sql/pagination.mdx @@ -0,0 +1,68 @@ +--- +title: "Catalog listing pagination" +description: "Use one continuation-token syntax for SQL catalog listings." +--- + +Catalog `SHOW` statements share one pagination suffix: + +```sql +SHOW [IN ] [LIMIT [FROM '']]; +``` + +This applies to tables, views, materialized views, functions and function +history, secrets, storage integrations, namespaces/schemas, and databases. + +```sql +SHOW TABLES LIMIT 100; +SHOW TABLES IN team$ml LIMIT 100; +SHOW TABLES IN team$ml LIMIT 100 FROM ''; +SHOW TABLES IN analytics.team$ml LIMIT 100; +SHOW DATABASES LIMIT 100 FROM ''; +``` + +## Namespace scope + +`IN` is optional. Without it, listings include root and every authorized +namespace in the current database, regardless of the session's default namespace. +With `IN`, objects are listed only in that exact namespace. The scope accepts a +schema directly: `IN team$ml` means the absolute namespace path `["team", "ml"]` +in the current database. Use `IN public` for root, or `IN other_db.team$ml` to +select a different database. Quote schema identifiers containing punctuation or +mixed case, for example `IN "Team$ML"`. + +`SHOW SCHEMAS` and `SHOW NAMESPACES` use the same rules: without `IN` they +include all namespace paths and the public root; with `IN` they list the +selected parent's immediate children. `SHOW DATABASES` remains global and +does not accept `IN`. + +SDK APIs that take a namespace send an explicit `IN` clause and continue to +list that one namespace. + +## Continuation metadata + +The Arrow result schema carries `lancedb.next_page_token` when more results +remain. Pass that opaque value unchanged in `FROM` on the next request. +The token identifies the object type, database, namespace scope, and complete +position, including namespace path and any numeric revision. It cannot be +reused with another object type or scope. + +The token is metadata, not an additional result column or a synthetic row. +Namespace-scoped object listings contain `namespace_path` and `name`; +databases contain only `name`. Function history retains revision metadata. +SDK listing APIs expose this server-issued value as the page's `page_token`. + +Continue until no token is returned. A short or empty page may still have a +token. Pages observe the live catalog; continuation does not create a snapshot. + +## Page size and ordering + +The default page limit is 1,000, with a maximum of 10,000. `LIMIT 0` returns +no rows. Object catalogs order identifiers by namespace path components and +unqualified name; database names are ordered by name. Table page boundaries +follow native catalog order, which may differ from logical name order for +directory-backed tables; table names are sorted within each returned page. Function history uses +numeric revision order within each name. The token preserves that complete +position, including when names repeat in different namespaces. + +The old name-comparison `WHERE` and Function `WITH` pagination forms are no +longer supported. Use the same `LIMIT ... FROM ...` suffix for every listing. diff --git a/python/python/tests/test_storage_integration.py b/python/python/tests/test_storage_integration.py index ff7995ab3..84052e54c 100644 --- a/python/python/tests/test_storage_integration.py +++ b/python/python/tests/test_storage_integration.py @@ -3,6 +3,7 @@ import contextlib import json +import re from pathlib import Path import pytest @@ -39,7 +40,30 @@ def remote_server(text_type=pa.string()): command = ticket.ticket calls.append(command) if b"SHOW STORAGE INTEGRATIONS" in command: - result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)}) + match = re.search( + rb'SHOW STORAGE INTEGRATIONS IN "public" ' + rb"LIMIT (\d+)(?: FROM '([^']+)')?", + command, + ) + assert match is not None, command + limit = int(match.group(1)) + names = [NAME, "zeta"] + if match.group(2) is not None: + assert match.group(2) == b"server-storage-page", command + names = names[1:] + page = names[:limit] + result = pa.table( + { + "namespace_path": pa.array( + ["[]"] * len(page), type=pa.string() + ), + "name": pa.array(page, type=text_type), + } + ) + if len(names) > limit: + result = result.replace_schema_metadata( + {b"lancedb.next_page_token": b"server-storage-page"} + ) elif b"DROP STORAGE INTEGRATION" in command: result = pa.table({"dropped": [True]}) else: @@ -195,6 +219,10 @@ def test_sync_storage_integration_lifecycle_and_aws_information(text_type): assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0] assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0] assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1] + listings = [call for call in calls if b"SHOW STORAGE INTEGRATIONS" in call] + assert len(listings) == 2 + assert b'SHOW STORAGE INTEGRATIONS IN "public" LIMIT 1' in listings[0] + assert b"FROM 'server-storage-page'" in listings[1] @pytest.mark.asyncio diff --git a/rust/lancedb/src/listing.rs b/rust/lancedb/src/listing.rs index a0f6e5d5e..a5541b629 100644 --- a/rust/lancedb/src/listing.rs +++ b/rust/lancedb/src/listing.rs @@ -19,7 +19,10 @@ pub struct ListingOptions { /// Starting continuation token; `None` starts at the beginning. pub page_token: Option, /// Maximum results per request, not a limit on the entire listing. - /// `None` uses the backend default. Must be between 1 and `i32::MAX`. + /// `None` uses the backend default. SQL-backed catalog listings default to + /// 1,000 rows and accept 1 through 10,000. The public listing API rejects + /// zero; SQL statements can separately use `LIMIT 0`. Other backends may + /// impose different limits. pub page_limit: Option, } @@ -31,6 +34,9 @@ impl ListingOptions { } /// Set the maximum number of results requested per page. + /// + /// SQL-backed catalog listings accept 1 through 10,000. A server can return + /// fewer rows, including none, with a continuation token. pub fn page_limit(mut self, limit: u32) -> Self { self.page_limit = Some(limit); self diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 7100e1b04..1a825bebc 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1008,30 +1008,9 @@ impl Database for RemoteDatabase { namespace_path: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace_path)?; - let result = self - .execute_query_async(ExecuteQueryRequest { - query: "SHOW STORAGE INTEGRATIONS".into(), - default_namespace_path: namespace_path.to_vec(), - parameters: None, - }) - .await?; - let mut names = - integration_sql::decode_names(&result.reader().await?.try_collect::>().await?)?; - if let Some(token) = options.page_token { - names.retain(|name| name > &token); - } - let mut page_token = None; - if let Some(limit) = options.page_limit - && names.len() > limit as usize - { - names.truncate(limit as usize); - page_token = names.last().cloned(); - } - Ok(ListingPage { - items: names, - page_token, - }) + self.sql_client()? + .list_names("SHOW STORAGE INTEGRATIONS", namespace_path, options) + .await } async fn drop_storage_integration(&self, name: &str, namespace_path: &[String]) -> Result<()> { diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index 19a1a6cbc..f0ebf1894 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -14,7 +14,6 @@ use crate::{ listing::{ListingOptions, ListingPage}, utils::{validate_function_name, validate_namespace}, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; /// The SQL result of one Function drop, before the public boolean wrapper /// discards the advisory details. @@ -89,81 +88,17 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid = || Error::InvalidInput { - message: "invalid function page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let bytes = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid())?; - let (database, prefix, path, name, version): ( - String, - Option, - Vec, - String, - String, - ) = serde_json::from_slice(&bytes).map_err(|_| invalid())?; - if database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid()); - } - Some((name, version)) - } else { - None - }; - let mut sql_options = vec![ - format!("limit = {}", u64::from(limit) + 1), - "include_definition = true".to_owned(), - ]; - if let Some((name, version)) = &after { - sql_options.push(format!("after_name = {}", literal(name))); - sql_options.push(format!("after_version = {}", literal(version))); - } - let mut items: Vec = self - .object_job( - ExecuteQueryRequest { - query: format!("SHOW FUNCTIONS HISTORY WITH ({})", sql_options.join(", ")), - default_namespace_path: namespace.to_vec(), - parameters: None, - }, - |batches| { - strings(&batches, "definition")? - .into_iter() - .map(|value| { - serde_json::from_str(&value).map_err(|error| Error::Runtime { - message: error.to_string(), - }) - }) - .collect::>>() - }, - ) - .await? - .wait() + let (batches, page_token) = self + .listing_page("SHOW FUNCTIONS HISTORY", namespace, options) .await?; - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let last = items.last().unwrap(); - let bytes = serde_json::to_vec(&( - &self.inner.database, - &self.inner.database_prefix, - namespace, - last.name(), - last.version(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(bytes)) - } else { - None - }; + let items = strings(&batches, "definition")? + .into_iter() + .map(|value| { + serde_json::from_str(&value).map_err(|error| Error::Runtime { + message: error.to_string(), + }) + }) + .collect::>>()?; Ok(ListingPage { items, page_token }) } pub(in crate::remote) async fn drop_function_outcome( diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index e982afac7..c8e1aa5c3 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -4,7 +4,6 @@ use std::sync::Arc; use arrow_array::{Array, RecordBatch, StringArray}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::TryStreamExt; use super::SqlClient; @@ -157,60 +156,7 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid materialized-view page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (database, prefix, path, last): (String, Option, Vec, String) = - serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!( - "SHOW MATERIALIZED VIEWS{after} LIMIT {}", - u64::from(limit) + 1 - ), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&batch, "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW MATERIALIZED VIEWS", namespace, options) + .await } } diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index ff87e0000..2ffb08936 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -1,42 +1,118 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use super::SqlClient; +use super::{SqlClient, materialized_view::quote_identifier}; use crate::{ database::ExecuteQueryRequest, error::{Error, Result}, job::Job, + listing::{ListingOptions, ListingPage}, + utils::validate_namespace, }; -use arrow_array::{Array, ListArray, RecordBatch, StringArray}; +use arrow_array::{Array, LargeStringArray, ListArray, RecordBatch, StringArray, StringViewArray}; use futures::TryStreamExt; use serde::{Serialize, de::DeserializeOwned}; use std::sync::Arc; +const DEFAULT_SQL_LISTING_LIMIT: u32 = 1_000; +const MAX_SQL_LISTING_LIMIT: u32 = 10_000; +const NEXT_PAGE_TOKEN_METADATA_KEY: &str = "lancedb.next_page_token"; + +impl SqlClient { + pub(in crate::remote) async fn listing_page( + &self, + statement: &str, + namespace: &[String], + options: ListingOptions, + ) -> Result<(Vec, Option)> { + validate_namespace(namespace)?; + let limit = options.page_limit.unwrap_or(DEFAULT_SQL_LISTING_LIMIT); + if limit > MAX_SQL_LISTING_LIMIT { + return Err(Error::InvalidInput { + message: format!("page limit must be between 0 and {MAX_SQL_LISTING_LIMIT}"), + }); + } + if options.page_token.as_ref().is_some_and(String::is_empty) { + return Err(Error::InvalidInput { + message: "page token must not be empty".into(), + }); + } + if limit == 0 { + return Ok((Vec::new(), None)); + } + let schema = if namespace.is_empty() { + "public".to_owned() + } else { + namespace.join("$") + }; + let mut statement = format!("{statement} IN {} LIMIT {limit}", quote_identifier(&schema)); + if let Some(token) = options.page_token { + statement.push_str(&format!(" FROM {}", literal(&token))); + } + let query = self + .execute(ExecuteQueryRequest { + query: statement, + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let reader = query.reader().await?; + let token = reader + .schema() + .metadata() + .get(NEXT_PAGE_TOKEN_METADATA_KEY) + .cloned() + .filter(|token| !token.is_empty()); + let batches = reader.try_collect::>().await?; + if batches.iter().map(RecordBatch::num_rows).sum::() > limit as usize { + return Err(Error::Runtime { + message: "SQL listing exceeded its requested page size".into(), + }); + } + Ok((batches, token)) + } + + pub(in crate::remote) async fn list_names( + &self, + statement: &str, + namespace: &[String], + options: ListingOptions, + ) -> Result> { + let (batches, page_token) = self.listing_page(statement, namespace, options).await?; + Ok(ListingPage { + items: strings(&batches, "name")?, + page_token, + }) + } +} + pub(super) fn literal(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } pub(super) fn strings(batches: &[RecordBatch], name: &str) -> Result> { - batches - .iter() - .map(|batch| { - let values = batch - .column_by_name(name) - .and_then(|column| column.as_any().downcast_ref::()) - .ok_or_else(|| Error::Runtime { - message: format!("SQL result is missing UTF-8 column '{name}'"), - })?; - if values.null_count() != 0 { - return Err(Error::Runtime { - message: format!("SQL result contains null '{name}'"), - }); - } - Ok(values - .iter() - .map(|value| value.unwrap().to_owned()) - .collect::>()) - }) - .collect::>>() - .map(|rows| rows.into_iter().flatten().collect()) + let mut result = Vec::new(); + for batch in batches { + let column = batch.column_by_name(name).ok_or_else(|| Error::Runtime { + message: format!("SQL result is missing string column '{name}'"), + })?; + if column.null_count() != 0 { + return Err(Error::Runtime { + message: format!("SQL result contains null '{name}'"), + }); + } + if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else { + return Err(Error::Runtime { + message: format!("SQL result column '{name}' is not a string"), + }); + } + } + Ok(result) } /// Read an optional `List` column. Older servers do not return the @@ -112,9 +188,9 @@ impl SqlClient { #[cfg(test)] mod tests { - use super::string_lists; + use super::{string_lists, strings}; use arrow_array::builder::{ListBuilder, StringBuilder}; - use arrow_array::{ArrayRef, RecordBatch}; + use arrow_array::{ArrayRef, LargeStringArray, RecordBatch, StringArray, StringViewArray}; use arrow_schema::{DataType, Field, Schema}; use std::sync::Arc; @@ -126,6 +202,24 @@ mod tests { )])) } + #[test] + fn listing_strings_accept_all_arrow_string_representations() { + for values in [ + Arc::new(StringArray::from(vec!["a", "z"])) as ArrayRef, + Arc::new(LargeStringArray::from(vec!["a", "z"])) as ArrayRef, + Arc::new(StringViewArray::from(vec!["a", "z"])) as ArrayRef, + ] { + let batch = RecordBatch::try_from_iter(vec![("name", values)]).unwrap(); + assert_eq!(strings(&[batch], "name").unwrap(), ["a", "z"]); + } + let batch = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringViewArray::from(vec![Some("a"), None])) as ArrayRef, + )]) + .unwrap(); + assert!(strings(&[batch], "name").is_err()); + } + #[test] fn reads_warnings_after_an_empty_first_batch() { let schema = warning_schema(); diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index 6ddc78645..93c2a6c6e 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -10,8 +10,6 @@ use crate::{ utils::{validate_namespace, validate_secret_name}, }; use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use futures::TryStreamExt; use std::sync::Arc; pub(in crate::remote) enum SecretWriteOperation { @@ -135,65 +133,7 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid secret page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (kind, database, prefix, path, last): ( - String, - String, - Option, - Vec, - String, - ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if kind != "secret" - || database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!("SHOW SECRETS{after} LIMIT {}", u64::from(limit) + 1), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&[batch], "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - "secret", - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW SECRETS", namespace, options).await } } diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index 513113187..b058269a0 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -9,8 +9,6 @@ use crate::{ utils::{validate_namespace, validate_view_name}, view::ViewDescription, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use futures::TryStreamExt; use lance_namespace::models::JsonArrowSchema; use std::sync::Arc; #[derive(Clone, serde::Serialize, serde::Deserialize)] @@ -147,64 +145,6 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid view page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (kind, database, prefix, path, last): ( - String, - String, - Option, - Vec, - String, - ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if kind != "view" - || database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!("SHOW VIEWS{after} LIMIT {}", u64::from(limit) + 1), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&[batch], "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - "view", - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW VIEWS", namespace, options).await } } diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 5c7ae7673..d7249da9b 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -14,7 +14,6 @@ use arrow_flight::{ FlightInfo, HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket, }; use arrow_schema::{DataType, Field, Schema}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::stream::BoxStream; use futures::{StreamExt, TryStreamExt}; use tonic::metadata::MetadataMap; @@ -2919,25 +2918,54 @@ async fn remote_optimize_full_rejects_explicit_pruning_options() { assert_rejected_before_submission(None, None, Some(true)).await; } +fn sql_listing_batch(column: &str, values: &[&str], token: Option<&str>) -> RecordBatch { + let mut columns: Vec<(&str, ArrayRef)> = Vec::new(); + if column == "name" { + columns.push(( + "namespace_path", + Arc::new(StringArray::from(vec![ + r#"["team","reports"]"#; + values.len() + ])), + )); + } + columns.push((column, Arc::new(StringArray::from(values.to_vec())))); + let batch = RecordBatch::try_from_iter(columns).unwrap(); + let metadata = token + .map(|token| HashMap::from([("lancedb.next_page_token".to_owned(), token.to_owned())])) + .unwrap_or_default(); + let schema = Arc::new(batch.schema().as_ref().clone().with_metadata(metadata)); + RecordBatch::try_new(schema, batch.columns().to_vec()).unwrap() +} + #[tokio::test] -async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { +async fn remote_mv_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["a", "b'c", "z"])) as ArrayRef, - )]) - .unwrap(); + let token = "server'opaque:token"; + let next_sql = + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); let headers = service.headers.clone(); - let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; - let db = RemoteDatabase::new_mock(|request| -> http::Response { - panic!("unexpected REST request: {}", request.url().path()); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; @@ -2948,41 +2976,31 @@ async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { ) .await .unwrap(); - assert_eq!(first.items, ["a", "b'c"]); - let token = first.page_token.unwrap(); - db.list_materialized_views( - &namespace, - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(&token), - ) - .await - .unwrap(); + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db + .list_materialized_views( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(second.items, ["z"]); + assert!(second.page_token.is_none()); assert_eq!( *statements.lock().unwrap(), [ - "SHOW MATERIALIZED VIEWS LIMIT 3", - "SHOW MATERIALIZED VIEWS WHERE name > 'b''c' LIMIT 3" + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2", + next_sql ] ); - assert!( - headers - .lock() - .unwrap() - .iter() - .all(|header| header.namespace_path == "team$reports") - ); - for (path, token) in [(vec![], token), (namespace, "invalid".into())] { - assert!(matches!( - db.list_materialized_views( - &path, - crate::listing::ListingOptions::default().page_token(token) - ) - .await, - Err(Error::InvalidInput { .. }) - )); + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } @@ -3123,7 +3141,10 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() let statements = statements.lock().unwrap(); assert!(statements[0].contains("STORAGE_AWS_REGION = 'us-east-1'")); assert_eq!(statements[1], "DESCRIBE STORAGE INTEGRATION \"raw\""); - assert_eq!(statements[2], "SHOW STORAGE INTEGRATIONS"); + assert_eq!( + statements[2], + "SHOW STORAGE INTEGRATIONS IN \"platform$aws\" LIMIT 1000" + ); assert_eq!(statements[3], "DROP STORAGE INTEGRATION \"raw\""); assert!(statements[4].contains( "STORAGE_AWS_ACCESS_KEY_ID_SECRET = \"platform/raw\".\"credentials\".\"key\"" @@ -3670,29 +3691,20 @@ async fn secret_description_uses_the_sql_metadata_projection() { } #[tokio::test] -async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { +async fn secret_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let first_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["api-key", "hf'prod", "openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let second_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ - ("SHOW SECRETS LIMIT 3".to_string(), first_result), - ( - "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3".to_string(), - second_result, - ), - ]))); + let token = "server'opaque:token"; + let next_sql = "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result_overrides, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -3704,11 +3716,10 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { ) .await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - let first = db .list_secrets( &namespace, @@ -3716,90 +3727,144 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { ) .await .unwrap(); - assert_eq!(first.items, ["api-key", "hf'prod"]); - let token = first.page_token.expect("a third row must produce a token"); - + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); let second = db .list_secrets( &namespace, crate::listing::ListingOptions::default() .page_limit(2) - .page_token(&token), + .page_token(first.page_token.unwrap()), ) .await .unwrap(); - assert_eq!(second.items, ["openai-prod"]); + assert_eq!(second.items, ["z"]); assert!(second.page_token.is_none()); - assert_eq!( *statements.lock().unwrap(), - [ - "SHOW SECRETS LIMIT 3", - "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3" - ] + ["SHOW SECRETS IN \"team$reports\" LIMIT 2", next_sql] ); - { - let headers = headers.lock().unwrap(); - assert!(!headers.is_empty()); - for header in headers.iter() { - assert_eq!(header.database, "analytics"); - assert_eq!(header.database_prefix, "tenant/production"); - assert_eq!(header.namespace_path, "team$reports"); - } + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - - for (path, token) in [ - (vec!["other".to_owned()], token), - (namespace.clone(), "invalid".to_owned()), - ] { - assert!(matches!( - db.list_secrets( - &path, - crate::listing::ListingOptions::default().page_token(token) - ) - .await, - Err(Error::InvalidInput { .. }) - )); - } - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } #[tokio::test] -async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() { - let empty = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(Vec::::new())) as ArrayRef, - )]) - .unwrap(); +async fn storage_integration_listing_uses_server_continuation_tokens() { + for defer in [false, true] { + let token = "server'opaque:token"; + let next_sql = + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; + let service = TestSqlService { + adaptive: true, + defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") + }) + .with_sql_client(client); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + let first = db + .list_storage_integrations( + &namespace, + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db + .list_storage_integrations( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(second.items, ["z"]); + assert!(second.page_token.is_none()); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2", + next_sql + ] + ); + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); + } + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn secret_listing_preserves_empty_continuations_and_validates_page_options() { let service = TestSqlService { adaptive: true, defer: true, - result: empty, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &[], Some("continue-empty")), + ), + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'continue-empty'".to_owned(), + sql_listing_batch("name", &["last"], None), + ), + ]))), ..Default::default() }; let statements = service.statements.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - let page = db .list_secrets( &namespace, - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(""), + crate::listing::ListingOptions::default().page_limit(2), ) .await .unwrap(); assert!(page.items.is_empty()); - assert!(page.page_token.is_none()); - - for limit in [0, i32::MAX as u32 + 1] { + assert_eq!(page.page_token.as_deref(), Some("continue-empty")); + let last = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(page.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(last.items, ["last"]); + assert!(last.page_token.is_none()); + for limit in [10_001, u32::MAX] { assert!(matches!( db.list_secrets( &namespace, @@ -3809,12 +3874,29 @@ async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() { Err(Error::InvalidInput { .. }) )); } - assert_eq!(*statements.lock().unwrap(), ["SHOW SECRETS LIMIT 3"]); + assert!( + db.list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_token("") + ) + .await + .is_err() + ); + let zero = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_limit(0), + ) + .await + .unwrap(); + assert!(zero.items.is_empty()); + assert!(zero.page_token.is_none()); + assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } #[tokio::test] -async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { +async fn function_listing_uses_server_tokens_for_numeric_revision_pages() { const VERSION: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" ); @@ -3824,74 +3906,65 @@ async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { let mut tenth: serde_json::Value = serde_json::from_str(VERSION).unwrap(); tenth["version"] = serde_json::json!("10"); let tenth = tenth.to_string(); - let result = RecordBatch::try_from_iter(vec![( - "definition", - Arc::new(StringArray::from(vec![ - VERSION, - second.as_str(), - tenth.as_str(), - ])) as ArrayRef, - )]) - .unwrap(); - let service = TestSqlService { - adaptive: true, - defer: true, - result, - ..Default::default() - }; - service.result_overrides.lock().unwrap().insert( - "SHOW FUNCTIONS HISTORY WITH (limit = 3, include_definition = true, after_name = 'embed', after_version = '2')".into(), - RecordBatch::try_from_iter(vec![("definition", Arc::new(StringArray::from(vec![tenth.as_str()])) as ArrayRef)]).unwrap(), - ); - let statements = service.statements.clone(); - let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; - let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); - }) - .with_sql_client(client); - let first = db - .list_functions( - &["team".into()], - crate::listing::ListingOptions::default().page_limit(2), - ) - .await - .unwrap(); - assert_eq!( - first - .items - .iter() - .map(|item| item.version()) - .collect::>(), - ["1", "2"] - ); - let token = first.page_token.unwrap(); - let second = db - .list_functions( - &["team".into()], - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(token.clone()), - ) - .await - .unwrap(); - assert_eq!(second.items.len(), 1); - assert_eq!(second.items[0].version(), "10"); - assert!(second.page_token.is_none()); - assert!( - db.list_functions( - &["other".into()], - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(token) - ) - .await - .is_err() - ); - let seen = statements.lock().unwrap(); - assert_eq!(seen.len(), 2); - assert!(seen[0].starts_with("SHOW FUNCTIONS HISTORY WITH (limit = 3,")); - assert!(seen[1].contains("after_version = '2'")); - shutdown.send(()).unwrap(); + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2".to_owned(), + sql_listing_batch("definition", &[VERSION, &second], Some("revision-cursor")), + ), + ( + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'".to_owned(), + sql_listing_batch("definition", &[&tenth], None), + ), + ]))), + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") + }) + .with_sql_client(client); + let first = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!( + first + .items + .iter() + .map(|item| item.version()) + .collect::>(), + ["1", "2"] + ); + assert_eq!(first.page_token.as_deref(), Some("revision-cursor")); + let last = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(last.items.len(), 1); + assert_eq!(last.items[0].version(), "10"); + assert!(last.page_token.is_none()); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2", + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'" + ] + ); + shutdown.send(()).unwrap(); + } } #[tokio::test] @@ -3999,29 +4072,20 @@ async fn view_drop_uses_a_repeatable_query_job() { } #[tokio::test] -async fn view_listing_uses_bounded_sql_and_scoped_cursors() { +async fn view_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let first_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["adults", "hf'prod", "openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let second_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ - ("SHOW VIEWS LIMIT 3".to_string(), first_result), - ( - "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3".to_string(), - second_result, - ), - ]))); + let token = "server'opaque:token"; + let next_sql = "SHOW VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result_overrides, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW VIEWS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -4033,107 +4097,39 @@ async fn view_listing_uses_bounded_sql_and_scoped_cursors() { ) .await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); - let connection = Connection::new( - Arc::new(db), - Arc::new(crate::embeddings::MemoryRegistry::new()), - ); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - - let first = connection + let first = db .list_views( &namespace, crate::listing::ListingOptions::default().page_limit(2), ) - .next_page() .await - .unwrap() .unwrap(); - assert_eq!(first.items, ["adults", "hf'prod"]); - let token = first.page_token.expect("a third row must produce a token"); - - let second = connection + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db .list_views( &namespace, crate::listing::ListingOptions::default() .page_limit(2) - .page_token(&token), + .page_token(first.page_token.unwrap()), ) - .next_page() .await - .unwrap() .unwrap(); - assert_eq!(second.items, ["openai-prod"]); + assert_eq!(second.items, ["z"]); assert!(second.page_token.is_none()); - assert_eq!( *statements.lock().unwrap(), - [ - "SHOW VIEWS LIMIT 3", - "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3" - ] + ["SHOW VIEWS IN \"team$reports\" LIMIT 2", next_sql] ); - { - let headers = headers.lock().unwrap(); - assert!(!headers.is_empty()); - for header in headers.iter() { - assert_eq!(header.database, "analytics"); - assert_eq!(header.database_prefix, "tenant/production"); - assert_eq!(header.namespace_path, "team$reports"); - } + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - - let encode_token = - |kind: &str, database: &str, prefix: Option<&str>, path: &[String], last: &str| { - URL_SAFE_NO_PAD.encode( - serde_json::to_vec(&(kind, database, prefix, path.to_vec(), last)).unwrap(), - ) - }; - for forged in [ - encode_token( - "secret", - "analytics", - Some("tenant/production"), - &namespace, - "hf'prod", - ), - encode_token( - "view", - "billing", - Some("tenant/production"), - &namespace, - "hf'prod", - ), - encode_token("view", "analytics", Some("other"), &namespace, "hf'prod"), - encode_token( - "view", - "analytics", - Some("tenant/production"), - &["other".to_owned()], - "hf'prod", - ), - "not-a-json-token".to_string(), - ] { - let mut listing = connection.list_views( - &namespace, - crate::listing::ListingOptions::default().page_token(forged), - ); - assert!(matches!( - listing.next_page().await, - Err(Error::InvalidInput { .. }) - )); - } - let mut listing = connection.list_views( - &["other".to_owned()], - crate::listing::ListingOptions::default().page_token(&token), - ); - assert!(matches!( - listing.next_page().await, - Err(Error::InvalidInput { .. }) - )); - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs index 48dab4c6a..6c132ab4b 100644 --- a/rust/lancedb/src/remote/storage_integration.rs +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -259,29 +259,6 @@ pub(super) fn decode_info(batches: &[RecordBatch]) -> Result Result> { - let mut names = Vec::new(); - for batch in batches { - let column = batch - .column_by_name("name") - .ok_or_else(|| invalid("SQL storage integration listing is missing names"))?; - for row in 0..batch.num_rows() { - if column.is_null(row) { - return Err(invalid("SQL storage integration name cannot be null")); - } - names.push( - string_value(column.as_ref(), row) - .ok_or_else(|| { - invalid("SQL storage integration listing requires string names") - })? - .to_string(), - ); - } - } - names.sort(); - Ok(names) -} - #[cfg(test)] mod tests { use std::sync::Arc; From 530d379fc4d3abbf8c4c8759f7d48804d2055677 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 15 Nov 2026 02:08:34 +0000 Subject: [PATCH 67/75] =?UTF-8?q?Bump=20version:=200.42.0-beta.13=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.14?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 04ce71470..8491e70dc 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.13" +current_version = "0.42.0-beta.14" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index a84f1d6fd..755ba70a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5992,7 +5992,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "ahash", "anyhow", @@ -6103,7 +6103,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "anyhow", "arrow-array", @@ -6146,7 +6146,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "arrow-array", "arrow-buffer", @@ -6171,7 +6171,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 1aadbe68f..ca0113382 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.13 + 0.42.0-beta.14 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index e8a9a76ec..0ed2c85d9 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.13 + 0.42.0-beta.14 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9b062f4e8..ead5955fa 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.13 + 0.42.0-beta.14 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 7f8468eb5..87919848f 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 0fb6fde09..4c29cfeb3 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 24e779721..86c223618 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 8ee7bd66b..2e32e7fc3 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 3c7c63b86..7d984b9f4 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 75e68cacd..3607a6b93 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 3422e095c..369ff1c10 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e9ceb4dfb..d0852d725 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 512e390aa..8520e7b83 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 0f7667320..08113dee6 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 2dac7bda3..3a963d193 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 581504423..0b566e596 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" edition = "2021" license.workspace = true repository.workspace = true From f17a07a2cda583af25f67797192ea776b8b8efa2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 15 Nov 2026 00:50:58 -0800 Subject: [PATCH 68/75] feat: expose server-side job listing filters (#5041) Expose server-side job filters and lazy Listing indexing, slicing, and length helpers. Document cache, cursor, and SDK/server compatibility behavior. --- docs/web/basics/jobs.mdx | 51 ++++++-- nodejs/__test__/remote.test.ts | 53 +++++++-- python/python/lancedb/_lancedb.pyi | 14 ++- python/python/lancedb/db.py | 136 ++++++++++++++++++--- python/python/lancedb/listing.py | 72 ++++++++++- python/python/lancedb/remote/db.py | 48 +++++++- python/python/tests/test_listing.py | 178 +++++++++++++++++++++++++++- python/src/connection.rs | 38 +++++- rust/lancedb/src/connection.rs | 35 +++++- rust/lancedb/src/database.rs | 47 ++++++++ rust/lancedb/src/remote/db.rs | 137 ++++++++++++++++++++- 11 files changed, 756 insertions(+), 53 deletions(-) diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 264acd728..db5b49ab5 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -177,14 +177,51 @@ for info in db.list_jobs(page_limit=50): live `Job` handles. Open an ID to inspect its full record. `page_limit` bounds each server request, not the total yielded items, and `page_token` resumes a listing. It is a lazy iterator: iteration performs requests and can raise -request errors. To materialize it, use `list(db.list_jobs(...))`; it does not -support list indexing, `len()`, or a `.to_list()` method. +request errors. Use `list(db.list_jobs(...))` to collect all remaining results; +there is no `.to_list()` method. -`Listing.num_page_results()` reports cached items remaining in the current -page and `Listing.page_token()` reports the next request's token. Drain the -cached items before saving that token, or resuming can skip them. A `None` -token after the final page can coexist with unread cached items. A resumed -listing is not a transactionally frozen view of jobs submitted in the meantime. + +Job filters and synchronous `Listing` indexing, slicing, and `len()` require +a Python SDK release that includes these APIs. Older SDKs expose only +`page_token` and `page_limit`; collect results with `list(...)` before indexing +or counting them. Filtering also requires a matching Enterprise server that +supports the requested filters. + + +Filter jobs on the server before pagination with `table`, `state`, `job_type` +or `job_types`, and creation-time bounds. `table` names a table in +`namespace_path` (the root by default) and includes all its branches. Requests +stay scoped to the connected database. Creation times are Unix milliseconds: +`created_at_gte_millis` is inclusive and `created_at_lt_millis` is exclusive. +Choose either `job_type` or `job_types`. + +The `state` filter uses registry states: `in_progress`, `succeeded`, `failed`, +`canceled`, and `timed_out`. These differ from the SDK lifecycle labels such +as `running` and `finished` returned in `JobInfo.state`. + +```python +jobs = db.list_jobs(table="events", state="in_progress", page_limit=5) +first_five = jobs[:5] +for info in first_five: + print(info.job_id, info.state) +``` + +Synchronous indexing and slicing refer to the remaining results without +consuming them. A bounded forward slice such as `jobs[:5]` fetches only enough +pages to reach its stop. `len(jobs)` returns the remaining count by fetching +and caching every remaining result. Negative indexes and open-ended or reverse +slices also fetch and cache all remaining results. These operations can raise +request errors; later iteration drains their cache. `AsyncListing` remains an +async iterator: use `async for` to read it. + +`Listing.num_page_results()` reports cached items available without another +request, including items retained by indexing, slicing, or counting. +`Listing.page_token()` reports the next request's token. Drain all cached +items before saving that token, or resuming can skip them. Resume with the same +filters, for example `db.list_jobs(table="events", state="in_progress", +page_token=saved_token, page_limit=5)`. A `None` token after the final page can +coexist with unread cached items. A resumed listing is not a transactionally +frozen view of jobs submitted in the meantime. `events.schema` describes the Arrow response. Use `events.to_pylist()` for Python row dictionaries. Common event columns are `event_seq` (int64), `state` diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 215df992d..9baa51292 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2318,10 +2318,30 @@ describe("remote connection jobs surface", () => { queue_reason: "Waiting for Function worker capacity", }); const descriptions = [ - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 3000, unknownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 2000, knownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(40, 60, 1000, unknownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(60, 0, 0, unknownFleet)}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 20, + 80, + 3000, + unknownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 20, + 80, + 2000, + knownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 40, + 60, + 1000, + unknownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress( + 60, + 0, + 0, + unknownFleet, + )}}`, ]; let describeCount = 0; @@ -2393,12 +2413,24 @@ describe("remote connection jobs surface", () => { it("does not derive ETA across a zero-rate, epoch, or pause boundary", async () => { const now = Date.now(); const descriptions = [ - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 5000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 4000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 3000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 2000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1500}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1000}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${ + now - 5000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${ + now - 4000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 3000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 2000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 1500 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 1000 + }}}`, ]; await withMockDatabase( @@ -2574,6 +2606,7 @@ describe("lazy resource listings", () => { if (kind === "jobs") { expect(url.pathname).toBe("/v1/jobs/list"); expect(request.body).toEqual({ + database: "dev", // biome-ignore lint/style/useNamingConvention: server wire format page_token: token, limit: 2, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a86bae9d5..0cce2085e 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -300,7 +300,19 @@ class Connection(object): page_limit: Optional[int] = None, ) -> NameListing: ... def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> JobListing: ... async def cancel_job(self, job_id: str) -> bool: ... async def pause_job(self, job_id: str) -> str: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 12c7edd5c..b225a6e65 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1602,13 +1602,39 @@ class DBConnection(EnforceOverrides): ) def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> Listing[JobInfo]: - """List server-side jobs across the database's tables. + """List server-side jobs, optionally filtered before pagination. - Returns a lazy iterator. ``page_limit`` limits each request, not the total; - ``page_token`` resumes from a saved token. Requests and errors occur during - iteration. See [pagination state][lancedb.listing.AsyncListing]. + ``table`` names a table in ``namespace_path`` (the root by default). + Listings include all branches of the table. A namespace filter requires + ``table``. + ``state`` uses registry states such as ``in_progress``, ``succeeded``, + ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's + ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``. + Creation-time bounds are Unix milliseconds, inclusive at + ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total. + Resume a ``page_token`` with the same filters. Requests and errors occur + during iteration. See [pagination state][lancedb.listing.AsyncListing]. + + For example, to inspect up to five jobs without fetching all history:: + + jobs = db.list_jobs(table="events", page_limit=5) + first_five = jobs[:5] """ raise NotImplementedError( _append_doc_url( @@ -2799,16 +2825,52 @@ class LanceDBConnection(DBConnection): @override def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> Listing[JobInfo]: - """List server-side jobs across the database's tables. + """List server-side jobs, optionally filtered before pagination. - Returns a lazy iterator. ``page_limit`` limits each request, not the total; - ``page_token`` resumes from a saved token. Requests and errors occur during - iteration. See [pagination state][lancedb.listing.AsyncListing]. + ``table`` names a table in ``namespace_path`` (the root by default). + Listings include all branches of the table. A namespace filter requires + ``table``. + ``state`` uses registry states such as ``in_progress``, ``succeeded``, + ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's + ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``. + Creation-time bounds are Unix milliseconds, inclusive at + ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total. + Resume a ``page_token`` with the same filters. Requests and errors occur + during iteration. See [pagination state][lancedb.listing.AsyncListing]. + + For example, to inspect up to five jobs without fetching all history:: + + jobs = db.list_jobs(table="events", page_limit=5) + first_five = jobs[:5] """ return Listing( - self._conn.list_jobs(page_token=page_token, page_limit=page_limit) + self._conn.list_jobs( + page_token=page_token, + page_limit=page_limit, + table=table, + namespace_path=namespace_path, + state=state, + job_type=job_type, + job_types=job_types, + created_at_gte_millis=created_at_gte_millis, + created_at_lt_millis=created_at_lt_millis, + ) ) @override @@ -4375,16 +4437,56 @@ class AsyncConnection(object): ) def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> AsyncListing[JobInfo]: - """List server-side jobs across the database's tables. + """List server-side jobs, optionally filtered before pagination. - Returns a lazy iterator. ``page_limit`` limits each request, not the total; - ``page_token`` resumes from a saved token. Requests and errors occur during - iteration. See [pagination state][lancedb.listing.AsyncListing]. + ``table`` names a table in ``namespace_path`` (the root by default). + Listings include all branches of the table. A namespace filter requires + ``table``. + ``state`` uses registry states such as ``in_progress``, ``succeeded``, + ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's + ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``. + Creation-time bounds are Unix milliseconds, inclusive at + ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total. + Resume a ``page_token`` with the same filters. Requests and errors occur + during iteration. See [pagination state][lancedb.listing.AsyncListing]. + + For example, to inspect up to five jobs without fetching all history:: + + jobs = db.list_jobs(table="events", page_limit=5) + first_five = [] + async for job in jobs: + first_five.append(job) + if len(first_five) == 5: + break """ return AsyncListing( - self._inner.list_jobs(page_token=page_token, page_limit=page_limit) + self._inner.list_jobs( + page_token=page_token, + page_limit=page_limit, + table=table, + namespace_path=namespace_path, + state=state, + job_type=job_type, + job_types=job_types, + created_at_gte_millis=created_at_gte_millis, + created_at_lt_millis=created_at_lt_millis, + ) ) async def cancel_job(self, job_id: str) -> bool: diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 59aba1431..f85599b2d 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -6,7 +6,19 @@ from __future__ import annotations import asyncio -from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar +from collections import deque +from itertools import islice +from operator import index +from typing import ( + Any, + AsyncIterator, + Callable, + Generic, + Iterator, + Optional, + TypeVar, + overload, +) from .background_loop import LOOP @@ -59,29 +71,85 @@ class Listing(Iterator[T], Generic[T]): print(name) Use ``list(connection.list_views())`` to collect all results. + + Indexes and slices refer to the remaining items and do not consume them. + A bounded forward slice, such as ``listing[:5]``, fetches only enough pages + to reach its stop. ``len(listing)``, negative indexes, and open-ended or + reverse slices fetch and cache all remaining results. Iteration then drains + that cache. These operations may perform requests and raise request errors. """ def __init__(self, inner: AsyncListing[T]): self._inner = inner + self._buffer: deque[T] = deque() def __iter__(self) -> Listing[T]: return self def __next__(self) -> T: + if self._buffer: + return self._buffer.popleft() try: return LOOP.run(self._inner.__anext__()) except StopAsyncIteration: raise StopIteration from None + def _fill(self, count: Optional[int]) -> None: + while count is None or len(self._buffer) < count: + try: + item = LOOP.run(self._inner.__anext__()) + except StopAsyncIteration: + return + self._buffer.append(item) + + def __len__(self) -> int: + """Fetch and cache every remaining item, returning the remaining count.""" + self._fill(None) + return len(self._buffer) + + def __bool__(self) -> bool: + self._fill(1) + return bool(self._buffer) + + @overload + def __getitem__(self, key: int) -> T: ... + + @overload + def __getitem__(self, key: slice) -> list[T]: ... + + def __getitem__(self, key: int | slice) -> T | list[T]: + """Read remaining items without consuming them; bounded slices stay lazy.""" + if isinstance(key, slice): + start = 0 if key.start is None else index(key.start) + stop = None if key.stop is None else index(key.stop) + step = 1 if key.step is None else index(key.step) + if step == 0: + raise ValueError("slice step cannot be zero") + if start >= 0 and stop is not None and stop >= 0 and step > 0: + if start >= stop: + return [] + self._fill(stop) + start, stop, step = key.indices(len(self._buffer)) + return list( + islice(self._buffer, start, stop, min(step, len(self._buffer) + 1)) + ) + self._fill(None) + return list(self._buffer)[key] + position = index(key) + self._fill(None if position < 0 else position + 1) + return self._buffer[position] + def num_page_results(self) -> int: """Return the number of cached items available without another request.""" - return self._inner.num_page_results() + return len(self._buffer) + self._inner.num_page_results() def page_token(self) -> Optional[str]: """Return the next request's token. See [AsyncListing.page_token][lancedb.listing.AsyncListing.page_token] for initial, cached, final-page, and error behavior. + Indexing, slicing, and counting can also advance this token; drain all + ``num_page_results()`` cached items before resuming from it. """ return self._inner.page_token() diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 913c8fc2c..2927f2726 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1324,16 +1324,52 @@ class RemoteDBConnection(DBConnection): @override def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> Listing[JobInfo]: - """List server-side jobs across the database's tables. + """List server-side jobs, optionally filtered before pagination. - Returns a lazy iterator. ``page_limit`` limits each request, not the total; - ``page_token`` resumes from a saved token. Requests and errors occur during - iteration. See [pagination state][lancedb.listing.AsyncListing]. + ``table`` names a table in ``namespace_path`` (the root by default). + Listings include all branches of the table. A namespace filter requires + ``table``. + ``state`` uses registry states such as ``in_progress``, ``succeeded``, + ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's + ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``. + Creation-time bounds are Unix milliseconds, inclusive at + ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total. + Resume a ``page_token`` with the same filters. Requests and errors occur + during iteration. See [pagination state][lancedb.listing.AsyncListing]. + + For example, to inspect up to five jobs without fetching all history:: + + jobs = db.list_jobs(table="events", page_limit=5) + first_five = jobs[:5] """ return Listing( - self._conn.list_jobs(page_token=page_token, page_limit=page_limit) + self._conn.list_jobs( + page_token=page_token, + page_limit=page_limit, + table=table, + namespace_path=namespace_path, + state=state, + job_type=job_type, + job_types=job_types, + created_at_gte_millis=created_at_gte_millis, + created_at_lt_millis=created_at_lt_millis, + ) ) @override diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py index cc1c44e90..d18e8580b 100644 --- a/python/python/tests/test_listing.py +++ b/python/python/tests/test_listing.py @@ -268,7 +268,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous) if kind == "jobs": assert verb == "POST" assert path.path == "/v1/jobs/list" - assert body == {"page_token": token, "limit": 2} + assert body == {"database": "dev", "page_token": token, "limit": 2} else: namespace = "team" resource = kind.removesuffix("s") @@ -326,3 +326,179 @@ async def test_listing_invalid_limit_does_not_fetch(listing_server, kind, page_l with pytest.raises(ValueError, match="limit"): await items.__anext__() assert requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("namespace", [[], ["team", "project"]]) +@pytest.mark.parametrize("multiple_types", [False, True]) +async def test_job_filters_persist_across_pages_and_resume( + listing_server, asynchronous, namespace, multiple_types +): + endpoint, requests, responses = listing_server + responses.extend( + (200, response_page("jobs", names, token)) + for names, token in [(["a"], "empty"), ([], "last"), (["b"], None)] + ) + db = await connection(endpoint, asynchronous) + types = ["column_refresh", "materialized_view_refresh"] + filters = dict( + table="events", + namespace_path=namespace, + state="in_progress", + created_at_gte_millis=100, + created_at_lt_millis=200, + **({"job_types": types} if multiple_types else {"job_type": types[0]}), + ) + items = db.list_jobs(page_limit=1, **filters) + assert requests == [] + assert (await advance(items, asynchronous)).job_id == "a" + assert len(requests) == 1 + resumed = db.list_jobs(page_token=items.page_token(), page_limit=1, **filters) + assert (await advance(resumed, asynchronous)).job_id == "b" + assert resumed.page_token() is None + assert len(requests) == 3 + expected = dict( + database="dev", + limit=1, + table_ref={ + "db_name": "dev", + "table_id": {"namespace_path": namespace, "table_name": "events"}, + }, + state="in_progress", + job_types=types if multiple_types else types[:1], + created_at_gte_millis=100, + created_at_lt_millis=200, + ) + for (_, path, body), token in zip(requests, [None, "empty", "last"]): + assert path == "/v1/jobs/list" + assert body == {**expected, **({"page_token": token} if token else {})} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "filters", + [ + {}, + {"state": "failed"}, + {"job_types": ["column_refresh"]}, + {"created_at_lt_millis": 200}, + ], +) +async def test_job_listing_without_table_stays_in_connected_database( + listing_server, asynchronous, filters +): + endpoint, requests, responses = listing_server + responses.append((200, response_page("jobs", ["a"], None))) + db = await connection(endpoint, asynchronous) + items = db.list_jobs(**filters) + assert (await advance(items, asynchronous)).job_id == "a" + assert requests[0][2] == {"database": "dev", **filters} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "filters, message", + [ + ({"namespace_path": ["team"]}, "requires a table"), + ({"created_at_gte_millis": 200, "created_at_lt_millis": 200}, "less than"), + ({"created_at_gte_millis": 201, "created_at_lt_millis": 200}, "less than"), + ({"job_type": "column_refresh", "job_types": []}, "only one"), + ({"state": "unknown"}, "state must be"), + ], +) +async def test_invalid_job_filters_do_not_fetch( + listing_server, asynchronous, filters, message +): + endpoint, requests, _ = listing_server + db = await connection(endpoint, asynchronous) + with pytest.raises(ValueError, match=message): + items = db.list_jobs(**filters) + await advance(items, asynchronous) + assert requests == [] + + +@pytest.mark.asyncio +async def test_listing_slice_and_index_fetch_only_needed_pages(listing_server): + endpoint, requests, responses = listing_server + responses.extend( + (200, response_page("jobs", names, token)) + for names, token in [(["a", "b"], "second"), (["c", "d"], "last")] + ) + db = await connection(endpoint, False) + items = db.list_jobs(table="events", page_limit=2) + assert items[:0] == [] + assert items[5:2] == [] + assert requests == [] + assert [job.job_id for job in items[:2]] == ["a", "b"] + assert len(requests) == 1 + assert items.num_page_results() == 2 + assert items.page_token() == "second" + assert items[1].job_id == "b" + assert next(items).job_id == "a" + assert [job.job_id for job in items[:2]] == ["b", "c"] + assert len(requests) == 2 + assert items.num_page_results() == 3 + assert items.page_token() == "last" + assert [job.job_id for job in items[0:3:2][:1]] == ["b"] + assert len(requests) == 2 + + +@pytest.mark.asyncio +async def test_listing_length_and_slices_preserve_remaining_items(listing_server): + endpoint, requests, responses = listing_server + responses.extend( + (200, response_page("jobs", names, token)) + for names, token in [(["a", "b"], "empty"), ([], "last"), (["c", "d"], None)] + ) + db = await connection(endpoint, False) + items = db.list_jobs(page_limit=2) + assert bool(items) + assert len(requests) == 1 + assert next(items).job_id == "a" + assert len(items) == 3 + assert len(requests) == 3 + assert items.num_page_results() == 3 + assert items.page_token() is None + assert items[-1].job_id == "d" + assert [job.job_id for job in items[::-1]] == ["d", "c", "b"] + assert [job.job_id for job in items[1:]] == ["c", "d"] + assert [job.job_id for job in items[:100:2]] == ["b", "d"] + assert [job.job_id for job in items[: 2**100 : 2**100]] == ["b"] + with pytest.raises(IndexError): + _ = items[3] + assert [job.job_id for job in items] == ["b", "c", "d"] + assert len(items) == 0 + assert not items + assert len(requests) == 3 + + +@pytest.mark.asyncio +async def test_listing_invalid_slice_does_not_fetch(listing_server): + endpoint, requests, _ = listing_server + db = await connection(endpoint, False) + items = db.list_jobs() + with pytest.raises(ValueError, match="step"): + _ = items[::0] + with pytest.raises(TypeError): + _ = items["invalid"] + with pytest.raises(TypeError): + _ = items[:1.5] + assert requests == [] + + +@pytest.mark.asyncio +async def test_listing_slice_failure_preserves_cache_and_retry_token(listing_server): + endpoint, requests, responses = listing_server + responses.extend([(200, response_page("jobs", ["a", "b"], "retry")), (401, {})]) + db = await connection(endpoint, False) + items = db.list_jobs(page_limit=2) + with pytest.raises(HttpError): + _ = items[:3] + assert items.page_token() == "retry" + assert items.num_page_results() == 2 + assert [job.job_id for job in items[:2]] == ["a", "b"] + assert [job.job_id for job in items] == ["a", "b"] + assert len(requests) == 2 diff --git a/python/src/connection.rs b/python/src/connection.rs index 1a171032c..2d65a0459 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -23,7 +23,7 @@ use lancedb::{ connection::Connection as LanceConnection, connection::NamespaceClientPushdownOperation, database::namespace::LanceNamespaceDatabase, - database::{CreateTableMode, Database, ReadConsistency}, + database::{CreateTableMode, Database, JobListFilter, JobListState, ReadConsistency}, function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, materialized_view::CreateMaterializedViewBuilder, @@ -1319,15 +1319,47 @@ impl Connection { )) } - #[pyo3(signature = (*, page_token=None, page_limit=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (*, page_token=None, page_limit=None, table=None, namespace_path=None, state=None, job_type=None, job_types=None, created_at_gte_millis=None, created_at_lt_millis=None))] pub fn list_jobs( &self, page_token: Option, page_limit: Option, + table: Option, + namespace_path: Option>, + state: Option, + job_type: Option, + job_types: Option>, + created_at_gte_millis: Option, + created_at_lt_millis: Option, ) -> PyResult { + if job_type.is_some() && job_types.is_some() { + return Err(PyValueError::new_err( + "set only one of job_type and job_types", + )); + } + let mut filter = JobListFilter::default(); + filter.table = table; + filter.namespace_path = namespace_path.unwrap_or_default(); + filter.state = state + .as_deref() + .map(|state| match state { + "in_progress" => Ok(JobListState::InProgress), + "succeeded" => Ok(JobListState::Succeeded), + "failed" => Ok(JobListState::Failed), + "canceled" => Ok(JobListState::Canceled), + "timed_out" => Ok(JobListState::TimedOut), + _ => Err(PyValueError::new_err( + "state must be one of: in_progress, succeeded, failed, canceled, timed_out", + )), + }) + .transpose()?; + filter.job_types = job_types.unwrap_or_else(|| job_type.into_iter().collect()); + filter.created_at_gte_millis = created_at_gte_millis; + filter.created_at_lt_millis = created_at_lt_millis; Ok(crate::listing::JobListing::new( self.get_inner()? - .list_jobs(crate::listing::options(page_token, page_limit)), + .list_jobs_filtered(filter, crate::listing::options(page_token, page_limit)), )) } diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 6dacbbbea..29f70d164 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -23,8 +23,8 @@ use crate::connection::create_table::CreateTableBuilder; use crate::data::scannable::Scannable; use crate::database::listing::ListingDatabase; use crate::database::{ - CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, OpenTableRequest, - PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest, + CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, JobListFilter, + OpenTableRequest, PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest, }; use crate::embeddings::{EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; @@ -1366,6 +1366,37 @@ impl Connection { }) } + /// List jobs using server-side filters, without scanning all history in the client. + /// + /// Filters are preserved on every page, including when resuming with a saved + /// token. Requests and errors occur during iteration, as with [`Self::list_jobs`]. + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// use lancedb::{database::JobListFilter, listing::ListingOptions}; + /// let mut filter = JobListFilter::default(); + /// filter.table = Some("events".into()); + /// let mut jobs = connection.list_jobs_filtered(filter, ListingOptions::default().page_limit(5)); + /// if let Some(job) = jobs.try_next().await? { + /// println!("{}", job.job_id); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn list_jobs_filtered( + &self, + filter: JobListFilter, + options: ListingOptions, + ) -> Listing { + let database = self.database().clone(); + Listing::new(options, move |options| { + let database = database.clone(); + let filter = filter.clone(); + async move { database.list_jobs_filtered(filter, options).await } + }) + } + /// Request cancellation of a server-side job by id. Returns true if the /// server accepted the cancellation, false if no such job exists. pub async fn cancel_job(&self, job_id: impl AsRef) -> Result { diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 638ae0dd5..8a7a941f6 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -238,6 +238,45 @@ pub enum ReadConsistency { Strong, } +/// Registry lifecycle states accepted when filtering jobs. +#[derive(Clone, Copy, Debug, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum JobListState { + /// A job that has not reached a terminal state. + InProgress, + /// A job that completed successfully. + Succeeded, + /// A job that failed. + Failed, + /// A job that was canceled. + Canceled, + /// A job that exceeded its timeout. + TimedOut, +} + +/// Server-side filters applied before job pagination. +/// +/// Continuation tokens must be resumed with the same filters. Creation times +/// are Unix timestamps in milliseconds; the lower bound is inclusive and the +/// upper bound is exclusive. +#[derive(Clone, Debug, Default)] +#[non_exhaustive] +pub struct JobListFilter { + /// Table name within `namespace_path`, including all its branches; absent means all tables. + pub table: Option, + /// Namespace of `table`; requires a table name. + pub namespace_path: Vec, + /// Registry state, such as `in_progress`, `succeeded`, or `failed`. + /// These are server states, rather than the labels in [`JobInfo::state`]. + pub state: Option, + /// Include jobs of any of these types; empty means all types. + pub job_types: Vec, + /// Inclusive creation-time lower bound. + pub created_at_gte_millis: Option, + /// Exclusive creation-time upper bound. + pub created_at_lt_millis: Option, +} + /// A row from [`Database::list_jobs`]: one server-side job (index build, /// compaction, column refresh, ...). #[derive(Debug, Clone)] @@ -781,6 +820,14 @@ pub trait Database: async fn list_jobs(&self, _options: ListingOptions) -> Result> { job_op_not_supported("list_jobs") } + /// Fetch one page of jobs matching server-side filters. + async fn list_jobs_filtered( + &self, + _filter: JobListFilter, + _options: ListingOptions, + ) -> Result> { + job_op_not_supported("list_jobs_filtered") + } /// Request cancellation of a job by id. Returns true if the server /// accepted the cancellation, false if no such job exists. Cancelling an /// already-terminal job is a no-op success. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 1a825bebc..125930cb7 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -22,7 +22,8 @@ use lance_namespace::models::{ use crate::Error; use crate::database::{ CloneTableRequest, CreateTableMode, CreateTableRequest, Database, DatabaseOptions, - ExecuteQueryRequest, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest, + ExecuteQueryRequest, JobInfo, JobListFilter, OpenTableRequest, ReadConsistency, + TableNamesRequest, }; use crate::error::Result; use crate::function::{FunctionRegistrationRequest, FunctionVersion, GpuClass}; @@ -1290,7 +1291,54 @@ impl Database for RemoteDatabase { } async fn list_jobs(&self, options: ListingOptions) -> Result> { - let mut body = serde_json::json!({}); + self.list_jobs_filtered(JobListFilter::default(), options) + .await + } + + async fn list_jobs_filtered( + &self, + filter: JobListFilter, + options: ListingOptions, + ) -> Result> { + if self.db_name.is_empty() { + return Err(Error::InvalidInput { + message: "list_jobs requires a connected database".into(), + }); + } + if filter.table.is_none() && !filter.namespace_path.is_empty() { + return Err(Error::InvalidInput { + message: "namespace_path requires a table filter".into(), + }); + } + if let (Some(start), Some(end)) = + (filter.created_at_gte_millis, filter.created_at_lt_millis) + && start >= end + { + return Err(Error::InvalidInput { + message: "created_at_gte_millis must be less than created_at_lt_millis".into(), + }); + } + let mut body = serde_json::json!({"database": self.db_name}); + if let Some(table) = filter.table { + validate_table_name(&table)?; + validate_namespace(&filter.namespace_path)?; + body["table_ref"] = serde_json::json!({ + "db_name": self.db_name, + "table_id": {"namespace_path": filter.namespace_path, "table_name": table}, + }); + } + if let Some(state) = filter.state { + body["state"] = serde_json::json!(state); + } + if !filter.job_types.is_empty() { + body["job_types"] = serde_json::json!(filter.job_types); + } + if let Some(start) = filter.created_at_gte_millis { + body["created_at_gte_millis"] = start.into(); + } + if let Some(end) = filter.created_at_lt_millis { + body["created_at_lt_millis"] = end.into(); + } if let Some(token) = options.page_token { body["page_token"] = token.into(); } @@ -1999,7 +2047,7 @@ mod tests { use rstest::rstest; use crate::connection::ConnectBuilder; - use crate::database::Database; + use crate::database::{Database, JobListFilter, JobListState}; use crate::error::{JobFailure, RemoteErrorMetadata, RemoteResourceIdentity}; use crate::graph::{EdgeTable, Endpoint, NodeTable, PropertyGraphDefinition}; use crate::materialized_view::CreateMaterializedViewRequest; @@ -4133,7 +4181,10 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) .unwrap(); - assert_eq!(body, serde_json::json!({"page_token": token, "limit": 2})); + assert_eq!( + body, + serde_json::json!({"database": "default", "page_token": token, "limit": 2}) + ); } else { let ns = "team"; assert_eq!( @@ -4336,6 +4387,84 @@ mod tests { )); } + #[tokio::test] + async fn test_list_jobs_filters_every_page_without_eager_fetching() { + let count = Arc::new(AtomicUsize::new(0)); + let seen = count.clone(); + let conn = Connection::new_with_handler(move |request| { + let page = seen.fetch_add(1, Ordering::SeqCst); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + let mut expected = serde_json::json!({ + "database": "default", + "table_ref": { + "db_name": "default", + "table_id": {"namespace_path": ["team", "project"], "table_name": "events"}, + }, + "state": "in_progress", + "job_types": ["column_refresh", "materialized_view_refresh"], + "created_at_gte_millis": 100, + "created_at_lt_millis": 200, + "limit": 1, + }); + if page > 0 { + expected["page_token"] = "next".into(); + } + assert_eq!(body, expected); + http::Response::builder().status(200).body(serde_json::json!({ + "jobs": [{"job_id": format!("job-{page}"), "table": "events", "job_type": "column_refresh", "state": "in_progress", "created_at_millis": 100}], + "page_token": (page == 0).then_some("next"), + }).to_string()).unwrap() + }); + let filter = JobListFilter { + table: Some("events".into()), + namespace_path: vec!["team".into(), "project".into()], + state: Some(JobListState::InProgress), + job_types: vec!["column_refresh".into(), "materialized_view_refresh".into()], + created_at_gte_millis: Some(100), + created_at_lt_millis: Some(200), + }; + let mut jobs = + conn.list_jobs_filtered(filter.clone(), ListingOptions::default().page_limit(1)); + assert_eq!(count.load(Ordering::SeqCst), 0); + assert_eq!(jobs.try_next().await.unwrap().unwrap().job_id, "job-0"); + assert_eq!(count.load(Ordering::SeqCst), 1); + let resumed = conn.list_jobs_filtered( + filter, + ListingOptions::default() + .page_limit(1) + .page_token(jobs.page_token().unwrap()), + ); + let remaining = resumed.try_collect::>().await.unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].job_id, "job-1"); + assert_eq!(count.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_list_jobs_invalid_filters_never_reach_server() { + let conn = Connection::new_with_handler(|_| -> http::Response { + panic!("invalid filters must not reach the server") + }); + let namespace_only = JobListFilter { + namespace_path: vec!["team".into()], + ..Default::default() + }; + let invalid_time = JobListFilter { + created_at_gte_millis: Some(200), + created_at_lt_millis: Some(100), + ..Default::default() + }; + for filter in [namespace_only, invalid_time] { + let mut jobs = conn.list_jobs_filtered(filter, ListingOptions::default()); + assert!(matches!( + jobs.try_next().await, + Err(Error::InvalidInput { .. }) + )); + assert!(jobs.try_next().await.unwrap().is_none()); + } + } + #[tokio::test] async fn test_list_jobs_does_not_truncate_after_100_pages() { let conn = Connection::new_with_handler(|request| { From 1feec84d2bb8166919a9c52640a7ad64d6f6e0e2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 15 Nov 2026 01:21:28 -0800 Subject: [PATCH 69/75] feat(python): expose FTS operators and match counts (#5042) String full-text searches now accept `operator="AND"` or `operator="OR"`, preserving the existing OR default. Sync and async FTS builders expose `count_rows()` to count every match satisfying the filter, independently of pagination, projection, ordering, and reranking. Counting streams matching scores without reading document columns; it can scan all matches. ```python query = table.search("gripper closed", query_type="fts", operator="AND") query = query.where("active = true") matching_rows = query.count_rows() page = query.limit(20).to_list() query = await async_table.search("gripper closed", query_type="fts", operator="AND") matching_rows = await query.where("active = true").count_rows() ``` Phrase searches keep the existing index default and now explain how to rebuild an index with `FTS(with_position=True)`. AND requests retain their operator through namespace pushdown and fail explicitly on older remote servers that cannot represent it. Regression coverage includes indexed and unindexed queries, filtered counts above the default limit, pagination preservation, remote serialization, and phrase indexes with and without positions. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/namespace.py | 25 ++++ python/python/lancedb/query.py | 127 ++++++++++++++++-- python/python/lancedb/remote/table.py | 8 ++ python/python/lancedb/table.py | 59 ++++++++- python/python/tests/test_fts.py | 184 ++++++++++++++++++++++++-- python/python/tests/test_namespace.py | 42 +++++- python/python/tests/test_remote_db.py | 43 ++++++ python/src/query.rs | 37 +++++- rust/lancedb/src/remote/table.rs | 16 ++- rust/lancedb/src/table/query.rs | 118 ++++++++++++----- 11 files changed, 599 insertions(+), 61 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 0cce2085e..63d442703 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -943,6 +943,7 @@ class FTSQuery: def add_query_vector(self, query_vec: pa.Array) -> None: ... def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ... def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... + async def count_rows(self) -> int: ... async def output_schema(self) -> pa.Schema: ... async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 67fcc61f7..463536619 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -10,6 +10,7 @@ through a namespace abstraction. from __future__ import annotations +import json import sys import warnings from typing import Any, Dict, Iterable, List, Optional, Union @@ -39,6 +40,9 @@ from lance_namespace_urllib3_client.models.query_table_request_vector import ( QueryTableRequestVector, ) from lance_namespace_urllib3_client.models.string_fts_query import StringFtsQuery +from lance_namespace_urllib3_client.models.structured_fts_query import ( + StructuredFtsQuery, +) from lance_namespace.errors import ( NamespaceNotEmptyError, NamespaceNotFoundError, @@ -78,6 +82,7 @@ from lancedb.materialized_view import ( SelectArg, ) from lancedb.table import AsyncTable, LanceTable, Table +from lancedb.query import MatchQuery, MultiMatchQuery, PhraseQuery from lancedb.util import validate_table_name from lancedb.common import DATA from lancedb.pydantic import LanceModel @@ -178,6 +183,26 @@ def _query_to_namespace_request( full_text_query_request = QueryTableRequestFullTextQuery( string_query=StringFtsQuery(query=fts_query) ) + elif getattr(fts_query, "operator", None) is not None: + columns = fts_query.columns or [] + text = fts_query.query + if len(text) >= 2 and text.startswith('"') and text.endswith('"'): + if len(columns) > 1: + raise ValueError( + "Phrase queries cannot be used with multiple columns." + ) + structured = PhraseQuery(text[1:-1], columns[0] if columns else None) + elif len(columns) > 1: + structured = MultiMatchQuery(text, columns, operator=fts_query.operator) + else: + structured = MatchQuery( + text, columns[0] if columns else None, operator=fts_query.operator + ) + full_text_query_request = QueryTableRequestFullTextQuery( + structured_query=StructuredFtsQuery.from_dict( + {"query": json.loads(structured.to_json())} + ) + ) elif hasattr(fts_query, "query"): full_text_query_request = QueryTableRequestFullTextQuery( string_query=StringFtsQuery( diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index f99aaeb73..214d2255f 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -42,7 +42,7 @@ from .rerankers.base import Reranker from .rerankers.rrf import RRFReranker from .rerankers.util import check_reranker_result from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field -from .util import _validate_query_vector, flatten_columns, get_uri_scheme +from .util import _validate_query_vector, add_note, flatten_columns, get_uri_scheme from . import _wal_hybrid # WAL-PK-FUSION: delete. from ._blob import ( BLOB_MODE_TO_HANDLING, @@ -873,10 +873,29 @@ class FullTextSearchQuery(pydantic.BaseModel): query: str | FullTextQuery If a string, it is treated as a MatchQuery. If a FullTextQuery object, it is used directly. + operator: FullTextOperator, optional + Combine terms in a string query using AND or OR (the default). + Quoted strings keep phrase semantics regardless of the operator. """ columns: Optional[List[str]] = None query: Union[str, FullTextQuery] + operator: Optional[FullTextOperator] = None + + @pydantic.model_validator(mode="after") + def _validate_operator(self) -> Self: + if self.operator is not None and not isinstance(self.query, str): + raise ValueError("operator requires a string full-text query") + return self + + +def _add_fts_position_error_note(error: Exception) -> None: + if "position is not found but required for phrase queries" in str(error): + add_note( + error, + "Phrase queries require an index built with positions. Rebuild it with " + "table.create_index(column, config=FTS(with_position=True), replace=True).", + ) class Query(pydantic.BaseModel): @@ -1147,6 +1166,7 @@ class LanceQueryBuilder(ABC): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: bool = None, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> Self: """ Create a query builder based on the given query and query type. @@ -1171,6 +1191,10 @@ class LanceQueryBuilder(ABC): fast_search: bool Skip flat search of unindexed data. """ + if operator is not None: + operator = FullTextOperator(operator) + if not isinstance(query, str) or query_type not in ("auto", "fts"): + raise ValueError("operator requires a string full-text query") if query_type != "fts": _validate_query_vector(query) @@ -1201,6 +1225,9 @@ class LanceQueryBuilder(ABC): table, query, query_type, vector_column_name ) + if operator is not None and query_type != "fts": + raise ValueError("operator requires a string full-text query") + if query_type == "hybrid": return LanceHybridQueryBuilder( table, query, vector_column_name, fts_columns=fts_columns @@ -1214,7 +1241,7 @@ class LanceQueryBuilder(ABC): ordering_field_name=ordering_field_name, fts_columns=fts_columns, fast_search=fast_search, - ) + ).operator(operator) if isinstance(query, (list, tuple)): query = np.array(query, dtype=np.float32) @@ -2563,6 +2590,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): super().__init__(table) self._query = query self._phrase_query = False + self._operator: Optional[FullTextOperator] = None # Deprecated compatibility parameter. Native FTS ordering is now # configured through order_by(); LanceQueryBuilder.create emits the warning. _ = ordering_field_name @@ -2572,6 +2600,36 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): fts_columns = [fts_columns] self._fts_columns = fts_columns + def operator( + self, operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] + ) -> LanceFtsQueryBuilder: + """Combine terms in a string query with ``"AND"`` or ``"OR"``. + + The default is OR. AND requires every term to match. For example, + ``table.search("gripper closed", query_type="fts").operator("AND")``. + Structured queries specify their own operators. Quoted strings and + ``phrase_query()`` retain their phrase semantics. + """ + if operator is not None and not isinstance(self._query, str): + raise ValueError("operator requires a string full-text query") + self._operator = FullTextOperator(operator) if operator is not None else None + return self + + def count_rows(self) -> int: + """Count all full-text matches satisfying the query's filter. + + Ignores limit, offset, selection, ordering, and reranking. ``fast_search`` + still restricts the count to indexed data. This streams matching scores + without loading document columns and may scan every match. + + For example, ``table.search("gripper closed", query_type="fts",`` + ``operator="AND").where("active = true").count_rows()``. + """ + self._table._ensure_no_legacy_fts_index() + query = self._table._table._sync_query_to_async(self.to_query_object()) + assert isinstance(query, AsyncFTSQuery) + return LOOP.run(query.count_rows()) + def phrase_query(self, phrase_query: bool = True) -> LanceFtsQueryBuilder: """Set whether to use phrase query. @@ -2628,7 +2686,9 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): fragment_ids=self._fragment_ids, use_rte=self._use_rte, full_text_query=FullTextSearchQuery( - query=self._query_with_phrase_semantics(), columns=self._fts_columns + query=self._query_with_phrase_semantics(), + columns=self._fts_columns, + operator=self._operator, ), offset=self._offset, fast_search=self._fast_search, @@ -4443,7 +4503,11 @@ class AsyncQuery(AsyncStandardQuery): ) def nearest_to_text( - self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None + self, + query: str | FullTextQuery, + columns: Union[str, List[str], None] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncFTSQuery: """ Find the documents that are most relevant to the given text query. @@ -4464,7 +4528,11 @@ class AsyncQuery(AsyncStandardQuery): columns: str or list of str, default None The columns to search in. If None, all indexed columns are searched. For now only one column can be searched at a time. + operator: "AND" or "OR", optional + Combine terms in a string query. Defaults to OR. Quoted strings use + phrase semantics and require an index built with positions. """ + fts_query = FullTextSearchQuery(query=query, operator=operator) if isinstance(columns, str): columns = [columns] if columns is None: @@ -4472,7 +4540,13 @@ class AsyncQuery(AsyncStandardQuery): if isinstance(query, str): return AsyncFTSQuery( - self._inner.nearest_to_text({"query": query, "columns": columns}), + self._inner.nearest_to_text( + { + "query": query, + "columns": columns, + "operator": fts_query.operator, + } + ), self._table, ) # FullTextQuery object @@ -4487,6 +4561,22 @@ class AsyncFTSQuery(AsyncStandardQuery): self._inner = inner self._reranker = None + async def count_rows(self) -> int: + """Count all full-text matches satisfying the query's filter. + + Ignores limit, offset, selection, ordering, and reranking. ``fast_search`` + still restricts the count to indexed data. Matching scores are streamed + without loading document columns, so counting may scan every match. + + For example, ``await table.query().nearest_to_text("gripper closed",`` + ``operator="AND").where("active = true").count_rows()``. + """ + try: + return await self._inner.count_rows() + except Exception as error: + _add_fts_position_error_note(error) + raise + def get_query(self) -> str: return self._inner.get_query() @@ -4580,10 +4670,16 @@ class AsyncFTSQuery(AsyncStandardQuery): timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: - reader = await super()._execute_batches( - timeout=timeout, blob_sources=blob_sources - ) - results = pa.Table.from_batches(await reader.read_all(), reader.schema) + try: + reader = await super()._execute_batches( + max_batch_length=max_batch_length, + timeout=timeout, + blob_sources=blob_sources, + ) + results = pa.Table.from_batches(await reader.read_all(), reader.schema) + except Exception as error: + _add_fts_position_error_note(error) + raise if self._reranker: source = results results = self._reranker.rerank_fts(self.get_query(), results) @@ -4861,7 +4957,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): return self def nearest_to_text( - self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None + self, + query: str | FullTextQuery, + columns: Union[str, List[str], None] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncHybridQuery: """ Find the documents that are most relevant to the given text query, @@ -4886,7 +4986,10 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): columns: str or list of str, default None The columns to search in. If None, all indexed columns are searched. For now only one column can be searched at a time. + operator: "AND" or "OR", optional + Combine terms in a string query. Defaults to OR. """ + fts_query = FullTextSearchQuery(query=query, operator=operator) if isinstance(columns, str): columns = [columns] if columns is None: @@ -4894,7 +4997,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): if isinstance(query, str): return AsyncHybridQuery( - self._inner.nearest_to_text({"query": query, "columns": columns}), + self._inner.nearest_to_text( + {"query": query, "columns": columns, "operator": fts_query.operator} + ), self._table, ) # FullTextQuery object diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 818d2a257..2d068536e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -65,6 +65,7 @@ from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.table import _normalize_progress from ..query import ( + FullTextOperator, AnalyzePlanDistributedMetrics, DocumentGranularity, FullTextQuery, @@ -799,6 +800,8 @@ class RemoteTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support @@ -857,6 +860,10 @@ class RemoteTable(Table): - *default None*, which leaves fast search disabled. + operator: "AND" or "OR", optional + Combine terms in a string full-text query; the default is OR. + Use ``query_type="fts"`` when the table also has embeddings. + Returns ------- LanceQueryBuilder @@ -893,6 +900,7 @@ class RemoteTable(Table): ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], fast_search=fast_search, + operator=operator, ) def _execute_query( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 4a713da06..807edbc46 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -91,6 +91,7 @@ from .functions import ( from .merge import LanceMergeInsertBuilder from .pydantic import LanceModel, model_to_dict from .query import ( + FullTextOperator, AnalyzePlanDistributedMetrics, AsyncFTSQuery, AsyncHybridQuery, @@ -138,6 +139,11 @@ def _requires_local_namespace_execution(query: Query) -> bool: or query.take_row_ids is not None or query.search_effort is not None or query.approx_mode is not None + or ( + query.full_text_query is not None + and query.fast_search is True + and query.vector is None + ) ) @@ -2443,6 +2449,8 @@ class Table(ABC): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -2506,6 +2514,10 @@ class Table(ABC): - If `query` is a string, then the query type is "vector" if the table has embedding functions else the query type is "fts" + operator: "AND" or "OR", optional + Combine terms in a string full-text query; the default is OR. + Use ``query_type="fts"`` when the table also has embeddings. + Returns ------- LanceQueryBuilder @@ -5061,6 +5073,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceVectorQueryBuilder: ... @overload @@ -5072,6 +5086,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceFtsQueryBuilder: ... @overload @@ -5085,6 +5101,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceHybridQueryBuilder: ... @overload @@ -5096,6 +5114,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceEmptyQueryBuilder: ... def search( @@ -5108,6 +5128,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -5168,6 +5190,10 @@ class LanceTable(Table): If None then the search is performed on all indexed columns. For now, only one column can be searched at a time. + operator: "AND" or "OR", optional + Combine terms in a string full-text query; the default is OR. + Use ``query_type="fts"`` when the table also has embeddings. + Returns ------- LanceQueryBuilder @@ -5193,6 +5219,7 @@ class LanceTable(Table): ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], fast_search=fast_search, + operator=operator, ) @classmethod @@ -7376,6 +7403,8 @@ class AsyncTable: query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncQuery: ... @overload @@ -7386,6 +7415,8 @@ class AsyncTable: query_type: Literal["auto"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> Union[AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]: ... @overload @@ -7396,6 +7427,8 @@ class AsyncTable: query_type: Literal["hybrid"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncHybridQuery: ... @overload @@ -7406,6 +7439,8 @@ class AsyncTable: query_type: Literal["auto"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncVectorQuery: ... @overload @@ -7416,6 +7451,8 @@ class AsyncTable: query_type: Literal["fts"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncFTSQuery: ... @overload @@ -7426,6 +7463,8 @@ class AsyncTable: query_type: Literal["vector"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncVectorQuery: ... async def search( @@ -7437,6 +7476,8 @@ class AsyncTable: query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> Union[AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -7480,12 +7521,20 @@ class AsyncTable: - If `query` is a string, then the query type is "vector" if the table has embedding functions else the query type is "fts" + operator: "AND" or "OR", optional + Combine terms in a string full-text query; the default is OR. + Use ``query_type="fts"`` when the table also has embeddings. + Returns ------- AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, or AsyncVectorQuery A query builder object representing the query. """ + if operator is not None: + operator = FullTextOperator(operator) + if not isinstance(query, str) or query_type not in ("auto", "fts"): + raise ValueError("operator requires a string full-text query") if query is None: return self.query() @@ -7604,13 +7653,17 @@ class AsyncTable: ) vector_query = await make_embedding(embedding_conf, query) + if operator is not None and query_type != "fts": + raise ValueError("operator requires a string full-text query") if query_type == "vector": builder = self.query().nearest_to(vector_query) if vector_column_name: builder = builder.column(vector_column_name) return builder elif query_type == "fts": - return self.query().nearest_to_text(query, columns=fts_columns) + return self.query().nearest_to_text( + query, columns=fts_columns, operator=operator + ) elif query_type == "hybrid": builder = self.query().nearest_to(vector_query) if vector_column_name: @@ -7720,7 +7773,9 @@ class AsyncTable: if query.full_text_query: async_query = async_query.nearest_to_text( - query.full_text_query.query, query.full_text_query.columns + query.full_text_query.query, + query.full_text_query.columns, + operator=query.full_text_query.operator, ) return async_query diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index f2fcc970b..26ce5e528 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -29,6 +29,7 @@ from lancedb.query import ( CombinedFieldsQuery, DocumentGranularity, FullTextOperator, + FullTextSearchQuery, MatchQuery, MultiMatchQuery, PhraseQuery, @@ -530,11 +531,9 @@ async def test_fts_select_async(async_table): def test_search_fts_phrase_query(table): table.create_fts_index("text", with_position=False) - try: - phrase_results = table.search('"puppy runs"').limit(100).to_list() - assert False - except Exception: - pass + with pytest.raises(Exception) as error: + table.search('"puppy runs"').limit(100).to_list() + assert "FTS(with_position=True)" in exception_output(error) table.create_fts_index("text", with_position=True, replace=True) results = table.search("puppy").limit(100).to_list() @@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table): @pytest.mark.asyncio async def test_search_fts_phrase_query_async(async_table): await async_table.create_index("text", config=FTS(with_position=False)) - try: - phrase_results = ( - await async_table.query().nearest_to_text("puppy runs").limit(100).to_list() - ) - assert False - except Exception: - pass + with pytest.raises(Exception) as error: + await async_table.query().nearest_to_text('"puppy runs"').to_list() + assert "FTS(with_position=True)" in exception_output(error) await async_table.create_index("text", config=FTS(with_position=True)) results = await async_table.query().nearest_to_text("puppy").limit(100).to_list() phrase_results = ( @@ -1948,3 +1943,168 @@ async def test_async_fts_code_analyzer(mem_db_async): rows = await table.query().nearest_to_text("http").to_list() assert len(rows) == 1 + + +@pytest.mark.parametrize("indexed", [False, True]) +@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)]) +def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected): + db = ldb.connect(tmp_path) + table = db.create_table( + "matches", + pa.table( + { + "id": list(range(30)), + "text": ["gripper closed"] * 15 + + ["gripper open"] * 10 + + ["camera ready"] * 5, + } + ), + ) + if indexed: + table.create_index("text", config=FTS()) + kwargs = {"fts_columns": "text"} + if operator is not None: + kwargs["operator"] = operator + query = table.search("gripper closed", query_type="fts", **kwargs) + assert query.count_rows() == expected + assert len(query.limit(100).to_list()) == expected + assert ( + table.search("gripper closed", query_type="fts", fts_columns="text") + .operator("AND") + .count_rows() + == 15 + ) + if operator is not None: + assert query.to_query_object().full_text_query.operator == operator + query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1) + before = query.to_query_object() + assert query.count_rows() == expected - 5 + assert query.to_query_object() == before + assert len(query.to_list()) <= 2 + assert ( + table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0 + ) + assert ( + table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows() + == 15 + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("indexed", [False, True]) +@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)]) +async def test_simple_fts_operator_and_count_async( + tmp_path, indexed, operator, expected +): + db = await ldb.connect_async(tmp_path) + table = await db.create_table( + "matches", + pa.table( + { + "id": list(range(30)), + "text": ["gripper closed"] * 15 + + ["gripper open"] * 10 + + ["camera ready"] * 5, + } + ), + ) + if indexed: + await table.create_index("text", config=FTS()) + query = await table.search( + "gripper closed", query_type="fts", fts_columns="text", operator=operator + ) + assert await query.count_rows() == expected + assert len(await query.limit(100).to_list()) == expected + query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1) + before = query.to_query_object() + assert await query.count_rows() == expected - 5 + assert query.to_query_object() == before + direct = table.query().nearest_to_text( + "gripper closed", columns="text", operator="AND" + ) + assert await direct.count_rows() == 15 + assert direct.to_query_object().full_text_query.query.operator == "AND" + assert ( + await table.query().nearest_to_text("absent", columns="text").count_rows() == 0 + ) + + +@pytest.mark.parametrize("with_position", [False, True]) +@pytest.mark.parametrize( + "query", ['"gripper closed"', PhraseQuery("gripper closed", "text")] +) +def test_fts_phrase_count_positions(tmp_path, with_position, query): + table = ldb.connect(tmp_path).create_table( + "phrases", pa.table({"text": ["gripper closed", "gripper often closed"]}) + ) + table.create_index("text", config=FTS(with_position=with_position)) + search = table.search(query, query_type="fts") + if with_position: + assert search.count_rows() == 1 + assert len(search.to_list()) == 1 + assert ( + table.search("gripper closed", query_type="fts", operator="AND") + .phrase_query() + .count_rows() + == 1 + ) + else: + with pytest.raises(Exception) as error: + search.count_rows() + assert "FTS(with_position=True)" in exception_output(error) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("with_position", [False, True]) +@pytest.mark.parametrize( + "query", ['"gripper closed"', PhraseQuery("gripper closed", "text")] +) +async def test_fts_phrase_count_positions_async(tmp_path, with_position, query): + db = await ldb.connect_async(tmp_path) + table = await db.create_table( + "phrases", pa.table({"text": ["gripper closed", "gripper often closed"]}) + ) + await table.create_index("text", config=FTS(with_position=with_position)) + search = table.query().nearest_to_text(query) + if with_position: + assert await search.count_rows() == 1 + assert len(await search.to_list()) == 1 + else: + with pytest.raises(Exception) as error: + await search.count_rows() + assert "FTS(with_position=True)" in exception_output(error) + + +def test_fts_operator_rejects_invalid_queries(table): + with pytest.raises(ValueError): + table.search("gripper", query_type="fts", operator="XOR") + for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]: + with pytest.raises( + ValueError, match="operator requires a string full-text query" + ): + table.search(query, operator="AND") + with pytest.raises(ValueError, match="operator requires a string full-text query"): + FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND") + + +@pytest.mark.asyncio +async def test_fts_operator_rejects_invalid_queries_async(async_table): + with pytest.raises(ValueError): + await async_table.search("gripper", query_type="fts", operator="XOR") + for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]: + with pytest.raises( + ValueError, match="operator requires a string full-text query" + ): + await async_table.search(query, operator="AND") + with pytest.raises(ValueError): + async_table.query().nearest_to_text(query, operator="AND") + + +def test_fts_count_fast_search(tmp_path): + table = ldb.connect(tmp_path).create_table( + "matches", pa.table({"text": ["gripper closed"] * 15}) + ) + table.create_index("text", config=FTS()) + table.add(pa.table({"text": ["gripper closed"] * 5})) + assert table.search("gripper", query_type="fts").count_rows() == 20 + assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15 diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 9bce1059d..b4ca746b0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -18,6 +18,7 @@ import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from utils import start_server_thread from lancedb.listing import AsyncListing, Listing +from lancedb.index import FTS from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY from lancedb.namespace import ( _MAX_QUERY_K, @@ -25,7 +26,7 @@ from lancedb.namespace import ( LanceNamespaceDBConnection, _query_to_namespace_request, ) -from lancedb.query import Query +from lancedb.query import FullTextSearchQuery, Query from lancedb.table import AsyncTable, LanceTable @@ -1524,3 +1525,42 @@ def test_python_namespace_attribute_access(tmp_path): # Missing dunder lookups still raise, so copy/hasattr probes work. assert not hasattr(request, "__missing_dunder__") assert copy.deepcopy(request) == request + + +@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]]) +def test_namespace_fts_operator_is_preserved(columns): + request = _query_to_namespace_request( + ["matches"], + Query( + full_text_query=FullTextSearchQuery( + query="gripper closed", columns=columns, operator="AND" + ) + ), + ) + structured = request.to_dict()["full_text_query"]["structured_query"]["query"] + if columns and len(columns) > 1: + assert all( + query["operator"] == "And" + for query in structured["multi_match"]["match_queries"] + ) + else: + assert structured["match"]["operator"] == "And" + assert structured["match"].get("column") == (columns[0] if columns else None) + + +def test_namespace_fts_count_fast_search(tmp_path): + properties = {"root": str(tmp_path)} + db = lancedb.connect_namespace("dir", properties) + table = db.create_table("matches", pa.table({"text": ["gripper"] * 15})) + table.create_index("text", config=FTS()) + table.add(pa.table({"text": ["gripper"] * 5})) + assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15 + pushed = lancedb.connect_namespace( + "dir", properties, namespace_client_pushdown_operations=["QueryTable"] + ).open_table("matches") + assert pushed.search("gripper", query_type="fts").count_rows() == 20 + query = pushed.search("gripper", query_type="fts").fast_search() + assert query.use_rte(False).count_rows() == 15 + query = pushed.search("gripper", query_type="fts").fast_search() + assert query.count_rows() == 15 + assert len(query.limit(100).to_list()) == 15 diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index f404e36f7..587e2d587 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -7802,3 +7802,46 @@ async def test_remote_index_exist_ok_wire(is_async, background, kwargs): assert body["replace"] is False else: assert "replace" not in body + + +@pytest.mark.parametrize("operator", ["AND", "OR"]) +def test_remote_fts_operator_and_count(operator): + def handler(body): + query = body["full_text_query"]["query"]["match"] + assert query["terms"] == "gripper closed" + assert query["operator"] == operator.title() + assert query["column"] == "text" + assert body["k"] == 2**63 - 1 + assert "offset" not in body + assert body["columns"] == ["_score"] + assert body["filter"] == "text IS NOT NULL" + assert body["prefilter"] is False + return pa.table({"_score": [1.0] * 25}) + + with query_test_table( + handler, server_version=Version("0.6.0"), vector_columns={} + ) as table: + query = ( + table.search( + "gripper closed", + query_type="fts", + fts_columns="text", + operator=operator, + ) + .where("text IS NOT NULL", prefilter=False) + .select(["text"]) + .limit(1) + .offset(3) + ) + assert query.count_rows() == 25 + assert query.to_query_object().limit == 1 + assert query.to_query_object().offset == 3 + + +def test_remote_fts_and_rejects_legacy_server(): + def handler(body): + pytest.fail("AND must not silently become OR on a legacy server") + + with query_test_table(handler, vector_columns={}) as table: + with pytest.raises(NotImplementedError, match="server version 0.3.0"): + table.search("gripper closed", query_type="fts", operator="AND").to_list() diff --git a/python/src/query.rs b/python/src/query.rs index 2097dac69..9864d7d74 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -16,19 +16,20 @@ use arrow::array::make_array; use arrow::pyarrow::FromPyArrow; use arrow::pyarrow::IntoPyArrow; use arrow::pyarrow::ToPyArrow; +use futures::TryStreamExt; use lancedb::ApproxMode; use lancedb::index::scalar::{ BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery, FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery, }; use lancedb::query::AnalyzePlanDistributedMetrics; -use lancedb::query::QueryBase; use lancedb::query::QueryExecutionOptions; use lancedb::query::QueryFilter; use lancedb::query::{ ColumnOrdering, ExecutableQuery, Query as LanceDbQuery, Select, TakeQuery as LanceDbTakeQuery, VectorQuery as LanceDbVectorQuery, }; +use lancedb::query::{HasQuery, QueryBase}; use lancedb::table::AnyQuery; use pyo3::Bound; use pyo3::IntoPyObject; @@ -616,8 +617,18 @@ impl Query { query_text = query_text[1..query_text.len() - 1].to_string(); } + let operator = query + .get_item("operator")? + .filter(|operator| !operator.is_none()) + .map(|operator| { + let operator = operator.extract::()?; + Operator::try_from(operator.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string())) + }) + .transpose()? + .unwrap_or(Operator::Or); let query: FtsQuery = match (is_phrase, is_multi_match) { - (false, _) => MatchQuery::new(query_text).into(), + (false, _) => MatchQuery::new(query_text).with_operator(operator).into(), (true, false) => PhraseQuery::new(query_text).into(), (true, true) => { return Err(PyValueError::new_err( @@ -898,6 +909,28 @@ impl FTSQuery { }) } + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { + let mut inner = self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()); + let request = inner.mut_query(); + request.limit = None; + request.offset = None; + request.select = Select::columns(&["_score"]); + request.order_by = None; + request.with_row_id = false; + request.reranker = None; + future_into_py(self_.py(), async move { + let mut stream = inner.execute().await.infer_error()?; + let mut count = 0_u64; + while let Some(batch) = stream.try_next().await.infer_error()? { + count += batch.num_rows() as u64; + } + Ok(count) + }) + } + pub fn nearest_to(&mut self, vector: Bound<'_, PyAny>) -> PyResult { let vector_query = Query::new(self.inner.clone()).nearest_to(vector)?; Ok(HybridQuery { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 2224203cf..1394f1ab0 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -20,7 +20,7 @@ use crate::error::{HttpErrorSource, RemoteErrorMetadata}; use crate::expr::expr_to_sql_string; use crate::index::Index; use crate::index::IndexStatistics; -use crate::index::scalar::FtsQuery; +use crate::index::scalar::{FtsQuery, Operator}; use crate::index::waiter::{MAX_WAIT, wait_for_index}; use crate::job::Job; use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult}; @@ -1374,6 +1374,20 @@ impl RemoteTable { "query": full_text_search.query.clone(), }); } else { + let has_and = match &full_text_search.query { + FtsQuery::Match(query) => query.operator == Operator::And, + FtsQuery::MultiMatch(query) => query + .match_queries + .iter() + .any(|query| query.operator == Operator::And), + _ => false, + }; + if has_and { + return Err(Error::NotSupported { + message: "AND full-text queries require server version 0.3.0 or later" + .into(), + }); + } body["full_text_query"] = serde_json::json!({ "columns": full_text_search.columns().into_iter().collect::>(), "query": full_text_search.query.query(), diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index e9bcd380d..7d98dc001 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -12,6 +12,7 @@ use super::NativeTable; use crate::connection::NamespaceClientPushdownOperation; use crate::error::{Error, Result}; use crate::expr::expr_to_sql_string; +use crate::index::scalar::{FtsQuery, Operator as FullTextOperator}; use crate::query::{ DEFAULT_TOP_K, QueryExecutionOptions, QueryFilter, QueryRequest, Select, VectorQueryRequest, }; @@ -36,12 +37,13 @@ use lance::io::exec::{ANNIvfBatchExec, ANNIvfSubIndexExec}; use lance_datafusion::exec::{analyze_plan as lance_analyze_plan, execute_plan}; use lance_index::IndexType; use lance_index::metrics::NoOpMetricsCollector; +use lance_index::scalar::FullTextSearchQuery; use lance_index::vector::DIST_COL; use lance_linalg::distance::DistanceType as LanceDistanceType; use lance_namespace::LanceNamespace; use lance_namespace::models::{ QueryTableRequest as NsQueryTableRequest, QueryTableRequestColumns, - QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, + QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, StructuredFtsQuery, }; #[derive(Debug, Clone)] @@ -124,6 +126,10 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { if query.base().use_rte.is_some() || query.base().has_take() { return true; } + if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some()) + { + return true; + } matches!( query, AnyQuery::VectorQuery(vector_query) @@ -858,6 +864,33 @@ async fn execute_namespace_query( parse_arrow_ipc_response(response_bytes).await } +fn namespace_fts_query(fts: &FullTextSearchQuery) -> Result> { + if !matches!(&fts.query, FtsQuery::Match(query) if query.operator == FullTextOperator::Or) { + let query = serde_json::to_value(&fts.query) + .and_then(serde_json::from_value) + .map_err(|error| Error::InvalidInput { + message: format!("Cannot serialize namespace full-text query: {error}"), + })?; + Ok(Box::new(QueryTableRequestFullTextQuery { + string_query: None, + structured_query: Some(Box::new(StructuredFtsQuery::new(query))), + })) + } else { + let columns = fts.columns(); + Ok(Box::new(QueryTableRequestFullTextQuery { + string_query: Some(Box::new(StringFtsQuery { + query: fts.query.query().clone(), + columns: if columns.is_empty() { + None + } else { + Some(columns.into_iter().collect()) + }, + })), + structured_query: None, + })) + } +} + /// Convert an AnyQuery to the namespace QueryTableRequest format. fn convert_to_namespace_query(query: &AnyQuery) -> Result { query.base().check_filter()?; @@ -912,21 +945,12 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { } // Convert FTS query if present - let full_text_query = vq.base.full_text_search.as_ref().map(|fts| { - let columns = fts.columns(); - let columns_vec = if columns.is_empty() { - None - } else { - Some(columns.into_iter().collect()) - }; - Box::new(QueryTableRequestFullTextQuery { - string_query: Some(Box::new(StringFtsQuery { - query: fts.query.to_string(), - columns: columns_vec, - })), - structured_query: None, - }) - }); + let full_text_query = vq + .base + .full_text_search + .as_ref() + .map(namespace_fts_query) + .transpose()?; Ok(NsQueryTableRequest { id: None, // Will be set in namespace_query @@ -963,7 +987,6 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { let k = match q.limit { Some(limit) => limit as i32, - None if q.full_text_search.is_some() => DEFAULT_TOP_K as i32, None => i32::MAX, }; @@ -995,20 +1018,11 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { }; // Handle full text search if present - let full_text_query = q.full_text_search.as_ref().map(|fts| { - let columns_vec = if fts.columns().is_empty() { - None - } else { - Some(fts.columns().iter().cloned().collect()) - }; - Box::new(QueryTableRequestFullTextQuery { - string_query: Some(Box::new(StringFtsQuery { - query: fts.query.to_string(), - columns: columns_vec, - })), - structured_query: None, - }) - }); + let full_text_query = q + .full_text_search + .as_ref() + .map(namespace_fts_query) + .transpose()?; // Empty vector for non-vector queries let vector = Box::new(QueryTableRequestVector { @@ -1023,6 +1037,7 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { filter, columns, prefilter: Some(q.prefilter), + fast_search: Some(q.fast_search), offset: q.offset.map(|o| o as i32), vector_column: None, // No vector column for plain queries with_row_id: Some(q.with_row_id), @@ -1147,6 +1162,7 @@ async fn parse_arrow_ipc_response(bytes: bytes::Bytes) -> Result Date: Sun, 15 Nov 2026 02:05:06 -0800 Subject: [PATCH 70/75] fix(python): show Function registration progress and image details (#5040) Report registration lifecycle and client elapsed time through existing job handles, and provide concise image inspection. Preserve quiet wait behavior, environment-lock forwarding, failure diagnostics and timeout recovery. --- docs/src/python/python.md | 19 ++ python/python/lancedb/db.py | 11 +- python/python/lancedb/functions.py | 59 +++++- python/python/lancedb/job.py | 75 ++++++- .../tests/test_first_class_function_slice1.py | 55 +++++ python/python/tests/test_job.py | 190 +++++++++++++++++- 6 files changed, 396 insertions(+), 13 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b7eb1704a..b0425e1f7 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -424,6 +424,25 @@ code that used the former LanceDB Enterprise-only argument order. ## Functions and Jobs +Use `progress=True` when waiting for Function registration in a notebook or +terminal. A callback receives structured snapshots instead: + +```python +fn = db.create_function(my_function, progress=True) +registration = db.create_function_async(other_function) +fn = registration.wait(progress=lambda snapshot: print(snapshot)) +print(fn.image.describe()) +``` + +Registration uses the existing SQL query handle. The current handle reports +lifecycle state and `client_elapsed_time_millis` since the handle was created; +detailed build phases and build logs are unavailable. Keep the same handle after +a wait timeout to resume waiting. Failures retain the server error and request +identifiers. `fn.image` has a concise representation; `describe()` exposes Python +and CUDA requirements without inspecting Pydantic internals. Platforms, base image +and size are `None` until the service reports them. The full image descriptor and +canonical JSON remain available. + A `@function` definition is also a local callable. Call a decorated function directly with row inputs, or call a decorated class with its initialization fields and then call the returned instance; call `close()` if the class defines it. This diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b225a6e65..8c9901aff 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1051,6 +1051,7 @@ class DBConnection(EnforceOverrides): exist_ok: bool = False, namespace_path: Optional[List[str]] = None, refresh_lock: bool = False, + progress: Any = False, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. @@ -1076,6 +1077,9 @@ class DBConnection(EnforceOverrides): refresh_lock : bool, default False Ask the server to resolve a fresh environment lock instead of reusing the published version's lock. + progress : bool, callable, or tqdm-like object, default False + Display lifecycle state and elapsed time, or receive structured + snapshots through a callback. See [Job.wait][lancedb.job.Job.wait]. When the registration job resolves, each resolved-environment warning reported by the server is emitted as a Python ``UserWarning``. Catalog @@ -1095,13 +1099,16 @@ class DBConnection(EnforceOverrides): ) ``` """ - return self.create_function_async( + job = self.create_function_async( definition, secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, refresh_lock=refresh_lock, - ).wait() + ) + if progress is False or progress is None: + return job.wait() + return job.wait(progress=progress) def create_function_async( self, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 548129211..f57a114dc 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -544,13 +544,70 @@ class PythonRuntimeSpec(_RemoteValue): class FunctionImage(_RemoteValue): - """A complete OCI Function image identified by its exact manifest digest.""" + """A complete OCI Function image identified by its exact manifest digest. + + ``describe()`` and the concise representation inspect the descriptor without + walking Pydantic model internals. Missing metadata is ``None`` (unknown). + The current service does not report image platforms, base image or byte size; + these cannot be inferred from the client's platform or the manifest digest. + The full descriptor remains available through ``descriptor``. + """ manifest_digest: str descriptor: Mapping[str, Any] source: bool models: tuple[HuggingFaceModel, ...] = () + def describe(self) -> dict[str, Any]: + """Return concise image details without fetching registry content. + + ``requires_gpu`` reflects a ``lance.cuda`` requirement in a v1 + descriptor, rather than promising compatibility with every GPU. + ``platforms``, ``base_image`` and ``size_bytes`` are unavailable from + the current wire contract and return ``None``. + + Examples + -------- + >>> print(fn.image.describe()) # doctest: +SKIP + """ + python = self.descriptor.get("python") + requires = self.descriptor.get("requires") + capabilities = ( + requires.get("capabilities") if isinstance(requires, Mapping) else None + ) + known_capabilities = ( + self.descriptor.get("format_version") == 1 + and isinstance(capabilities, (list, tuple)) + and all(isinstance(item, Mapping) for item in capabilities) + ) + cuda = ( + next( + (item for item in capabilities if item.get("type") == "lance.cuda"), + None, + ) + if known_capabilities + else None + ) + python_version = python.get("version") if isinstance(python, Mapping) else None + cuda_toolkit = cuda.get("cuda_toolkit") if cuda is not None else None + return { + "manifest_digest": self.manifest_digest, + "python_version": python_version + if isinstance(python_version, str) + else None, + "requires_gpu": cuda is not None if known_capabilities else None, + "cuda_toolkit": cuda_toolkit if isinstance(cuda_toolkit, str) else None, + "platforms": None, + "base_image": None, + "size_bytes": None, + } + + def __repr_args__(self): + for name, value in self.describe().items(): + if isinstance(value, str) and len(value) > 80: + value = value[:77] + "..." + yield name, value + class ResolvedPackage(_RemoteValue): """One installed Python distribution measured from a baked environment. diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 9195e01ae..e49609e1f 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -4,8 +4,10 @@ """Handles to asynchronous registry jobs, SQL queries, and local operations.""" import asyncio +import logging import reprlib import time +from contextlib import suppress from datetime import timedelta from os import PathLike from pathlib import Path @@ -53,11 +55,13 @@ def _timeout_message( ) -def _normalize_job_progress(progress): +def _normalize_job_progress(progress, *, query=False): """Normalize ``wait(progress=...)`` using the same convention as writes.""" if progress is True: from tqdm.auto import tqdm + if query: + return tqdm(bar_format="Query{postfix} [{elapsed}]"), True return tqdm(unit=" rows"), True if progress is False or progress is None: return None, False @@ -65,6 +69,7 @@ def _normalize_job_progress(progress): _ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000 +_QUERY_PROGRESS_INTERVAL_SECONDS = 1.0 def _progress_eta(previous, current): @@ -203,6 +208,7 @@ class AsyncJob(Generic[T]): self._inner = inner self._result_decoder = result_decoder self._last_progress_snapshot = None + self._created_at = time.monotonic() def _enrich_progress(self, snapshot): enriched = _with_progress_eta(self._last_progress_snapshot, snapshot) @@ -235,17 +241,29 @@ class AsyncJob(Generic[T]): async def progress(self) -> Optional[dict[str, Any]]: """Fetch a structured progress snapshot. - Registry jobs always report lifecycle fields. Queue metadata and - counters are included when supplied by the server. Older servers may + Registry jobs always report lifecycle fields. SQL query handles report + lifecycle state and ``client_elapsed_time_millis``, measured since this + handle was created. They do not expose server build phases or logs. + Queue metadata and counters are included when supplied by the server. + Older servers may omit counters, and in-process operations return ``None``. A missing counter is unknown rather than zero. This is additive to :meth:`status`, whose string contract is unchanged. """ if self._inner is None: return None - await self._inner.status() + state = await self._inner.status() description = getattr(self._inner, "_description", None) if description is None or description.progress is None: + if self.job_type == "query": + return { + "job_id": self.id, + "job_type": "query", + "state": state, + "client_elapsed_time_millis": int( + (time.monotonic() - self._created_at) * 1_000 + ), + } return None return self._enrich_progress(description.progress) @@ -270,6 +288,13 @@ class AsyncJob(Generic[T]): new execution epoch or smaller plan resets the bar to that plan. ``False`` preserves the original wait behavior. + For SQL-backed Function registration, progress shows the query's + lifecycle state and client elapsed time. It observes the existing + query handle while its original waiter runs; it does not resubmit or + cancel the registration. Detailed bake phases and build logs are not + available from the current query handle. Failure exceptions retain the + server's cause and request identifiers. + Raises `JobFailedError` if the operation failed, `JobCancelledError` if it was cancelled, and `TimeoutError` if `timeout` elapses first. Transient connection and read errors are retried with capped exponential @@ -285,7 +310,10 @@ class AsyncJob(Generic[T]): """ if self._inner is None: return cast(T, None) - progress_obj, owns = _normalize_job_progress(progress) + query_progress = ( + progress is not False and progress is not None and self.job_type == "query" + ) + progress_obj, owns = _normalize_job_progress(progress, query=query_progress) progress_callback = _job_progress_callback(progress_obj, self._enrich_progress) last_error = None @@ -311,13 +339,46 @@ class AsyncJob(Generic[T]): await asyncio.sleep(delay) delay = min(delay * 2, 30.0) + async def observe_query(): + async def report(): + try: + snapshot = await self.progress() + if snapshot is not None: + progress_callback(snapshot) + except Exception: + logging.getLogger(__name__).warning( + "job progress observer failed", exc_info=True + ) + + waiter = asyncio.create_task(wait_with_retries()) + try: + while not waiter.done(): + await report() + await asyncio.wait( + {waiter}, timeout=_QUERY_PROGRESS_INTERVAL_SECONDS + ) + try: + return await waiter + finally: + await report() + finally: + if not waiter.done(): + waiter.cancel() + with suppress(asyncio.CancelledError): + await waiter + + wait_for_result = ( + observe_query + if query_progress and progress_callback is not None + else wait_with_retries + ) try: try: if timeout is None: - result = await wait_with_retries() + result = await wait_for_result() else: result = await asyncio.wait_for( - wait_with_retries(), timeout.total_seconds() + wait_for_result(), timeout.total_seconds() ) except asyncio.TimeoutError as error: if last_error is None: diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 07be57e15..004aca90c 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import json +import warnings from collections import UserDict from pathlib import Path from types import MappingProxyType @@ -13,6 +14,7 @@ import lancedb.functions as functions from lancedb.functions import ( FunctionApplication, FunctionBinding, + FunctionImage, FunctionVersion, PythonRuntimeSpec, SecretBinding, @@ -149,6 +151,59 @@ def test_function_version_identity_is_immutable_and_exact(): FunctionVersion(**{**value, "version": invalid}) +@pytest.mark.parametrize("gpu", [False, True]) +def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu): + value = job_result("remote_function_job.json")["image"] + value["descriptor"]["future_metadata"] = "x" * 100_000 + if gpu: + value["descriptor"]["requires"]["capabilities"] = [ + { + "type": "lance.cuda", + "version": 1, + "device_count": 1, + "cuda_toolkit": "12.4", + } + ] + image = FunctionImage(**value) + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + details = image.describe() + rendered = repr(image) + assert "manifest_digest=" in str(image) + encoded = json.loads(image.to_canonical_json()) + assert details == { + "manifest_digest": value["manifest_digest"], + "python_version": "3.12.14", + "requires_gpu": gpu, + "cuda_toolkit": "12.4" if gpu else None, + "platforms": None, + "base_image": None, + "size_bytes": None, + } + assert len(rendered) < 350 + assert f"requires_gpu={gpu}" in rendered + assert "future_metadata" not in rendered + assert encoded == value + + +@pytest.mark.parametrize( + "descriptor", + [ + {}, + {"format_version": 2, "requires": {"capabilities": []}}, + {"format_version": 1, "requires": {"capabilities": [None]}}, + {"python": {"version": {"future": "x" * 100_000}}}, + ], +) +def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor): + image = FunctionImage( + manifest_digest="sha256:example", descriptor=descriptor, source=True + ) + assert image.describe()["requires_gpu"] is None + assert image.describe()["python_version"] is None + assert len(repr(image)) < 350 + + @pytest.mark.parametrize( "case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"] ) diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 9897d97b5..e71945b7f 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest from lancedb.exceptions import JobCancelledError, JobFailedError +from lancedb.db import DBConnection from lancedb.job import AsyncJob, Job, _progress_eta from lancedb.remote.errors import HttpError, RetryError @@ -729,15 +730,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing( @pytest.mark.asyncio -async def test_wait_progress_false_keeps_legacy_inner_wait_call(): +@pytest.mark.parametrize("progress", [False, None]) +async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress): class NoProgressArgument: id = "job-legacy" - job_type = None + + @property + def job_type(self): + raise AssertionError("quiet waits must not inspect progress metadata") async def wait(self): return None - assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None + assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None + + +class _RegistrationQuery: + id = "registration-query" + job_type = "query" + _description = None + + def __init__(self, error=None): + self.ready = asyncio.Event() + self.error = error + self.state = "running" + self.wait_calls = 0 + self.cancel_calls = 0 + + async def status(self): + return self.state + + async def wait(self, progress=None): + self.wait_calls += 1 + await self.ready.wait() + if self.error is not None: + self.state = ( + "cancelled" if isinstance(self.error, JobCancelledError) else "failed" + ) + raise self.error + self.state = "finished" + return '{"version": "1"}' + + async def cancel(self): + self.cancel_calls += 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch): + monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0) + inner = _RegistrationQuery() + job = AsyncJob(inner, json.loads) + updates = [] + + def observe(snapshot): + updates.append(snapshot) + if len(updates) == 2: + inner.ready.set() + + if sync: + result = await asyncio.to_thread(Job(job).wait, progress=observe) + else: + result = await job.wait(progress=observe) + assert result == {"version": "1"} + assert inner.wait_calls == 1 + assert inner.cancel_calls == 0 + assert updates[0]["state"] == "running" + assert updates[-1]["state"] == "finished" + assert all(snapshot["job_id"] == inner.id for snapshot in updates) + elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates] + assert elapsed == sorted(elapsed) + assert elapsed[0] >= 0 + assert all("phase" not in snapshot for snapshot in updates) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "error", + [ + JobFailedError("bake failed", job_id="registration-query"), + JobCancelledError("cancelled"), + ], +) +async def test_query_progress_preserves_terminal_exceptions(error): + inner = _RegistrationQuery(error) + inner.ready.set() + updates = [] + with pytest.raises(type(error)) as raised: + await AsyncJob(inner).wait(progress=updates.append) + assert raised.value is error + assert updates[-1]["state"] == inner.state + assert inner.wait_calls == 1 + + +@pytest.mark.asyncio +async def test_query_progress_display_has_no_row_counter_and_closes_on_failure( + monkeypatch, +): + tqdm_module = pytest.importorskip("tqdm.auto") + bar = SimpleNamespace( + n=0, + total=None, + update=MagicMock(), + set_postfix_str=MagicMock(), + close=MagicMock(), + ) + constructor = MagicMock(return_value=bar) + monkeypatch.setattr(tqdm_module, "tqdm", constructor) + inner = _RegistrationQuery(JobFailedError("bake failed")) + inner.ready.set() + + with pytest.raises(JobFailedError, match="bake failed"): + await AsyncJob(inner).wait(progress=True) + assert "elapsed" in constructor.call_args.kwargs["bar_format"] + assert "rows" not in str(constructor.call_args) + assert bar.set_postfix_str.call_args.args == ("failed",) + bar.close.assert_called_once_with() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failed", [False, True]) +@pytest.mark.parametrize("observer_error", ["status", "callback"]) +async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure( + failed, observer_error, caplog +): + error = ( + JobFailedError("bake failed", job_id="registration-query") if failed else None + ) + inner = _RegistrationQuery(error) + inner.ready.set() + if observer_error == "status": + inner.status = AsyncMock(side_effect=RuntimeError("observer failed")) + + def observe(snapshot): + if observer_error == "callback": + raise RuntimeError("observer failed") + + job = AsyncJob(inner, json.loads) + if failed: + with pytest.raises(JobFailedError) as raised: + await job.wait(progress=observe) + assert raised.value is error + else: + assert await job.wait(progress=observe) == {"version": "1"} + assert inner.wait_calls == 1 + assert inner.cancel_calls == 0 + assert "job progress observer failed" in caplog.text + + +@pytest.mark.asyncio +async def test_query_progress_timeout_keeps_registration_available_on_same_handle(): + inner = _RegistrationQuery() + job = AsyncJob(inner, json.loads) + updates = [] + with pytest.raises(TimeoutError, match="keep this handle"): + await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append) + assert inner.state == "running" + assert inner.cancel_calls == 0 + inner.ready.set() + assert await job.wait(progress=updates.append) == {"version": "1"} + assert inner.wait_calls == 2 + assert updates[-1]["state"] == "finished" + + +@pytest.mark.parametrize("refresh_lock", [False, True]) +def test_blocking_create_function_forwards_progress_to_registration_handle( + refresh_lock, +): + connection = MagicMock() + definition = object() + progress = object() + result = DBConnection.create_function( + connection, definition, refresh_lock=refresh_lock, progress=progress + ) + connection.create_function_async.assert_called_once_with( + definition, + secrets=None, + exist_ok=False, + namespace_path=None, + refresh_lock=refresh_lock, + ) + connection.create_function_async.return_value.wait.assert_called_once_with( + progress=progress + ) + assert result is connection.create_function_async.return_value.wait.return_value + + +@pytest.mark.parametrize("progress", [False, None]) +def test_blocking_create_function_preserves_quiet_wait_call(progress): + connection = MagicMock() + result = DBConnection.create_function(connection, object(), progress=progress) + connection.create_function_async.return_value.wait.assert_called_once_with() + assert result is connection.create_function_async.return_value.wait.return_value @pytest.mark.asyncio From 613653a7db1d023da706823e5287d9e4a236af6b Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sun, 15 Nov 2026 06:04:30 -0800 Subject: [PATCH 71/75] chore: update lance dependency to v15.0.0-beta.22 (#5057) Update Rust and Java Lance dependencies to [v15.0.0-beta.22](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.22), synchronize the Python test pin to `pylance==15.0.0b22`, and refresh the lockfiles with all published platform wheels. Preserve Function freshness only when an UPDATE changes rows, so beta.22's no-match updates cannot mark previously invalidated outputs as fresh. Extend the existing regression cases to cover no-match updates after input and output changes, including unchanged table versions. Rust formatting passed. CI validates the compatibility fix; no local builds or tests were run. --------- Co-authored-by: Jack Ye --- Cargo.lock | 134 +++++++++++++++++----------- Cargo.toml | 30 +++---- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 18 ++-- rust/lancedb/src/table/freshness.rs | 19 ++-- rust/lancedb/src/table/update.rs | 15 ++-- 7 files changed, 132 insertions(+), 88 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 755ba70a4..f454ff87a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1361,6 +1361,12 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "better_io" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef0a3155e943e341e557863e69a708999c94ede624e37865c8e2a91b94efa78f" + [[package]] name = "bigdecimal" version = "0.4.10" @@ -3278,6 +3284,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "dtype_dispatch" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab23e69df104e2fd85ee63a533a22d2132ef5975dc6b36f9f3e5a7305e4a8ed7" + [[package]] name = "dunce" version = "1.0.5" @@ -3824,8 +3836,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5303,8 +5315,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5379,8 +5391,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5402,7 +5414,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5416,7 +5428,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5425,8 +5437,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrayref", "crunchy", @@ -5436,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5475,8 +5487,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5507,8 +5519,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5533,8 +5545,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5546,13 +5558,13 @@ dependencies = [ "hex", "rand 0.9.5", "rand_distr 0.5.1", - "rand_xoshiro", + "rand_xoshiro 0.7.0", ] [[package]] name = "lance-derive" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "proc-macro2", "quote", @@ -5561,8 +5573,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-arith", "arrow-array", @@ -5585,6 +5597,7 @@ dependencies = [ "log", "lz4", "num-traits", + "pco", "prost", "serde_json", "tokio", @@ -5595,8 +5608,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-arith", "arrow-array", @@ -5627,8 +5640,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5659,8 +5672,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5733,8 +5746,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5757,8 +5770,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5803,8 +5816,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "byteorder", "ethnum", @@ -5821,8 +5834,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5837,8 +5850,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "async-trait", @@ -5852,8 +5865,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5907,8 +5920,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5922,8 +5935,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5964,8 +5977,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5978,8 +5991,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "frostem", "icu_segmenter", @@ -6651,7 +6664,7 @@ dependencies = [ "quanta", "radix_trie", "rand 0.9.5", - "rand_xoshiro", + "rand_xoshiro 0.7.0", "sketches-ddsketch", ] @@ -7837,6 +7850,18 @@ dependencies = [ "hmac 0.12.1", ] +[[package]] +name = "pco" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f01ab51a847e7002371c2384b2c88f50dd45982cc2764e7997751971f1bfbf" +dependencies = [ + "better_io", + "dtype_dispatch", + "half", + "rand_xoshiro 0.6.0", +] + [[package]] name = "pem" version = "3.0.6" @@ -9025,6 +9050,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xoshiro" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "rand_xoshiro" version = "0.7.0" diff --git a/Cargo.toml b/Cargo.toml index bc9d85c72..0e60bcb51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index ead5955fa..2b7a90e03 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.21 + 15.0.0-beta.22 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index d464424c7..e2b140626 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b21", + "pylance==15.0.0b22", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 31ac68b4d..8e03e90d8 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b21" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b22" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b21" +version = "15.0.0b22" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,13 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_mzSgZ/pylance-15.0.0b21-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:251682fe543131c371a6af45d8c672ea53b6ee83b5f777885f15ce383144d820" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1UfHMZ/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cbc92a2bac73f179a382e1bdb495fa3631a17e35687c2f00721af073eeb445a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Ugv8b/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59bd56971aa41a21783e938e18a752fdaa97a37cfdd8940ed2f37d0c665d0fdd" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1mO0GG/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a0da124e95240e448daa981664a5e64e87bc99411eb4c408cbd50147096654f4" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1n5aaN/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:341a1abcd62e6134982968a5236f8128d88211ab288d329924a812d87e555555" }, - { url = "https://pypi.fury.io/lance-format/-/ver_RVDDc/pylance-15.0.0b21-cp310-abi3-win_amd64.whl", hash = "sha256:f5dbd51b2553d70b927c537672bad41075cd8615f5e951008d7cd59c7365e587" }, - { url = "https://pypi.fury.io/lance-format/-/ver_GJeqW/pylance-15.0.0b21-cp310-abi3-win_arm64.whl", hash = "sha256:ddd517d555c6674c94b0eeee78ed6c3c3ac7b32319e27c47dd6f78a2639d6837" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2gkGO/pylance-15.0.0b22-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:401df8ce31ae6263656915c63d3da4411cae59bde2a6d71d12c552e3fa72b6bf" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pfuJc/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5c9ee37b23da4d6fbc341d0e18d355b1602c98fbf096e4589b08ecce57c56ea" }, + { url = "https://pypi.fury.io/lance-format/-/ver_YPb1X/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:38e6ed648816ae54ee3e76f21a30c092d47028da1f99242922ec1288d79a1722" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1a1jcd/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:1b7e9f1dfe7ff8e3cbb3b06a3ebd99667629725b6d9a119146f9e1bfac20871f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_KRwHG/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c31b41b8a8d070f969dcb9dd06aa31190f79d036b27cb5d5ae6d64d5d425502f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2cABdZ/pylance-15.0.0b22-cp310-abi3-win_amd64.whl", hash = "sha256:7b3d36ea7ab7a6a43caecc96ca7f969be11ad89d24ccc6d1788d751fb39e720d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1j6gGW/pylance-15.0.0b22-cp310-abi3-win_arm64.whl", hash = "sha256:20c4e391b4b83008dc2b7877bdd0ad9b3b1251ea05116d79b5637807f4961cc8" }, ] [[package]] diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 563a2a4e5..9980c3a75 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -3460,15 +3460,18 @@ mod tests { } #[rstest::rstest] - #[case::input_same_rows("body", "a", true)] - #[case::input_other_rows("body", "c", false)] - #[case::output_same_rows("search_text", "a", true)] - #[case::output_other_rows("search_text", "c", false)] + #[case::input_same_rows("body", "a", true, 1)] + #[case::input_other_rows("body", "c", false, 1)] + #[case::input_no_rows("body", "missing", false, 0)] + #[case::output_same_rows("search_text", "a", true, 1)] + #[case::output_other_rows("search_text", "c", false, 1)] + #[case::output_no_rows("search_text", "missing", false, 0)] #[tokio::test] async fn function_write_preserves_prior_invalidation( #[case] changed_column: &str, #[case] title: &str, #[case] dirty_product: bool, + #[case] expected_updated_rows: u64, ) { let table = fresh_function_table().await; let native = table.as_native().unwrap(); @@ -3489,14 +3492,20 @@ mod tests { ); native.dataset.update(result.new_dataset.as_ref().clone()); - table + let before_version = table.version().await.unwrap(); + let update = table .update() .only_if(format!("title = '{title}'")) .column("spare", "1") .execute() .await .unwrap(); + assert_eq!(update.rows_updated, expected_updated_rows); let dataset = native.dataset.get().await.unwrap(); + if expected_updated_rows == 0 { + assert_eq!(update.version, before_version); + assert_eq!(dataset.version().version, before_version); + } let stale = function_plan(&dataset, "search_text").await; assert_eq!(stale.is_dirty(3), dirty_product, "{stale:?}"); if !dirty_product { diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 93e8a08ea..10895aa69 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -130,13 +130,14 @@ pub(crate) async fn execute_update( let operation = builder.build()?; let res = operation.execute().await?; let mut new_dataset = res.new_dataset.as_ref().clone(); - if let Err(error) = super::freshness::preserve_function_freshness( - &mut new_dataset, - super::freshness::FunctionWrite::Update { - columns: &written_columns, - }, - ) - .await + if res.rows_updated > 0 + && let Err(error) = super::freshness::preserve_function_freshness( + &mut new_dataset, + super::freshness::FunctionWrite::Update { + columns: &written_columns, + }, + ) + .await { log::warn!("update committed but Function freshness could not be preserved: {error}"); } From 2ab103d7754308cac7e4eceb91fd72b0ed8460df Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 15 Nov 2026 14:05:38 +0000 Subject: [PATCH 72/75] =?UTF-8?q?Bump=20version:=200.42.0-beta.14=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.15?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 8491e70dc..99297338c 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.14" +current_version = "0.42.0-beta.15" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index f454ff87a..a6ae84b72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index ca0113382..9d7162444 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.14 + 0.42.0-beta.15 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 0ed2c85d9..21f80cd99 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.14 + 0.42.0-beta.15 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 2b7a90e03..26c94d3bf 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.14 + 0.42.0-beta.15 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 87919848f..3cee8b0ad 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 4c29cfeb3..03c295432 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 86c223618..2cb5a722c 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 2e32e7fc3..70880c70a 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 7d984b9f4..ed2f276a1 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 3607a6b93..748cc1640 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 369ff1c10..52d79a178 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index d0852d725..60cebaa37 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 8520e7b83..92c70bc3b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 08113dee6..fe135a99d 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 3a963d193..d00feaf72 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 0b566e596..5b1744cc3 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" edition = "2021" license.workspace = true repository.workspace = true From c7d972fe48000ae3c91563b5f699a0e378455d0f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Mon, 16 Nov 2026 18:56:39 +0800 Subject: [PATCH 73/75] fix(python): explain blob descriptor copy guidance (#5060) The descriptor-copy error only named the missing `data`/`uri` child. It now says that this shape is an SDK blob descriptor rather than payload bytes, and points to `blob_mode="bytes"` for supported materialization, `blob_mode="descriptions"` for inspection, and the row-id plus `fetch_blobs`/`fetch_blob_files` copy path while the source stays unchanged. This reuses the merged guidance from #4940 and the direct-materialization contract from #4973. Ray integration remains out of scope for ENT-3556. Refs ENT-3556 Test: `python/tests/test_blob.py` (210 passed, 39 skipped), including a regression that writes default lazy descriptor rows into a blob-schema table, checks the guidance, and confirms no target is created. `python/tests/test_util.py -k blob` (12 passed, 2 skipped). --- python/python/lancedb/table.py | 9 ++++++++- python/python/tests/test_blob.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 807edbc46..7f378a34c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1150,7 +1150,14 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field: if not any(child.name in ("data", "uri") for child in source_type): raise ValueError( f"blob struct input for column '{field.name}' must contain " - "a 'data' or 'uri' child" + "a 'data' or 'uri' child. A blob query returns an SDK " + "descriptor in this shape, and a descriptor is not payload " + "bytes. Use blob_mode='bytes' to materialize payloads, or " + "inspect descriptors with blob_mode='descriptions'. To copy " + "payloads, select row IDs with with_row_id(True), then call " + "table.fetch_blobs(column, row_ids) or " + "table.fetch_blob_files(column, row_ids). Keep the source " + "unchanged between selection and fetching." ) elif not _can_coerce_to_blob(source_type) and not isinstance( source_type, pa.ExtensionType diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index bb946c37c..f1bacb262 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1135,6 +1135,24 @@ def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path): assert sorted(copied, key=lambda row: row["id"]) == rows[:3] +def test_copy_blob_descriptor_rows_explains_payload_materialization(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + source = db.create_table("source", data=[{"id": 1, "image": b"one"}], schema=schema) + hits = source.search().where("id = 1").to_arrow() + + with pytest.raises(ValueError, match="must contain a 'data' or 'uri' child") as exc: + db.create_table("copy", data=hits, schema=schema) + + message = str(exc.value) + assert "blob_mode='bytes'" in message + assert "blob_mode='descriptions'" in message + assert "with_row_id(True)" in message + assert "fetch_blobs(column, row_ids)" in message + assert "fetch_blob_files(column, row_ids)" in message + assert not db.table_exists(["copy"]) + + def test_fetch_blobs_round_trip(): table = _blob_table( "round_trip", From d475005592fd9a0290f9da48783380adfef15c50 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 16 Nov 2026 11:40:27 +0000 Subject: [PATCH 74/75] =?UTF-8?q?Bump=20version:=200.42.0-beta.15=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.16?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 99297338c..865a04f56 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.15" +current_version = "0.42.0-beta.16" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index a6ae84b72..8e0589190 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 9d7162444..6c223c01b 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.15 + 0.42.0-beta.16 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 21f80cd99..852218a55 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.15 + 0.42.0-beta.16 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 26c94d3bf..c5ee0dbf0 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.15 + 0.42.0-beta.16 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 3cee8b0ad..38a88697c 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 03c295432..ab5c07329 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 2cb5a722c..c527594ba 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 70880c70a..21d262c8e 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index ed2f276a1..dd6cccb01 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 748cc1640..c0e414ca5 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 52d79a178..f7fcbc5db 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 60cebaa37..9dfeb21e2 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 92c70bc3b..9f9665a26 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index fe135a99d..2d9579e04 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index d00feaf72..d2054c9e6 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 5b1744cc3..31428d5f3 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" edition = "2021" license.workspace = true repository.workspace = true From 3b7c4dcf6602b97f6a5543937e2544dce6af25cd Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Mon, 16 Nov 2026 20:23:25 +0800 Subject: [PATCH 75/75] fix: allow matched merge updates to Function inputs (#5062) Matched merge-insert updates rejected every non-key source column that a Function binding reads, while update already accepts input changes and the merge freshness path records their changed signatures. Use the same `ensure_not_written` guard for the matched source columns: inputs pass, computed outputs and assignment columns stay rejected before any write, and insert-only or unrelated-column merges keep their behavior. Regressions confirm a matched input update retains prior outputs, dirties only the affected rows, keeps an independent binding fresh, and rejects mixed input/output sources without committing. Tested on `2ab103d7` + this change: `cargo test -p lancedb --lib` 1083 passed, 82 ignored. Refs ENT-3515 --- rust/lancedb/src/table/freshness.rs | 130 ++++++++++++++++++++++++++++ rust/lancedb/src/table/merge.rs | 68 +++++++++++---- 2 files changed, 180 insertions(+), 18 deletions(-) diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 9980c3a75..5d9ee26a6 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -3248,6 +3248,136 @@ mod tests { } } + #[tokio::test] + async fn input_merge_dirties_only_the_updated_rows_and_retains_outputs() { + let table = fresh_function_table().await; + let source = + arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + let result = merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + assert_eq!(result.num_updated_rows, 1); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for output in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, output).await; + let mut dirty_rows = 0; + for fragment in dataset.get_fragments() { + if stale.needs_recompute(fragment.id() as u32) { + let batch = fragment + .scan() + .project(&["title"]) + .unwrap() + .try_into_batch() + .await + .unwrap(); + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}"); + dirty_rows += batch.num_rows(); + } + } + assert_eq!(dirty_rows, 1, "{stale:?}"); + } + assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1); + } + + #[tokio::test] + async fn input_merge_keeps_an_independent_function_binding_fresh() { + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, ["x", "y", "z", "w"]), + ("search_text", Utf8, ["a x", "b y", "c z", "d w"]), + ("search_token_count", Int64, [2, 2, 2, 2]), + ("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]), + ("search_token_count_other", Int64, [2, 2, 2, 2]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("independent_merge", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut other = serde_json::to_value(text_features_binding("_other")).unwrap(); + other["inputs"][1]["field_path"] = serde_json::json!("title"); + other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone(); + let bindings = [ + text_features_binding(""), + serde_json::from_value(other).unwrap(), + ]; + stamp_bindings(&table, &bindings).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + for binding in &bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let inputs = fields_for_paths(dataset.schema(), &paths).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + } + native.dataset.update(dataset); + let source = + arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .needs_recompute(2) + ); + let other = &bindings[1]; + let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap(); + for output in other.outputs() { + let stale = + staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs) + .await + .unwrap(); + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index fe131d907..79c724f3e 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -249,11 +249,13 @@ impl MergeInsertBuilder { Ok(()) } - /// The existing columns a matched row takes from `source`: every source - /// column but the join keys, which a match leaves equal. An insert-only - /// merge rewrites none; its new rows get Function outputs from the next - /// refresh, as appended rows do. - pub(crate) fn function_guarded_columns(&self, source: &Fields) -> Vec { + /// The source columns a matched row writes: every column but the join + /// keys, which a match leaves equal. Function inputs stay writable; the + /// merge records their changed signatures so the next refresh recomputes + /// the affected rows. Computed outputs and assignment columns remain + /// protected by the direct-write guard. An insert-only merge writes none; + /// its new rows get Function outputs from the next refresh. + pub(crate) fn matched_source_columns(&self, source: &Fields) -> Vec { if !self.when_matched_update_all { return Vec::new(); } @@ -351,10 +353,10 @@ pub(crate) async fn execute_merge_insert( ) -> Result { params.canonicalize_filters()?; let schema = table.schema().await?; - super::computed_columns::ensure_not_function_bound( + let matched_columns = params.matched_source_columns(new_data.schema().fields()); + super::computed_columns::ensure_not_written( schema.as_ref(), - "merge_insert", - params.function_guarded_columns(new_data.schema().fields()), + matched_columns.iter().map(String::as_str), )?; // Normalize blob layouts and JSON extension metadata just as on append. // Keep arrow.json text labelled until Lance encodes it as JSONB. @@ -970,10 +972,11 @@ mod tests { assert_eq!(table.count_rows(None).await.unwrap(), 2); } - /// A matched row takes every non-key source column, so the merge is - /// refused only when one of those is a binding's input or output. + /// A matched row takes every non-key source column. Function inputs are + /// writable and become stale for the next refresh; computed outputs stay + /// protected, and a mixed input/output source is rejected before commit. #[tokio::test] - async fn merge_update_on_a_function_table_refuses_only_bound_columns() { + async fn merge_update_allows_function_inputs_but_protects_outputs() { let table = crate::table::computed_columns::test_support::bound_table_from( arrow_array::record_batch!( ("id", Int32, [1]), @@ -998,18 +1001,47 @@ mod tests { let mut merge = table.merge_insert(&["id"]); merge.when_matched_update_all(None); - let err = merge + let result = merge .execute(reader( arrow_array::record_batch!(("id", Int32, [1]), ("title", Utf8, ["z"])).unwrap(), )) .await - .unwrap_err(); - assert!( - matches!(&err, crate::Error::InvalidInput { message } - if message.contains("merge_insert of 'title'") - && message.contains("a Function binding reads or writes it")), - "{err:?}" + .unwrap(); + assert_eq!(result.num_updated_rows, 1); + assert_eq!( + table + .count_rows(Some("title = 'z' AND search_text = 'a b'".into())) + .await + .unwrap(), + 1 ); + + let version = table.version().await.unwrap(); + for source in [ + arrow_array::record_batch!(("id", Int32, [1]), ("search_text", Utf8, ["uncomputed"])) + .unwrap(), + arrow_array::record_batch!( + ("id", Int32, [1]), + ("title", Utf8, ["must not commit"]), + ("search_text", Utf8, ["uncomputed"]) + ) + .unwrap(), + ] { + let mut merge = table.merge_insert(&["id"]); + merge.when_matched_update_all(None); + let err = merge.execute(reader(source)).await.unwrap_err(); + assert!( + matches!(&err, crate::Error::InvalidInput { message } + if message.contains("is computed") + && message.contains("cannot be written directly")), + "{err:?}" + ); + assert_eq!(table.version().await.unwrap(), version); + assert_eq!( + table.count_rows(Some("title = 'z'".into())).await.unwrap(), + 1 + ); + } } }