From 6aa2a85dde3abecd23d5ee6d9d67bb9a501282c5 Mon Sep 17 00:00:00 2001 From: ChilePiquin Date: Sat, 14 Nov 2026 16:23:27 -0800 Subject: [PATCH] feat(sdk): add durable compaction jobs with typed results --- Cargo.lock | 1 + docs/src/js/classes/Connection.md | 20 ++- docs/src/js/classes/Job.md | 10 +- docs/src/js/classes/Table.md | 46 ++++- docs/src/js/globals.md | 1 + docs/src/js/interfaces/CompactionResult.md | 99 +++++++++++ docs/src/python/python.md | 2 + docs/web/maintenance/compaction.mdx | 67 ++++++++ nodejs/Cargo.toml | 1 + nodejs/__test__/remote.test.ts | 44 +++++ nodejs/__test__/table.test.ts | 16 ++ nodejs/lancedb/compaction.ts | 41 +++++ nodejs/lancedb/connection.ts | 6 +- nodejs/lancedb/index.ts | 2 + nodejs/lancedb/job.ts | 37 ++-- nodejs/lancedb/table.ts | 64 +++++-- nodejs/src/connection.rs | 9 +- nodejs/src/job.rs | 37 +++- nodejs/src/table.rs | 17 ++ python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/compaction.py | 36 ++++ python/python/lancedb/job.py | 3 + python/python/lancedb/remote/table.py | 8 + python/python/lancedb/table.py | 48 ++++++ python/python/tests/test_remote_db.py | 190 +++++++++++++++++++++ python/src/connection.rs | 4 + python/src/table.rs | 33 ++++ rust/lancedb/src/remote/sql_test.rs | 66 +++++++ rust/lancedb/src/remote/table.rs | 47 +++-- rust/lancedb/src/remote/table/optimize.rs | 77 +++++++++ rust/lancedb/src/table.rs | 41 +++++ rust/lancedb/src/table/optimize.rs | 29 ++++ 32 files changed, 1043 insertions(+), 62 deletions(-) create mode 100644 docs/src/js/interfaces/CompactionResult.md create mode 100644 nodejs/lancedb/compaction.ts create mode 100644 python/python/lancedb/compaction.py diff --git a/Cargo.lock b/Cargo.lock index 22b0f1e6f..d1b0c02a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6165,6 +6165,7 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "serde", "serde_json", ] diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 4876e3a52..83c182cf2 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -456,7 +456,7 @@ Rejects a table that exists but is not a materialized view. ### dropMaterializedViewAsync() ```ts -abstract dropMaterializedViewAsync(name, namespacePath?): Promise +abstract dropMaterializedViewAsync(name, namespacePath?): Promise> ``` Start dropping the materialized view named `name` and return its job. @@ -473,7 +473,7 @@ Rejects a table that exists but is not a materialized view. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -532,7 +532,7 @@ Drop an existing table. ### dropTableAsync() ```ts -abstract dropTableAsync(name, namespacePath?): Promise +abstract dropTableAsync(name, namespacePath?): Promise> ``` Start dropping a table and return its cleanup job. @@ -548,7 +548,7 @@ on the returned job to know when cleanup has finished. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -579,7 +579,7 @@ catalog removal; physical cleanup continues in the background. ### dropViewAsync() ```ts -abstract dropViewAsync(name, namespacePath?): Promise +abstract dropViewAsync(name, namespacePath?): Promise> ``` Drop a view and return its SQL query job. @@ -594,7 +594,7 @@ catalog removal; physical cleanup continues in the background. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -729,7 +729,7 @@ state and error behavior; options control page size and the starting token. ### openJob() ```ts -abstract openJob(jobId): Promise +abstract openJob(jobId): Promise> ``` Open a server-side job by id, returning a handle with its record already @@ -740,13 +740,17 @@ The returned [Job](Job.md) answers for its own state, specification, result, failure and event history, so there is no separate connection-level call for any of them. +#### Type Parameters + +• **T** = `void` + #### Parameters * **jobId**: `string` #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`T`>> *** diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index 8fd59c964..e4e506e9c 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -4,7 +4,7 @@ [@lancedb/lancedb](../globals.md) / Job -# Class: Job +# Class: Job<T> A handle to an operation that may still be running. @@ -20,6 +20,10 @@ extra round trip on every call: - Registry details are null until one of those runs. Query handles report jobType "query" immediately. +## Type Parameters + +• **T** = `void` + ## Accessors ### creationMs @@ -241,7 +245,7 @@ printing it. ### wait() ```ts -wait(progressCallback?): Promise +wait(progressCallback?): Promise ``` Wait until the operation reaches a terminal state. @@ -259,4 +263,4 @@ callback exception does not reject `wait`. #### Returns -`Promise`<`void`> +`Promise`<`T`> diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 37686a77e..68952fdc3 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -305,6 +305,40 @@ It is a no-op when no writers are cached. *** +### compactAsync() + +```ts +compactAsync(_options?): Promise> +``` + +Submit remote compaction and return its durable job after acceptance. + +Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires +a compatible remote server and table Ownership plus parent Usage. Local and +historical-version handles are unsupported. Existing optimize() behavior is unchanged. +Waiting tracks the rewrite itself and returns actual row/file statistics. +Missing result payloads are errors; older workers can omit file counts. +Status, progress, events and cancellation reuse the generic HTTP job APIs. +Reopen with db.openJob(job.id!). A wait timeout does not cancel work. + +#### Parameters + +* **\_options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`CompactionResult`](../interfaces/CompactionResult.md)>> + +#### Example + +```ts +const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); +const result = await job.wait(); +console.log(result.rowsSucceeded, result.fragmentsRemoved); +``` + +*** + ### compactRTE() ```ts @@ -423,7 +457,7 @@ await table.createIndex("my_float_col"); ### createIndexAsync() ```ts -abstract createIndexAsync(column, options?): Promise +abstract createIndexAsync(column, options?): Promise> ``` Create an index, returning a handle to the indexing job. @@ -444,7 +478,7 @@ account for the replacement caveat described in [Table.createIndex](Table.md#cre #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -1076,7 +1110,7 @@ Prewarm one or more columns of data in the table. ### prewarmDataAsync() ```ts -abstract prewarmDataAsync(options?): Promise +abstract prewarmDataAsync(options?): Promise> ``` Submit data prewarm through SQL and return its durable warming-job handle. @@ -1098,7 +1132,7 @@ the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> #### Example @@ -1238,7 +1272,7 @@ number of rows filled and the new version number of the table. ### refreshColumnAsync() ```ts -abstract refreshColumnAsync(column, options?): Promise +abstract refreshColumnAsync(column, options?): Promise> ``` Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh @@ -1285,7 +1319,7 @@ LanceDB Enterprise it is the server's backfill job. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> #### Example diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 44094dcd6..a7e4f9df8 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -75,6 +75,7 @@ - [ColumnAlteration](interfaces/ColumnAlteration.md) - [ColumnOrdering](interfaces/ColumnOrdering.md) - [CompactionOptions](interfaces/CompactionOptions.md) +- [CompactionResult](interfaces/CompactionResult.md) - [CompactionStats](interfaces/CompactionStats.md) - [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md) - [ConnectionOptions](interfaces/ConnectionOptions.md) diff --git a/docs/src/js/interfaces/CompactionResult.md b/docs/src/js/interfaces/CompactionResult.md new file mode 100644 index 000000000..3190ea5c7 --- /dev/null +++ b/docs/src/js/interfaces/CompactionResult.md @@ -0,0 +1,99 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CompactionResult + +# Interface: CompactionResult + +Actual committed outcome of one remote compaction job. + +## Properties + +### completionPercentage + +```ts +completionPercentage: number; +``` + +Percentage of planned live rows committed, from 0 to 100. + +*** + +### filesAdded + +```ts +filesAdded: null | number; +``` + +Data files added by committed rewrites; null if an older worker omitted it. + +*** + +### filesRemoved + +```ts +filesRemoved: null | number; +``` + +Data files removed by committed rewrites; null if an older worker omitted it. + +*** + +### fragmentsAdded + +```ts +fragmentsAdded: null | number; +``` + +Fragments added by committed rewrites; null if an older worker omitted it. + +*** + +### fragmentsRemoved + +```ts +fragmentsRemoved: null | number; +``` + +Fragments removed by committed rewrites; null if an older worker omitted it. + +*** + +### moreWork + +```ts +moreWork: boolean; +``` + +A bounded run left eligible work for another invocation. + +*** + +### partialCommit + +```ts +partialCommit: boolean; +``` + +Some planned groups were not committed. + +*** + +### rowsFailed + +```ts +rowsFailed: number; +``` + +Planned live rows not committed by this job. + +*** + +### rowsSucceeded + +```ts +rowsSucceeded: number; +``` + +Live source rows in committed rewrite groups. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 36f47c8f0..c436e4b07 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1432,3 +1432,5 @@ 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. + +::: lancedb.compaction.CompactionResult diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index e7b79f768..1678a30e7 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -63,6 +63,73 @@ separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs even though `optimize()` bundles both in one LanceDB Embedded call. +## Track on-demand Enterprise compaction {#compaction-jobs} + +On compatible Enterprise deployments, `compact_async()` / `compactAsync()` +submits SQL `OPTIMIZE ... REWRITE DATA` and returns a durable job handle. +The table handle supplies the namespace and branch. The existing remote +`optimize()` call keeps returning after submission with placeholder statistics; +use the job-returning API to wait for the actual rewrite and obtain its result. + + +```python Python +from datetime import timedelta + +job = table.compact_async( + compaction_options={"target_rows_per_fragment": 1000, "batch_size": 128} +) +result = job.wait(timeout=timedelta(minutes=10)) +print(result.rows_succeeded, result.fragments_removed, result.fragments_added) + +# Resume from another process with the same connection settings. +result = db.open_job(job.id).wait() +``` +```typescript TypeScript +import type { CompactionResult } from "@lancedb/lancedb"; + +const job = await table.compactAsync({ + targetRowsPerFragment: 1000, batchSize: 128, +}); +const result = await job.wait(); +console.log(result.rowsSucceeded, result.fragmentsRemoved, result.fragmentsAdded); + +if (job.id !== null) { + await (await db.openJob(job.id)).wait(); +} +``` +```rust Rust +use lancedb::table::{CompactionResult, optimize::CompactionOverrides}; + +let job = table.compact_async(CompactionOverrides { + target_rows_per_fragment: Some(1000), + batch_size: Some(128), + ..Default::default() +}).await?; +let result = job.wait().await?; +println!("Committed {} rows", result.rows_succeeded); + +if let Some(id) = job.id() { + db.open_job(id).await?.into_typed::()?.wait().await?; +} +``` + + +The result describes this job's committed rewrites, not a comparison of table +versions that could include concurrent writes. `partial_commit` identifies an +incomplete commit; `rows_failed` counts planned rows left uncommitted. +`more_work` means a bounded run left eligible work for another invocation. +A genuine no-op reports zero file/fragment counts; counts omitted by an older +worker are `None` in Python/Rust or `null` in TypeScript. A server that publishes +no compaction result raises an error when waiting, rather than fabricating zero +statistics. + +Submission requires Flight SQL connectivity and, under Standard authorization, +table Ownership plus Usage on the database and namespace hierarchy. Status, +progress, events, and cancellation use the generic HTTP job APIs and their +existing permissions. A wait timeout or dropping the handle does not cancel +the job. Local tables and historical-version checkouts are unsupported by the +job-returning API; ordinary embedded `optimize()` remains available. + ## Retraining indexes {#retrain} Folding new rows into an index preserves the structure the index was trained on. diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 22cfe6ecc..76897a3b4 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -30,6 +30,7 @@ napi = { version = "3.15.0", default-features = false, features = [ "serde-json", ] } chrono.workspace = true +serde.workspace = true serde_json.workspace = true napi-derive = "3.6.13" # Prevent dynamic linking of lzma, which comes from datafusion diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index a9989b84e..56662cfbf 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2351,3 +2351,47 @@ describe("lazy resource listings", () => { }); } }); + +describe("remote compaction job results", () => { + test.each([true, false])( + "reopens typed compaction result (counts=%s)", + async (counts) => { + await withMockDatabase( + (request, response) => { + expect(request.url).toBe("/v1/jobs/describe"); + const result = JSON.parse(`{ + "partial_commit": false, + "rows_succeeded": 12, + "rows_failed": 0, + "completion_percentage": 100 + }`); + if (counts) { + Object.assign( + result, + JSON.parse(`{ + "files_added": 1, + "files_removed": 3, + "fragments_added": 1, + "fragments_removed": 3 + }`), + ); + } + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + `{"job_id":"compacting-job","job_type":"compact","job_state":"DONE","result":${JSON.stringify(result)}}`, + ); + }, + async (db) => { + const job = + await db.openJob( + "compacting-job", + ); + const result = await job.wait(); + expect(result.rowsSucceeded).toBe(12); + expect(result.moreWork).toBe(false); + expect(result.fragmentsRemoved).toBe(counts ? 3 : null); + }, + ); + }, + ); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 5e9df4665..1eb234ebf 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5818,3 +5818,19 @@ describe("computed columns", () => { expect(rows.map((r) => r.doubled).sort()).toEqual([10, 2]); }); }); + +describe("durable compaction validation", () => { + test("rejects local tables and unknown options", async () => { + const db = await connect(`memory://compaction-job-${Date.now()}`); + const table = await db.createTable("test", [{ id: 1 }]); + await expect(table.compactAsync()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.compactAsync({ unrecognizedLimit: 1 } as never), + ).rejects.toThrow("Unsupported compaction option"); + await expect( + table.compactAsync({ targetRowsPerFragment: 0 }), + ).rejects.toThrow("safe integer"); + }); +}); diff --git a/nodejs/lancedb/compaction.ts b/nodejs/lancedb/compaction.ts new file mode 100644 index 000000000..b14c98b0c --- /dev/null +++ b/nodejs/lancedb/compaction.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Actual committed outcome of one remote compaction job. */ +export interface CompactionResult { + /** A bounded run left eligible work for another invocation. */ + moreWork: boolean; + /** Some planned groups were not committed. */ + partialCommit: boolean; + /** Live source rows in committed rewrite groups. */ + rowsSucceeded: number; + /** Planned live rows not committed by this job. */ + rowsFailed: number; + /** Percentage of planned live rows committed, from 0 to 100. */ + completionPercentage: number; + /** Data files added by committed rewrites; null if an older worker omitted it. */ + filesAdded: number | null; + /** Data files removed by committed rewrites; null if an older worker omitted it. */ + filesRemoved: number | null; + /** Fragments added by committed rewrites; null if an older worker omitted it. */ + fragmentsAdded: number | null; + /** Fragments removed by committed rewrites; null if an older worker omitted it. */ + fragmentsRemoved: number | null; +} + +/** @internal */ +export function decodeCompactionResult(value: unknown): CompactionResult { + // The Rust typed-job decoder validates the wire payload before it reaches JS. + const result = value as Record; + return { + moreWork: result.more_work as boolean, + partialCommit: result.partial_commit as boolean, + rowsSucceeded: result.rows_succeeded as number, + rowsFailed: result.rows_failed as number, + completionPercentage: result.completion_percentage as number, + filesAdded: (result.files_added as number | null) ?? null, + filesRemoved: (result.files_removed as number | null) ?? null, + fragmentsAdded: (result.fragments_added as number | null) ?? null, + fragmentsRemoved: (result.fragments_removed as number | null) ?? null, + }; +} diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 9c83d833f..ce71c4e89 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -583,7 +583,7 @@ export abstract class Connection { * result, failure and event history, so there is no separate * connection-level call for any of them. */ - abstract openJob(jobId: string): Promise; + abstract openJob(jobId: string): Promise>; /** * Iterate lazily over server-side jobs across the database's tables. @@ -1017,8 +1017,8 @@ export class LocalConnection extends Connection { ); } - async openJob(jobId: string): Promise { - return new Job(await this.inner.openJob(jobId)); + async openJob(jobId: string): Promise> { + return new Job(await this.inner.openJob(jobId)); } listJobs(options: ListingOptions = {}): Listing { diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index cde32e536..c050cc376 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -662,3 +662,5 @@ export { } from "./catalog"; export { Listing, ListingOptions } from "./listing"; + +export type { CompactionResult } from "./compaction"; diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index f38d8d7fa..8c05ae04a 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { Table as ArrowTable, tableFromIPC } from "apache-arrow"; +import { decodeCompactionResult } from "./compaction"; import { JobFailureInfo, Job as NativeJob } from "./native"; /** Which of a job's events {@link Job.events} returns. */ @@ -71,11 +72,18 @@ export type JobProgressCallback = (progress: JobProgress) => void; * * @hideconstructor */ -export class Job { +export class Job { private readonly inner: NativeJob; - constructor(inner: NativeJob) { + private readonly resultDecoder?: (value: unknown) => T; + + constructor(inner: NativeJob, resultDecoder?: (value: unknown) => T) { this.inner = inner; + this.resultDecoder = + resultDecoder ?? + (inner.jobType === "compact" + ? (decodeCompactionResult as (value: unknown) => T) + : undefined); } /** @@ -162,17 +170,22 @@ export class Job { * throws, the error is logged with `console.warn` and waiting continues; a * callback exception does not reject `wait`. */ - async wait(progressCallback?: JobProgressCallback): Promise { - if (progressCallback === undefined) { - return this.inner.wait(); + async wait(progressCallback?: JobProgressCallback): Promise { + const callback = + progressCallback === undefined + ? undefined + : (progress: Record) => { + try { + progressCallback(this.enrichProgress(progress)); + } catch (error) { + console.warn("Job progress callback threw:", error); + } + }; + if (this.resultDecoder !== undefined) { + return this.resultDecoder(await this.inner.waitResult(callback)); } - return this.inner.wait((progress) => { - try { - progressCallback(this.enrichProgress(progress)); - } catch (error) { - console.warn("Job progress callback threw:", error); - } - }); + await this.inner.wait(callback); + return undefined as T; } /** Request cancellation. Cancelling a finished operation is a no-op. */ diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 9eed3a280..cb9d18893 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { CompactionResult, decodeCompactionResult } from "./compaction"; + import { Table as ArrowTable, Data, @@ -1235,6 +1237,28 @@ export abstract class Table { * out state and the read_consistency_interval, if any, will apply. */ abstract restore(): Promise; + /** + * Submit remote compaction and return its durable job after acceptance. + * + * Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires + * a compatible remote server and table Ownership plus parent Usage. Local and + * historical-version handles are unsupported. Existing optimize() behavior is unchanged. + * Waiting tracks the rewrite itself and returns actual row/file statistics. + * Missing result payloads are errors; older workers can omit file counts. + * Status, progress, events and cancellation reuse the generic HTTP job APIs. + * Reopen with db.openJob(job.id!). A wait timeout does not cancel work. + * + * @example + * const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); + * const result = await job.wait(); + * console.log(result.rowsSucceeded, result.fragmentsRemoved); + */ + async compactAsync( + _options?: CompactionOptions, + ): Promise> { + throw new Error("compaction jobs are only supported on remote tables"); + } + /** * Optimize the on-disk data and indices for better performance. * @@ -1919,20 +1943,18 @@ export class LocalTable extends Table { return this.inner.currentBranch() ?? null; } + async compactAsync( + options?: CompactionOptions, + ): Promise> { + validateCompactionOptions(options); + return new Job( + await this.inner.compactAsync(options), + decodeCompactionResult, + ); + } + async optimize(options?: Partial): Promise { - // JavaScript callers can supply extra keys that TypeScript would reject. - // Refuse them before the native binding can silently discard a work limit. - const supported = new Set([ - "targetRowsPerFragment", - "maxSourceRows", - "ioBufferSize", - "batchSize", - ]); - for (const key of Object.keys(options?.compactionOptions ?? {})) { - if (!supported.has(key)) { - throw new Error(`Unsupported compaction option: ${key}`); - } - } + validateCompactionOptions(options?.compactionOptions); return await this.inner.optimize( options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, @@ -2232,3 +2254,19 @@ function rowIdsToBigInts(rowIds: readonly (bigint | number)[]): bigint[] { return BigInt(id); }); } + +function validateCompactionOptions(options?: CompactionOptions): void { + // JavaScript callers can supply extra keys that TypeScript would reject. + // Refuse them before the native binding can silently discard a work limit. + const supported = new Set([ + "targetRowsPerFragment", + "maxSourceRows", + "ioBufferSize", + "batchSize", + ]); + for (const key of Object.keys(options ?? {})) { + if (!supported.has(key)) { + throw new Error(`Unsupported compaction option: ${key}`); + } + } +} diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 914f9e4c9..33b97bda0 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -567,7 +567,14 @@ impl Connection { #[napi(catch_unwind)] pub async fn open_job(&self, job_id: String) -> napi::Result { let job = self.get_inner()?.open_job(&job_id).await.default_error()?; - Ok(crate::job::Job::new(job)) + if job.job_type().as_deref() == Some("compact") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) + } else { + Ok(crate::job::Job::new(job)) + } } /// List server-side jobs across the database's tables. diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 09b245f97..b0f3e019c 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -17,7 +17,7 @@ type JobProgressFn = /// A handle to an operation that may still be running. #[napi] pub struct Job { - inner: Arc, + inner: Arc, String>>>, } impl Job { @@ -26,7 +26,19 @@ impl Job { T: Clone + Send + Sync + 'static, { Self { - inner: Arc::new(inner.map(|_| ())), + inner: Arc::new(inner.map(|_| Ok(None))), + } + } + pub(crate) fn new_typed(inner: lancedb::Job) -> Self + where + T: Clone + serde::Serialize + Send + Sync + 'static, + { + Self { + inner: Arc::new(inner.map(|result| { + serde_json::to_value(result) + .map(Some) + .map_err(|error| format!("failed to serialize typed job result: {error}")) + })), } } } @@ -70,7 +82,19 @@ impl Job { ts_args_type = "progressCallback?: (progress: Record) => void" )] pub async fn wait(&self, progress_callback: Option) -> napi::Result<()> { - if let Some(progress_callback) = progress_callback { + self.wait_result(progress_callback).await.map(|_| ()) + } + + /// The typed terminal value used by result-returning SDK operations. + #[napi( + catch_unwind, + ts_args_type = "progressCallback?: (progress: Record) => void" + )] + pub async fn wait_result( + &self, + progress_callback: Option, + ) -> napi::Result> { + let result = if let Some(progress_callback) = progress_callback { self.inner .wait_with_progress(move |description| { progress_callback.call( @@ -79,10 +103,11 @@ impl Job { ); }) .await - .default_error() + .default_error()? } else { - self.inner.wait().await.default_error() - } + self.inner.wait().await.default_error()? + }; + result.map_err(napi::Error::from_reason) } /// Request cancellation. Cancelling a finished operation is a no-op. diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index de51312c1..d19a415ac 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -909,6 +909,23 @@ impl Table { Ok(self.inner_ref()?.current_branch()) } + #[napi(catch_unwind)] + pub async fn compact_async( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(CompactionOptions::into_overrides) + .transpose()? + .unwrap_or_default(); + let job = self + .inner_ref()? + .compact_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + #[napi(catch_unwind)] pub async fn optimize( &self, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index fd964e3d4..4fd6e296e 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -726,6 +726,9 @@ class Table: async def update_field_metadata( self, updates: list[dict[str, Any]] ) -> UpdateFieldMetadataResult: ... + async def compact_async( + self, compaction_options: Optional[Dict[str, Any]] = None + ) -> Job: ... async def optimize( self, *, diff --git a/python/python/lancedb/compaction.py b/python/python/lancedb/compaction.py new file mode 100644 index 000000000..5c8bc297b --- /dev/null +++ b/python/python/lancedb/compaction.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Results of durable remote compaction jobs.""" + +from dataclasses import dataclass, fields +import json +from typing import Optional + + +@dataclass(frozen=True) +class CompactionResult: + """Actual committed outcome of one remote compaction invocation. + + ``rows_failed`` counts planned live rows that were not committed, including + partial progress. ``more_work`` means a bounded run left eligible work for + another invocation. File/fragment counts are None if an older worker did + not report them; they are never inferred from unrelated table versions. + """ + + partial_commit: bool + rows_succeeded: int + rows_failed: int + completion_percentage: float + more_work: bool = False + files_added: Optional[int] = None + files_removed: Optional[int] = None + fragments_added: Optional[int] = None + fragments_removed: Optional[int] = None + + @classmethod + def from_json(cls, raw: str) -> "CompactionResult": + """Decode a server result, ignoring additive fields from newer servers.""" + value = json.loads(raw) + names = {field.name for field in fields(cls)} + return cls(**{key: item for key, item in value.items() if key in names}) diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index bf9605567..c2716b118 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -18,6 +18,7 @@ from lancedb.background_loop import LOOP from . import _lancedb from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url from .functions import RefreshColumnResult +from .compaction import CompactionResult from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -698,4 +699,6 @@ def _typed_job( 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) + if inner.job_type == "compact": + return _typed_job(inner, CompactionResult.from_json) return AsyncJob(inner) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 38a735087..50c1c3546 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -76,6 +76,7 @@ from ..table import ( BlobMode, Branches, CompactionOptions, + CompactionResult, IndexStatistics, Query, Table, @@ -1085,6 +1086,13 @@ class RemoteTable(Table): ) pass + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + return Job( + LOOP.run(self._table.compact_async(compaction_options=compaction_options)) + ) + def optimize( self, *, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 0858a60c4..185af45e4 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -49,6 +49,7 @@ from .types import BlobMode from lancedb.arrow import peek_reader from lancedb.background_loop import LOOP, embedding_executor from lancedb.job import AsyncJob, Job, _typed_job +from lancedb.compaction import CompactionResult from .dependencies import ( _check_for_hugging_face, _check_for_lance, @@ -2999,6 +3000,33 @@ class Table(ABC): compaction for you automatically. """ + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + """Submit remote compaction and return a durable job after acceptance. + + Uses SQL OPTIMIZE with the table handle's branch and namespace. Supports + the four per-job settings in + [CompactionOptions][lancedb.table.CompactionOptions]. + Requires a compatible remote server, table Ownership and parent Usage. + Local and historical-version handles are unsupported. Existing + ``optimize()`` retains its return-on-submission behavior remotely. + + ``job.wait()`` waits for the actual rewrite and returns + [CompactionResult][lancedb.compaction.CompactionResult]. Partial/bounded + runs report uncommitted rows and ``more_work``; unknown file statistics + are None. Servers without a result payload raise an error rather than + returning fabricated zero statistics. Wait timeouts do not cancel work. + Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and + cancellation use generic HTTP job APIs and their existing permissions. + + >>> job = table.compact_async( # doctest: +SKIP + ... compaction_options={"target_rows_per_fragment": 1000}) + >>> result = job.wait() # doctest: +SKIP + >>> print(result.rows_succeeded) # doctest: +SKIP + """ + raise NotImplementedError("compaction jobs are only supported on remote tables") + @abstractmethod def optimize( self, @@ -5477,6 +5505,13 @@ class LanceTable(Table): self.checkout_latest() return stats + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + return Job( + LOOP.run(self._table.compact_async(compaction_options=compaction_options)) + ) + def optimize( self, *, @@ -8824,6 +8859,19 @@ class AsyncTable: """The branch this table handle is scoped to, or ``None`` for ``main``.""" return self._inner.current_branch() + async def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> AsyncJob[CompactionResult]: + """Submit remote compaction; await the returned job for actual results. + + See [Table.compact_async][lancedb.table.Table.compact_async] for options, + permissions, completion semantics and compatibility requirements. + """ + return _typed_job( + await self._inner.compact_async(compaction_options), + CompactionResult.from_json, + ) + async def optimize( self, *, diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 836850a5c..043872383 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -7563,3 +7563,193 @@ def test_remote_data_prewarm_malformed_receipt_is_not_retried(): with pytest.raises(Exception, match="inspect jobs before retrying"): table.prewarm_data_async() assert len(server.tickets) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "outcome", + [ + "counts", + "legacy", + "partial", + "bounded", + "no_op", + "missing", + "FAILED", + "CANCELLED", + ], +) +async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): + flight = pytest.importorskip("pyarrow.flight") + polls = [] + result = { + "partial_commit": False, + "rows_succeeded": 12, + "rows_failed": 0, + "completion_percentage": 100.0, + } + if outcome == "counts": + result.update( + files_added=1, files_removed=3, fragments_added=1, fragments_removed=3 + ) + + if outcome == "partial": + result.update( + partial_commit=True, + rows_succeeded=8, + rows_failed=4, + completion_percentage=100 * 8 / 12, + ) + if outcome == "bounded": + result.update(more_work=True) + if outcome == "no_op": + result.update( + rows_succeeded=0, + files_added=0, + files_removed=0, + fragments_added=0, + fragments_removed=0, + ) + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream(pa.table({"job_id": ["compacting-job"]})) + + def handler(request): + if request.path != "/v1/jobs/describe": + return _create_table_handler(request) + body = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert body == {"job_id": "compacting-job"} + polls.append(body) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "compacting-job", + "job_type": "compact", + "job_state": outcome + if outcome in ("FAILED", "CANCELLED") + else "DONE", + "result": None if outcome == "missing" else result, + } + ).encode() + ) + + server = Server() + with _mock_remote_sql_connection(server, handler) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + job = await table.compact_async( + compaction_options={"target_rows_per_fragment": 100} + ) + assert job.id == "compacting-job" and not polls + if outcome in ("missing", "FAILED", "CANCELLED"): + with pytest.raises( + Exception, + match={ + "missing": "did not contain a result", + "FAILED": "failed", + "CANCELLED": "cancel", + }[outcome], + ): + await job.wait() + else: + stats = await job.wait() + reopened = await db.open_job(job.id) + assert await reopened.wait() == stats + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + job = table.compact_async( + compaction_options={"target_rows_per_fragment": 100} + ) + assert job.id == "compacting-job" and not polls + if outcome in ("missing", "FAILED", "CANCELLED"): + with pytest.raises( + Exception, + match={ + "missing": "did not contain a result", + "FAILED": "failed", + "CANCELLED": "cancel", + }[outcome], + ): + job.wait() + else: + stats = job.wait() + assert db.open_job(job.id).wait() == stats + if outcome in ("counts", "legacy", "partial", "bounded", "no_op"): + from lancedb.compaction import CompactionResult + + assert isinstance(stats, CompactionResult) + assert stats.rows_succeeded == ( + 0 if outcome == "no_op" else 8 if outcome == "partial" else 12 + ) + assert stats.rows_failed == (4 if outcome == "partial" else 0) + assert stats.partial_commit == (outcome == "partial") + assert stats.more_work == (outcome == "bounded") + assert stats.fragments_removed == ( + 3 if outcome == "counts" else 0 if outcome == "no_op" else None + ) + assert len(server.tickets) == 1 + assert b"OPTIMIZE" in server.tickets[0] + assert b"target_rows_per_fragment = 100" in server.tickets[0] + + +@pytest.mark.parametrize("ids", [[], [None], [""], ["a", "b"]]) +def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids): + flight = pytest.importorskip("pyarrow.flight") + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = 0 + + def do_get(self, context, ticket): + self.calls += 1 + return flight.RecordBatchStream( + pa.table({"job_id": pa.array(ids, pa.string())}) + ) + + server = Server() + with _mock_remote_sql_connection(server) as kwargs: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + with pytest.raises(Exception, match="inspect jobs before retrying"): + table.compact_async() + assert server.calls == 1 + + +@pytest.mark.parametrize("method", ["compact_async", "optimize"]) +@pytest.mark.parametrize( + "option", + ["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"], +) +@pytest.mark.parametrize("value", [False, True]) +def test_remote_compaction_rejects_boolean_budgets_without_submitting( + method, option, value +): + flight = pytest.importorskip("pyarrow.flight") + + class UnusedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = 0 + + def do_get(self, context, ticket): + self.calls += 1 + raise AssertionError("boolean compaction settings must not submit SQL") + + server = UnusedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(ValueError, match="must be an integer, not a bool"): + getattr(table, method)(compaction_options={option: value}) + assert server.calls == 0 diff --git a/python/src/connection.rs b/python/src/connection.rs index a32c00be1..e4b666926 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -898,6 +898,10 @@ impl Connection { job.into_typed::().infer_error()?, )) } + Some("compact") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), _ => Ok(crate::job::Job::new(job)), } }) diff --git a/python/src/table.rs b/python/src/table.rs index 2fc421986..ddb934a16 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -370,6 +370,16 @@ fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult() + { + return Err(PyValueError::new_err(format!( + "{key} must be an integer, not a bool" + ))); + } match key.as_str() { "target_rows_per_fragment" => { parsed.target_rows_per_fragment = positive_u32(&value, &key)? @@ -2119,6 +2129,29 @@ impl Table { }) } + /// Submit remote compaction and retain its durable job and actual result. + #[pyo3(signature = (compaction_options=None))] + pub fn compact_async<'py>( + self_: PyRef<'py, Self>, + compaction_options: Option<&Bound<'py, PyDict>>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let target_specified = compaction_options + .map(|options| options.contains("target_rows_per_fragment")) + .transpose()? + .unwrap_or(false); + let options = parse_compaction_options(compaction_options)?; + let mut overrides = + lancedb::table::optimize::CompactionOverrides::try_from(options).infer_error()?; + if !target_specified { + overrides.target_rows_per_fragment = None; + } + future_into_py(self_.py(), async move { + let job = inner.compact_async(overrides).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + /// Optimize the on-disk data by compacting and pruning old data, for better performance. #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))] pub fn optimize<'py>( diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 0e057f3db..4177ddcf8 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -4552,3 +4552,69 @@ async fn remote_prewarm_rejects_historical_checkout_without_submitting() { assert!(statements.lock().unwrap().is_empty()); shutdown.send(()).unwrap(); } + +#[tokio::test] +async fn remote_compaction_tracks_registry_job_and_real_result() { + use crate::table::optimize::CompactionOverrides; + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([( + "job_id", + Arc::new(StringArray::from(vec!["compacting-job"])) as ArrayRef, + )]) + .unwrap(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "compacting-job"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"compacting-job","job_type":"compact","job_state":"DONE", + "result":{"partial_commit":false,"rows_succeeded":12,"rows_failed":0, + "completion_percentage":100.0,"files_added":1,"files_removed":3, + "fragments_added":1,"fragments_removed":3}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "inner".into()], + "team$inner$events".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("experiment".into())); + let job = table + .compact_async(CompactionOverrides { + target_rows_per_fragment: Some(100), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(job.id(), Some("compacting-job")); + assert_eq!(polls.load(Ordering::SeqCst), 0); + let result = job.wait().await.unwrap(); + assert_eq!(result.rows_succeeded, 12); + assert_eq!(result.fragments_removed, Some(3)); + assert!(!result.more_work); + assert_eq!( + *statements.lock().unwrap(), + [ + "OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'experiment', target_rows_per_fragment = 100)" + ] + ); + shutdown.send(()).unwrap(); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 895b89026..92d1d6f30 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4007,19 +4007,10 @@ impl BaseTable for RemoteTable { options: crate::table::optimize::CompactionOverrides, ) -> Result { self.check_mutable().await?; - let compaction_options = optimize::compaction_sql_options(&options)?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; let sql_client = self.sql_client.clone().ok_or_else(|| Error::NotSupported { message: "SQL is unavailable for this remote table client".to_string(), })?; - let mut statement = format!("OPTIMIZE {} REWRITE DATA", quote_sql_identifier(&self.name)); - let mut sql_options = Vec::new(); - if let Some(branch) = &self.branch { - sql_options.push(format!("branch = {}", quote_sql_string(branch))); - } - sql_options.extend(compaction_options); - if !sql_options.is_empty() { - statement.push_str(&format!(" WITH ({})", sql_options.join(", "))); - } // `OptimizeStats` carries `lance::dataset::optimize` metric types that // are not `Serialize`/`Deserialize`/`Clone`, which `Job` requires, // so the job itself only signals completion; the real (placeholder) @@ -4036,6 +4027,42 @@ impl BaseTable for RemoteTable { prune: None, }) } + async fn compact_async( + &self, + options: crate::table::optimize::CompactionOverrides, + ) -> Result> { + self.check_mutable().await?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "compaction jobs require a Flight SQL endpoint".into(), + })?; + let query = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(optimize::map_optimize_error)?; + let mut reader = query.reader().await.map_err(optimize::map_optimize_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader + .try_next() + .await + .map_err(optimize::map_optimize_error)? + { + batches.push(batch); + } + let job_id = optimize::receipt(&batches)?; + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + async fn add_columns( &self, transforms: NewColumnTransform, diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 6f4b7f7e8..80d4d9639 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -4,6 +4,49 @@ //! Compaction options supported by the remote SQL submission protocol. use crate::error::{Error, Result}; +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &crate::table::optimize::CompactionOverrides, +) -> Result { + let mut settings = compaction_sql_options(options)?; + if let Some(branch) = branch { + settings.insert(0, format!("branch = {}", super::quote_sql_string(branch))); + } + let mut sql = format!( + "OPTIMIZE {} REWRITE DATA", + super::quote_sql_identifier(table) + ); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + Ok(sql) +} + +/// Submission can already have created work: reject ambiguous receipts without +/// retrying or confusing the SQL query's identity with the compaction job. +pub(super) fn receipt(batches: &[arrow_array::RecordBatch]) -> Result { + use arrow_array::{Array, StringArray}; + let invalid = || { + Error::Runtime { message: "OPTIMIZE did not return a single nonempty job_id receipt; inspect jobs before retrying because compaction may already have been submitted".into() } + }; + if batches.iter().map(|batch| batch.num_rows()).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let ids = batch + .column_by_name("job_id") + .and_then(|a| a.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if ids.is_null(0) || ids.value(0).is_empty() { + return Err(invalid()); + } + Ok(ids.value(0).into()) +} + pub(super) fn compaction_sql_options( options: &crate::table::optimize::CompactionOverrides, ) -> Result> { @@ -258,3 +301,37 @@ mod tests { } } } + +#[cfg(test)] +mod receipt_tests { + use super::*; + use arrow_array::{ArrayRef, RecordBatch, StringArray}; + use std::sync::Arc; + + #[test] + fn compaction_receipt_requires_one_unambiguous_registry_id() { + let batch = |ids: Vec>| { + RecordBatch::try_from_iter([("job_id", Arc::new(StringArray::from(ids)) as ArrayRef)]) + .unwrap() + }; + assert_eq!( + receipt(&[batch(vec![Some("compacting-job")])]).unwrap(), + "compacting-job" + ); + for batches in [ + vec![], + vec![batch(vec![])], + vec![batch(vec![None])], + vec![batch(vec![Some("")])], + vec![batch(vec![Some("a"), Some("b")])], + vec![batch(vec![Some("a")]), batch(vec![Some("b")])], + ] { + assert!( + receipt(&batches) + .unwrap_err() + .to_string() + .contains("inspect jobs before retrying") + ); + } + } +} diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index e8ce17b7b..e6cc43855 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -86,6 +86,7 @@ pub mod freshness; pub mod function_column_status; pub mod merge; pub mod optimize; +pub use optimize::CompactionResult; mod prewarm; pub use prewarm::PrewarmDataOptions; pub(crate) mod primary_key; @@ -887,6 +888,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn tags(&self) -> Result>; /// Optimize the dataset. async fn optimize(&self, action: OptimizeAction) -> Result; + /// Submit remote compaction and retain its durable job and actual outcome. + async fn compact_async( + &self, + _options: optimize::CompactionOverrides, + ) -> Result> { + Err(Error::NotSupported { + message: "compaction jobs are only supported on remote tables".into(), + }) + } /// Compact with optional fields, preserving remote policy inheritance. async fn compact(&self, options: optimize::CompactionOverrides) -> Result { self.optimize(OptimizeAction::Compact { @@ -2040,6 +2050,37 @@ impl Table { self.inner.compact(options).await } + /// Submit remote compaction and return its durable job after acceptance. + /// + /// Uses SQL `OPTIMIZE ... REWRITE DATA` with the table handle's namespace + /// and branch. The four fields of [`optimize::CompactionOverrides`] retain + /// server defaults when omitted. Requires a compatible remote SQL server + /// and table Ownership plus database/namespace Usage under Standard authorization. + /// Historical-version and local handles are unsupported. + /// + /// Unlike [`Self::optimize`], waiting on this handle waits for compaction + /// itself and returns actual [`CompactionResult`] values. Status, progress, + /// events, and cancellation use the generic HTTP job APIs. A timeout or + /// dropping the handle does not cancel work. Missing result payloads are + /// errors, never placeholder zero statistics. An older worker may omit + /// file counts, represented as `None`. Reopen with + /// `connection.open_job(id).await?.into_typed::()?`. + /// + /// ```no_run + /// # async fn compact(table: &lancedb::Table) -> lancedb::Result<()> { + /// let job = table.compact_async(Default::default()).await?; + /// let result = job.wait().await?; + /// println!("Committed {} rows", result.rows_succeeded); + /// # Ok(()) + /// # } + /// ``` + pub async fn compact_async( + &self, + options: optimize::CompactionOverrides, + ) -> Result> { + self.inner.compact_async(options).await + } + /// Language-binding entry point retaining optional compaction fields. #[doc(hidden)] pub async fn optimize_full_with_overrides( diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index ab34e05c6..0089cdd3f 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -32,6 +32,35 @@ pub use lance::dataset::optimize::{CompactionMode, CompactionOptions, IndexRemap const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64; +/// Actual outcome of one remote compaction job, returned by its job handle. +/// +/// A successful bounded run can leave more work for another invocation. A +/// partial commit reports uncommitted rows rather than inventing file counts. +/// File/fragment counts are unknown (`None`) when an older worker omitted them. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct CompactionResult { + /// A complete bounded plan left eligible work for a later invocation. + #[serde(default)] + pub more_work: bool, + /// Some planned groups were not committed. + pub partial_commit: bool, + /// Live source rows in committed rewrite groups. + pub rows_succeeded: u64, + /// Planned live rows not committed by this job. + pub rows_failed: u64, + /// Percentage of planned live rows committed, from 0 to 100. + pub completion_percentage: f64, + /// Data files added by committed rewrites, when reported by the server. + pub files_added: Option, + /// Data files removed by committed rewrites, when reported by the server. + pub files_removed: Option, + /// Fragments added by committed rewrites, when reported by the server. + pub fragments_added: Option, + /// Fragments removed by committed rewrites, when reported by the server. + pub fragments_removed: Option, +} + struct PrecomputedCompactionPlanner { plan: Mutex>, }