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
+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,