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
+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):