mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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.
282 lines
9.6 KiB
Rust
282 lines
9.6 KiB
Rust
// SPDX-License-Identifier: Apache-2.0
|
|
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
use std::{sync::Arc, time::Duration};
|
|
|
|
use arrow_array::RecordBatch;
|
|
use lancedb::job::{JobEventsRequest, JobWaitOptions};
|
|
use napi::bindgen_prelude::Buffer;
|
|
use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
|
|
use napi_derive::napi;
|
|
|
|
use crate::error::NapiErrorExt;
|
|
|
|
type JobProgressFn =
|
|
ThreadsafeFunction<serde_json::Value, (), serde_json::Value, napi::Status, false>;
|
|
|
|
/// A handle to an operation that may still be running.
|
|
#[napi]
|
|
pub struct Job {
|
|
inner: Arc<lancedb::Job<std::result::Result<Option<serde_json::Value>, String>>>,
|
|
}
|
|
|
|
impl Job {
|
|
pub(crate) fn new<T>(inner: lancedb::Job<T>) -> Self
|
|
where
|
|
T: Clone + Send + Sync + 'static,
|
|
{
|
|
Self {
|
|
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}"))
|
|
})),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[napi]
|
|
impl Job {
|
|
/// The operation's opaque ID. Interpret registry and query IDs using job_type().
|
|
/// Local handles have no ID.
|
|
#[napi(getter)]
|
|
pub fn id(&self) -> Option<String> {
|
|
self.inner.id().map(str::to_string)
|
|
}
|
|
|
|
/// The operation's current lifecycle state: "running", "finished",
|
|
/// "failed", or "cancelled".
|
|
///
|
|
/// A point snapshot; unlike {@link Job.wait} it does not block or reject
|
|
/// on a terminal failure state. States a newer server reports that this
|
|
/// client version does not know pass through as-is.
|
|
#[napi(catch_unwind)]
|
|
pub async fn status(&self) -> napi::Result<String> {
|
|
self.inner.status().await.default_error()
|
|
}
|
|
|
|
/// The current structured progress snapshot, or null for an in-process
|
|
/// operation. Registry snapshots include lifecycle and queue metadata even
|
|
/// when the job type or server does not report counters.
|
|
#[napi(
|
|
catch_unwind,
|
|
ts_return_type = "Promise<Record<string, unknown> | null>"
|
|
)]
|
|
pub async fn progress(&self) -> napi::Result<Option<serde_json::Value>> {
|
|
self.inner.progress().await.default_error()
|
|
}
|
|
|
|
/// Wait until the operation reaches a terminal state. When a callback is
|
|
/// supplied, observe the same progress snapshots fetched by the existing
|
|
/// backend poller without starting another polling loop.
|
|
#[napi(
|
|
catch_unwind,
|
|
ts_args_type = "progressCallback?: (progress: Record<string, unknown>) => void, timeoutMs?: number"
|
|
)]
|
|
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.
|
|
#[napi(catch_unwind)]
|
|
pub async fn cancel(&self) -> napi::Result<()> {
|
|
self.inner.cancel().await.default_error()
|
|
}
|
|
|
|
/// Ask the backend for this job's current state, and for a server-side job
|
|
/// its full record, then cache it for the getters below.
|
|
///
|
|
/// Registry details are null until this runs; query handles already expose
|
|
/// job_type "query". {@link Job.status} fetches the whole registry record too;
|
|
/// {@link Job.wait} records only the terminal state it establishes.
|
|
#[napi(catch_unwind)]
|
|
pub async fn refresh(&self) -> napi::Result<()> {
|
|
self.inner.refresh().await.default_error()
|
|
}
|
|
|
|
/// The last observed lifecycle state, without contacting the backend.
|
|
#[napi(getter)]
|
|
pub fn state(&self) -> Option<String> {
|
|
self.inner.state()
|
|
}
|
|
|
|
/// "query" immediately for SQL-backed handles; otherwise the cached
|
|
/// server-reported job type. Null for in-process handles.
|
|
#[napi(getter)]
|
|
pub fn job_type(&self) -> Option<String> {
|
|
self.inner.job_type()
|
|
}
|
|
|
|
/// When the job was created, in milliseconds since the epoch.
|
|
#[napi(getter)]
|
|
pub fn creation_ms(&self) -> Option<i64> {
|
|
self.inner.creation_ms()
|
|
}
|
|
|
|
/// The job-type-specific specification as a JSON string, when present.
|
|
#[napi(getter)]
|
|
pub fn spec_json(&self) -> Option<String> {
|
|
self.inner.spec().map(|spec| spec.to_string())
|
|
}
|
|
|
|
/// The job-type-specific terminal result as a JSON string. Null until the
|
|
/// job succeeds, so a job that never terminates reports its progress
|
|
/// through {@link Job.events} instead.
|
|
#[napi(getter)]
|
|
pub fn result_json(&self) -> Option<String> {
|
|
self.inner.result().map(|result| result.to_string())
|
|
}
|
|
|
|
/// Why the job failed, when it failed and the server reports a reason.
|
|
#[napi(getter)]
|
|
pub fn failure(&self) -> Option<JobFailureInfo> {
|
|
self.inner.failure().map(Into::into)
|
|
}
|
|
|
|
/// This job's recorded lifecycle events, as an Arrow IPC stream buffer.
|
|
/// The TypeScript wrapper turns it into an Arrow table.
|
|
#[napi(catch_unwind)]
|
|
pub async fn events(&self, limit: Option<u32>, filter: Option<String>) -> napi::Result<Buffer> {
|
|
let batches = self
|
|
.inner
|
|
.events(JobEventsRequest { limit, filter })
|
|
.await
|
|
.default_error()?;
|
|
batches_to_ipc_buffer(&batches)
|
|
}
|
|
}
|
|
|
|
/// Serialise Arrow batches as a single IPC stream for the TypeScript layer.
|
|
fn batches_to_ipc_buffer(batches: &[RecordBatch]) -> napi::Result<Buffer> {
|
|
let Some(first) = batches.first() else {
|
|
return Ok(Buffer::from(Vec::<u8>::new()));
|
|
};
|
|
let mut out = Vec::new();
|
|
let mut writer = arrow_ipc::writer::StreamWriter::try_new(&mut out, &first.schema())
|
|
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
|
|
for batch in batches {
|
|
writer
|
|
.write(batch)
|
|
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
|
|
}
|
|
writer
|
|
.finish()
|
|
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
|
|
drop(writer);
|
|
Ok(Buffer::from(out))
|
|
}
|
|
|
|
/// A row from `Connection.listJobs`: one server-side job.
|
|
#[napi(object)]
|
|
pub struct JobInfo {
|
|
/// The job id -- what `Connection.openJob` and `Connection.cancelJob`
|
|
/// accept.
|
|
pub job_id: String,
|
|
/// The table the job runs against, without URI or namespace.
|
|
pub table: String,
|
|
pub job_type: String,
|
|
/// Lifecycle state: "running", "finished", "failed", or "cancelled".
|
|
pub state: String,
|
|
/// When the job was created, in milliseconds since the epoch.
|
|
pub created_at_millis: i64,
|
|
/// Structured lifecycle, queue, pause, and job-type-specific progress.
|
|
#[napi(ts_type = "Record<string, unknown>")]
|
|
pub progress: serde_json::Value,
|
|
/// Whether an operator has parked this job.
|
|
pub paused: bool,
|
|
}
|
|
|
|
impl From<lancedb::database::JobInfo> for JobInfo {
|
|
fn from(info: lancedb::database::JobInfo) -> Self {
|
|
let progress = info.progress_snapshot();
|
|
Self {
|
|
job_id: info.job_id,
|
|
table: info.table,
|
|
job_type: info.job_type,
|
|
state: info.state,
|
|
created_at_millis: info.created_at_millis,
|
|
progress,
|
|
paused: info.paused,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The server's account of why a job failed.
|
|
#[napi(object)]
|
|
#[derive(Clone, Debug)]
|
|
pub struct JobFailureInfo {
|
|
pub phase: Option<String>,
|
|
pub message: Option<String>,
|
|
/// User-code traceback, possibly truncated by the server.
|
|
pub traceback: Option<String>,
|
|
pub retryable: Option<bool>,
|
|
/// Isolated SQL job that raised this failure, when supplied by the server.
|
|
pub sql_job_id: Option<String>,
|
|
}
|
|
|
|
impl From<lancedb::error::JobFailure> for JobFailureInfo {
|
|
fn from(failure: lancedb::error::JobFailure) -> Self {
|
|
Self {
|
|
phase: failure.phase,
|
|
message: failure.message,
|
|
traceback: failure.traceback,
|
|
retryable: failure.retryable,
|
|
sql_job_id: failure.sql_job_id,
|
|
}
|
|
}
|
|
}
|