Files
lancedb/python/python/lancedb/cleanup.py
T
Bruno Ramirez baea02eebd 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.
2026-11-20 14:34:07 -08:00

93 lines
3.4 KiB
Python

# 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")