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