mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
feat(sdk)!: add typed SQL job handles for compaction and data prewarm (#5056)
Remote data prewarm used REST even though SQL supported filters and concurrency, and both maintenance APIs returned after acceptance without exposing a consistent typed completion handle. Compaction's legacy statistics therefore could not describe the work committed by its durable job. This PR adds job-returning compaction and data-prewarm methods across Rust, Python sync/async and TypeScript, and moves data-prewarm submission to SQL. Legacy methods retain return-after-acceptance behavior; data prewarm now requires a compatible SQL PREWARM server and Flight SQL connectivity. This consolidates #5037, #5055 and #4906. This was accomplished with the following changes: - Added `compact_async()` / `compactAsync()` and `prewarm_data_async()` / `prewarmDataAsync()`, retaining the command receipt's durable job ID. - Added `PrewarmDataOptions` for columns, a metadata-pruning filter and concurrency; both operations inherit database, namespace and branch from the table handle. - Added filter/concurrency arguments to legacy Python `prewarm_data()` and a TypeScript `prewarmData(options)` overload, preserving the columns-array form and discarding the handle after acceptance. - Added typed `CompactionResult` and `PrewarmDataResult` decoding, including reopened jobs; missing result payloads fail explicitly and omitted measurements remain unknown. - Reused the shared Job lifecycle for status, refresh, progress callbacks, cancellation and events; Python maintenance progress bars display rewritten rows or completed executors. - Added TypeScript `wait({ timeoutMs, onProgress })` and Rust `wait_with_options(JobWaitOptions)`, complementing Python's existing timeout argument without cancelling the durable job. - Validated single unambiguous receipts, preserved compaction option presence/default inheritance, and returned actionable unsupported-server errors without dropping options or falling back to REST. - Updated native bindings, API references and maintenance documentation with job methods, result semantics, tuning and compatibility requirements. ### Usage and behaviour **New** = added here; **Enhanced** = existing support extended; **Existing** = already on main. This table describes remote SDK behavior; server-side SQL/CLI capabilities are prerequisites, not additions made by this SDK PR. | Surface | Capability | Compact | Data prewarm | Assessment | | --- | --- | --- | --- | --- | | Rust / Python sync+async / TypeScript | Submission transport | Existing SQL OPTIMIZE | **New:** REST → SQL PREWARM | Both now submit through SQL | | All SDKs | Durable job-returning API | **New:** `compact_async` / `compactAsync` | **New:** `prewarm_data_async` / `prewarmDataAsync` | Same lifecycle model | | All SDKs | Options and target scope | **New handle:** four existing compaction overrides, with omitted fields inherited | **New options:** columns/filter/concurrency | Namespace and branch preserved for both | | Python / TypeScript | Legacy convenience calls | Existing optimize acceptance behavior preserved | **Enhanced:** legacy methods accept filter/concurrency and use SQL | Return after acceptance; no completion wait | | All SDKs | Typed successful result | **New:** committed rows, file/fragment changes, partial commit and `more_work` | **New:** pinned version, fragments and executor outcomes | Different measurements are intentional | | All SDKs | Status / refresh / progress | Existing Job APIs reused by **new** maintenance handle | Existing Job APIs reused by **new** maintenance handle | HTTP monitoring remains | | Python / TypeScript | Progress presentation | **Enhanced:** rewrite rows/groups | **Enhanced:** executor progress | Shared callbacks; Python bars use operation counters | | All SDKs | Bounded wait | Python existing; **new** TS/Rust timeout controls | Same shared timeout support | Timeout stops this wait; job continues | | All SDKs | Reopen and await typed outcome | **New:** compaction result decoding on reopened handle | **New:** prewarm result decoding on reopened handle | Rust selects the typed result explicitly | | All SDKs | Cancel / events | Existing shared APIs available on **new** handle | Same | HTTP underneath; permissions unchanged | | All SDKs | Typed preview helper | Unavailable | Unavailable | General SQL where exposed; no helper added | | Authorization | Submission | Existing table Ownership plus parent Usage | SQL path uses Select plus parent Usage | Intentional difference | | All SDKs | Local / historical handles | New durable API rejects them | New durable API rejects them | Remote current-branch jobs only | ```python from datetime import timedelta # Legacy convenience call: returns None after acceptance. table.prewarm_data(["payload"], filter="id >= 1000", concurrency=4) warm = table.prewarm_data_async(["payload"], filter="id >= 1000", concurrency=4) warmed = warm.wait(timeout=timedelta(minutes=10), progress=print) print(warmed.table_version, warmed.executors_completed) compact = table.compact_async(compaction_options={"max_source_rows": 1000000}) committed = compact.wait(timeout=timedelta(minutes=10), progress=print) print(committed.rows_succeeded, committed.fragments_removed, committed.more_work) reopened_result = db.open_job(compact.id).wait() ``` ```typescript await table.prewarmData({ columns: ["payload"], filter: "id >= 1000", concurrency: 4 }); const job = await table.prewarmDataAsync({ columns: ["payload"], filter: "id >= 1000", concurrency: 4, }); const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log }); ``` ```rust use std::time::Duration; use lancedb::job::JobWaitOptions; let job = table.compact_async(Default::default()).await?; let result = job.wait_with_options( JobWaitOptions::new().timeout(Duration::from_secs(600)), ).await?; ``` Python async tables await both submission and Job methods. Rust's legacy `prewarm_data(columns)` keeps its columns-only signature; use `PrewarmDataOptions` on the new job-returning method for filtering/concurrency. Wait deadlines cover pending status requests and polling delays. Existing `wait()`, TypeScript `wait(callback)` and Rust `wait_with_progress(callback)` remain supported. Status/progress/refresh/cancel/events still use generic HTTP job APIs; those endpoints and their read/event/cancel permissions must remain available. Cancelling or timing out does not roll back committed work. Compaction results describe committed rewrites and include deletion files in file counts. Prewarm results describe work against a pinned snapshot, with partial executors included in completed executors; nonempty byte/range measurements remain unknown. Missing results require compatible server/worker support rather than placeholder zero statistics. Filtering uses conservative metadata pruning, not an exact row-filter scan. ### Testing Six checked-in live Python sync/async cases pass against matching server/worker builds for compaction, job-returning prewarm and legacy filtered submission. Ten additional live Node scenarios pass for legacy/default/options forms, filters/concurrency, empty plans, validation, persisted specifications and readback. Targeted regressions pass: Python remote maintenance (80), shared jobs (82), local prewarm rejection (4); Node remote (107) and prewarm API cases (28), plus the previously exercised Rust remote regressions. Tests cover receipt parsing, typed results, reopening, unknown measurements, timeouts, and legacy calls returning None/undefined without polling. Dependency pins are unchanged. Azure account-hint acknowledgment was verified locally with filesystem storage; real Azure-backed storage still needs deployment-specific validation.
This commit is contained in:
@@ -567,7 +567,19 @@ impl Connection {
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn open_job(&self, job_id: String) -> napi::Result<crate::job::Job> {
|
||||
let job = self.get_inner()?.open_job(&job_id).await.default_error()?;
|
||||
Ok(crate::job::Job::new(job))
|
||||
if job.job_type().as_deref() == Some("prewarm_page_cache") {
|
||||
Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::PrewarmDataResult>()
|
||||
.default_error()?,
|
||||
))
|
||||
} else if job.job_type().as_deref() == Some("compact") {
|
||||
Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CompactionResult>()
|
||||
.default_error()?,
|
||||
))
|
||||
} else {
|
||||
Ok(crate::job::Job::new(job))
|
||||
}
|
||||
}
|
||||
|
||||
/// List server-side jobs across the database's tables.
|
||||
|
||||
+64
-18
@@ -1,10 +1,10 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use arrow_array::RecordBatch;
|
||||
use lancedb::job::JobEventsRequest;
|
||||
use lancedb::job::{JobEventsRequest, JobWaitOptions};
|
||||
use napi::bindgen_prelude::Buffer;
|
||||
use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
|
||||
use napi_derive::napi;
|
||||
@@ -17,7 +17,7 @@ type JobProgressFn =
|
||||
/// A handle to an operation that may still be running.
|
||||
#[napi]
|
||||
pub struct Job {
|
||||
inner: Arc<lancedb::Job>,
|
||||
inner: Arc<lancedb::Job<std::result::Result<Option<serde_json::Value>, String>>>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
@@ -26,7 +26,19 @@ impl Job {
|
||||
T: Clone + Send + Sync + 'static,
|
||||
{
|
||||
Self {
|
||||
inner: Arc::new(inner.map(|_| ())),
|
||||
inner: Arc::new(inner.map(|_| Ok(None))),
|
||||
}
|
||||
}
|
||||
pub(crate) fn new_typed<T>(inner: lancedb::Job<T>) -> Self
|
||||
where
|
||||
T: Clone + serde::Serialize + Send + Sync + 'static,
|
||||
{
|
||||
Self {
|
||||
inner: Arc::new(inner.map(|result| {
|
||||
serde_json::to_value(result)
|
||||
.map(Some)
|
||||
.map_err(|error| format!("failed to serialize typed job result: {error}"))
|
||||
})),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,22 +79,56 @@ impl Job {
|
||||
/// backend poller without starting another polling loop.
|
||||
#[napi(
|
||||
catch_unwind,
|
||||
ts_args_type = "progressCallback?: (progress: Record<string, unknown>) => void"
|
||||
ts_args_type = "progressCallback?: (progress: Record<string, unknown>) => void, timeoutMs?: number"
|
||||
)]
|
||||
pub async fn wait(&self, progress_callback: Option<JobProgressFn>) -> napi::Result<()> {
|
||||
if let Some(progress_callback) = progress_callback {
|
||||
self.inner
|
||||
.wait_with_progress(move |description| {
|
||||
progress_callback.call(
|
||||
description.progress_snapshot(),
|
||||
ThreadsafeFunctionCallMode::NonBlocking,
|
||||
);
|
||||
})
|
||||
.await
|
||||
.default_error()
|
||||
} else {
|
||||
self.inner.wait().await.default_error()
|
||||
pub async fn wait(
|
||||
&self,
|
||||
progress_callback: Option<JobProgressFn>,
|
||||
timeout_ms: Option<f64>,
|
||||
) -> napi::Result<()> {
|
||||
self.wait_result(progress_callback, timeout_ms)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// The typed terminal value used by result-returning SDK operations.
|
||||
#[napi(
|
||||
catch_unwind,
|
||||
ts_args_type = "progressCallback?: (progress: Record<string, unknown>) => void, timeoutMs?: number"
|
||||
)]
|
||||
pub async fn wait_result(
|
||||
&self,
|
||||
progress_callback: Option<JobProgressFn>,
|
||||
timeout_ms: Option<f64>,
|
||||
) -> napi::Result<Option<serde_json::Value>> {
|
||||
let mut options = JobWaitOptions::new();
|
||||
if let Some(timeout_ms) = timeout_ms {
|
||||
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
|
||||
if !timeout_ms.is_finite()
|
||||
|| timeout_ms.fract() != 0.0
|
||||
|| !(0.0..=MAX_SAFE_INTEGER).contains(&timeout_ms)
|
||||
{
|
||||
return Err(napi::Error::new(
|
||||
napi::Status::InvalidArg,
|
||||
"timeoutMs must be a nonnegative safe integer",
|
||||
));
|
||||
}
|
||||
options = options.timeout(Duration::from_millis(timeout_ms as u64));
|
||||
}
|
||||
if let Some(progress_callback) = progress_callback {
|
||||
options = options.progress(move |description| {
|
||||
progress_callback.call(
|
||||
description.progress_snapshot(),
|
||||
ThreadsafeFunctionCallMode::NonBlocking,
|
||||
);
|
||||
});
|
||||
}
|
||||
let result = self
|
||||
.inner
|
||||
.wait_with_options(options)
|
||||
.await
|
||||
.default_error()?;
|
||||
result.map_err(napi::Error::from_reason)
|
||||
}
|
||||
|
||||
/// Request cancellation. Cancelling a finished operation is a no-op.
|
||||
|
||||
@@ -27,6 +27,32 @@ use crate::merge::NativeMergeInsertBuilder;
|
||||
use crate::query::{Query, TakeQuery, VectorQuery};
|
||||
use crate::util::schema_to_buffer;
|
||||
|
||||
/// Settings for durable data-cache prewarm submission.
|
||||
#[napi(object)]
|
||||
pub struct PrewarmDataOptions {
|
||||
pub columns: Option<Vec<String>>,
|
||||
pub filter: Option<String>,
|
||||
pub concurrency: Option<f64>,
|
||||
}
|
||||
|
||||
impl PrewarmDataOptions {
|
||||
fn into_options(self) -> napi::Result<lancedb::table::PrewarmDataOptions> {
|
||||
let mut options =
|
||||
lancedb::table::PrewarmDataOptions::new().columns(self.columns.unwrap_or_default());
|
||||
options.filter = self.filter;
|
||||
if let Some(value) = self.concurrency {
|
||||
if !value.is_finite() || value.fract() != 0.0 || value < 1.0 || value > u32::MAX as f64
|
||||
{
|
||||
return Err(napi::Error::from_reason(
|
||||
"concurrency must be an integer between 1 and 4294967295",
|
||||
));
|
||||
}
|
||||
options.concurrency = Some(value as u32);
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-invocation file-compaction settings. All numbers must be safe integers.
|
||||
#[napi(object)]
|
||||
pub struct CompactionOptions {
|
||||
@@ -298,6 +324,23 @@ impl Table {
|
||||
.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn prewarm_data_async(
|
||||
&self,
|
||||
options: Option<PrewarmDataOptions>,
|
||||
) -> napi::Result<crate::job::Job> {
|
||||
let options = options
|
||||
.map(PrewarmDataOptions::into_options)
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let job = self
|
||||
.inner_ref()?
|
||||
.prewarm_data_async(options)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn wait_for_index(&self, index_names: Vec<String>, timeout_s: i64) -> Result<()> {
|
||||
let timeout = std::time::Duration::from_secs(timeout_s.try_into().unwrap());
|
||||
@@ -894,6 +937,23 @@ impl Table {
|
||||
Ok(self.inner_ref()?.current_branch())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn compact_async(
|
||||
&self,
|
||||
options: Option<CompactionOptions>,
|
||||
) -> napi::Result<crate::job::Job> {
|
||||
let options = options
|
||||
.map(CompactionOptions::into_overrides)
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let job = self
|
||||
.inner_ref()?
|
||||
.compact_async(options)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn optimize(
|
||||
&self,
|
||||
|
||||
Reference in New Issue
Block a user