mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
Make all Python `Job` and `AsyncJob` data access method-only. Cached property accessors are private and underscore-prefixed; public reads use `id()`, `state()`, `job_type()`, `creation_ms()`, `spec()`, `result()` and `failure()`. `checkout_latest()` refreshes the complete cached registry record in place and returns `None`. ```python job.checkout_latest() print(job.state(), job.result(), job.failure()) print(job.id(), job.job_type(), job.creation_ms(), job.spec()) ``` Cached read methods are synchronous on both handle types. Async handles use `await job.checkout_latest()` for the live refresh; event history remains a separate request through `events()`. Update Python SDK callers, tests and guides to use method calls, including progress/timeout handling and bounded repr. Cover method-only visibility and holistic snapshot freshness through both sync and async clients. BREAKING CHANGE: Python job data access now requires method calls, such as `job.state()` instead of `job.state`. No property compatibility aliases remain. Fixes https://linear.app/lancedb/issue/ENT-3902/sdk-make-cached-versus-live-job-accessors-unambiguous
483 lines
21 KiB
Plaintext
483 lines
21 KiB
Plaintext
---
|
||
title: "Compaction and cleanup"
|
||
sidebarTitle: "Compaction"
|
||
description: "Merge small files, prune old versions, and fold new rows into existing indexes."
|
||
icon: broom
|
||
availability:
|
||
embedded: available
|
||
enterprise: available
|
||
---
|
||
|
||
import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompactionTuning } from '/snippets/doc_storage_examples.mdx';
|
||
|
||
Every write commits a new table version, and versions accumulate: small files
|
||
from frequent appends, superseded files from updates and deletes, and rows added
|
||
since an index was built. In the embedded library, `optimize()` addresses all
|
||
three. LanceDB Enterprise schedules maintenance in the background and also
|
||
supports explicit compaction jobs through the CLI, SQL, and compatible SDKs.
|
||
[Manual Enterprise compaction](#enterprise-manual-compaction) rewrites data files;
|
||
cleanup and index optimization remain separate operations.
|
||
|
||
Run optimization as regular table maintenance, particularly after many small
|
||
writes or a large ingest.
|
||
|
||
{/*
|
||
Draft for the LanceDB Embedded compaction SQ partition check release. Keep this section
|
||
unpublished until that behavior ships.
|
||
|
||
### Recover from an oversized SQ partition {#oversized-sq-partition}
|
||
|
||
Compacting a table with an IVF scalar-quantized (SQ) vector index can stop
|
||
before rewriting files if an affected partition is too large to remap. The
|
||
error identifies the index, segment, partition size, and vector dimension
|
||
instead of letting the remap fail at Arrow's fixed-size-list `u32`
|
||
child-array limit.
|
||
|
||
Rebuild the affected vector index with enough IVF partitions to keep each
|
||
partition at or below `floor(u32::MAX / dimension)` vectors, then retry the
|
||
optimize. Rebuilding with the default IVF partitioning can also choose enough
|
||
partitions.
|
||
*/}
|
||
|
||
## Optimize an Embedded table {#what-it-does}
|
||
|
||
<CodeGroup>
|
||
```python Python icon="python"
|
||
table.optimize()
|
||
```
|
||
</CodeGroup>
|
||
|
||
Three operations, in one call:
|
||
|
||
| | |
|
||
| --- | --- |
|
||
| **Compaction** | merges small files into larger ones |
|
||
| **Prune** | removes versions older than the retention window (see [Garbage Collection](/maintenance/cleanup)) |
|
||
| **Index** | folds newly added rows into existing indexes (see [Incremental Indexing](/indexing/incremental-indexing)) |
|
||
|
||
Compaction itself is only the first of the three: merging small fragments back
|
||
into larger ones, which is what keeps a scan from opening more files than it
|
||
needs to.
|
||
|
||
<Note>
|
||
**Enterprise job type:** `compact`. Runs automatically as data accumulates,
|
||
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({ timeoutMs: 600_000 });
|
||
console.log(result.rowsSucceeded, result.fragmentsRemoved, result.fragmentsAdded);
|
||
|
||
if (job.id !== null) {
|
||
await (await db.openJob<CompactionResult>(job.id)).wait();
|
||
}
|
||
```
|
||
```rust Rust
|
||
use std::time::Duration;
|
||
use lancedb::job::JobWaitOptions;
|
||
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_with_options(
|
||
JobWaitOptions::new().timeout(Duration::from_secs(600)),
|
||
).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.
|
||
|
||
## Submit Enterprise compaction {#enterprise-manual-compaction}
|
||
|
||
Use an existing Enterprise table and a connection configured for its database.
|
||
The `lancedb admin ...` and `lancedb job ...` examples on this page require the
|
||
**Enterprise administrative CLI**, available from your deployment administrator.
|
||
Check that `lancedb --help` lists `admin` and `job`. It needs Flight SQL
|
||
connectivity to submit the job and REST connectivity to read table settings and
|
||
job progress.
|
||
|
||
The [public CLI installation](/tools/cli#install) supplies the client commands
|
||
`auth`, `profile`, and `sql`, without the administrative commands. You can use
|
||
that client for the SQL alternative below or submit through an SDK. Ask your
|
||
deployment administrator for the Enterprise CLI when you need the administrative
|
||
examples.
|
||
|
||
<Note>
|
||
Use versions of the SDK, query nodes, agents, and workers that support these
|
||
options.
|
||
Older agents or workers can silently discard new job fields and run without the
|
||
requested source-row cap. Older-server errors propagate through the SDK without
|
||
retrying after dropping the settings. Manual submission requires a deployment
|
||
with SQL job submission enabled. Targets are resolved through the service
|
||
catalog, including PostgreSQL-backed SaaS catalogs.
|
||
</Note>
|
||
|
||
Submit the same four invocation settings through any of these interfaces:
|
||
|
||
<CodeGroup>
|
||
```bash CLI icon="terminal"
|
||
lancedb admin table optimize --table events \
|
||
--target-rows-per-fragment 100000 \
|
||
--max-source-rows 1000000 \
|
||
--io-buffer-size 67108864 \
|
||
--batch-size 1024 \
|
||
--wait --wait-timeout-seconds 600 --poll-interval-seconds 5
|
||
```
|
||
```sql SQL icon="database"
|
||
OPTIMIZE events REWRITE DATA WITH (
|
||
target_rows_per_fragment = 100000,
|
||
max_source_rows = 1000000,
|
||
io_buffer_size = 67108864,
|
||
batch_size = 1024
|
||
);
|
||
```
|
||
</CodeGroup>
|
||
|
||
With the public CLI, execute SQL directly using a profile configured for the
|
||
same database and Flight SQL endpoint:
|
||
|
||
```bash
|
||
lancedb sql --profile production --command \
|
||
'OPTIMIZE events REWRITE DATA WITH (max_source_rows = 1000000);'
|
||
```
|
||
|
||
Add `--branch exp` to the Enterprise CLI's `admin table optimize` command or
|
||
`branch = 'exp'` to SQL's `WITH` clause to target a branch. SDK calls use the table handle's selected branch.
|
||
Without a branch, the job targets main. CLI and SQL validate the table and branch
|
||
through the service catalog before creating a job.
|
||
|
||
SQL and the CLI without `--wait` return after durable submission. The
|
||
job-returning SDK methods above preserve the ID and return committed statistics
|
||
when waiting completes. The CLI's `--wait` polls the same durable job and prints
|
||
its result. A timeout leaves the job running. Legacy remote `optimize()` still
|
||
returns after acceptance with placeholder statistics.
|
||
|
||
Find earlier submissions with a table-scoped list, replacing `DATABASE` with
|
||
the database name:
|
||
|
||
```bash
|
||
lancedb job list --db-name DATABASE --table-name events --job-type compact
|
||
```
|
||
|
||
For a namespaced table or branch, also pass `--namespace` or `--branch-name`.
|
||
Correlate the job's submission time and stored specification, then inspect
|
||
completion and worker events with a CLI profile for that deployment:
|
||
|
||
```bash
|
||
lancedb job describe --job-id JOB_ID
|
||
lancedb job events --job-id JOB_ID
|
||
```
|
||
|
||
Under Standard authorization, submission requires table Ownership. `job describe`
|
||
accepts system Usage or, for a table job, Usage on its database and every namespace
|
||
in its path. `job list` and `job events` require system Usage; `job cancel`
|
||
requires system Operate. An unauthorized describe request returns 404 to hide
|
||
the job's existence; denied list/events requests return 403. Submission does not
|
||
grant system-level access to job lists or events.
|
||
|
||
Manual compaction uses one worker with atomic execution and inline index
|
||
remapping. Remote `optimize` does not prune old versions or optimize indexes;
|
||
explicit pruning, index optimization, and unsupported non-default compaction
|
||
settings are rejected. Cleanup continues through the deployment's separate
|
||
[cleanup policy](/maintenance/cleanup).
|
||
|
||
### Preview and inspect a run
|
||
|
||
```sql
|
||
EXPLAIN OPTIMIZE events REWRITE DATA WITH (
|
||
target_rows_per_fragment = 100000,
|
||
max_source_rows = 1000000
|
||
);
|
||
|
||
DESCRIBE JOB '<job_id>' FORMAT JSON;
|
||
```
|
||
|
||
The preview uses the execution planner to report the source version, resolved
|
||
options, planned groups/fragments/rows, and whether more eligible work remains.
|
||
It creates no job. Submission plans against its own snapshot, so concurrent
|
||
writes can change the work after a preview. `EXPLAIN ANALYZE` is unsupported.
|
||
|
||
JSON job diagnostics include reported maintenance progress and the completed
|
||
operation result alongside the existing time profile. While a job runs, its
|
||
result is null. SDK progress callbacks and CLI `--wait` expose the same worker
|
||
observations: rewritten groups/rows are execution progress, not proof of a
|
||
successful commit. Repeated task reports are counted once within an execution.
|
||
Python's `job.wait(progress=True)` displays rewritten rows; read the completion
|
||
result for committed statistics.
|
||
|
||
### Choose invocation settings {#compaction-invocation-options}
|
||
|
||
| SQL / Python / Rust | TypeScript | Meaning |
|
||
| --- | --- | --- |
|
||
| `target_rows_per_fragment` | `targetRowsPerFragment` | Positive target rows per output fragment; also affects candidate selection. This is a target, not an exact output-size guarantee. |
|
||
| `max_source_rows` | `maxSourceRows` | Positive live-source-row budget across whole planned tasks. Selection stops before a task would exceed the remaining budget. If the first useful task exceeds the budget, worker planning fails with the required live rows and source fragment count. |
|
||
| `io_buffer_size` | `ioBufferSize` | Nonnegative I/O read-ahead budget in bytes. Zero disables byte-based I/O backpressure; a positive value limits read-ahead. It is not a total-memory limit. |
|
||
| `batch_size` | `batchSize` | Positive scanner input-batch size in rows. |
|
||
|
||
These settings do not impose a runtime limit. Values must be integers in the
|
||
interface's supported range. Python and TypeScript fragment targets and batch
|
||
sizes are limited to `u32::MAX`; TypeScript additionally requires safe integers.
|
||
|
||
### Set table defaults {#table-compaction-defaults}
|
||
|
||
Table tuning supports the same four fields under `job_types.compaction`:
|
||
|
||
```bash
|
||
lancedb admin table overrides get --table events
|
||
lancedb admin table overrides set --table events \
|
||
'{"job_types":{"compaction":{"enabled":false,"target_rows_per_fragment":100000,"max_source_rows":1000000,"io_buffer_size":67108864,"batch_size":1024}}}'
|
||
```
|
||
|
||
`set` replaces the whole overrides object. The example assumes no other settings
|
||
need preserving; read the current object and retain unrelated fields when
|
||
editing an existing policy. Use the same namespace and branch for policy reads,
|
||
writes, and compaction submission.
|
||
|
||
The Python, TypeScript, and Rust SDKs can update selected fields while retaining
|
||
unrelated overrides from the current read snapshot. For an existing Enterprise
|
||
`table` handle:
|
||
|
||
<CodeGroup>
|
||
```python Python
|
||
table.update_table_overrides(
|
||
job_types={
|
||
"compaction": {
|
||
"target_rows_per_fragment": 100000,
|
||
"max_source_rows": 1000000,
|
||
}
|
||
}
|
||
)
|
||
```
|
||
```typescript TypeScript
|
||
await table.updateTableOverrides({
|
||
job_types: {
|
||
compaction: {
|
||
target_rows_per_fragment: 100000,
|
||
max_source_rows: 1000000,
|
||
},
|
||
},
|
||
});
|
||
```
|
||
```rust Rust
|
||
table
|
||
.update_table_overrides(serde_json::json!({
|
||
"job_types": {
|
||
"compaction": {
|
||
"target_rows_per_fragment": 100000,
|
||
"max_source_rows": 1000000
|
||
}
|
||
}
|
||
}))
|
||
.await?;
|
||
```
|
||
</CodeGroup>
|
||
|
||
Override keys use the server's `snake_case` names in every SDK. These examples
|
||
retain other compaction settings, such as `enabled`, and settings for other job
|
||
types from the read snapshot. An empty update only reads the current overrides;
|
||
use `reset_table_overrides()` / `resetTableOverrides()` to clear all overrides.
|
||
|
||
SDK updates perform **GET → recursive merge in the client → full PUT**. This
|
||
read–modify–write is not atomic: concurrent edits can be overwritten, even to
|
||
unrelated fields. Coordinate override writers when concurrent edits must be
|
||
preserved. CLI `set` and REST PUT replace the object without merging.
|
||
|
||
These methods require a compatible Enterprise deployment. For namespaced tables,
|
||
confirm that the deployment supports table-override reads and resets within
|
||
namespaces before relying on these APIs.
|
||
|
||
Each manual field resolves as **invocation option → table tuning →
|
||
deployment/built-in default**. Automatic jobs resolve **table tuning →
|
||
deployment/built-in default**. The fragment target has a shared deployment
|
||
default. Automatic atomic jobs also use the deployment
|
||
`agent.jobTypes.compaction.atomicMaxSourceRows` when the table has no source-row
|
||
override; manual and deferred-remap jobs do not inherit that agent-only fallback.
|
||
Otherwise, an omitted source-row budget is unbounded. Unset I/O and batch settings
|
||
use the existing Lance/scanner defaults.
|
||
|
||
The table's `enabled` flag controls automatic scheduling and admission. An
|
||
explicit manual job can run while table or deployment automatic compaction is
|
||
disabled. For example, inherit the table's target, source budget, and batch size
|
||
while overriding I/O backpressure for one run:
|
||
|
||
```bash
|
||
lancedb admin table optimize --table events --io-buffer-size 0
|
||
```
|
||
|
||
```sql
|
||
OPTIMIZE events REWRITE DATA WITH (io_buffer_size = 0);
|
||
```
|
||
|
||
Resolved tuning is stored with the durable job. A later table-policy change
|
||
affects future jobs and does not rewrite an existing job's settings. If the
|
||
budget cannot admit the first useful task, automatic preflight reports an error
|
||
without launching a compaction worker. A submitted manual job fails in worker
|
||
planning. Raise the budget to the reported requirement or review a smaller
|
||
fragment target; the target alone does not guarantee that a whole task fits.
|
||
Genuinely empty plans are still skipped by automatic preflight.
|
||
|
||
Successful bounded automatic atomic runs record whether work remains, allowing
|
||
later runs below the normal fragment-count threshold. Run intervals, index
|
||
readiness, refresh, and failure-backoff gates still apply. Failed or timed-out
|
||
attempts retain pending continuation; explicit cancellation clears it. Changing
|
||
the effective source-row budget re-arms automatic failures recorded under a
|
||
different budget; toggling automatic enablement alone does not reset backoff.
|
||
|
||
SDKs forward supplied fields and leave inheritance to the server. An explicitly
|
||
supplied SDK-default fragment target still overrides table tuning. Rust callers
|
||
should use `Table::compact_async(CompactionOverrides)` for that distinction: the legacy
|
||
`OptimizeAction::Compact` path treats its default-valued Lance fragment target
|
||
as unspecified because the options type has no presence bit.
|
||
|
||
## Retraining indexes {#retrain}
|
||
|
||
Folding new rows into an index preserves the structure the index was trained on.
|
||
When the data distribution has shifted enough that the index's clusters are a
|
||
poor fit, recreate the index with `replace=True` to train it on the current data.
|
||
The deprecated `retrain` argument to `optimize()` does not rebuild indexes.
|
||
|
||
This example assumes a populated table whose `vector` column has an IVF_FLAT
|
||
index configured for L2 distance and four partitions:
|
||
|
||
<CodeGroup>
|
||
<CodeBlock filename="Python" language="Python" icon="python">
|
||
{PyStorageRebuildVectorIndex}
|
||
</CodeBlock>
|
||
</CodeGroup>
|
||
|
||
Use your index's column, type, distance metric, and training settings when
|
||
rebuilding it. Recreating an index is more expensive than a normal optimize,
|
||
and can help after a large ingest that changed the data distribution.
|
||
|
||
## When to run it {#when}
|
||
|
||
In the embedded library there is no background compactor: `optimize()` runs
|
||
when you call it. A deployment compacts a table automatically once enough small
|
||
fragments accumulate, unless its operator turns this off.
|
||
|
||
Frequent small appends are what make it necessary, because each one commits
|
||
files. A table written in a few large batches needs it rarely; one taking
|
||
continuous small writes needs it on a schedule.
|
||
|
||
Opening a table in LanceDB Embedded logs a warning at most once per table per
|
||
process when at least 100 fragments have fewer than 100,000 rows each. Set
|
||
`LANCEDB_LOG=warn` to surface this log if your logger hides warnings by default.
|
||
|
||
<Note>
|
||
Compaction rewrites files, which conflicts with a concurrent
|
||
[computed-column refresh](/feature-engineering/add-computed-column) or
|
||
[view refresh](/feature-engineering/refresh-materialized-view) planned against the
|
||
version it replaces. Sequence them rather than running both at once.
|
||
</Note>
|
||
|
||
See [Garbage Collection](/maintenance/cleanup) for pruning old versions, and
|
||
[Incremental Indexing](/indexing/incremental-indexing) for the index-folding half of
|
||
`optimize()`.
|
||
|
||
## Performance {#performance}
|
||
|
||
Two things accumulate on a long-lived table as more and more data gets added to it:
|
||
|
||
- **Many small fragments build up as you write**, slowing down queries that have to scan across more files. **Compaction** merges them back into larger fragments.
|
||
- **Old versions build up as the table changes**, growing disk usage beyond the live data size (LanceDB retains them for time-travel and rollback). **Cleanup** prunes versions older than a retention window.
|
||
|
||
In LanceDB Embedded, you run them yourself via `optimize()`, which bundles both into a single call:
|
||
|
||
<CodeGroup>
|
||
```python Python icon="python"
|
||
from datetime import timedelta
|
||
table.optimize() # 7-day default retention
|
||
table.optimize(cleanup_older_than=timedelta(days=1)) # reclaim space sooner
|
||
```
|
||
</CodeGroup>
|
||
|
||
The best practice is to run `optimize()` after large writes or on a schedule. It also bundles incremental index updates. See [Incremental Indexing](/indexing/incremental-indexing) for the breakdown. Updates also move rows out of the vector index, so they remain searchable but unindexed. Update or rebuild the index after large update batches.
|
||
|
||
{/*
|
||
Draft for the Python compaction_options release. Keep this section unpublished
|
||
until the first supported release is confirmed.
|
||
|
||
### Tune compaction for wide rows {#tune-wide-rows}
|
||
|
||
For an existing LanceDB Embedded table, derive a fragment row target from the expected
|
||
row size. These examples use rows averaging 1 KiB and a 64 KiB fragment
|
||
target; choose sizes for your workload. Smaller scan batches and one compaction
|
||
task at a time can also reduce memory use.
|
||
|
||
<CodeGroup>
|
||
<CodeBlock filename="Python" language="Python" icon="python">
|
||
{PyStorageCompactionTuning}
|
||
</CodeBlock>
|
||
<CodeBlock filename="Rust" language="Rust" icon="rust">
|
||
{RsStorageCompactionTuning}
|
||
</CodeBlock>
|
||
</CodeGroup>
|
||
|
||
The Rust example runs compaction only. Run pruning and index optimization
|
||
separately when needed; Python's `optimize()` includes those steps.
|
||
|
||
TypeScript's `optimize()` exposes the fragment row target through
|
||
`compactionOptions.targetRowsPerFragment` and the scanner batch size through
|
||
`compactionOptions.batchSize`. Compaction thread count is not exposed. The tuning
|
||
examples above use Python and Rust tables in LanceDB Embedded.
|
||
|
||
Planning remains row based. The row target bounds later passes after existing
|
||
oversized fragments have been rewritten; the first pass rewrites those
|
||
fragments whole, so peak memory can exceed the target. `max_bytes_per_file`
|
||
limits output file size rather than compaction memory.
|
||
|
||
The `max_source_rows` and `max_source_bytes` budgets admit whole planned tasks.
|
||
If the first task exceeds a budget, that run performs no compaction. See the
|
||
[CompactionOptions reference](https://lancedb.github.io/lancedb/python/python/#lancedb.table.CompactionOptions)
|
||
for all options and their limits.
|
||
*/}
|