feat(sdk): add durable compaction jobs with typed results

This commit is contained in:
ChilePiquin
2026-11-14 16:23:27 -08:00
parent eaa160c1b7
commit 6aa2a85dde
32 changed files with 1043 additions and 62 deletions
Generated
+1
View File
@@ -6165,6 +6165,7 @@ dependencies = [
"napi",
"napi-build",
"napi-derive",
"serde",
"serde_json",
]
+12 -8
View File
@@ -456,7 +456,7 @@ Rejects a table that exists but is not a materialized view.
### dropMaterializedViewAsync()
```ts
abstract dropMaterializedViewAsync(name, namespacePath?): Promise<Job>
abstract dropMaterializedViewAsync(name, namespacePath?): Promise<Job<void>>
```
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`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
***
@@ -532,7 +532,7 @@ Drop an existing table.
### dropTableAsync()
```ts
abstract dropTableAsync(name, namespacePath?): Promise<Job>
abstract dropTableAsync(name, namespacePath?): Promise<Job<void>>
```
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`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
***
@@ -579,7 +579,7 @@ catalog removal; physical cleanup continues in the background.
### dropViewAsync()
```ts
abstract dropViewAsync(name, namespacePath?): Promise<Job>
abstract dropViewAsync(name, namespacePath?): Promise<Job<void>>
```
Drop a view and return its SQL query job.
@@ -594,7 +594,7 @@ catalog removal; physical cleanup continues in the background.
#### Returns
`Promise`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
***
@@ -729,7 +729,7 @@ state and error behavior; options control page size and the starting token.
### openJob()
```ts
abstract openJob(jobId): Promise<Job>
abstract openJob<T>(jobId): Promise<Job<T>>
```
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`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`T`&gt;&gt;
***
+7 -3
View File
@@ -4,7 +4,7 @@
[@lancedb/lancedb](../globals.md) / Job
# Class: Job
# Class: Job&lt;T&gt;
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<void>
wait(progressCallback?): Promise<T>
```
Wait until the operation reaches a terminal state.
@@ -259,4 +263,4 @@ callback exception does not reject `wait`.
#### Returns
`Promise`&lt;`void`&gt;
`Promise`&lt;`T`&gt;
+40 -6
View File
@@ -305,6 +305,40 @@ It is a no-op when no writers are cached.
***
### compactAsync()
```ts
compactAsync(_options?): Promise<Job<CompactionResult>>
```
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<CompactionResult>(job.id!). A wait timeout does not cancel work.
#### Parameters
* **\_options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md)
#### Returns
`Promise`&lt;[`Job`](Job.md)&lt;[`CompactionResult`](../interfaces/CompactionResult.md)&gt;&gt;
#### 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<Job>
abstract createIndexAsync(column, options?): Promise<Job<void>>
```
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`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
***
@@ -1076,7 +1110,7 @@ Prewarm one or more columns of data in the table.
### prewarmDataAsync()
```ts
abstract prewarmDataAsync(options?): Promise<Job>
abstract prewarmDataAsync(options?): Promise<Job<void>>
```
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`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
#### Example
@@ -1238,7 +1272,7 @@ number of rows filled and the new version number of the table.
### refreshColumnAsync()
```ts
abstract refreshColumnAsync(column, options?): Promise<Job>
abstract refreshColumnAsync(column, options?): Promise<Job<void>>
```
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`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
#### Example
+1
View File
@@ -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)
@@ -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.
+2
View File
@@ -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
+67
View File
@@ -63,6 +63,73 @@ separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs
even though `optimize()` bundles both in one LanceDB Embedded call.
</Note>
## 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.
<CodeGroup>
```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<CompactionResult>(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::<CompactionResult>()?.wait().await?;
}
```
</CodeGroup>
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.
+1
View File
@@ -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
+44
View File
@@ -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<import("../lancedb").CompactionResult>(
"compacting-job",
);
const result = await job.wait();
expect(result.rowsSucceeded).toBe(12);
expect(result.moreWork).toBe(false);
expect(result.fragmentsRemoved).toBe(counts ? 3 : null);
},
);
},
);
});
+16
View File
@@ -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");
});
});
+41
View File
@@ -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<string, number | boolean | null>;
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,
};
}
+3 -3
View File
@@ -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<Job>;
abstract openJob<T = void>(jobId: string): Promise<Job<T>>;
/**
* 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<Job> {
return new Job(await this.inner.openJob(jobId));
async openJob<T = void>(jobId: string): Promise<Job<T>> {
return new Job<T>(await this.inner.openJob(jobId));
}
listJobs(options: ListingOptions = {}): Listing<JobInfo> {
+2
View File
@@ -662,3 +662,5 @@ export {
} from "./catalog";
export { Listing, ListingOptions } from "./listing";
export type { CompactionResult } from "./compaction";
+25 -12
View File
@@ -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<T = void> {
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<void> {
if (progressCallback === undefined) {
return this.inner.wait();
async wait(progressCallback?: JobProgressCallback): Promise<T> {
const callback =
progressCallback === undefined
? undefined
: (progress: Record<string, unknown>) => {
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. */
+51 -13
View File
@@ -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<void>;
/**
* 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<CompactionResult>(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<Job<CompactionResult>> {
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<Job<CompactionResult>> {
validateCompactionOptions(options);
return new Job(
await this.inner.compactAsync(options),
decodeCompactionResult,
);
}
async optimize(options?: Partial<OptimizeOptions>): Promise<OptimizeStats> {
// 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}`);
}
}
}
+8 -1
View File
@@ -567,7 +567,14 @@ impl Connection {
#[napi(catch_unwind)]
pub async fn open_job(&self, job_id: String) -> napi::Result<crate::job::Job> {
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::<lancedb::table::CompactionResult>()
.default_error()?,
))
} else {
Ok(crate::job::Job::new(job))
}
}
/// List server-side jobs across the database's tables.
+31 -6
View File
@@ -17,7 +17,7 @@ type JobProgressFn =
/// A handle to an operation that may still be running.
#[napi]
pub struct Job {
inner: Arc<lancedb::Job>,
inner: Arc<lancedb::Job<std::result::Result<Option<serde_json::Value>, 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<T>(inner: lancedb::Job<T>) -> 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<string, unknown>) => void"
)]
pub async fn wait(&self, progress_callback: Option<JobProgressFn>) -> 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<string, unknown>) => void"
)]
pub async fn wait_result(
&self,
progress_callback: Option<JobProgressFn>,
) -> napi::Result<Option<serde_json::Value>> {
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.
+17
View File
@@ -909,6 +909,23 @@ impl Table {
Ok(self.inner_ref()?.current_branch())
}
#[napi(catch_unwind)]
pub async fn compact_async(
&self,
options: Option<CompactionOptions>,
) -> napi::Result<crate::job::Job> {
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,
+3
View File
@@ -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,
*,
+36
View File
@@ -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})
+3
View File
@@ -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)
+8
View File
@@ -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,
*,
+48
View File
@@ -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,
*,
+190
View File
@@ -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
+4
View File
@@ -898,6 +898,10 @@ impl Connection {
job.into_typed::<RefreshColumnResult>().infer_error()?,
))
}
Some("compact") => Ok(crate::job::Job::new_typed(
job.into_typed::<lancedb::table::CompactionResult>()
.infer_error()?,
)),
_ => Ok(crate::job::Job::new(job)),
}
})
+33
View File
@@ -370,6 +370,16 @@ fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<Com
for (key, value) in options.iter() {
let key: String = key.extract()?;
// Python bool is an int subclass: never turn True into a one-row budget.
if matches!(
key.as_str(),
"target_rows_per_fragment" | "max_source_rows" | "io_buffer_size" | "batch_size"
) && value.is_instance_of::<PyBool>()
{
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<Bound<'py, PyAny>> {
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>(
+66
View File
@@ -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();
}
+37 -10
View File
@@ -4007,19 +4007,10 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
options: crate::table::optimize::CompactionOverrides,
) -> Result<OptimizeStats> {
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<T>` requires,
// so the job itself only signals completion; the real (placeholder)
@@ -4036,6 +4027,42 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
prune: None,
})
}
async fn compact_async(
&self,
options: crate::table::optimize::CompactionOverrides,
) -> Result<Job<crate::table::CompactionResult>> {
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,
+77
View File
@@ -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<String> {
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<String> {
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::<usize>() != 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::<StringArray>())
.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<Vec<String>> {
@@ -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<Option<&str>>| {
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")
);
}
}
}
+41
View File
@@ -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<Box<dyn Tags + '_>>;
/// Optimize the dataset.
async fn optimize(&self, action: OptimizeAction) -> Result<OptimizeStats>;
/// Submit remote compaction and retain its durable job and actual outcome.
async fn compact_async(
&self,
_options: optimize::CompactionOverrides,
) -> Result<Job<CompactionResult>> {
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<OptimizeStats> {
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::<CompactionResult>()?`.
///
/// ```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<Job<CompactionResult>> {
self.inner.compact_async(options).await
}
/// Language-binding entry point retaining optional compaction fields.
#[doc(hidden)]
pub async fn optimize_full_with_overrides(
+29
View File
@@ -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<u64>,
/// Data files removed by committed rewrites, when reported by the server.
pub files_removed: Option<u64>,
/// Fragments added by committed rewrites, when reported by the server.
pub fragments_added: Option<u64>,
/// Fragments removed by committed rewrites, when reported by the server.
pub fragments_removed: Option<u64>,
}
struct PrecomputedCompactionPlanner {
plan: Mutex<Option<CompactionPlan>>,
}