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
+123
View File
@@ -4802,6 +4802,84 @@ async fn remote_prewarm_rejects_historical_checkout_without_submitting() {
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn remote_cleanup_tracks_registry_job_and_real_result() {
use crate::table::CleanupOptions;
let service = TestSqlService {
adaptive: true,
result: RecordBatch::try_from_iter([(
"job_id",
Arc::new(StringArray::from(vec!["cleanup-job"])) as ArrayRef,
)])
.unwrap(),
..Default::default()
};
let statements = service.statements.clone();
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
let polls = Arc::new(AtomicUsize::new(0));
let observed = polls.clone();
let client = client_with_handler(move |request| {
assert_eq!(request.url().path(), "/v1/jobs/describe");
observed.fetch_add(1, Ordering::SeqCst);
http::Response::builder()
.status(200)
.body(
serde_json::json!({
"job_id":"cleanup-job","job_type":"cleanup","job_state":"DONE",
"result":{"format_version":1,"min_age_seconds":0,"statistics_complete":true,
"old_versions":2,"bytes_removed":123}
})
.to_string(),
)
.unwrap()
});
let table = RemoteTable::new_with_sql_client(
client,
"analytics".into(),
"events".into(),
vec!["team".into(), "inner".into()],
"team$inner$events".into(),
Default::default(),
Some(sql),
)
.with_branch(Some("o'brien".into()));
let job = table
.cleanup_async(CleanupOptions::new().min_age_seconds(0))
.await
.unwrap();
assert_eq!(job.id(), Some("cleanup-job"));
assert_eq!(polls.load(Ordering::SeqCst), 0);
let result = job.wait().await.unwrap();
assert_eq!(result.old_versions, Some(2));
assert_eq!(result.bytes_removed, Some(123));
assert_eq!(
*statements.lock().unwrap(),
["VACUUM \"events\" WITH (branch = 'o''brien', min_age_seconds = 0)"]
);
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn remote_cleanup_rejects_historical_checkout_without_submitting() {
let table = RemoteTable::new_with_sql_client(
client_with_handler(|request| {
assert_eq!(request.url().path(), "/v1/table/events/describe/");
http::Response::builder()
.status(200)
.body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string())
.unwrap()
}),
"analytics".into(),
"events".into(),
vec![],
"events".into(),
Default::default(),
None,
);
table.checkout(7).await.unwrap();
assert!(table.cleanup_async(Default::default()).await.is_err());
}
#[tokio::test]
async fn remote_compaction_tracks_registry_job_and_real_result() {
use crate::table::optimize::CompactionOverrides;
@@ -4943,3 +5021,48 @@ async fn remote_prewarm_preview_uses_sql_without_any_http_jobs() {
shutdown.send(()).unwrap();
}
}
#[tokio::test]
async fn remote_cleanup_preview_uses_sql_without_job_calls() {
let payload = serde_json::json!({"format_version":1,"source_version":42,"min_age_seconds":0,
"cutoff_millis":123,"versions_to_remove":2,"bytes_to_remove":100});
let service = TestSqlService {
adaptive: true,
result: RecordBatch::try_from_iter([
(
"plan_type",
Arc::new(StringArray::from(vec!["logical_plan"])) as ArrayRef,
),
(
"plan",
Arc::new(StringArray::from(vec![payload.to_string()])) as ArrayRef,
),
])
.unwrap(),
..Default::default()
};
let statements = service.statements.clone();
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
let table = RemoteTable::new_with_sql_client(
client_with_handler(|_| -> http::Response<String> {
panic!("preview must not use HTTP jobs or execution fallback")
}),
"analytics".into(),
"events".into(),
vec!["team".into()],
"team$events".into(),
Default::default(),
Some(sql),
);
let plan = table
.explain_cleanup(crate::table::CleanupOptions::new().min_age_seconds(0))
.await
.unwrap();
assert_eq!(plan.source_version, 42);
assert_eq!(plan.versions_to_remove, 2);
assert_eq!(
*statements.lock().unwrap(),
["EXPLAIN (FORMAT JSON) VACUUM \"events\" WITH (min_age_seconds = 0)"]
);
shutdown.send(()).unwrap();
}
+62
View File
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
pub mod blobs;
mod cleanup;
pub mod insert;
mod ipc_stream;
mod optimize;
@@ -4175,6 +4176,67 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
prune: None,
})
}
async fn explain_cleanup(
&self,
options: crate::table::CleanupOptions,
) -> Result<crate::table::CleanupPlan> {
self.check_mutable().await?;
let statement = format!(
"EXPLAIN (FORMAT JSON) {}",
cleanup::statement(&self.name, self.branch.as_deref(), &options)?
);
let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported {
message: "cleanup previews require a Flight SQL endpoint with EXPLAIN (FORMAT JSON) VACUUM support".into(),
})?;
let query = client
.execute(crate::database::ExecuteQueryRequest {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
})
.await
.map_err(cleanup::map_error)?;
let mut reader = query.reader().await.map_err(cleanup::map_error)?;
let mut batches = Vec::new();
while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? {
batches.push(batch);
}
cleanup::plan(&batches)
}
async fn cleanup_async(
&self,
options: crate::table::CleanupOptions,
) -> Result<Job<crate::table::CleanupResult>> {
self.check_mutable().await?;
let statement = cleanup::statement(&self.name, self.branch.as_deref(), &options)?;
let client = self
.sql_client
.as_ref()
.ok_or_else(|| Error::NotSupported {
message: "manual cleanup requires a Flight SQL endpoint and SQL VACUUM support"
.into(),
})?;
let query = client
.execute(crate::database::ExecuteQueryRequest {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
})
.await
.map_err(cleanup::map_error)?;
let mut reader = query.reader().await.map_err(cleanup::map_error)?;
let mut batches = Vec::new();
while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? {
batches.push(batch);
}
let job_id = cleanup::receipt(&batches)?;
Ok(Job::new_typed(Box::new(RemoteJob::new(
self.client.clone(),
job_id,
))))
}
async fn compact_async(
&self,
options: crate::table::optimize::CompactionOverrides,
+234
View File
@@ -0,0 +1,234 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! SQL VACUUM submission; never replay an ambiguous acceptance response.
use crate::{Error, Result, table::CleanupOptions};
use arrow_array::{Array, RecordBatch, StringArray};
pub(super) fn statement(
table: &str,
branch: Option<&str>,
options: &CleanupOptions,
) -> Result<String> {
let mut settings = Vec::new();
if let Some(branch) = branch {
if branch.trim().is_empty() {
return Err(Error::InvalidInput {
message: "cleanup branch must not be empty".into(),
});
}
settings.push(format!("branch = {}", super::quote_sql_string(branch)));
}
if let Some(age) = options.min_age_seconds {
if i64::try_from(age)
.ok()
.and_then(chrono::Duration::try_seconds)
.and_then(|duration| chrono::Utc::now().checked_sub_signed(duration))
.is_none()
{
return Err(Error::InvalidInput {
message: "min_age_seconds is out of range".into(),
});
}
settings.push(format!("min_age_seconds = {age}"));
}
let mut sql = format!("VACUUM {}", super::quote_sql_identifier(table));
if !settings.is_empty() {
sql.push_str(&format!(" WITH ({})", settings.join(", ")));
}
Ok(sql)
}
pub(super) fn receipt(batches: &[RecordBatch]) -> Result<String> {
let invalid = || {
Error::Runtime { message: "VACUUM did not return a single nonempty job_id receipt; inspect jobs before retrying because cleanup may already have been submitted".into() }
};
if batches.iter().map(RecordBatch::num_rows).sum::<usize>() != 1 {
return Err(invalid());
}
let batch = batches
.iter()
.find(|batch| batch.num_rows() == 1)
.ok_or_else(invalid)?;
let ids = batch
.column_by_name("job_id")
.and_then(|array| array.as_any().downcast_ref::<StringArray>())
.ok_or_else(invalid)?;
if ids.is_null(0) || ids.value(0).trim().is_empty() {
return Err(invalid());
}
Ok(ids.value(0).to_string())
}
pub(super) fn plan(batches: &[RecordBatch]) -> Result<crate::table::CleanupPlan> {
let invalid = || {
Error::Runtime { message: "EXPLAIN VACUUM did not return a valid versioned preview; a compatible EXPLAIN (FORMAT JSON) VACUUM server is required. No execution fallback was attempted".into() }
};
if batches.iter().map(RecordBatch::num_rows).sum::<usize>() != 1 {
return Err(invalid());
}
let batch = batches
.iter()
.find(|batch| batch.num_rows() == 1)
.ok_or_else(invalid)?;
let kind = batch
.column_by_name("plan_type")
.and_then(|column| column.as_any().downcast_ref::<StringArray>())
.ok_or_else(invalid)?;
let payload = batch
.column_by_name("plan")
.and_then(|column| column.as_any().downcast_ref::<StringArray>())
.ok_or_else(invalid)?;
if kind.is_null(0) || kind.value(0) != "logical_plan" || payload.is_null(0) {
return Err(invalid());
}
serde_json::from_str(payload.value(0)).map_err(|_| invalid())
}
pub(super) fn map_error(error: Error) -> Error {
fn unsupported(error: &Error) -> Option<&Error> {
match error {
Error::Sql {
message, grpc_code, ..
} => {
let message = message.to_ascii_lowercase();
(*grpc_code == tonic::Code::Unimplemented as i32
|| (*grpc_code == tonic::Code::Internal as i32
&& message.contains("invalid explain format")
&& message.contains("json"))
|| (*grpc_code == tonic::Code::InvalidArgument as i32
&& (message.contains("parsererror")
|| message.contains("unknown vacuum option")
|| message.contains("vacuum is not supported by this deployment"))))
.then_some(error)
}
Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported),
_ => None,
}
}
if let Some(source) = unsupported(&error) {
let diagnostic = if matches!(error, Error::Sql { .. }) {
error.to_string()
} else {
format!("{error}; {source}")
};
Error::NotSupported {
message: format!(
"Manual cleanup requires a compatible SQL VACUUM server; upgrade the server. No options were removed and no REST fallback was attempted. Server diagnostic: {diagnostic}"
),
}
} else {
error
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn wrapped_cleanup_compatibility_keeps_job_and_request_identity() {
let sql = Error::Sql {
message: "ParserError: found VACUUM".into(),
request_id: "cleanup-request".into(),
grpc_code: tonic::Code::InvalidArgument as i32,
metadata: Default::default(),
};
let error = Error::JobFailed {
job_id: Some("query-job".into()),
failure: Box::new(crate::error::JobFailure {
phase: Some("planning".into()),
message: Some("statement failed".into()),
source: Some(Arc::new(sql)),
..Default::default()
}),
};
let mapped = map_error(error);
assert!(matches!(mapped, Error::NotSupported { .. }));
let diagnostic = mapped.to_string();
assert!(diagnostic.contains("query-job"));
assert!(diagnostic.contains("cleanup-request"));
}
#[test]
fn cleanup_statement_preserves_inheritance_zero_and_quoting() {
assert_eq!(
statement("events", None, &CleanupOptions::new()).unwrap(),
"VACUUM \"events\""
);
assert_eq!(
statement(
"a\"b",
Some("o'brien"),
&CleanupOptions::new().min_age_seconds(0)
)
.unwrap(),
"VACUUM \"a\"\"b\" WITH (branch = 'o''brien', min_age_seconds = 0)"
);
assert!(statement("t", None, &CleanupOptions::new().min_age_seconds(u64::MAX)).is_err());
}
#[test]
fn ambiguous_cleanup_receipts_never_become_query_handles() {
let batch = |values: Vec<Option<&str>>| {
RecordBatch::try_from_iter([(
"job_id",
Arc::new(StringArray::from(values)) as arrow_array::ArrayRef,
)])
.unwrap()
};
for batches in [
vec![],
vec![batch(vec![])],
vec![batch(vec![None])],
vec![batch(vec![Some("")])],
vec![batch(vec![Some("one"), Some("two")])],
] {
assert!(
receipt(&batches)
.unwrap_err()
.to_string()
.contains("inspect jobs before retrying")
);
}
assert_eq!(
receipt(&[batch(vec![]), batch(vec![Some("durable-job")])]).unwrap(),
"durable-job"
);
}
#[test]
fn cleanup_compatibility_preserves_permissions_and_transport_errors() {
for (code, diagnostic, expected) in [
(
tonic::Code::InvalidArgument,
"ParserError: found VACUUM",
true,
),
(
tonic::Code::InvalidArgument,
"Unknown VACUUM option future",
true,
),
(tonic::Code::PermissionDenied, "ParserError: denied", false),
(tonic::Code::Unavailable, "transport unavailable", false),
(
tonic::Code::InvalidArgument,
"min_age_seconds is out of range",
false,
),
] {
let error = Error::Sql {
message: diagnostic.into(),
request_id: "cleanup-request".into(),
grpc_code: code as i32,
metadata: Default::default(),
};
let mapped = map_error(error);
assert_eq!(matches!(mapped, Error::NotSupported { .. }), expected);
assert!(mapped.to_string().contains("cleanup-request"));
}
}
}
+44
View File
@@ -89,6 +89,8 @@ pub mod function_column_status;
pub mod merge;
pub mod optimize;
pub use optimize::CompactionResult;
mod cleanup;
pub use cleanup::{CleanupOptions, CleanupPlan, CleanupResult};
mod prewarm;
pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary};
pub(crate) mod primary_key;
@@ -907,6 +909,19 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
async fn tags(&self) -> Result<Box<dyn Tags + '_>>;
/// Optimize the dataset.
async fn optimize(&self, action: OptimizeAction) -> Result<OptimizeStats>;
/// Submit Enterprise version cleanup and retain its durable job and outcome.
async fn cleanup_async(&self, _options: CleanupOptions) -> Result<Job<CleanupResult>> {
Err(Error::NotSupported {
message: "durable cleanup jobs are only supported on remote tables".into(),
})
}
async fn explain_cleanup(&self, _options: CleanupOptions) -> Result<CleanupPlan> {
Err(Error::NotSupported {
message: "cleanup previews require LanceDB Enterprise".into(),
})
}
/// Submit remote compaction and retain its durable job and actual outcome.
async fn compact_async(
&self,
@@ -2140,6 +2155,35 @@ impl Table {
self.inner.compact_async(options).await
}
/// Submit durable version cleanup through SQL VACUUM and return after acceptance.
///
/// Retention resolves invocation > selected table/branch > deployment. Requires
/// Ownership and parent Usage. Local and historical handles are unsupported.
/// Operators must disable/drain automatic cleanup and prevent other cleanup,
/// tag/branch publication and restore until completion, including direct clients.
/// The server does not enforce that coordination. Preview is available without deletion.
/// Wait, cancel and reopen reuse the shared Job APIs; timeout does not cancel,
/// and cancellation cannot undo deletion or prove storage I/O has stopped.
///
/// ```
/// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> {
/// let job = table.cleanup_async(lancedb::table::CleanupOptions::new()
/// .min_age_seconds(604800)).await?;
/// let result = job.wait().await?;
/// println!("{:?}", result.old_versions);
/// # Ok(()) }
/// ```
pub async fn cleanup_async(&self, options: CleanupOptions) -> Result<Job<CleanupResult>> {
self.inner.cleanup_async(options).await
}
/// Explain Enterprise version cleanup without deleting files or submitting a job.
/// Requires the same ownership and retention options as [`Self::cleanup_async`].
/// Counts are observational estimates, not a reservation for later execution.
pub async fn explain_cleanup(&self, options: CleanupOptions) -> Result<CleanupPlan> {
self.inner.explain_cleanup(options).await
}
/// Language-binding entry point retaining optional compaction fields.
#[doc(hidden)]
pub async fn optimize_full_with_overrides(
+135
View File
@@ -0,0 +1,135 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! Options and results for durable remote version cleanup.
/// Per-invocation retention. Omission inherits table/branch then deployment policy.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CleanupOptions {
/// Minimum old-version age in seconds. None inherits server policy.
pub min_age_seconds: Option<u64>,
}
impl CleanupOptions {
/// Inherit selected table/branch and deployment retention.
pub fn new() -> Self {
Self::default()
}
/// Set the minimum old-version age in seconds; zero is explicit, not omitted.
pub fn min_age_seconds(mut self, seconds: u64) -> Self {
self.min_age_seconds = Some(seconds);
self
}
}
/// Successful remote version cleanup. Auxiliary sweeps are best effort and
/// excluded from the counts. Retry/recovery can leave counts unknown (`None`).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "CleanupResultWire")]
#[non_exhaustive]
pub struct CleanupResult {
/// Objects that could not be deleted, if measured. Other removals remain committed.
pub failed_deletes: Option<u64>,
/// Public result schema version; currently 1.
pub format_version: u32,
/// Retention resolved and recorded when the server accepted this job.
pub min_age_seconds: u64,
/// Whether the entire invocation's version-deletion counts are known.
pub statistics_complete: bool,
/// Old versions removed, or None after uncertain retry/recovery.
pub old_versions: Option<u64>,
/// Bytes removed by version deletion, excluding auxiliary sweeps.
pub bytes_removed: Option<u64>,
}
#[derive(serde::Deserialize)]
struct CleanupResultWire {
failed_deletes: Option<u64>,
format_version: u32,
min_age_seconds: u64,
statistics_complete: bool,
old_versions: Option<u64>,
bytes_removed: Option<u64>,
}
impl TryFrom<CleanupResultWire> for CleanupResult {
type Error = &'static str;
fn try_from(value: CleanupResultWire) -> std::result::Result<Self, Self::Error> {
if value.format_version != 1
|| if value.statistics_complete {
value.old_versions.is_none() || value.bytes_removed.is_none()
} else {
value.old_versions.is_some()
|| value.bytes_removed.is_some()
|| value.failed_deletes.is_some()
}
{
return Err("unsupported or inconsistent cleanup result");
}
Ok(Self {
failed_deletes: value.failed_deletes,
format_version: value.format_version,
min_age_seconds: value.min_age_seconds,
statistics_complete: value.statistics_complete,
old_versions: value.old_versions,
bytes_removed: value.bytes_removed,
})
}
}
/// Read-only version-deletion estimate. Execution re-evaluates current state;
/// no job or deletion snapshot is reserved and auxiliary sweeps are excluded.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct CleanupPlan {
#[serde(deserialize_with = "preview_version")]
pub format_version: u32,
pub source_version: u64,
pub min_age_seconds: u64,
pub cutoff_millis: i64,
pub versions_to_remove: u64,
pub bytes_to_remove: u64,
}
fn preview_version<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<u32, D::Error> {
let version = <u32 as serde::Deserialize>::deserialize(deserializer)?;
if version != 1 {
return Err(serde::de::Error::custom(
"unsupported cleanup preview format",
));
}
Ok(version)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cleanup_result_distinguishes_known_zero_unknown_and_invalid() {
let mut value = serde_json::json!({"format_version":1,"min_age_seconds":0,
"statistics_complete":true,"old_versions":0,"bytes_removed":0,"future":true});
assert_eq!(
serde_json::from_value::<CleanupResult>(value.clone())
.unwrap()
.old_versions,
Some(0)
);
value["statistics_complete"] = false.into();
assert!(serde_json::from_value::<CleanupResult>(value.clone()).is_err());
value["old_versions"] = serde_json::Value::Null;
value["bytes_removed"] = serde_json::Value::Null;
assert_eq!(
serde_json::from_value::<CleanupResult>(value.clone())
.unwrap()
.old_versions,
None
);
value["format_version"] = 2.into();
assert!(serde_json::from_value::<CleanupResult>(value).is_err());
}
}