feat: add cleanup jobs and previews across SDKs (#5107)

LanceDB SDK users connected to Enterprise had no explicit API to submit
durable cleanup or preview its work; Python's existing cleanup helper
remained a warning-only no-op. This PR adds the SDK support for
[ENT-2687](https://linear.app/lancedb/issue/ENT-2687) through public SQL
and Job APIs. It requires a compatible Enterprise release supporting
`VACUUM`, JSON preview and result format version 1. Existing
cleanup/optimize helpers retain their behavior; the new APIs reject
Embedded and historical-version handles.

This was accomplished with the following changes:

- Add `cleanup_async()` / `cleanupAsync()` and `explain_cleanup()` /
`explainCleanup()` in Python sync/async, TypeScript and Rust.
- Preserve the handle's namespace/branch and resolve retention as
invocation → table/branch TTL → deployment default. Omission inherits,
zero is explicit, and malformed options fail rather than being
discarded.
- Require one nonempty durable SQL receipt, preserving diagnostics
without REST fallback, query-ID substitution or automatic resubmission
after ambiguous acceptance.
- Add versioned `CleanupPlan` estimates and `CleanupResult`
measurements. Preview creates no cleanup job or reservation; results
preserve known zero, unknown retry/recovery totals and nonfatal failed
deletes, excluding auxiliary sweeps.
- Retain typed results on reopening and reuse shared
status/progress/events/wait/cancel APIs. Timeout leaves work running;
cancellation cannot undo deletion or prove storage I/O stopped.
- Document Ownership/parent Usage and required coordination at every
retention value: disable/drain automatic cleanup and prevent competing
cleanup, tag creation/update, branch creation and restore across all
clients until completion. The server does not enforce exclusion;
concurrent restore can leave the current table unreadable.
- Update Python's legacy no-op warning and the maintenance, Python, Rust
and generated TypeScript references.

| Interface | Submit with seven-day retention |
| --- | --- |
| SQL | `VACUUM events WITH (min_age_seconds = 604800);` |
| CLI | `lancedb admin table cleanup --table events --min-age-seconds
604800 --wait` |
| Python | `job = table.cleanup_async(min_age_seconds=604800)` (use
`await` with AsyncTable) |
| TypeScript | `const job = await table.cleanupAsync({ minAgeSeconds:
604800 });` |
| Rust | `let job =
table.cleanup_async(CleanupOptions::new().min_age_seconds(604800)).await?;`
|

### Testing

Added submission/preview, validation, typed-result and reopening tests,
and updated the legacy no-op warning assertion. Focused Python
cleanup/Job and compaction/prewarm regressions passed, alongside **34
TypeScript** and **46 Rust** tests. **31 end-to-end scenarios** passed
against a real Enterprise server, covering CLI/SQL/REST/SDK submission,
retention precedence, restart/reopening, timeouts, cancellation and
branch/namespace isolation.

Local native SDK validation used a separate `libsais-rs 0.2.0` lockfile
because the registry could not resolve `0.2.4`; this PR retains main's
dependency pins and lockfile.
This commit is contained in:
Bruno Ramirez
2026-11-20 14:34:07 -08:00
committed by GitHub
parent 8fd1c716d9
commit baea02eebd
30 changed files with 1679 additions and 18 deletions
+50
View File
@@ -268,6 +268,38 @@ const after = await table.getRTEStats();
***
### cleanupAsync()
```ts
cleanupAsync(_options?): Promise<Job<CleanupResult>>
```
Submit durable remote cleanup through SQL VACUUM and return after acceptance.
Requires table Ownership and parent Usage. Retention inherits from the table
then deployment when omitted. Local/historical handles are unsupported.
Before submission, disable/drain automatic cleanup and prevent other cleanup,
tag/branch publication and restore until completion, including direct clients.
Coordination is not enforced by the server. Cancellation cannot undo deletion
or prove storage I/O stopped. Preview is available without deletion.
Wait timeout leaves work running; save the ID and reopen with db.openJob().
#### Parameters
* **\_options?**: [`CleanupOptions`](../interfaces/CleanupOptions.md)
#### Returns
`Promise`&lt;[`Job`](Job.md)&lt;[`CleanupResult`](../interfaces/CleanupResult.md)&gt;&gt;
#### Example
```ts
const job = await table.cleanupAsync({ minAgeSeconds: 604800 });
const result = await job.wait({ timeoutMs: 600000 });
```
***
### close()
```ts
@@ -653,6 +685,24 @@ await table.enableRTE({
***
### explainCleanup()
```ts
explainCleanup(_options?): Promise<CleanupPlan>
```
Preview version deletion without creating a job. Execution re-evaluates current state.
#### Parameters
* **\_options?**: [`CleanupOptions`](../interfaces/CleanupOptions.md)
#### Returns
`Promise`&lt;[`CleanupPlan`](../interfaces/CleanupPlan.md)&gt;
***
### explainPrewarmData()
```ts
+3
View File
@@ -71,6 +71,9 @@
- [CherryPickError](interfaces/CherryPickError.md)
- [CherryPickPreview](interfaces/CherryPickPreview.md)
- [CherryPickResult](interfaces/CherryPickResult.md)
- [CleanupOptions](interfaces/CleanupOptions.md)
- [CleanupPlan](interfaces/CleanupPlan.md)
- [CleanupResult](interfaces/CleanupResult.md)
- [ClientConfig](interfaces/ClientConfig.md)
- [ColumnAlteration](interfaces/ColumnAlteration.md)
- [ColumnOrdering](interfaces/ColumnOrdering.md)
+19
View File
@@ -0,0 +1,19 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / CleanupOptions
# Interface: CleanupOptions
Per-run retention; omission inherits selected table/branch then deployment policy.
## Properties
### minAgeSeconds?
```ts
optional minAgeSeconds: number;
```
Minimum old-version age in seconds. Zero is explicit, not omitted.
+57
View File
@@ -0,0 +1,57 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / CleanupPlan
# Interface: CleanupPlan
Read-only deletion estimates; no job or deletion snapshot is reserved.
## Properties
### bytesToRemove
```ts
bytesToRemove: number;
```
***
### cutoffMillis
```ts
cutoffMillis: number;
```
***
### formatVersion
```ts
formatVersion: number;
```
***
### minAgeSeconds
```ts
minAgeSeconds: number;
```
***
### sourceVersion
```ts
sourceVersion: number;
```
***
### versionsToRemove
```ts
versionsToRemove: number;
```
+61
View File
@@ -0,0 +1,61 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / CleanupResult
# Interface: CleanupResult
Version-deletion outcome. Best-effort auxiliary sweeps are excluded.
## Properties
### bytesRemoved
```ts
bytesRemoved: null | number;
```
***
### failedDeletes
```ts
failedDeletes: null | number;
```
Failed object deletions, if measured. Successful removals are retained.
***
### formatVersion
```ts
formatVersion: number;
```
***
### minAgeSeconds
```ts
minAgeSeconds: number;
```
***
### oldVersions
```ts
oldVersions: null | number;
```
***
### statisticsComplete
```ts
statisticsComplete: boolean;
```
False after uncertain retry/recovery; both counts are then null.
+4
View File
@@ -1580,6 +1580,10 @@ Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or
::: lancedb.compaction.CompactionResult
::: lancedb.cleanup.CleanupPlan
::: lancedb.cleanup.CleanupResult
::: lancedb.prewarm.PrewarmDataResult
::: lancedb.prewarm.PrewarmDataPlan
@@ -125,14 +125,19 @@ for the fields, precedence, source-budget planning failures, and compatible-vers
they referenced. In LanceDB Embedded, that always happens because you asked
for it, through a call to `optimize()`. In LanceDB Enterprise, a
[manual `optimize()` call](/maintenance/compaction#enterprise-manual-compaction)
submits compaction only. Cleanup remains this planner's own decision, off by
default unless the deployment sets a minimum version age:
submits compaction only. This planner controls automatic cleanup, which is
disabled by default unless the deployment sets a minimum version age:
with no minimum age configured, nothing is ever old enough to clean up
automatically, and old versions simply accumulate until an operator enables
it. A table can also disable it individually even when the deployment allows
it, overriding the deployment-wide setting for just that table.
automatically. A table can also disable automatic cleanup individually even
when the deployment allows it, overriding the deployment-wide setting for
just that table.
Once enabled, a table becomes due for cleanup when any one of these is true:
You can [submit manual cleanup](/maintenance/cleanup#enterprise-manual-cleanup)
even when automatic cleanup is disabled. Follow the coordination requirements
in that guide before submitting a manual run.
Once automatic cleanup is enabled, a table becomes due when any one of these
is true:
| Trigger | Condition |
| --- | --- |
+115 -4
View File
@@ -17,12 +17,15 @@ those versions referenced.
<Note>
**Enterprise job type:** `cleanup`. Distinct from `compact`: compaction
merges files, cleanup removes them. `optimize()` in LanceDB Embedded runs both in one call;
Enterprise schedules them as separate jobs, and runs cleanup only when the
deployment's configuration enables it.
Enterprise schedules them as separate jobs. Automatic cleanup follows deployment
and table policy; authorized manual cleanup can run while automatic cleanup is disabled.
</Note>
## Retention {#retention}
The Embedded examples below keep their existing behavior. For an explicit
Enterprise job, use [manual cleanup](#enterprise-manual-cleanup).
<CodeGroup>
```python Python icon="python"
from datetime import timedelta
@@ -77,6 +80,114 @@ to cover the range you
need before running this, not after.
</Warning>
## Enterprise manual cleanup {#enterprise-manual-cleanup}
Requires compatible SDK and Enterprise query-node, agent and worker releases
with SQL `VACUUM` and cleanup result format version 1. Submission requires table
Ownership and database/namespace Usage. SDK methods use the table handle's
namespace and branch; historical-version handles and LanceDB Embedded are unsupported.
<Warning>
Before submission, disable automatic cleanup for the table and its branches,
drain existing cleanup workers, and prevent other cleanup, tag creation/update,
branch creation and restore until completion, including direct storage clients.
The server does not enforce this coordination. Restore prior scheduling settings
afterward. Disabling scheduling or cancelling a job does not prove outstanding
storage requests stopped. Concurrent restore can make the current table unreadable.
These restrictions apply to every retention value, including zero.
</Warning>
<CodeGroup>
```python Python icon="python"
from datetime import timedelta
job = table.cleanup_async(min_age_seconds=604800)
print(job.id) # Save this durable ID.
result = job.wait(timeout=timedelta(minutes=10), progress=print)
print(result.old_versions, result.bytes_removed)
reopened = db.open_job(job.id)
```
```python Python async icon="python"
job = await table.cleanup_async(min_age_seconds=604800)
result = await job.wait()
reopened = await db.open_job(job.id)
```
```typescript TypeScript icon="js"
const job = await table.cleanupAsync({ minAgeSeconds: 604800 });
const result = await job.wait({ timeoutMs: 600000, onProgress: console.log });
console.log(result.oldVersions, result.bytesRemoved);
const reopened = await db.openJob(job.id!);
```
```rust Rust icon="rust"
use lancedb::table::{CleanupOptions, CleanupResult};
let job = table.cleanup_async(CleanupOptions::new().min_age_seconds(604800)).await?;
let result = job.wait().await?;
println!("{:?} {:?}", result.old_versions, result.bytes_removed);
let reopened = db.open_job(job.id().unwrap()).await?.into_typed::<CleanupResult>()?;
```
</CodeGroup>
Submission returns after durable acceptance, before deletion finishes. Omit the
retention option to inherit selected table/branch `job_types.cleanup.ttl_seconds`,
then deployment retention. Zero is explicit; invalid/missing effective retention
fails. The resolved age stays with the job and does not change table policy.
The worker calculates its cutoff against latest state at execution; the observed
submission version is not a reserved deletion snapshot.
Status, progress, events, waiting, cancellation and reopening reuse the shared
[Job APIs](/basics/jobs) and their existing REST permissions. Describe supports
scoped database/namespace Usage; events require system Usage and cancellation
requires system Operate. Waiting timeout leaves the job running. Failure or
cancellation may follow partial deletion and cannot roll it back.
`CleanupResult` reports effective retention, `statistics_complete` and optional
`old_versions` / `bytes_removed` (`statisticsComplete`, `oldVersions` and
`bytesRemoved` in TypeScript). Counts cover version deletion, not best-effort
auxiliary sweeps. Unknown totals after retry/recovery remain None/null; measured
zero stays zero. `failed_deletes` / `failedDeletes` reports nonfatal object deletion failures
when measured; successful removals are retained. Missing or incompatible typed results raise an error rather
than inventing counts. Completion does not guarantee every orphaned file was reclaimed.
Preview deletion using the same options, without creating a job:
<CodeGroup>
```python Python icon="python"
plan = table.explain_cleanup(min_age_seconds=604800)
print(plan.source_version, plan.versions_to_remove, plan.bytes_to_remove)
# AsyncTable: plan = await table.explain_cleanup(min_age_seconds=604800)
```
```typescript TypeScript icon="js"
const plan = await table.explainCleanup({ minAgeSeconds: 604800 });
console.log(plan.sourceVersion, plan.versionsToRemove, plan.bytesToRemove);
```
```rust Rust icon="rust"
let plan = table.explain_cleanup(CleanupOptions::new().min_age_seconds(604800)).await?;
println!("{} {}", plan.versions_to_remove, plan.bytes_to_remove);
```
</CodeGroup>
`CleanupPlan` is a versioned SQL `EXPLAIN (FORMAT JSON) VACUUM` response. It
reports observed source version, effective retention, cutoff milliseconds and
version/byte deletion estimates. It can list metadata/storage objects but does
not delete, submit or monitor a job, expose file paths, or reserve the preview
snapshot. Auxiliary sweeps are excluded. Execution re-evaluates latest state;
actual removals can differ. `EXPLAIN ANALYZE` is rejected. Read-only preview does
not require draining automatic work; actual cleanup still requires coordination.
The SDK does not fall back to execution/REST or silently drop unsupported
options. If acceptance is ambiguous, inspect jobs before retrying; an independent
submission can create another job.
Python's existing Enterprise `cleanup_old_versions()` remains a warning-only
no-op for compatibility. Use `cleanup_async()` explicitly to submit a job.
Embedded cleanup and Enterprise `optimize()` retain their existing behavior.
## Managed blob objects {#managed-blobs}
[Managed blobs](/management/table#managed-blobs) store out-of-line payloads
@@ -98,8 +209,8 @@ them, and reopen handles created before that upgrade.
For LanceDB Embedded tables, `optimize()` performs compaction and cleanup.
Enterprise schedules them as separate background jobs. With compatible releases,
remote `optimize()` also submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction),
but does not prune versions or remove their files. Cleanup remains governed by
the deployment's separate policy.
but does not prune versions or remove their files. Automatic cleanup remains governed by
the deployment's separate policy; explicit manual cleanup uses the retention rules above.
See [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path.
## Disk usage does not drop immediately {#disk}
+83
View File
@@ -0,0 +1,83 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import {
type CleanupOptions,
decodeCleanupPlan,
decodeCleanupResult,
validateCleanupOptions,
} from "../lancedb/cleanup";
test.each([null, [], 1, true, "options"])(
"cleanup rejects malformed options instead of inheriting retention (%p)",
(options) => {
expect(() =>
validateCleanupOptions(options as unknown as CleanupOptions),
).toThrow("cleanup options must be an object");
},
);
test("cleanup never silently discards an unknown option", () => {
expect(() =>
validateCleanupOptions({ force: true } as unknown as CleanupOptions),
).toThrow("Unknown cleanup option");
});
test.each([undefined, 0, 604800])(
"cleanup retention accepts omission and explicit zero (%s)",
(age) => {
expect(() => validateCleanupOptions({ minAgeSeconds: age })).not.toThrow();
},
);
test.each([
-1,
1.5,
Number.NaN,
Number.POSITIVE_INFINITY,
Number.MAX_SAFE_INTEGER + 1,
])("cleanup retention rejects invalid values (%s)", (age) => {
expect(() => validateCleanupOptions({ minAgeSeconds: age })).toThrow();
});
test.each([0, 2, null])(
"cleanup results distinguish known zero and unknown (%s)",
(count) => {
const result = decodeCleanupResult(
JSON.parse(
JSON.stringify({
["format_version"]: 1,
["min_age_seconds"]: 0,
["statistics_complete"]: count !== null,
["old_versions"]: count,
["bytes_removed"]: count,
future: "ignored",
}),
),
);
expect(result.oldVersions).toBe(count);
},
);
test.each([
null,
{},
{ ["format_version"]: 2 },
{
["format_version"]: 1,
["min_age_seconds"]: 0,
["statistics_complete"]: false,
["old_versions"]: 1,
},
])("cleanup rejects incompatible results (%p)", (value) => {
expect(() => decodeCleanupResult(value)).toThrow();
});
test("cleanup preview validates its versioned contract", () => {
const value = JSON.parse(
'{"format_version":1,"source_version":42,"min_age_seconds":0,"cutoff_millis":-1,"versions_to_remove":2,"bytes_to_remove":100}',
);
expect(decodeCleanupPlan(value).versionsToRemove).toBe(2);
value.format_version = 2;
expect(() => decodeCleanupPlan(value)).toThrow();
});
+56
View File
@@ -3223,3 +3223,59 @@ describe("table overrides", () => {
expect(requests).toEqual([]);
});
});
describe("cleanup typed results", () => {
test.each(["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"])(
"reopens and waits for cleanup (%s)",
async (outcome) => {
const known = outcome !== "unknown";
await withMockDatabase(
(request, response) => {
expect(request.url).toBe("/v1/jobs/describe");
response.writeHead(200, { "Content-Type": "application/json" });
response.end(
JSON.stringify({
["job_id"]: "cleanup-job",
["job_type"]: "cleanup",
["job_state"]: ["FAILED", "CANCELLED"].includes(outcome)
? outcome
: "DONE",
result:
outcome === "missing"
? null
: {
["format_version"]: 1,
["min_age_seconds"]: 0,
["statistics_complete"]: known,
["old_versions"]: known
? outcome === "no_op"
? 0
: 2
: null,
["bytes_removed"]: known
? outcome === "no_op"
? 0
: 123
: null,
},
}),
);
},
async (db) => {
const job =
await db.openJob<import("../lancedb").CleanupResult>("cleanup-job");
if (["missing", "FAILED", "CANCELLED"].includes(outcome)) {
await expect(job.wait()).rejects.toThrow();
} else {
const result = await job.wait();
expect(result.statisticsComplete).toBe(known);
expect(result.oldVersions).toBe(
known ? (outcome === "no_op" ? 0 : 2) : null,
);
expect(result.minAgeSeconds).toBe(0);
}
},
);
},
);
});
+120
View File
@@ -0,0 +1,120 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
/** Per-run retention; omission inherits selected table/branch then deployment policy. */
export interface CleanupOptions {
/** Minimum old-version age in seconds. Zero is explicit, not omitted. */
minAgeSeconds?: number;
}
/** Version-deletion outcome. Best-effort auxiliary sweeps are excluded. */
export interface CleanupResult {
formatVersion: number;
minAgeSeconds: number;
/** False after uncertain retry/recovery; both counts are then null. */
statisticsComplete: boolean;
oldVersions: number | null;
bytesRemoved: number | null;
/** Failed object deletions, if measured. Successful removals are retained. */
failedDeletes: number | null;
}
/** Read-only deletion estimates; no job or deletion snapshot is reserved. */
export interface CleanupPlan {
formatVersion: number;
sourceVersion: number;
minAgeSeconds: number;
cutoffMillis: number;
versionsToRemove: number;
bytesToRemove: number;
}
/** @internal */
export function decodeCleanupPlan(value: unknown): CleanupPlan {
if (typeof value !== "object" || value === null)
throw new Error("invalid cleanup preview");
const plan = value as Record<string, unknown>;
if (
plan.format_version !== 1 ||
[
"source_version",
"min_age_seconds",
"cutoff_millis",
"versions_to_remove",
"bytes_to_remove",
].some(
(key) =>
!Number.isSafeInteger(plan[key]) ||
(key !== "cutoff_millis" && (plan[key] as number) < 0),
)
) {
throw new Error("unsupported or invalid cleanup preview");
}
return {
formatVersion: 1,
sourceVersion: plan.source_version as number,
minAgeSeconds: plan.min_age_seconds as number,
cutoffMillis: plan.cutoff_millis as number,
versionsToRemove: plan.versions_to_remove as number,
bytesToRemove: plan.bytes_to_remove as number,
};
}
/** @internal */
export function validateCleanupOptions(options?: CleanupOptions): void {
if (
options !== undefined &&
(typeof options !== "object" || options === null || Array.isArray(options))
) {
throw new Error("cleanup options must be an object");
}
for (const key of Object.keys(options ?? {})) {
if (key !== "minAgeSeconds")
throw new Error(`Unknown cleanup option: ${key}`);
}
const age = options?.minAgeSeconds;
if (age !== undefined && (!Number.isSafeInteger(age) || age < 0)) {
throw new Error("minAgeSeconds must be a nonnegative safe integer");
}
}
/** @internal */
export function decodeCleanupResult(value: unknown): CleanupResult {
if (typeof value !== "object" || value === null)
throw new Error("invalid cleanup result");
const result = value as Record<string, unknown>;
const counts = [result.old_versions ?? null, result.bytes_removed ?? null];
const failed = result.failed_deletes ?? null;
if (
failed !== null &&
(!Number.isSafeInteger(failed) ||
(failed as number) < 0 ||
result.statistics_complete !== true)
) {
throw new Error("invalid cleanup failed-deletion measurement");
}
if (
result.format_version !== 1 ||
typeof result.statistics_complete !== "boolean" ||
!Number.isSafeInteger(result.min_age_seconds) ||
(result.min_age_seconds as number) < 0 ||
counts.some(
(count) =>
count !== null &&
(!Number.isSafeInteger(count) || (count as number) < 0),
) ||
(result.statistics_complete
? counts.some((count) => count === null)
: counts.some((count) => count !== null))
) {
throw new Error("unsupported or inconsistent cleanup result");
}
return {
formatVersion: 1,
minAgeSeconds: result.min_age_seconds as number,
statisticsComplete: result.statistics_complete,
oldVersions: counts[0] as number | null,
bytesRemoved: counts[1] as number | null,
failedDeletes: (result.failed_deletes as number | null) ?? null,
};
}
+1
View File
@@ -668,6 +668,7 @@ export {
export { Listing, ListingOptions } from "./listing";
export type { CompactionResult } from "./compaction";
export type { CleanupOptions, CleanupPlan, CleanupResult } from "./cleanup";
export type {
PrewarmDataPlan,
+4 -1
View File
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { Table as ArrowTable, tableFromIPC } from "apache-arrow";
import { decodeCleanupResult } from "./cleanup";
import { decodeCompactionResult } from "./compaction";
import { JobFailureInfo, Job as NativeJob } from "./native";
import { decodePrewarmDataResult } from "./prewarm";
@@ -123,7 +124,9 @@ export class Job<T = void> {
? (decodePrewarmDataResult as (value: unknown) => T)
: inner.jobType === "compact"
? (decodeCompactionResult as (value: unknown) => T)
: undefined);
: inner.jobType === "cleanup"
? (decodeCleanupResult as (value: unknown) => T)
: undefined);
}
/**
+45
View File
@@ -1,6 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import {
CleanupOptions,
CleanupPlan,
CleanupResult,
decodeCleanupPlan,
decodeCleanupResult,
validateCleanupOptions,
} from "./cleanup";
import { CompactionResult, decodeCompactionResult } from "./compaction";
import {
PrewarmDataPlan,
@@ -1341,6 +1349,28 @@ export abstract class Table {
* out state and the read_consistency_interval, if any, will apply.
*/
abstract restore(): Promise<void>;
/**
* Submit durable remote cleanup through SQL VACUUM and return after acceptance.
* Requires table Ownership and parent Usage. Retention inherits from the table
* then deployment when omitted. Local/historical handles are unsupported.
* Before submission, disable/drain automatic cleanup and prevent other cleanup,
* tag/branch publication and restore until completion, including direct clients.
* Coordination is not enforced by the server. Cancellation cannot undo deletion
* or prove storage I/O stopped. Preview is available without deletion.
* Wait timeout leaves work running; save the ID and reopen with db.openJob().
* @example
* const job = await table.cleanupAsync({ minAgeSeconds: 604800 });
* const result = await job.wait({ timeoutMs: 600000 });
*/
async cleanupAsync(_options?: CleanupOptions): Promise<Job<CleanupResult>> {
throw new Error("durable cleanup jobs are only supported on remote tables");
}
/** Preview version deletion without creating a job. Execution re-evaluates current state. */
async explainCleanup(_options?: CleanupOptions): Promise<CleanupPlan> {
throw new Error("cleanup previews require LanceDB Enterprise");
}
/**
* Submit remote compaction and return its durable job after acceptance.
*
@@ -2091,6 +2121,21 @@ export class LocalTable extends Table {
);
}
async cleanupAsync(options?: CleanupOptions): Promise<Job<CleanupResult>> {
validateCleanupOptions(options);
return new Job(
await this.inner.cleanupAsync(options?.minAgeSeconds),
decodeCleanupResult,
);
}
async explainCleanup(options?: CleanupOptions): Promise<CleanupPlan> {
validateCleanupOptions(options);
return decodeCleanupPlan(
await this.inner.explainCleanup(options?.minAgeSeconds),
);
}
async optimize(options?: Partial<OptimizeOptions>): Promise<OptimizeStats> {
validateCompactionOptions(options?.compactionOptions);
return await this.inner.optimize(
+5
View File
@@ -572,6 +572,11 @@ impl Connection {
job.into_typed::<lancedb::table::PrewarmDataResult>()
.default_error()?,
))
} else if job.job_type().as_deref() == Some("cleanup") {
Ok(crate::job::Job::new_typed(
job.into_typed::<lancedb::table::CleanupResult>()
.default_error()?,
))
} else if job.job_type().as_deref() == Some("compact") {
Ok(crate::job::Job::new_typed(
job.into_typed::<lancedb::table::CompactionResult>()
+43
View File
@@ -1001,6 +1001,33 @@ impl Table {
Ok(self.inner_ref()?.current_branch())
}
#[napi(catch_unwind)]
pub async fn explain_cleanup(
&self,
min_age_seconds: Option<f64>,
) -> napi::Result<serde_json::Value> {
let plan = self
.inner_ref()?
.explain_cleanup(parse_cleanup_options(min_age_seconds)?)
.await
.default_error()?;
serde_json::to_value(plan).map_err(|error| napi::Error::from_reason(error.to_string()))
}
#[napi(catch_unwind)]
pub async fn cleanup_async(
&self,
min_age_seconds: Option<f64>,
) -> napi::Result<crate::job::Job> {
let options = parse_cleanup_options(min_age_seconds)?;
let job = self
.inner_ref()?
.cleanup_async(options)
.await
.default_error()?;
Ok(crate::job::Job::new_typed(job))
}
#[napi(catch_unwind)]
pub async fn compact_async(
&self,
@@ -2557,3 +2584,19 @@ impl Branches {
})
}
}
fn parse_cleanup_options(
min_age_seconds: Option<f64>,
) -> napi::Result<lancedb::table::CleanupOptions> {
let mut options = lancedb::table::CleanupOptions::new();
if let Some(age) = min_age_seconds {
if !age.is_finite() || age.fract() != 0.0 || !(0.0..=9_007_199_254_740_991.0).contains(&age)
{
return Err(napi::Error::from_reason(
"minAgeSeconds must be a nonnegative safe integer",
));
}
options.min_age_seconds = Some(age as u64);
}
Ok(options)
}
+2
View File
@@ -813,6 +813,8 @@ class Table:
async def update_field_metadata(
self, updates: list[dict[str, Any]]
) -> UpdateFieldMetadataResult: ...
async def cleanup_async(self, min_age_seconds: Optional[int] = None) -> Job: ...
async def explain_cleanup(self, min_age_seconds: Optional[int] = None) -> str: ...
async def compact_async(
self, compaction_options: Optional[Dict[str, Any]] = None
) -> Job: ...
+92
View File
@@ -0,0 +1,92 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Results of durable remote version cleanup."""
from dataclasses import dataclass, fields
import json
from typing import Optional
@dataclass(frozen=True)
class CleanupResult:
"""Version-deletion outcome, excluding best-effort auxiliary sweeps.
Unknown totals after retry/recovery are None, never fabricated zeroes.
Completion does not guarantee that every orphaned file was reclaimed.
"""
format_version: int
min_age_seconds: int
statistics_complete: bool
old_versions: Optional[int] = None
bytes_removed: Optional[int] = None
failed_deletes: Optional[int] = None
@classmethod
def from_json(cls, raw: str) -> "CleanupResult":
"""Decode the versioned contract, preserving unknown measurements."""
value = json.loads(raw)
if (
not isinstance(value, dict)
or type(value.get("format_version")) is not int
or value["format_version"] != 1
):
raise ValueError("unsupported cleanup result format")
if type(value.get("statistics_complete")) is not bool:
raise ValueError("invalid cleanup result statistics_complete")
for key in (
"min_age_seconds",
"old_versions",
"bytes_removed",
"failed_deletes",
):
count = value.get(key)
if count is None and key != "min_age_seconds":
continue
if type(count) is not int or count < 0:
raise ValueError(f"invalid cleanup result {key}")
counts = [value.get("old_versions"), value.get("bytes_removed")]
if not value["statistics_complete"] and value.get("failed_deletes") is not None:
raise ValueError("inconsistent cleanup failed-deletion measurement")
if (
value["statistics_complete"] and any(count is None for count in counts)
) or (
not value["statistics_complete"]
and any(count is not None for count in counts)
):
raise ValueError("inconsistent cleanup result statistics")
names = {field.name for field in fields(cls)}
return cls(**{key: item for key, item in value.items() if key in names})
@dataclass(frozen=True)
class CleanupPlan:
"""Read-only version-deletion estimates, excluding auxiliary sweeps.
No job or deletion snapshot is reserved. Execution plans current state again.
"""
format_version: int
source_version: int
min_age_seconds: int
cutoff_millis: int
versions_to_remove: int
bytes_to_remove: int
@classmethod
def from_json(cls, raw: str) -> "CleanupPlan":
value = json.loads(raw)
if not isinstance(value, dict) or value.get("format_version") != 1:
raise ValueError("unsupported cleanup preview format")
names = {field.name for field in fields(cls)}
for name in names:
item = value.get(name)
if type(item) is not int or (name != "cutoff_millis" and item < 0):
raise ValueError(f"invalid cleanup preview {name}")
return cls(**{key: item for key, item in value.items() if key in names})
def _validate_min_age_seconds(value: Optional[int]) -> None:
if value is not None and (type(value) is not int or value < 0):
raise ValueError("min_age_seconds must be a nonnegative integer or None")
+3
View File
@@ -22,6 +22,7 @@ from . import _lancedb
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
from .functions import RefreshColumnResult
from .compaction import CompactionResult
from .cleanup import CleanupResult
from .prewarm import PrewarmDataResult
from .remote.errors import HttpError, RetryError
@@ -858,6 +859,8 @@ def _typed_job(
def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
if inner.job_type == "cleanup":
return _typed_job(inner, CleanupResult.from_json)
if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"):
return _typed_job(inner, RefreshColumnResult.from_json)
if inner.job_type == "prewarm_page_cache":
+16 -1
View File
@@ -50,6 +50,7 @@ from lancedb.index import (
LabelList,
)
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
from lancedb.cleanup import CleanupPlan, CleanupResult
from lancedb.job import Job
from lancedb.functions import (
FunctionProvenance,
@@ -1101,7 +1102,8 @@ class RemoteTable(Table):
cleanup_old_versions() is a no-op in LanceDB Enterprise.
"""
warnings.warn(
"cleanup_old_versions() is a no-op in LanceDB Enterprise.",
"cleanup_old_versions() is a no-op in LanceDB Enterprise. "
"Use cleanup_async() to submit durable cleanup explicitly.",
stacklevel=2,
)
pass
@@ -1116,6 +1118,19 @@ class RemoteTable(Table):
)
pass
def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
"""Preview cleanup without submitting a job or deleting files."""
return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds))
def cleanup_async(
self, *, min_age_seconds: Optional[int] = None
) -> Job[CleanupResult]:
"""Submit cleanup. See
[Table.cleanup_async][lancedb.table.Table.cleanup_async].
"""
return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds)))
def compact_async(
self, *, compaction_options: Optional[CompactionOptions] = None
) -> Job[CompactionResult]:
+60
View File
@@ -52,6 +52,7 @@ from lancedb.background_loop import LOOP, embedding_executor
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
from lancedb.job import AsyncJob, Job, _typed_job
from lancedb.compaction import CompactionResult
from lancedb.cleanup import CleanupPlan, CleanupResult, _validate_min_age_seconds
from .dependencies import (
_check_for_hugging_face,
_check_for_lance,
@@ -3194,6 +3195,38 @@ class Table(ABC):
compaction for you automatically.
"""
def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
"""Preview version deletion without submitting a job or deleting files.
Uses the same retention, branch and Ownership boundary as cleanup_async.
Estimates exclude auxiliary sweeps and reserve no snapshot for execution.
"""
raise NotImplementedError("cleanup previews require LanceDB Enterprise")
def cleanup_async(
self, *, min_age_seconds: Optional[int] = None
) -> Job[CleanupResult]:
"""Submit durable remote version cleanup through SQL VACUUM.
Omitted retention inherits selected table/branch then deployment policy.
Requires Ownership and parent Usage. Local/historical handles are unsupported.
Disable/drain automatic cleanup and prevent other cleanup, tag/branch
publication and restore until completion, including direct storage clients.
The server does not enforce coordination. Cancellation cannot undo deletion
or prove storage I/O stopped. Preview is available without deletion.
Save ``job.id`` to reopen with ``db.open_job(id)``. Waiting returns
[CleanupResult][lancedb.cleanup.CleanupResult]; timeout leaves work running.
Unknown totals after retry/recovery remain None. Auxiliary sweeps are
best effort and excluded from the version-deletion counts.
>>> job = table.cleanup_async(min_age_seconds=604800) # doctest: +SKIP
>>> result = job.wait() # doctest: +SKIP
"""
raise NotImplementedError(
"durable cleanup jobs are only supported on remote tables"
)
def compact_async(
self, *, compaction_options: Optional[CompactionOptions] = None
) -> Job[CompactionResult]:
@@ -6240,6 +6273,14 @@ class LanceTable(Table):
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
)
def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds))
def cleanup_async(
self, *, min_age_seconds: Optional[int] = None
) -> Job[CleanupResult]:
return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds)))
def optimize(
self,
*,
@@ -9983,6 +10024,25 @@ class AsyncTable:
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
return self._inner.current_branch()
async def explain_cleanup(
self, *, min_age_seconds: Optional[int] = None
) -> CleanupPlan:
"""Read-only preview; see Table.explain_cleanup."""
_validate_min_age_seconds(min_age_seconds)
return CleanupPlan.from_json(await self._inner.explain_cleanup(min_age_seconds))
async def cleanup_async(
self, *, min_age_seconds: Optional[int] = None
) -> AsyncJob[CleanupResult]:
"""Submit cleanup. See
[Table.cleanup_async][lancedb.table.Table.cleanup_async].
"""
_validate_min_age_seconds(min_age_seconds)
return _typed_job(
await self._inner.cleanup_async(min_age_seconds), CleanupResult.from_json
)
async def compact_async(
self, *, compaction_options: Optional[CompactionOptions] = None
) -> AsyncJob[CompactionResult]:
+187
View File
@@ -0,0 +1,187 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import pyarrow as pa
import pytest
import lancedb
from lancedb.cleanup import CleanupResult
from test_remote_db import _create_table_handler, _mock_remote_sql_connection
@pytest.mark.parametrize("counts", [(0, 0), (2, 123), (None, None)])
def test_cleanup_result_preserves_measurements(counts):
versions, size = counts
result = CleanupResult.from_json(
json.dumps(
{
"format_version": 1,
"min_age_seconds": 0,
"statistics_complete": versions is not None,
"old_versions": versions,
"bytes_removed": size,
"future": True,
}
)
)
assert result.old_versions == versions
assert result.bytes_removed == size
@pytest.mark.parametrize(
"payload",
[
None,
{},
{"format_version": 2},
{
"format_version": 1,
"min_age_seconds": 0,
"statistics_complete": False,
"old_versions": 1,
},
],
)
def test_cleanup_result_rejects_missing_unknown_or_inconsistent_contract(payload):
with pytest.raises(ValueError):
CleanupResult.from_json(json.dumps(payload))
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"outcome", ["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"]
)
async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome):
flight = pytest.importorskip("pyarrow.flight")
polls = []
result = {
"format_version": 1,
"min_age_seconds": 0,
"statistics_complete": outcome != "unknown",
"old_versions": None
if outcome == "unknown"
else 0
if outcome == "no_op"
else 2,
"bytes_removed": None
if outcome == "unknown"
else 0
if outcome == "no_op"
else 123,
}
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": ["cleanup-job"]}))
def handler(request):
if request.path != "/v1/jobs/describe":
return _create_table_handler(request)
polls.append(
json.loads(request.rfile.read(int(request.headers["Content-Length"])))
)
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(
json.dumps(
{
"job_id": "cleanup-job",
"job_type": "cleanup",
"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.cleanup_async(min_age_seconds=0)
else:
db = lancedb.connect(**kwargs)
table = db.create_table("test", [{"id": 1}])
job = table.cleanup_async(min_age_seconds=0)
assert job.id == "cleanup-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],
):
if asynchronous:
await job.wait()
else:
job.wait()
else:
stats = await job.wait() if asynchronous else job.wait()
assert isinstance(stats, CleanupResult)
assert stats.old_versions == result["old_versions"]
reopened = (
await db.open_job(job.id) if asynchronous else db.open_job(job.id)
)
assert (await reopened.wait() if asynchronous else reopened.wait()) == stats
assert len(server.tickets) == 1
assert b"VACUUM" in server.tickets[0]
assert b"min_age_seconds = 0" in server.tickets[0]
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
async def test_cleanup_preview_is_read_only(asynchronous):
flight = pytest.importorskip("pyarrow.flight")
payload = {
"format_version": 1,
"source_version": 42,
"min_age_seconds": 0,
"cutoff_millis": 123,
"versions_to_remove": 2,
"bytes_to_remove": 100,
}
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({"plan_type": ["logical_plan"], "plan": [json.dumps(payload)]})
)
def handler(request):
assert not request.path.startswith("/v1/jobs"), (
"preview must not submit/monitor jobs"
)
return _create_table_handler(request)
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}])
plan = await table.explain_cleanup(min_age_seconds=0)
else:
db = lancedb.connect(**kwargs)
table = db.create_table("test", [{"id": 1}])
plan = table.explain_cleanup(min_age_seconds=0)
assert plan.source_version == 42
assert plan.versions_to_remove == 2
assert len(server.tickets) == 1
assert b"EXPLAIN (FORMAT JSON) VACUUM" in server.tickets[0]
+9 -6
View File
@@ -3737,13 +3737,16 @@ def test_remote_python_only_messages():
f"{method}() is not supported in LanceDB Enterprise. "
f"Use table.search().{method}() instead."
)
for method in ["compact_files", "cleanup_old_versions"]:
for method, expected in {
"compact_files": "compact_files() is a no-op in LanceDB Enterprise.",
"cleanup_old_versions": (
"cleanup_old_versions() is a no-op in LanceDB Enterprise. "
"Use cleanup_async() to submit durable cleanup explicitly."
),
}.items():
with pytest.warns(UserWarning) as warning:
getattr(table, method)()
assert (
str(warning[0].message)
== f"{method}() is a no-op in LanceDB Enterprise."
)
assert getattr(table, method)() is None
assert str(warning[0].message) == expected
def test_remote_embedding_config_does_not_warn_or_drop_metadata(caplog):
+4
View File
@@ -1054,6 +1054,10 @@ impl Connection {
job.into_typed::<lancedb::table::PrewarmDataResult>()
.infer_error()?,
)),
Some("cleanup") => Ok(crate::job::Job::new_typed(
job.into_typed::<lancedb::table::CleanupResult>()
.infer_error()?,
)),
Some("compact") => Ok(crate::job::Job::new_typed(
job.into_typed::<lancedb::table::CompactionResult>()
.infer_error()?,
+31
View File
@@ -2326,6 +2326,37 @@ impl Table {
})
}
/// Explain Enterprise version cleanup without submitting a job.
#[pyo3(signature = (min_age_seconds=None))]
pub fn explain_cleanup<'py>(
self_: PyRef<'py, Self>,
min_age_seconds: Option<u64>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self_.inner_ref()?.clone();
let mut options = lancedb::table::CleanupOptions::new();
options.min_age_seconds = min_age_seconds;
future_into_py(self_.py(), async move {
let plan = inner.explain_cleanup(options).await.infer_error()?;
serde_json::to_string(&plan)
.map_err(|error| pyo3::exceptions::PyRuntimeError::new_err(error.to_string()))
})
}
/// Submit Enterprise version cleanup and retain its durable job and result.
#[pyo3(signature = (min_age_seconds=None))]
pub fn cleanup_async<'py>(
self_: PyRef<'py, Self>,
min_age_seconds: Option<u64>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self_.inner_ref()?.clone();
let mut options = lancedb::table::CleanupOptions::new();
options.min_age_seconds = min_age_seconds;
future_into_py(self_.py(), async move {
let job = inner.cleanup_async(options).await.infer_error()?;
Ok(crate::job::Job::new_typed(job))
})
}
/// Submit remote compaction and retain its durable job and actual result.
#[pyo3(signature = (compaction_options=None))]
pub fn compact_async<'py>(
+123
View File
@@ -4802,6 +4802,84 @@ async fn remote_prewarm_rejects_historical_checkout_without_submitting() {
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn remote_cleanup_tracks_registry_job_and_real_result() {
use crate::table::CleanupOptions;
let service = TestSqlService {
adaptive: true,
result: RecordBatch::try_from_iter([(
"job_id",
Arc::new(StringArray::from(vec!["cleanup-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");
observed.fetch_add(1, Ordering::SeqCst);
http::Response::builder()
.status(200)
.body(
serde_json::json!({
"job_id":"cleanup-job","job_type":"cleanup","job_state":"DONE",
"result":{"format_version":1,"min_age_seconds":0,"statistics_complete":true,
"old_versions":2,"bytes_removed":123}
})
.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("o'brien".into()));
let job = table
.cleanup_async(CleanupOptions::new().min_age_seconds(0))
.await
.unwrap();
assert_eq!(job.id(), Some("cleanup-job"));
assert_eq!(polls.load(Ordering::SeqCst), 0);
let result = job.wait().await.unwrap();
assert_eq!(result.old_versions, Some(2));
assert_eq!(result.bytes_removed, Some(123));
assert_eq!(
*statements.lock().unwrap(),
["VACUUM \"events\" WITH (branch = 'o''brien', min_age_seconds = 0)"]
);
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn remote_cleanup_rejects_historical_checkout_without_submitting() {
let table = RemoteTable::new_with_sql_client(
client_with_handler(|request| {
assert_eq!(request.url().path(), "/v1/table/events/describe/");
http::Response::builder()
.status(200)
.body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string())
.unwrap()
}),
"analytics".into(),
"events".into(),
vec![],
"events".into(),
Default::default(),
None,
);
table.checkout(7).await.unwrap();
assert!(table.cleanup_async(Default::default()).await.is_err());
}
#[tokio::test]
async fn remote_compaction_tracks_registry_job_and_real_result() {
use crate::table::optimize::CompactionOverrides;
@@ -4943,3 +5021,48 @@ async fn remote_prewarm_preview_uses_sql_without_any_http_jobs() {
shutdown.send(()).unwrap();
}
}
#[tokio::test]
async fn remote_cleanup_preview_uses_sql_without_job_calls() {
let payload = serde_json::json!({"format_version":1,"source_version":42,"min_age_seconds":0,
"cutoff_millis":123,"versions_to_remove":2,"bytes_to_remove":100});
let service = TestSqlService {
adaptive: true,
result: RecordBatch::try_from_iter([
(
"plan_type",
Arc::new(StringArray::from(vec!["logical_plan"])) as ArrayRef,
),
(
"plan",
Arc::new(StringArray::from(vec![payload.to_string()])) as ArrayRef,
),
])
.unwrap(),
..Default::default()
};
let statements = service.statements.clone();
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
let table = RemoteTable::new_with_sql_client(
client_with_handler(|_| -> http::Response<String> {
panic!("preview must not use HTTP jobs or execution fallback")
}),
"analytics".into(),
"events".into(),
vec!["team".into()],
"team$events".into(),
Default::default(),
Some(sql),
);
let plan = table
.explain_cleanup(crate::table::CleanupOptions::new().min_age_seconds(0))
.await
.unwrap();
assert_eq!(plan.source_version, 42);
assert_eq!(plan.versions_to_remove, 2);
assert_eq!(
*statements.lock().unwrap(),
["EXPLAIN (FORMAT JSON) VACUUM \"events\" WITH (min_age_seconds = 0)"]
);
shutdown.send(()).unwrap();
}
+62
View File
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
pub mod blobs;
mod cleanup;
pub mod insert;
mod ipc_stream;
mod optimize;
@@ -4175,6 +4176,67 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
prune: None,
})
}
async fn explain_cleanup(
&self,
options: crate::table::CleanupOptions,
) -> Result<crate::table::CleanupPlan> {
self.check_mutable().await?;
let statement = format!(
"EXPLAIN (FORMAT JSON) {}",
cleanup::statement(&self.name, self.branch.as_deref(), &options)?
);
let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported {
message: "cleanup previews require a Flight SQL endpoint with EXPLAIN (FORMAT JSON) VACUUM support".into(),
})?;
let query = client
.execute(crate::database::ExecuteQueryRequest {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
})
.await
.map_err(cleanup::map_error)?;
let mut reader = query.reader().await.map_err(cleanup::map_error)?;
let mut batches = Vec::new();
while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? {
batches.push(batch);
}
cleanup::plan(&batches)
}
async fn cleanup_async(
&self,
options: crate::table::CleanupOptions,
) -> Result<Job<crate::table::CleanupResult>> {
self.check_mutable().await?;
let statement = cleanup::statement(&self.name, self.branch.as_deref(), &options)?;
let client = self
.sql_client
.as_ref()
.ok_or_else(|| Error::NotSupported {
message: "manual cleanup requires a Flight SQL endpoint and SQL VACUUM support"
.into(),
})?;
let query = client
.execute(crate::database::ExecuteQueryRequest {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
})
.await
.map_err(cleanup::map_error)?;
let mut reader = query.reader().await.map_err(cleanup::map_error)?;
let mut batches = Vec::new();
while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? {
batches.push(batch);
}
let job_id = cleanup::receipt(&batches)?;
Ok(Job::new_typed(Box::new(RemoteJob::new(
self.client.clone(),
job_id,
))))
}
async fn compact_async(
&self,
options: crate::table::optimize::CompactionOverrides,
+234
View File
@@ -0,0 +1,234 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! SQL VACUUM submission; never replay an ambiguous acceptance response.
use crate::{Error, Result, table::CleanupOptions};
use arrow_array::{Array, RecordBatch, StringArray};
pub(super) fn statement(
table: &str,
branch: Option<&str>,
options: &CleanupOptions,
) -> Result<String> {
let mut settings = Vec::new();
if let Some(branch) = branch {
if branch.trim().is_empty() {
return Err(Error::InvalidInput {
message: "cleanup branch must not be empty".into(),
});
}
settings.push(format!("branch = {}", super::quote_sql_string(branch)));
}
if let Some(age) = options.min_age_seconds {
if i64::try_from(age)
.ok()
.and_then(chrono::Duration::try_seconds)
.and_then(|duration| chrono::Utc::now().checked_sub_signed(duration))
.is_none()
{
return Err(Error::InvalidInput {
message: "min_age_seconds is out of range".into(),
});
}
settings.push(format!("min_age_seconds = {age}"));
}
let mut sql = format!("VACUUM {}", super::quote_sql_identifier(table));
if !settings.is_empty() {
sql.push_str(&format!(" WITH ({})", settings.join(", ")));
}
Ok(sql)
}
pub(super) fn receipt(batches: &[RecordBatch]) -> Result<String> {
let invalid = || {
Error::Runtime { message: "VACUUM did not return a single nonempty job_id receipt; inspect jobs before retrying because cleanup may already have been submitted".into() }
};
if batches.iter().map(RecordBatch::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(|array| array.as_any().downcast_ref::<StringArray>())
.ok_or_else(invalid)?;
if ids.is_null(0) || ids.value(0).trim().is_empty() {
return Err(invalid());
}
Ok(ids.value(0).to_string())
}
pub(super) fn plan(batches: &[RecordBatch]) -> Result<crate::table::CleanupPlan> {
let invalid = || {
Error::Runtime { message: "EXPLAIN VACUUM did not return a valid versioned preview; a compatible EXPLAIN (FORMAT JSON) VACUUM server is required. No execution fallback was attempted".into() }
};
if batches.iter().map(RecordBatch::num_rows).sum::<usize>() != 1 {
return Err(invalid());
}
let batch = batches
.iter()
.find(|batch| batch.num_rows() == 1)
.ok_or_else(invalid)?;
let kind = batch
.column_by_name("plan_type")
.and_then(|column| column.as_any().downcast_ref::<StringArray>())
.ok_or_else(invalid)?;
let payload = batch
.column_by_name("plan")
.and_then(|column| column.as_any().downcast_ref::<StringArray>())
.ok_or_else(invalid)?;
if kind.is_null(0) || kind.value(0) != "logical_plan" || payload.is_null(0) {
return Err(invalid());
}
serde_json::from_str(payload.value(0)).map_err(|_| invalid())
}
pub(super) fn map_error(error: Error) -> Error {
fn unsupported(error: &Error) -> Option<&Error> {
match error {
Error::Sql {
message, grpc_code, ..
} => {
let message = message.to_ascii_lowercase();
(*grpc_code == tonic::Code::Unimplemented as i32
|| (*grpc_code == tonic::Code::Internal as i32
&& message.contains("invalid explain format")
&& message.contains("json"))
|| (*grpc_code == tonic::Code::InvalidArgument as i32
&& (message.contains("parsererror")
|| message.contains("unknown vacuum option")
|| message.contains("vacuum is not supported by this deployment"))))
.then_some(error)
}
Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported),
_ => None,
}
}
if let Some(source) = unsupported(&error) {
let diagnostic = if matches!(error, Error::Sql { .. }) {
error.to_string()
} else {
format!("{error}; {source}")
};
Error::NotSupported {
message: format!(
"Manual cleanup requires a compatible SQL VACUUM server; upgrade the server. No options were removed and no REST fallback was attempted. Server diagnostic: {diagnostic}"
),
}
} else {
error
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn wrapped_cleanup_compatibility_keeps_job_and_request_identity() {
let sql = Error::Sql {
message: "ParserError: found VACUUM".into(),
request_id: "cleanup-request".into(),
grpc_code: tonic::Code::InvalidArgument as i32,
metadata: Default::default(),
};
let error = Error::JobFailed {
job_id: Some("query-job".into()),
failure: Box::new(crate::error::JobFailure {
phase: Some("planning".into()),
message: Some("statement failed".into()),
source: Some(Arc::new(sql)),
..Default::default()
}),
};
let mapped = map_error(error);
assert!(matches!(mapped, Error::NotSupported { .. }));
let diagnostic = mapped.to_string();
assert!(diagnostic.contains("query-job"));
assert!(diagnostic.contains("cleanup-request"));
}
#[test]
fn cleanup_statement_preserves_inheritance_zero_and_quoting() {
assert_eq!(
statement("events", None, &CleanupOptions::new()).unwrap(),
"VACUUM \"events\""
);
assert_eq!(
statement(
"a\"b",
Some("o'brien"),
&CleanupOptions::new().min_age_seconds(0)
)
.unwrap(),
"VACUUM \"a\"\"b\" WITH (branch = 'o''brien', min_age_seconds = 0)"
);
assert!(statement("t", None, &CleanupOptions::new().min_age_seconds(u64::MAX)).is_err());
}
#[test]
fn ambiguous_cleanup_receipts_never_become_query_handles() {
let batch = |values: Vec<Option<&str>>| {
RecordBatch::try_from_iter([(
"job_id",
Arc::new(StringArray::from(values)) as arrow_array::ArrayRef,
)])
.unwrap()
};
for batches in [
vec![],
vec![batch(vec![])],
vec![batch(vec![None])],
vec![batch(vec![Some("")])],
vec![batch(vec![Some("one"), Some("two")])],
] {
assert!(
receipt(&batches)
.unwrap_err()
.to_string()
.contains("inspect jobs before retrying")
);
}
assert_eq!(
receipt(&[batch(vec![]), batch(vec![Some("durable-job")])]).unwrap(),
"durable-job"
);
}
#[test]
fn cleanup_compatibility_preserves_permissions_and_transport_errors() {
for (code, diagnostic, expected) in [
(
tonic::Code::InvalidArgument,
"ParserError: found VACUUM",
true,
),
(
tonic::Code::InvalidArgument,
"Unknown VACUUM option future",
true,
),
(tonic::Code::PermissionDenied, "ParserError: denied", false),
(tonic::Code::Unavailable, "transport unavailable", false),
(
tonic::Code::InvalidArgument,
"min_age_seconds is out of range",
false,
),
] {
let error = Error::Sql {
message: diagnostic.into(),
request_id: "cleanup-request".into(),
grpc_code: code as i32,
metadata: Default::default(),
};
let mapped = map_error(error);
assert_eq!(matches!(mapped, Error::NotSupported { .. }), expected);
assert!(mapped.to_string().contains("cleanup-request"));
}
}
}
+44
View File
@@ -89,6 +89,8 @@ pub mod function_column_status;
pub mod merge;
pub mod optimize;
pub use optimize::CompactionResult;
mod cleanup;
pub use cleanup::{CleanupOptions, CleanupPlan, CleanupResult};
mod prewarm;
pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary};
pub(crate) mod primary_key;
@@ -907,6 +909,19 @@ 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 Enterprise version cleanup and retain its durable job and outcome.
async fn cleanup_async(&self, _options: CleanupOptions) -> Result<Job<CleanupResult>> {
Err(Error::NotSupported {
message: "durable cleanup jobs are only supported on remote tables".into(),
})
}
async fn explain_cleanup(&self, _options: CleanupOptions) -> Result<CleanupPlan> {
Err(Error::NotSupported {
message: "cleanup previews require LanceDB Enterprise".into(),
})
}
/// Submit remote compaction and retain its durable job and actual outcome.
async fn compact_async(
&self,
@@ -2140,6 +2155,35 @@ impl Table {
self.inner.compact_async(options).await
}
/// Submit durable version cleanup through SQL VACUUM and return after acceptance.
///
/// Retention resolves invocation > selected table/branch > deployment. Requires
/// Ownership and parent Usage. Local and historical handles are unsupported.
/// Operators must disable/drain automatic cleanup and prevent other cleanup,
/// tag/branch publication and restore until completion, including direct clients.
/// The server does not enforce that coordination. Preview is available without deletion.
/// Wait, cancel and reopen reuse the shared Job APIs; timeout does not cancel,
/// and cancellation cannot undo deletion or prove storage I/O has stopped.
///
/// ```
/// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> {
/// let job = table.cleanup_async(lancedb::table::CleanupOptions::new()
/// .min_age_seconds(604800)).await?;
/// let result = job.wait().await?;
/// println!("{:?}", result.old_versions);
/// # Ok(()) }
/// ```
pub async fn cleanup_async(&self, options: CleanupOptions) -> Result<Job<CleanupResult>> {
self.inner.cleanup_async(options).await
}
/// Explain Enterprise version cleanup without deleting files or submitting a job.
/// Requires the same ownership and retention options as [`Self::cleanup_async`].
/// Counts are observational estimates, not a reservation for later execution.
pub async fn explain_cleanup(&self, options: CleanupOptions) -> Result<CleanupPlan> {
self.inner.explain_cleanup(options).await
}
/// Language-binding entry point retaining optional compaction fields.
#[doc(hidden)]
pub async fn optimize_full_with_overrides(
+135
View File
@@ -0,0 +1,135 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! Options and results for durable remote version cleanup.
/// Per-invocation retention. Omission inherits table/branch then deployment policy.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CleanupOptions {
/// Minimum old-version age in seconds. None inherits server policy.
pub min_age_seconds: Option<u64>,
}
impl CleanupOptions {
/// Inherit selected table/branch and deployment retention.
pub fn new() -> Self {
Self::default()
}
/// Set the minimum old-version age in seconds; zero is explicit, not omitted.
pub fn min_age_seconds(mut self, seconds: u64) -> Self {
self.min_age_seconds = Some(seconds);
self
}
}
/// Successful remote version cleanup. Auxiliary sweeps are best effort and
/// excluded from the counts. Retry/recovery can leave counts unknown (`None`).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "CleanupResultWire")]
#[non_exhaustive]
pub struct CleanupResult {
/// Objects that could not be deleted, if measured. Other removals remain committed.
pub failed_deletes: Option<u64>,
/// Public result schema version; currently 1.
pub format_version: u32,
/// Retention resolved and recorded when the server accepted this job.
pub min_age_seconds: u64,
/// Whether the entire invocation's version-deletion counts are known.
pub statistics_complete: bool,
/// Old versions removed, or None after uncertain retry/recovery.
pub old_versions: Option<u64>,
/// Bytes removed by version deletion, excluding auxiliary sweeps.
pub bytes_removed: Option<u64>,
}
#[derive(serde::Deserialize)]
struct CleanupResultWire {
failed_deletes: Option<u64>,
format_version: u32,
min_age_seconds: u64,
statistics_complete: bool,
old_versions: Option<u64>,
bytes_removed: Option<u64>,
}
impl TryFrom<CleanupResultWire> for CleanupResult {
type Error = &'static str;
fn try_from(value: CleanupResultWire) -> std::result::Result<Self, Self::Error> {
if value.format_version != 1
|| if value.statistics_complete {
value.old_versions.is_none() || value.bytes_removed.is_none()
} else {
value.old_versions.is_some()
|| value.bytes_removed.is_some()
|| value.failed_deletes.is_some()
}
{
return Err("unsupported or inconsistent cleanup result");
}
Ok(Self {
failed_deletes: value.failed_deletes,
format_version: value.format_version,
min_age_seconds: value.min_age_seconds,
statistics_complete: value.statistics_complete,
old_versions: value.old_versions,
bytes_removed: value.bytes_removed,
})
}
}
/// Read-only version-deletion estimate. Execution re-evaluates current state;
/// no job or deletion snapshot is reserved and auxiliary sweeps are excluded.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct CleanupPlan {
#[serde(deserialize_with = "preview_version")]
pub format_version: u32,
pub source_version: u64,
pub min_age_seconds: u64,
pub cutoff_millis: i64,
pub versions_to_remove: u64,
pub bytes_to_remove: u64,
}
fn preview_version<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<u32, D::Error> {
let version = <u32 as serde::Deserialize>::deserialize(deserializer)?;
if version != 1 {
return Err(serde::de::Error::custom(
"unsupported cleanup preview format",
));
}
Ok(version)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cleanup_result_distinguishes_known_zero_unknown_and_invalid() {
let mut value = serde_json::json!({"format_version":1,"min_age_seconds":0,
"statistics_complete":true,"old_versions":0,"bytes_removed":0,"future":true});
assert_eq!(
serde_json::from_value::<CleanupResult>(value.clone())
.unwrap()
.old_versions,
Some(0)
);
value["statistics_complete"] = false.into();
assert!(serde_json::from_value::<CleanupResult>(value.clone()).is_err());
value["old_versions"] = serde_json::Value::Null;
value["bytes_removed"] = serde_json::Value::Null;
assert_eq!(
serde_json::from_value::<CleanupResult>(value.clone())
.unwrap()
.old_versions,
None
);
value["format_version"] = 2.into();
assert!(serde_json::from_value::<CleanupResult>(value).is_err());
}
}