Files
lancedb/docs/web/maintenance/cleanup.mdx
Bruno Ramirez 16af729792 feat(sdk)!: add typed SQL job handles for compaction and data prewarm (#5056)
Remote data prewarm used REST even though SQL supported filters and
concurrency, and both maintenance APIs returned after acceptance without
exposing a consistent typed completion handle. Compaction's legacy
statistics therefore could not describe the work committed by its
durable job. This PR adds job-returning compaction and data-prewarm
methods across Rust, Python sync/async and TypeScript, and moves
data-prewarm submission to SQL. Legacy methods retain
return-after-acceptance behavior; data prewarm now requires a compatible
SQL PREWARM server and Flight SQL connectivity. This consolidates #5037,
#5055 and #4906.

This was accomplished with the following changes:

- Added `compact_async()` / `compactAsync()` and `prewarm_data_async()`
/ `prewarmDataAsync()`, retaining the command receipt's durable job ID.
- Added `PrewarmDataOptions` for columns, a metadata-pruning filter and
concurrency; both operations inherit database, namespace and branch from
the table handle.
- Added filter/concurrency arguments to legacy Python `prewarm_data()`
and a TypeScript `prewarmData(options)` overload, preserving the
columns-array form and discarding the handle after acceptance.
- Added typed `CompactionResult` and `PrewarmDataResult` decoding,
including reopened jobs; missing result payloads fail explicitly and
omitted measurements remain unknown.
- Reused the shared Job lifecycle for status, refresh, progress
callbacks, cancellation and events; Python maintenance progress bars
display rewritten rows or completed executors.
- Added TypeScript `wait({ timeoutMs, onProgress })` and Rust
`wait_with_options(JobWaitOptions)`, complementing Python's existing
timeout argument without cancelling the durable job.
- Validated single unambiguous receipts, preserved compaction option
presence/default inheritance, and returned actionable unsupported-server
errors without dropping options or falling back to REST.
- Updated native bindings, API references and maintenance documentation
with job methods, result semantics, tuning and compatibility
requirements.

### Usage and behaviour

**New** = added here; **Enhanced** = existing support extended;
**Existing** = already on main. This table describes remote SDK
behavior; server-side SQL/CLI capabilities are prerequisites, not
additions made by this SDK PR.

| Surface | Capability | Compact | Data prewarm | Assessment |
| --- | --- | --- | --- | --- |
| Rust / Python sync+async / TypeScript | Submission transport |
Existing SQL OPTIMIZE | **New:** REST → SQL PREWARM | Both now submit
through SQL |
| All SDKs | Durable job-returning API | **New:** `compact_async` /
`compactAsync` | **New:** `prewarm_data_async` / `prewarmDataAsync` |
Same lifecycle model |
| All SDKs | Options and target scope | **New handle:** four existing
compaction overrides, with omitted fields inherited | **New options:**
columns/filter/concurrency | Namespace and branch preserved for both |
| Python / TypeScript | Legacy convenience calls | Existing optimize
acceptance behavior preserved | **Enhanced:** legacy methods accept
filter/concurrency and use SQL | Return after acceptance; no completion
wait |
| All SDKs | Typed successful result | **New:** committed rows,
file/fragment changes, partial commit and `more_work` | **New:** pinned
version, fragments and executor outcomes | Different measurements are
intentional |
| All SDKs | Status / refresh / progress | Existing Job APIs reused by
**new** maintenance handle | Existing Job APIs reused by **new**
maintenance handle | HTTP monitoring remains |
| Python / TypeScript | Progress presentation | **Enhanced:** rewrite
rows/groups | **Enhanced:** executor progress | Shared callbacks; Python
bars use operation counters |
| All SDKs | Bounded wait | Python existing; **new** TS/Rust timeout
controls | Same shared timeout support | Timeout stops this wait; job
continues |
| All SDKs | Reopen and await typed outcome | **New:** compaction result
decoding on reopened handle | **New:** prewarm result decoding on
reopened handle | Rust selects the typed result explicitly |
| All SDKs | Cancel / events | Existing shared APIs available on **new**
handle | Same | HTTP underneath; permissions unchanged |
| All SDKs | Typed preview helper | Unavailable | Unavailable | General
SQL where exposed; no helper added |
| Authorization | Submission | Existing table Ownership plus parent
Usage | SQL path uses Select plus parent Usage | Intentional difference
|
| All SDKs | Local / historical handles | New durable API rejects them |
New durable API rejects them | Remote current-branch jobs only |

```python
from datetime import timedelta

# Legacy convenience call: returns None after acceptance.
table.prewarm_data(["payload"], filter="id >= 1000", concurrency=4)

warm = table.prewarm_data_async(["payload"], filter="id >= 1000", concurrency=4)
warmed = warm.wait(timeout=timedelta(minutes=10), progress=print)
print(warmed.table_version, warmed.executors_completed)

compact = table.compact_async(compaction_options={"max_source_rows": 1000000})
committed = compact.wait(timeout=timedelta(minutes=10), progress=print)
print(committed.rows_succeeded, committed.fragments_removed, committed.more_work)

reopened_result = db.open_job(compact.id).wait()
```

```typescript
await table.prewarmData({ columns: ["payload"], filter: "id >= 1000", concurrency: 4 });
const job = await table.prewarmDataAsync({
  columns: ["payload"], filter: "id >= 1000", concurrency: 4,
});
const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log });
```

```rust
use std::time::Duration;
use lancedb::job::JobWaitOptions;

let job = table.compact_async(Default::default()).await?;
let result = job.wait_with_options(
    JobWaitOptions::new().timeout(Duration::from_secs(600)),
).await?;
```

Python async tables await both submission and Job methods. Rust's legacy
`prewarm_data(columns)` keeps its columns-only signature; use
`PrewarmDataOptions` on the new job-returning method for
filtering/concurrency.

Wait deadlines cover pending status requests and polling delays.
Existing `wait()`, TypeScript `wait(callback)` and Rust
`wait_with_progress(callback)` remain supported.
Status/progress/refresh/cancel/events still use generic HTTP job APIs;
those endpoints and their read/event/cancel permissions must remain
available. Cancelling or timing out does not roll back committed work.

Compaction results describe committed rewrites and include deletion
files in file counts. Prewarm results describe work against a pinned
snapshot, with partial executors included in completed executors;
nonempty byte/range measurements remain unknown. Missing results require
compatible server/worker support rather than placeholder zero
statistics. Filtering uses conservative metadata pruning, not an exact
row-filter scan.

### Testing

Six checked-in live Python sync/async cases pass against matching
server/worker builds for compaction, job-returning prewarm and legacy
filtered submission. Ten additional live Node scenarios pass for
legacy/default/options forms, filters/concurrency, empty plans,
validation, persisted specifications and readback.

Targeted regressions pass: Python remote maintenance (80), shared jobs
(82), local prewarm rejection (4); Node remote (107) and prewarm API
cases (28), plus the previously exercised Rust remote regressions. Tests
cover receipt parsing, typed results, reopening, unknown measurements,
timeouts, and legacy calls returning None/undefined without polling.

Dependency pins are unchanged. Azure account-hint acknowledgment was
verified locally with filesystem storage; real Azure-backed storage
still needs deployment-specific validation.
2026-11-17 10:57:56 -08:00

152 lines
6.1 KiB
Plaintext

---
title: "Garbage Collection"
sidebarTitle: "Garbage Collection"
description: "Pruning old versions and the files only they referenced."
icon: broom
keywords: ["cleanup", "garbage collection", "retention", "prune", "delete_unverified", "vacuum"]
availability:
embedded: available
enterprise: available
---
Every write keeps the version before it, which is what makes
[time travel](/management/table#versioning) possible. Cleanup is what ends
that: pruning versions older than a retention window, and the files that only
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.
</Note>
## Retention {#retention}
<CodeGroup>
```python Python icon="python"
from datetime import timedelta
table.optimize(cleanup_older_than=timedelta(days=30))
```
</CodeGroup>
`cleanup_older_than` defaults to **7 days**. Versions older than that are
removed, along with the files only they referenced. In LanceDB Enterprise, the
retention period comes from its configuration instead.
The latest version is never removed, whatever you pass. `timedelta(0)` makes
every older version eligible for removal, but cleanup still keeps tagged
versions{/* Draft until branching reaches early access: restore " and the files branches still read" */}, as the warning below describes.
<Warning>
Pruning is what makes [time travel](/management/table#versioning) finite: an
eligible version outside the retention window is gone. Cleanup keeps a version,
whatever its age, when it is:
- the **latest** version;
- a **tagged** version.
{/*
Draft until branching reaches early access.
Cleanup also keeps the files a **branch** still reads, and the version the
branch was forked from while the branch's remaining versions read the parent's
files. That does not keep the fork for good: once the branch has replaced the
data it inherited and its own older versions are pruned, cleanup prunes the
fork version like any other.
*/}
To keep a version recoverable, tag it, subject to the policy below, or keep
the window wide enough to cover it.
Under the default policy, a tag can also stop cleanup. When a tagged version is
older than the window and is not the latest, cleanup refuses to run: it raises
an error naming the tag and prunes nothing. To let it proceed, move the tag to a
version inside the window, delete the tag, or widen the window.
A tag on the latest version does not stop cleanup. But `optimize()` compacts
before it prunes, and compacting commits a new version whenever it merges
files, so a tag on what was the latest version can become an older one by the
time cleanup runs. `optimize()` then raises after compacting, and its index
update does not run.
Enterprise background cleanup keeps tagged snapshots while pruning unrelated
expired versions. If you rely on reading untagged old versions, set the window
to cover the range you
need before running this, not after.
</Warning>
## Managed blob objects {#managed-blobs}
[Managed blobs](/management/table#managed-blobs) store out-of-line payloads
under the table's `_blobs/` directory. Cleanup follows the references from
retained snapshots, including protected tags{/* Draft until branching reaches early access: restore " and branches" */}, before selecting
objects for deletion. Replacing a blob or deleting a row makes its old payload
eligible only after no retained snapshot references it.
Cleanup removes whole objects. If a packed object contains several blobs, it
remains while any of them is live. Compaction preserves Managed payload objects
rather than copying their bytes, so compaction alone does not reclaim the
unused portion of a packed object.
Use table maintenance to remove Managed objects; deleting `_blobs/` files
directly can corrupt current or historical snapshots. Upgrade all clients and
maintenance workers to a version that understands Managed blobs before using
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.
See [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path.
## Disk usage does not drop immediately {#disk}
Compaction writes new, merged files before the old ones are removed, so disk
usage can rise before it falls. Space is reclaimed only when cleanup prunes the
versions that referenced the superseded files.
If you need to reclaim space aggressively in the embedded library, shorten the
retention window rather than waiting for the default:
<CodeGroup>
```python Python icon="python"
table.optimize(cleanup_older_than=timedelta(days=1))
```
</CodeGroup>
## Files from failed transactions {#unverified}
A write that fails partway can leave files that look like an operation still
in progress. Cleanup will not remove them until they are at least seven days
old, because it cannot tell them apart from a live write.
<CodeGroup>
```python Python icon="python"
table.optimize(delete_unverified=True)
```
</CodeGroup>
This option belongs to `optimize()` in the embedded library. A deployment's
cleanup jobs never set it.
<Warning>
`delete_unverified=True` removes them regardless of age. Only set it when you
can guarantee **no other process is writing to the table**. Otherwise it can
delete files belonging to a write that is genuinely in progress, and corrupt
the table.
</Warning>
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Compaction" icon="broom" href="/maintenance/compaction">
Merging small files, the other half of `optimize()`.
</Card>
<Card title="Intelligent Auto-Maintenance" icon="brain" href="/enterprise/intelligent-auto-maintenance#cleanup">
How Enterprise decides to run cleanup without a call from you.
</Card>
</CardGroup>