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:
Bruno Ramirez
2026-11-17 10:57:56 -08:00
committed by GitHub
parent e3a0a29bdb
commit 16af729792
61 changed files with 4339 additions and 249 deletions
Generated
+1
View File
@@ -6179,6 +6179,7 @@ dependencies = [
"napi",
"napi-build",
"napi-derive",
"serde",
"serde_json",
]
+12 -8
View File
@@ -456,7 +456,7 @@ Rejects a table that exists but is not a materialized view.
### dropMaterializedViewAsync()
```ts
abstract dropMaterializedViewAsync(name, namespacePath?): Promise<Job>
abstract dropMaterializedViewAsync(name, namespacePath?): Promise<Job<void>>
```
Start dropping the materialized view named `name` and return its job.
@@ -473,7 +473,7 @@ Rejects a table that exists but is not a materialized view.
#### Returns
`Promise`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
***
@@ -532,7 +532,7 @@ Drop an existing table.
### dropTableAsync()
```ts
abstract dropTableAsync(name, namespacePath?): Promise<Job>
abstract dropTableAsync(name, namespacePath?): Promise<Job<void>>
```
Start dropping a table and return its cleanup job.
@@ -548,7 +548,7 @@ on the returned job to know when cleanup has finished.
#### Returns
`Promise`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
***
@@ -579,7 +579,7 @@ catalog removal; physical cleanup continues in the background.
### dropViewAsync()
```ts
abstract dropViewAsync(name, namespacePath?): Promise<Job>
abstract dropViewAsync(name, namespacePath?): Promise<Job<void>>
```
Drop a view and return its SQL query job.
@@ -594,7 +594,7 @@ catalog removal; physical cleanup continues in the background.
#### Returns
`Promise`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
***
@@ -729,7 +729,7 @@ state and error behavior; options control page size and the starting token.
### openJob()
```ts
abstract openJob(jobId): Promise<Job>
abstract openJob<T>(jobId): Promise<Job<T>>
```
Open a server-side job by id, returning a handle with its record already
@@ -740,13 +740,17 @@ The returned [Job](Job.md) answers for its own state, specification,
result, failure and event history, so there is no separate
connection-level call for any of them.
#### Type Parameters
• **T** = `void`
#### Parameters
* **jobId**: `string`
#### Returns
`Promise`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`T`&gt;&gt;
***
+19 -4
View File
@@ -4,7 +4,7 @@
[@lancedb/lancedb](../globals.md) / Job
# Class: Job
# Class: Job&lt;T&gt;
A handle to an operation that may still be running.
@@ -20,6 +20,10 @@ extra round trip on every call:
- Registry details are null until one of those runs. Query handles report
jobType "query" immediately.
## Type Parameters
• **T** = `void`
## Accessors
### creationMs
@@ -241,7 +245,7 @@ printing it.
### wait()
```ts
wait(progressCallback?): Promise<void>
wait(optionsOrProgress?): Promise<T>
```
Wait until the operation reaches a terminal state.
@@ -253,10 +257,21 @@ synchronous observer: its return value is ignored and not awaited. If it
throws, the error is logged with `console.warn` and waiting continues; a
callback exception does not reject `wait`.
Pass an options object to set a client-side timeout. Expiry rejects with an
error and stops this wait, including pending status requests and backoff.
The operation continues; use the same handle to wait again. Registry jobs
can also be reopened with `Connection.openJob`; query IDs cannot.
#### Parameters
* **progressCallback?**: [`JobProgressCallback`](../type-aliases/JobProgressCallback.md)
* **optionsOrProgress?**: [`JobWaitOptions`](../interfaces/JobWaitOptions.md) \| [`JobProgressCallback`](../type-aliases/JobProgressCallback.md)
#### Returns
`Promise`&lt;`void`&gt;
`Promise`&lt;`T`&gt;
#### Example
```ts
const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log });
```
+120 -17
View File
@@ -305,6 +305,40 @@ It is a no-op when no writers are cached.
***
### compactAsync()
```ts
compactAsync(_options?): Promise<Job<CompactionResult>>
```
Submit remote compaction and return its durable job after acceptance.
Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires
a compatible remote server and table Ownership plus parent Usage. Local and
historical-version handles are unsupported. Existing optimize() behavior is unchanged.
Waiting tracks the rewrite itself and returns actual row/file statistics.
Missing result payloads are errors; older workers can omit file counts.
Status, progress, events and cancellation reuse the generic HTTP job APIs.
Reopen with db.openJob<CompactionResult>(job.id!). A wait timeout does not cancel work.
#### Parameters
* **\_options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md)
#### Returns
`Promise`&lt;[`Job`](Job.md)&lt;[`CompactionResult`](../interfaces/CompactionResult.md)&gt;&gt;
#### Example
```ts
const job = await table.compactAsync({ targetRowsPerFragment: 1000 });
const result = await job.wait();
console.log(result.rowsSucceeded, result.fragmentsRemoved);
```
***
### compactRTE()
```ts
@@ -423,7 +457,7 @@ await table.createIndex("my_float_col");
### createIndexAsync()
```ts
abstract createIndexAsync(column, options?): Promise<Job>
abstract createIndexAsync(column, options?): Promise<Job<void>>
```
Create an index, returning a handle to the indexing job.
@@ -444,7 +478,7 @@ account for the replacement caveat described in [Table.createIndex](Table.md#cre
#### Returns
`Promise`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
***
@@ -1047,29 +1081,98 @@ retrying with the settings removed.
### prewarmData()
#### prewarmData(options)
```ts
abstract prewarmData(columns?): Promise<void>
abstract prewarmData(options?): Promise<void>
```
Prewarm one or more columns of data in the table.
#### Parameters
This will load the column data into the page cache so that future queries that
read those columns avoid the initial cold-start latency. This call initiates
prewarming and returns once the request is accepted; the warming itself may
continue in the background. Submission uses SQL PREWARM and needs Flight
SQL connectivity. Use [prewarmDataAsync](Table.md#prewarmdataasync) to retain the job handle.
Prewarming is generally useful for columns used in filters or projections.
Large columns (e.g. high-dimensional vectors or binary data) may not be
practical to prewarm.
This feature is currently only supported in LanceDB Enterprise.
##### Parameters
* **options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md)
Columns, a metadata-pruning filter, and per-executor concurrency.
Omitted or empty columns warm every column.
##### Returns
`Promise`&lt;`void`&gt;
##### Example
```ts
await table.prewarmData({
columns: ["payload"], filter: "quality > 0.7", concurrency: 4,
});
```
#### prewarmData(columns)
```ts
abstract prewarmData(columns?): Promise<void>
```
Submit data prewarm using the columns-array form and return after acceptance.
##### Parameters
* **columns?**: `string`[]
The columns to prewarm. If undefined, all columns are prewarmed.
This will load the column data into the page cache so that future queries that
read those columns avoid the initial cold-start latency. This call initiates
prewarming and returns once the request is accepted; the warming itself may
continue in the background. Calling it on already-prewarmed columns is a
no-op on the server.
Prewarming is generally useful for columns used in filters or projections.
Large columns (e.g. high-dimensional vectors or binary data) may not be
practical to prewarm.
This feature is currently only supported in LanceDB Enterprise.
Columns to warm; omitted or empty means every column.
##### Returns
`Promise`&lt;`void`&gt;
***
### prewarmDataAsync()
```ts
abstract prewarmDataAsync(options?): Promise<Job<PrewarmDataResult>>
```
Submit data prewarm through SQL and return its durable warming-job handle.
The table handle supplies the branch and namespace. Requires a compatible
SQL PREWARM server and Flight SQL connectivity. Standard authorization
requires table Select and database/namespace Usage. Status/wait use generic
HTTP job APIs; events and cancellation retain their own privileges.
No REST fallback or option-dropping retry is performed. Historical-version
handles are unsupported; call `checkoutLatest()` first.
Submission returns after acceptance. Use `job.wait()` for completion, or
save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel
the job. After `job.refresh()`, `job.spec.table_version` is the pinned version.
#### Parameters
* **options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md)
#### Returns
`Promise`&lt;`void`&gt;
`Promise`&lt;[`Job`](Job.md)&lt;[`PrewarmDataResult`](../interfaces/PrewarmDataResult.md)&gt;&gt;
#### Example
```ts
const job = await table.prewarmDataAsync({
columns: ["video"], filter: "quality > 0.7", concurrency: 4,
});
await job.wait();
```
***
@@ -1200,7 +1303,7 @@ number of rows filled and the new version number of the table.
### refreshColumnAsync()
```ts
abstract refreshColumnAsync(column, options?): Promise<Job>
abstract refreshColumnAsync(column, options?): Promise<Job<void>>
```
Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh
@@ -1253,7 +1356,7 @@ LanceDB Enterprise it is the server's backfill job.
#### Returns
`Promise`&lt;[`Job`](Job.md)&gt;
`Promise`&lt;[`Job`](Job.md)&lt;`void`&gt;&gt;
#### Example
+4
View File
@@ -75,6 +75,7 @@
- [ColumnAlteration](interfaces/ColumnAlteration.md)
- [ColumnOrdering](interfaces/ColumnOrdering.md)
- [CompactionOptions](interfaces/CompactionOptions.md)
- [CompactionResult](interfaces/CompactionResult.md)
- [CompactionStats](interfaces/CompactionStats.md)
- [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md)
- [ConnectionOptions](interfaces/ConnectionOptions.md)
@@ -119,6 +120,7 @@
- [JobFailureInfo](interfaces/JobFailureInfo.md)
- [JobInfo](interfaces/JobInfo.md)
- [JobProgress](interfaces/JobProgress.md)
- [JobWaitOptions](interfaces/JobWaitOptions.md)
- [ListingOptions](interfaces/ListingOptions.md)
- [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md)
- [MemtableStats](interfaces/MemtableStats.md)
@@ -128,6 +130,8 @@
- [OpenTableOptions](interfaces/OpenTableOptions.md)
- [OptimizeOptions](interfaces/OptimizeOptions.md)
- [OptimizeStats](interfaces/OptimizeStats.md)
- [PrewarmDataOptions](interfaces/PrewarmDataOptions.md)
- [PrewarmDataResult](interfaces/PrewarmDataResult.md)
- [QueryExecutionOptions](interfaces/QueryExecutionOptions.md)
- [RTEStats](interfaces/RTEStats.md)
- [RTEWriteSpec](interfaces/RTEWriteSpec.md)
@@ -0,0 +1,99 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / CompactionResult
# Interface: CompactionResult
Actual committed outcome of one remote compaction job.
## Properties
### completionPercentage
```ts
completionPercentage: number;
```
Percentage of planned live rows committed, from 0 to 100.
***
### filesAdded
```ts
filesAdded: null | number;
```
Files added, including deletion files; null if an older worker omitted it.
***
### filesRemoved
```ts
filesRemoved: null | number;
```
Files removed, including deletion files; null if an older worker omitted it.
***
### fragmentsAdded
```ts
fragmentsAdded: null | number;
```
Fragments added by committed rewrites; null if an older worker omitted it.
***
### fragmentsRemoved
```ts
fragmentsRemoved: null | number;
```
Fragments removed by committed rewrites; null if an older worker omitted it.
***
### moreWork
```ts
moreWork: boolean;
```
A bounded run left eligible work for another invocation.
***
### partialCommit
```ts
partialCommit: boolean;
```
Some planned groups were not committed.
***
### rowsFailed
```ts
rowsFailed: number;
```
Planned live rows not committed by this job.
***
### rowsSucceeded
```ts
rowsSucceeded: number;
```
Live source rows in committed rewrite groups.
+98
View File
@@ -17,6 +17,14 @@ different counters. A missing counter is unknown; it is not zero.
## Properties
### bytes\_read?
```ts
optional bytes_read: null | number;
```
***
### estimated\_remaining\_time\_millis?
```ts
@@ -37,6 +45,72 @@ Execution identity and sample time used for client-side ETA derivation.
***
### executors\_active?
```ts
optional executors_active: null | number;
```
***
### executors\_completed?
```ts
optional executors_completed: null | number;
```
***
### executors\_failed?
```ts
optional executors_failed: null | number;
```
***
### executors\_partial?
```ts
optional executors_partial: null | number;
```
***
### executors\_targeted?
```ts
optional executors_targeted: null | number;
```
***
### fragments\_selected?
```ts
optional fragments_selected: null | number;
```
***
### groups\_completed?
```ts
optional groups_completed: null | number;
```
***
### groups\_planned?
```ts
optional groups_planned: null | number;
```
Maintenance work observations; rewritten rows are not committed rows.
***
### paused?
```ts
@@ -57,6 +131,22 @@ Coarse server-derived phase, including phases from newer servers.
***
### ranges\_completed?
```ts
optional ranges_completed: null | number;
```
***
### ranges\_planned?
```ts
optional ranges_planned: null | number;
```
***
### rows\_computed?
```ts
@@ -92,6 +182,14 @@ optional rows_remaining: null | number;
***
### rows\_rewritten?
```ts
optional rows_rewritten: null | number;
```
***
### rows\_skipped?
```ts
+31
View File
@@ -0,0 +1,31 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / JobWaitOptions
# Interface: JobWaitOptions
Client-side controls for waiting without cancelling the underlying job.
## Properties
### onProgress?
```ts
optional onProgress: JobProgressCallback;
```
Observe progress using the same poller that waits for completion.
***
### timeoutMs?
```ts
optional timeoutMs: number;
```
Maximum wait in milliseconds, including status requests and polling backoff.
Must be a nonnegative safe integer. Omit to wait indefinitely; zero allows
only an immediately ready result.
@@ -0,0 +1,39 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / PrewarmDataOptions
# Interface: PrewarmDataOptions
Settings for submitting a durable remote data-cache prewarm job.
## Properties
### columns?
```ts
optional columns: string[];
```
Lance field paths to warm; omitted or empty means every column.
***
### concurrency?
```ts
optional concurrency: number;
```
Positive per-executor concurrency, at most 4294967295.
***
### filter?
```ts
optional filter: string;
```
A single SQL predicate for conservative metadata pruning.
@@ -0,0 +1,79 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / PrewarmDataResult
# Interface: PrewarmDataResult
Reported executor work for a pinned snapshot; unavailable measurements stay null.
## Properties
### bytesRead
```ts
bytesRead: null | number;
```
Reported bytes read, or null when unavailable.
***
### executorsCompleted
```ts
executorsCompleted: null | number;
```
Executors that finished successfully or partially, or null when unavailable.
***
### executorsPartial
```ts
executorsPartial: null | number;
```
Subset of completed executors reporting partial warming, or null when unavailable.
***
### executorsTargeted
```ts
executorsTargeted: null | number;
```
Reported executors targeted, or null when unavailable.
***
### fragmentsSelected
```ts
fragmentsSelected: null | number;
```
Reported fragments selected, or null when unavailable.
***
### rangesCompleted
```ts
rangesCompleted: null | number;
```
Reported ranges completed, or null when unavailable.
***
### tableVersion
```ts
tableVersion: number;
```
The source snapshot captured by submission.
+4
View File
@@ -1494,3 +1494,7 @@ that accepts `python_bundle.resources`.
Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or
`conda=` for platform-specific dependencies and `models=` for large model snapshots.
::: lancedb.compaction.CompactionResult
::: lancedb.prewarm.PrewarmDataResult
+20 -9
View File
@@ -19,7 +19,7 @@ file format, so moving data from one edition to the other does not require a dat
| **Mode** | Single process | Distributed fleet | LanceDB Embedded runs on one host, so scale is limited to what it can provide. Enterprise spreads work across nodes, adds capacity by adding nodes, and keeps serving even if one node fails. |
| **Query serving** | Uses the resources of your application process | Adds independently scaled query compute | Size the Enterprise cluster for your workload and latency target. See the expected-performance sections on [vector search](/search/vector-search#expected-performance) and [full-text search](/search/full-text-search#expected-performance) for representative measurements. |
| **Cache** | In-process index and metadata caches | Adds a distributed NVMe data cache | LanceDB Embedded caches indexes and metadata in your application's memory. Enterprise also keeps hot table data near compute on NVMe and avoids repeated S3 calls -- see the [Data Page Cache](/enterprise/data-page-cache). |
| **Indexing & compaction** | Manual | Platform-managed workflows | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). |
| **Indexing & compaction** | Manual | Platform-managed workflows and explicit compaction | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). |
| **Data format** | Lance | Lance | Both use the same open table format. Plan catalog registration, access and transfer when moving existing data. |
| **Deployment** | Embedded in your code | BYOC or Managed | Enterprise adds deployment operations and support for shared workloads. |
| **SQL analytics** | Not available | Arrow Flight SQL | Enterprise runs joins, grouping, sampling and [curation](/curation) over SQL. See [SQL reference](/sql). |
@@ -137,15 +137,26 @@ Instead, materialize results through query/search builders, for example
### 4\. Maintenance lifecycle {#4-maintenance-lifecycle}
In LanceDB Embedded, you run maintenance yourself: `optimize()` compacts data files, adds new rows to
existing indexes, and removes old table versions. In Enterprise, the cluster runs this work -- along with
async write and reindexing workflows -- as background jobs, and the SDK's maintenance calls do not trigger
it. On an Enterprise table, the synchronous Python `optimize()`, `compact_files()`, and
`cleanup_old_versions()` only emit a warning, and the asynchronous Python, TypeScript, and Rust clients
reject `optimize()` as not supported.
In LanceDB Embedded, `optimize()` compacts data files, adds new rows to existing
indexes, and removes old table versions. LanceDB Enterprise schedules that work
through separate background jobs and also accepts explicit compaction requests
with compatible releases.
That means maintenance is managed by platform behavior and cluster configuration, not by explicit
per-table maintenance calls in your application code.
Python sync/async `compact_async()`, TypeScript `compactAsync()`, and Rust
`Table::compact_async(CompactionOverrides)` return durable compaction job handles;
waiting returns the committed rewrite statistics. Legacy remote `optimize()`
and Rust `Table::compact()` return after submission with placeholder counts.
Remote optimize does not prune versions or optimize indexes;
explicit requests for those unsupported operations are rejected. The synchronous
Python `compact_files()` and `cleanup_old_versions()` helpers remain warning-only
no-ops in LanceDB Enterprise.
Manual compaction accepts four invocation options and inherits omitted fields
from the selected branch's table tuning, then deployment/built-in defaults.
Automatic-compaction enablement gates background scheduling while explicit
manual jobs can still run. See
[manual Enterprise compaction](/maintenance/compaction#enterprise-manual-compaction)
for CLI, SQL, and SDK examples and rollout requirements.
### 5\. Guardrails and limits {#5-guardrails-and-limits}
+26 -1
View File
@@ -95,7 +95,7 @@ In Python, `job.status()` returns the current state:
It returns `failed` or `cancelled` for unsuccessful jobs.
Use `job.wait()` to wait for completion and raise if the job fails or is
cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection
cancelled. Python's `Job.wait()` and `AsyncJob.wait()` retry transient connection
and read errors with capped
exponential backoff within the caller's timeout. Without a timeout, retries
continue indefinitely.
@@ -123,8 +123,33 @@ except ConnectionError as exc:
except TimeoutError:
print(f"still running: {job.status()}")
```
```typescript TypeScript
const result = await job.wait({
timeoutMs: 600_000,
onProgress: progress => console.log(progress),
});
```
```rust Rust
use std::time::Duration;
use lancedb::job::JobWaitOptions;
let result = job.wait_with_options(
JobWaitOptions::new()
.timeout(Duration::from_secs(600))
.progress(|description| println!("{}", description.progress_snapshot())),
).await?;
```
</CodeGroup>
TypeScript's `timeoutMs` and Rust's `JobWaitOptions::timeout` bound the existing
wait poller, including pending status requests and retry/polling delays.
Expiry rejects the TypeScript promise or returns Rust's `Error::Timeout`;
the operation is not cancelled. Calling `wait()` without options still waits
indefinitely. TypeScript's existing `wait(callback)` and Rust's
`wait_with_progress(callback)` remain available. A zero timeout only permits
an immediately ready result. TypeScript timeouts use nonnegative safe-integer
milliseconds; Rust uses `std::time::Duration`.
After connectivity returns, reopen an Enterprise registry job by its saved ID
and continue waiting on the existing operation:
@@ -20,11 +20,13 @@ independently: `optimize()` compacts and remaps affected indexes in the
same call, before returning. Compaction's `defer_index_remap` option opts
out of that -- the call returns once compaction itself commits, leaving
the remap for later -- which is what lets a custom remapper or a
stable-row-ID table skip the synchronous step. LanceDB Enterprise runs
compaction and indexing as separate, independently scheduled
background jobs -- a table can compact while an index build is still
catching up from an earlier compaction -- so it needs a way to keep an index
correct without forcing every compaction to wait for a synchronous remap.
stable-row-ID table skip the synchronous step. LanceDB Enterprise schedules
automatic compaction and indexing independently, so an eligible table can compact
while an index build is still catching up from earlier compaction. Deferred
remapping keeps indexes correct without making every automatic compaction wait
for a synchronous remap. Explicit
[manual compaction](/maintenance/compaction#enterprise-manual-compaction) uses one
worker with atomic execution and inline index remapping instead.
## The fragment reuse index {#fri}
+139 -12
View File
@@ -1,23 +1,25 @@
---
title: "Cache Prewarm"
sidebarTitle: "Cache Prewarm"
description: "Populate the tiered index cache ahead of a request, instead of filling it lazily on first read."
description: "Warm indexes at executor startup or submit on-demand jobs to populate the data page cache."
icon: "fire"
keywords: ["prewarm", "cache", "index cache", "startup"]
keywords: ["prewarm", "cache", "index cache", "data page cache", "startup"]
availability:
embedded: unavailable
enterprise: available
---
Cache Prewarm loads the [tiered index cache](/enterprise/tiered-index-cache)
a plan executor keeps as part of Enterprise's serving layer, instead of
leaving it to fill lazily on first read. You configure which tables to
prewarm; on startup, each plan executor loads those tables' indexes into
cache before it joins the fleet. The executor does not accept queries until
prewarming finishes, so it never serves a request against a cold cache.
Enterprise supports two kinds of cache prewarm: startup index prewarm fills
the [tiered index cache](/enterprise/tiered-index-cache), and
[on-demand data prewarm](#on-demand-data-prewarm) fills the
[data page cache](/enterprise/data-page-cache) through a durable job.
LanceDB Embedded has no such cache, so there is nothing for it to warm
there. Embedded does have its own, separate `prewarm_index()` on a table --
For startup index prewarm, you configure which tables to warm. Each plan
executor loads those tables' indexes before it joins the fleet. The executor
does not accept queries until startup prewarming finishes.
These Enterprise caches are not available in LanceDB Embedded.
Embedded does have its own, separate `prewarm_index()` on a table --
an idempotent hint that loads a built index into memory ahead of a query.
<div className="hidden dark:block">
@@ -72,14 +74,139 @@ and rollouts instead of dipping right after each one.
[Contact us](https://www.lancedb.com/contact) to learn more about how
prewarming is configured for your deployment.
## On-demand data prewarm {#on-demand-data-prewarm}
On compatible Enterprise deployments, the SDK submits data prewarm through
SQL. Flight SQL connectivity is required; the existing generic HTTP job API is
used to inspect or wait for the durable warming job. Under Standard
authorization, submission requires table Select plus Usage on the database
and namespace hierarchy. Job events require System Usage and cancellation
requires System Operate.
The table handle determines the database, namespace, and branch in every SDK.
<Tabs>
<Tab title="Python">
```python
from datetime import timedelta
job = table.prewarm_data_async(
["video"], filter="quality > 0.7", concurrency=4
)
print(job.id)
result = job.wait(timeout=timedelta(minutes=10), progress=print)
print(result.table_version, result.executors_completed, result.fragments_selected)
# Reattach in a later process using the same database connection settings.
db.open_job(job.id).wait()
```
</Tab>
<Tab title="TypeScript">
```typescript
const job = await table.prewarmDataAsync({
columns: ["video"],
filter: "quality > 0.7",
concurrency: 4,
});
console.log(job.id);
const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log });
console.log(result.tableVersion, result.executorsCompleted);
// Reattach using the same database connection settings.
if (job.id !== null) {
await (await db.openJob(job.id)).wait();
}
```
</Tab>
<Tab title="Rust">
```rust
use std::time::Duration;
use lancedb::job::JobWaitOptions;
use lancedb::table::{PrewarmDataOptions, PrewarmDataResult};
let job = table
.prewarm_data_async(
PrewarmDataOptions::new()
.columns(["video"])
.filter("quality > 0.7")
.concurrency(4),
)
.await?;
println!("{:?}", job.id());
let result = job.wait_with_options(
JobWaitOptions::new().timeout(Duration::from_secs(600)),
).await?;
println!("Snapshot {}: {:?} executors completed", result.table_version, result.executors_completed);
// Reattach using the same database connection settings.
if let Some(id) = job.id() {
db.open_job(id).await?.into_typed::<PrewarmDataResult>()?.wait().await?;
}
```
</Tab>
</Tabs>
The method returns when the job is accepted. Waiting finishes when warming
reaches a terminal state; a timeout does not cancel the job. Use
`job.refresh()` and `job.spec["table_version"]` to inspect the captured source
version. In Python's asynchronous API, await submission and `job.wait()`.
Node exposes `table.prewarmDataAsync({ columns, filter, concurrency })` with
the same lifecycle.
Waiting returns a typed `PrewarmDataResult`: the pinned source version,
selected fragment count, targeted/completed executor counts, and partial
executor count when reported. Completed executors include partial completions;
`executors_partial` is that subset, which can reflect cache pressure. These are observations of executor work, not a guarantee that every
page remains resident. Counters omitted by older workers stay unknown.
The current executor status protocol does not report byte/range measurements
for nonempty prewarms, so `bytes_read` and `ranges_completed` are None/null there.
A new worker performing an empty plan reports known zero work. Progress exposes
planning/dispatch phases, selected fragments, executor fan-out, and the latest
active/completed/partial/failed executor counts without inventing percentages.
In Python, `job.wait(progress=True)` displays completed executors. Pass a
callback instead to inspect the full structured snapshots.
The Enterprise administrative CLI supports the same lifecycle:
```bash
lancedb admin cache prewarm data --profile production --table events \
--column payload --filter 'id >= 1000' --concurrency 4 \
--wait --wait-timeout-seconds 600 --poll-interval-seconds 5
```
SQL submission and preview use the same options. Submission returns a job ID
and pinned source version; preview creates no job:
```sql
PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000;
EXPLAIN PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000;
DESCRIBE JOB '<job_id>' FORMAT JSON;
```
The filter is a single SQL predicate used for conservative metadata pruning.
Unknown or unavailable metadata keeps data eligible for warming. Omitted
columns warm all fields; concurrency must be a positive integer. Historical
version checkouts are unsupported: use the latest version of the selected
branch. The server never needs to scan rows merely to evaluate the predicate.
`prewarm_data(columns, filter=..., concurrency=...)` and
`prewarmData({ columns, filter, concurrency })` accept the same options as the
job-returning methods but return after acceptance without retaining the handle.
The existing TypeScript `prewarmData(columns)` array form remains supported.
These methods require SQL PREWARM support and Flight SQL connectivity.
Unsupported servers fail without a REST fallback or silently
dropping options. Repeated submissions may create distinct jobs; warming
already-cached data is safe. Index prewarm keeps its existing behavior.
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Data Page Cache" icon="database" href="/enterprise/data-page-cache">
The raw-data-page cache -- a separate cache from the one prewarm fills.
The raw-data-page cache populated by on-demand data prewarm jobs.
</Card>
<Card title="Tiered Index Cache" icon="layer-group" href="/enterprise/tiered-index-cache">
The deserialized-index cache prewarm fills.
The deserialized-index cache populated by startup index prewarm.
</Card>
<Card title="Architecture" icon="diagram-project" href="/index#architecture">
Where plan executors and query nodes sit in the serving fleet.
@@ -76,6 +76,14 @@ rest of the job's tasks commit without waiting on it. See
[Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution)
for when compaction defers a remap at all.
Automatic compaction can use this distributed path when table state and index
safety permit it. Explicit CLI, SQL, and SDK compaction jobs use one worker with
atomic execution and inline index remapping. Their tuning resolves from the
invocation, then table settings, then deployment/built-in defaults. Automatic
jobs use table settings before those defaults. See
[manual compaction](/maintenance/compaction#enterprise-manual-compaction) for
submission, the four tuning fields, and job completion checks.
## Compaction interfaces {#compaction-interfaces}
- [Compaction](/maintenance/compaction) for triggering and configuring a compaction.
@@ -112,13 +112,21 @@ a compaction and a cleanup are unrelated and can both launch together -- but
some gate each other where running them at the same time would be unsafe,
like index operations waiting on a compaction that can't defer its remap.
Compaction's four tuning fields can be set per table. Automatic jobs use table
tuning before deployment/built-in defaults; explicit manual invocation values
take precedence over both. Automatic enablement still gates background jobs,
while manual compaction can run with it disabled. Resolved tuning is captured in
each job. See [table compaction defaults](/maintenance/compaction#table-compaction-defaults)
for the fields, precedence, source-budget planning failures, and compatible-version requirements.
### When cleanup is due {#cleanup}
[Cleanup](/maintenance/cleanup) prunes old table versions and the files only
they referenced. In LanceDB Embedded, that always happens because you asked
for it -- a call to `optimize()`. LanceDB Enterprise does not support a
manual `optimize()` call at all; cleanup there is entirely this planner's own
decision, off by default unless the deployment sets a minimum version age --
for it, through a call to `optimize()`. In LanceDB Enterprise, a
[manual `optimize()` call](/maintenance/compaction#enterprise-manual-compaction)
submits compaction only. Cleanup remains this planner's own decision, off by
default unless the deployment sets a minimum version age:
with no minimum age configured, nothing is ever old enough to clean up
automatically, and old versions simply accumulate until an operator enables
it. A table can also disable it individually even when the deployment allows
+4 -3
View File
@@ -41,10 +41,11 @@ default. The name says which algorithm is building, not a separate feature.
## Triggering an incremental update {#incremental-reindexing}
In the embedded library, you trigger an incremental indexing operation on
updated data with the `optimize()` method on a table. A deployment does this
for you and does not support `optimize()`, as described below.
updated data with the `optimize()` method on a table. LanceDB Enterprise updates
indexes in the background. Its [manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction)
submits compaction only and does not trigger incremental index updates.
Table optimization performs three maintenance operations:
In LanceDB Embedded, table optimization performs three maintenance operations:
1. **Compaction**: merges small fragments into larger ones to improve read performance
2. **Pruning/Cleanup**: removes files from versions older than a retention window (7 days by default) -- see [Cleanup](/maintenance/cleanup) for how retention works
+6 -1
View File
@@ -90,7 +90,12 @@ Updating the table data (adding, deleting, or modifying records) requires that y
</CodeGroup>
<Note title="LanceDB Enterprise">
New data added after creating the scalar index will still appear in search results if optimize is not used, but with increased latency due to a flat search on the unindexed portion. LanceDB Enterprise does not support `optimize()`; instead it adds new rows to `BTREE`, `BITMAP` and `LABEL_LIST` indexes in the background once enough have accumulated. It does not update `FM` indexes automatically.
New data added after creating the scalar index remains searchable through a
slower flat scan of the unindexed rows. LanceDB Enterprise adds new rows to
`BTREE`, `BITMAP`, and `LABEL_LIST` indexes in the background once enough have
accumulated. It does not update `FM` indexes automatically. The Enterprise
[manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction)
submits compaction only and does not trigger this index maintenance.
</Note>
### 4\. Run Indexed Searches
+3 -1
View File
@@ -301,7 +301,9 @@ fallback and searches only indexed rows.
**Operational checks**
In the embedded library, use `optimize()` after appends or other writes to fold new rows into existing indexes.
A deployment does this in the background, and `optimize()` is not available there.
LanceDB Enterprise does this in the background. Its
[manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction)
submits compaction only and does not add unindexed rows to the vector index.
</Info>
#### Check Index Status
+4 -2
View File
@@ -96,8 +96,10 @@ maintenance workers to a version that understands Managed blobs before using
them, and reopen handles created before that upgrade.
For LanceDB Embedded tables, `optimize()` performs compaction and cleanup.
Enterprise runs these as background jobs; Python tables connected to Enterprise
do not support `optimize()`.
Enterprise schedules them as separate background jobs. With compatible releases,
remote `optimize()` also submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction),
but does not prune versions or remove their files. Cleanup remains governed by
the deployment's separate policy.
See [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path.
## Disk usage does not drop immediately {#disk}
+265 -3
View File
@@ -13,8 +13,10 @@ import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompac
Every write commits a new table version, and versions accumulate: small files
from frequent appends, superseded files from updates and deletes, and rows added
since an index was built. In the embedded library, `optimize()` addresses all
three. Enterprise handles maintenance in the background and also supports
on-demand compaction through `optimize()` on compatible servers.
three. LanceDB Enterprise schedules maintenance in the background and also
supports explicit compaction jobs through the CLI, SQL, and compatible SDKs.
[Manual Enterprise compaction](#enterprise-manual-compaction) rewrites data files;
cleanup and index optimization remain separate operations.
Run optimization as regular table maintenance, particularly after many small
writes or a large ingest.
@@ -37,7 +39,7 @@ optimize. Rebuilding with the default IVF partitioning can also choose enough
partitions.
*/}
## Optimize a table {#what-it-does}
## Optimize an Embedded table {#what-it-does}
<CodeGroup>
```python Python icon="python"
@@ -63,6 +65,266 @@ separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs
even though `optimize()` bundles both in one LanceDB Embedded call.
</Note>
## Track on-demand Enterprise compaction {#compaction-jobs}
On compatible Enterprise deployments, `compact_async()` / `compactAsync()`
submits SQL `OPTIMIZE ... REWRITE DATA` and returns a durable job handle.
The table handle supplies the namespace and branch. The existing remote
`optimize()` call keeps returning after submission with placeholder statistics;
use the job-returning API to wait for the actual rewrite and obtain its result.
<CodeGroup>
```python Python
from datetime import timedelta
job = table.compact_async(
compaction_options={"target_rows_per_fragment": 1000, "batch_size": 128}
)
result = job.wait(timeout=timedelta(minutes=10))
print(result.rows_succeeded, result.fragments_removed, result.fragments_added)
# Resume from another process with the same connection settings.
result = db.open_job(job.id).wait()
```
```typescript TypeScript
import type { CompactionResult } from "@lancedb/lancedb";
const job = await table.compactAsync({
targetRowsPerFragment: 1000, batchSize: 128,
});
const result = await job.wait({ timeoutMs: 600_000 });
console.log(result.rowsSucceeded, result.fragmentsRemoved, result.fragmentsAdded);
if (job.id !== null) {
await (await db.openJob<CompactionResult>(job.id)).wait();
}
```
```rust Rust
use std::time::Duration;
use lancedb::job::JobWaitOptions;
use lancedb::table::{CompactionResult, optimize::CompactionOverrides};
let job = table.compact_async(CompactionOverrides {
target_rows_per_fragment: Some(1000),
batch_size: Some(128),
..Default::default()
}).await?;
let result = job.wait_with_options(
JobWaitOptions::new().timeout(Duration::from_secs(600)),
).await?;
println!("Committed {} rows", result.rows_succeeded);
if let Some(id) = job.id() {
db.open_job(id).await?.into_typed::<CompactionResult>()?.wait().await?;
}
```
</CodeGroup>
The result describes this job's committed rewrites, not a comparison of table
versions that could include concurrent writes. `partial_commit` identifies an
incomplete commit; `rows_failed` counts planned rows left uncommitted.
`more_work` means a bounded run left eligible work for another invocation.
A genuine no-op reports zero file/fragment counts; counts omitted by an older
worker are `None` in Python/Rust or `null` in TypeScript. A server that publishes
no compaction result raises an error when waiting, rather than fabricating zero
statistics.
Submission requires Flight SQL connectivity and, under Standard authorization,
table Ownership plus Usage on the database and namespace hierarchy. Status,
progress, events, and cancellation use the generic HTTP job APIs and their
existing permissions. A wait timeout or dropping the handle does not cancel
the job. Local tables and historical-version checkouts are unsupported by the
job-returning API; ordinary embedded `optimize()` remains available.
## Submit Enterprise compaction {#enterprise-manual-compaction}
Use an existing Enterprise table and a connection configured for its database.
The `lancedb admin ...` and `lancedb job ...` examples on this page require the
**Enterprise administrative CLI**, available from your deployment administrator.
Check that `lancedb --help` lists `admin` and `job`. It needs Flight SQL
connectivity to submit the job and REST connectivity to read table settings and
job progress.
The [public CLI installation](/tools/cli#install) supplies the client commands
`auth`, `profile`, and `sql`, without the administrative commands. You can use
that client for the SQL alternative below or submit through an SDK. Ask your
deployment administrator for the Enterprise CLI when you need the administrative
examples.
<Note>
Use versions of the SDK, query nodes, agents, and workers that support these
options.
Older agents or workers can silently discard new job fields and run without the
requested source-row cap. Older-server errors propagate through the SDK without
retrying after dropping the settings. Manual submission requires a deployment
with SQL job submission enabled. Targets are resolved through the service
catalog, including PostgreSQL-backed SaaS catalogs.
</Note>
Submit the same four invocation settings through any of these interfaces:
<CodeGroup>
```bash CLI icon="terminal"
lancedb admin table optimize --table events \
--target-rows-per-fragment 100000 \
--max-source-rows 1000000 \
--io-buffer-size 67108864 \
--batch-size 1024 \
--wait --wait-timeout-seconds 600 --poll-interval-seconds 5
```
```sql SQL icon="database"
OPTIMIZE events REWRITE DATA WITH (
target_rows_per_fragment = 100000,
max_source_rows = 1000000,
io_buffer_size = 67108864,
batch_size = 1024
);
```
</CodeGroup>
With the public CLI, execute SQL directly using a profile configured for the
same database and Flight SQL endpoint:
```bash
lancedb sql --profile production --command \
'OPTIMIZE events REWRITE DATA WITH (max_source_rows = 1000000);'
```
Add `--branch exp` to the Enterprise CLI's `admin table optimize` command or
`branch = 'exp'` to SQL's `WITH` clause to target a branch. SDK calls use the table handle's selected branch.
Without a branch, the job targets main. CLI and SQL validate the table and branch
through the service catalog before creating a job.
SQL and the CLI without `--wait` return after durable submission. The
job-returning SDK methods above preserve the ID and return committed statistics
when waiting completes. The CLI's `--wait` polls the same durable job and prints
its result. A timeout leaves the job running. Legacy remote `optimize()` still
returns after acceptance with placeholder statistics.
Find earlier submissions with a table-scoped list, replacing `DATABASE` with
the database name:
```bash
lancedb job list --db-name DATABASE --table-name events --job-type compact
```
For a namespaced table or branch, also pass `--namespace` or `--branch-name`.
Correlate the job's submission time and stored specification, then inspect
completion and worker events with a CLI profile for that deployment:
```bash
lancedb job describe --job-id JOB_ID
lancedb job events --job-id JOB_ID
```
Under Standard authorization, submission requires table Ownership. `job describe`
accepts system Usage or, for a table job, Usage on its database and every namespace
in its path. `job list` and `job events` require system Usage; `job cancel`
requires system Operate. An unauthorized describe request returns 404 to hide
the job's existence; denied list/events requests return 403. Submission does not
grant system-level access to job lists or events.
Manual compaction uses one worker with atomic execution and inline index
remapping. Remote `optimize` does not prune old versions or optimize indexes;
explicit pruning, index optimization, and unsupported non-default compaction
settings are rejected. Cleanup continues through the deployment's separate
[cleanup policy](/maintenance/cleanup).
### Preview and inspect a run
```sql
EXPLAIN OPTIMIZE events REWRITE DATA WITH (
target_rows_per_fragment = 100000,
max_source_rows = 1000000
);
DESCRIBE JOB '<job_id>' FORMAT JSON;
```
The preview uses the execution planner to report the source version, resolved
options, planned groups/fragments/rows, and whether more eligible work remains.
It creates no job. Submission plans against its own snapshot, so concurrent
writes can change the work after a preview. `EXPLAIN ANALYZE` is unsupported.
JSON job diagnostics include reported maintenance progress and the completed
operation result alongside the existing time profile. While a job runs, its
result is null. SDK progress callbacks and CLI `--wait` expose the same worker
observations: rewritten groups/rows are execution progress, not proof of a
successful commit. Repeated task reports are counted once within an execution.
Python's `job.wait(progress=True)` displays rewritten rows; read the completion
result for committed statistics.
### Choose invocation settings {#compaction-invocation-options}
| SQL / Python / Rust | TypeScript | Meaning |
| --- | --- | --- |
| `target_rows_per_fragment` | `targetRowsPerFragment` | Positive target rows per output fragment; also affects candidate selection. This is a target, not an exact output-size guarantee. |
| `max_source_rows` | `maxSourceRows` | Positive live-source-row budget across whole planned tasks. Selection stops before a task would exceed the remaining budget. If the first useful task exceeds the budget, worker planning fails with the required live rows and source fragment count. |
| `io_buffer_size` | `ioBufferSize` | Nonnegative I/O read-ahead budget in bytes. Zero disables byte-based I/O backpressure; a positive value limits read-ahead. It is not a total-memory limit. |
| `batch_size` | `batchSize` | Positive scanner input-batch size in rows. |
These settings do not impose a runtime limit. Values must be integers in the
interface's supported range. Python and TypeScript fragment targets and batch
sizes are limited to `u32::MAX`; TypeScript additionally requires safe integers.
### Set table defaults {#table-compaction-defaults}
Table tuning supports the same four fields under `job_types.compaction`:
```bash
lancedb admin table overrides get --table events
lancedb admin table overrides set --table events \
'{"job_types":{"compaction":{"enabled":false,"target_rows_per_fragment":100000,"max_source_rows":1000000,"io_buffer_size":67108864,"batch_size":1024}}}'
```
`set` replaces the whole overrides object. The example assumes no other settings
need preserving; read the current object and retain unrelated fields when
editing an existing policy. Use the same namespace and branch for policy reads,
writes, and compaction submission.
Each manual field resolves as **invocation option → table tuning →
deployment/built-in default**. Automatic jobs resolve **table tuning →
deployment/built-in default**. The fragment target has a shared deployment
default. Automatic atomic jobs also use the deployment
`agent.jobTypes.compaction.atomicMaxSourceRows` when the table has no source-row
override; manual and deferred-remap jobs do not inherit that agent-only fallback.
Otherwise, an omitted source-row budget is unbounded. Unset I/O and batch settings
use the existing Lance/scanner defaults.
The table's `enabled` flag controls automatic scheduling and admission. An
explicit manual job can run while table or deployment automatic compaction is
disabled. For example, inherit the table's target, source budget, and batch size
while overriding I/O backpressure for one run:
```bash
lancedb admin table optimize --table events --io-buffer-size 0
```
```sql
OPTIMIZE events REWRITE DATA WITH (io_buffer_size = 0);
```
Resolved tuning is stored with the durable job. A later table-policy change
affects future jobs and does not rewrite an existing job's settings. If the
budget cannot admit the first useful task, automatic preflight reports an error
without launching a compaction worker. A submitted manual job fails in worker
planning. Raise the budget to the reported requirement or review a smaller
fragment target; the target alone does not guarantee that a whole task fits.
Genuinely empty plans are still skipped by automatic preflight.
Successful bounded automatic atomic runs record whether work remains, allowing
later runs below the normal fragment-count threshold. Run intervals, index
readiness, refresh, and failure-backoff gates still apply. Failed or timed-out
attempts retain pending continuation; explicit cancellation clears it. Changing
the effective source-row budget re-arms automatic failures recorded under a
different budget; toggling automatic enablement alone does not reset backoff.
SDKs forward supplied fields and leave inheritance to the server. An explicitly
supplied SDK-default fragment target still overrides table tuning. Rust callers
should use `Table::compact_async(CompactionOverrides)` for that distinction: the legacy
`OptimizeAction::Compact` path treats its default-valued Lance fragment target
as unspecified because the options type has no presence bit.
## Retraining indexes {#retrain}
Folding new rows into an index preserves the structure the index was trained on.
+4 -1
View File
@@ -1790,7 +1790,10 @@ mixing in lower-level Lance file operations.
System operations like `optimize()`, index updates, and table compaction also increment table version numbers.
In LanceDB Embedded, `optimize()` can prune older versions based on its retention setting (`cleanup_older_than`, 7 days by default),
which is when old-version files are removed and disk space is reclaimed. A deployment prunes them in the background
when its configuration enables [cleanup](/maintenance/cleanup); `optimize()` is not available there.
when its configuration enables [cleanup](/maintenance/cleanup). With compatible
releases, Enterprise `optimize()` submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction)
only; it does not prune old versions. Submission returns before workers finish,
so observe the completed job and resulting table state before expecting a new version.
**Tagged versions are never pruned.** A version with a tag pointing at it is
retained regardless of age. When a tagged version is older than the retention window and
+17 -3
View File
@@ -67,9 +67,23 @@ DESC JOB '<job_id>' [FORMAT TEXT | TABLE | JSON]
```
</CodeGroup>
Both spellings show a finished root job's timing profile. `TEXT` is the
default; `TABLE` returns typed phase/step rows and `JSON` returns the
profile as one document. A running job has no profile rows.
`TEXT` is the default and shows a finished root job's timing profile;
`TABLE` returns typed phase/step rows. These formats have no profile rows
while a job runs.
On compatible deployments, `JSON` returns one document in the `profile`
column with `job_id`, `job_type`, `job_state`, reported `progress`, and the
successful operation's `result`, alongside any timing profile. It works
while the job runs, when `result` is null. Compaction counters describe
committed work only in the result; progress counters describe observed
execution work. Data prewarm results identify the pinned table version and
reported executor work. Unavailable measurements remain absent or null.
```sql
DESCRIBE JOB '<job_id>' FORMAT JSON;
```
Older deployments return only the timing profile.
## SHOW ERRORS {#errors}
+52 -2
View File
@@ -1,9 +1,9 @@
---
title: "Table"
sidebarTitle: "Table"
description: "CREATE, DESCRIBE, ALTER, CLONE and DROP TABLE."
description: "CREATE, DESCRIBE, ALTER, OPTIMIZE, CLONE and DROP TABLE."
icon: table
keywords: ["create table", "alter table", "drop table", "describe", "clone", "ddl"]
keywords: ["create table", "alter table", "drop table", "describe", "clone", "optimize", "ddl"]
availability:
embedded: unavailable
enterprise: available
@@ -258,6 +258,56 @@ deployment stores its catalog. See
[Object teardown](/basics/jobs#teardown).
</Note>
## OPTIMIZE REWRITE DATA {#optimize}
Submit a durable manual compaction job on a compatible Enterprise deployment:
```sql
OPTIMIZE events REWRITE DATA WITH (
target_rows_per_fragment = 100000,
max_source_rows = 1000000,
io_buffer_size = 67108864,
batch_size = 1024
);
```
Write the table name immediately after `OPTIMIZE`, without a `TABLE` keyword.
All four settings are optional. Add `branch = 'exp'` in the same `WITH (...)`
clause to select a branch; an omitted branch targets main. Row targets,
source-row budgets, and scanner batch sizes must be positive integers. The I/O
budget is in bytes and accepts zero to disable byte-based I/O backpressure.
Unknown or duplicate options and invalid numbers are rejected before submission.
Each field uses its invocation value, then that branch's table tuning, then
deployment/built-in defaults. The automatic-compaction `enabled` flags do not
block an explicit manual job. Tuning is captured in the durable specification;
later table changes affect future jobs.
The statement returns a `job_id` after submission, before worker completion.
It runs atomic compaction on one worker with inline index remapping, without
pruning versions or optimizing indexes. The source-row budget admits whole
tasks; if the first useful task exceeds it, worker planning fails with the
required live rows and source fragment count. The table and branch are validated
through the service catalog before creating a job.
See [manual compaction](/maintenance/compaction#enterprise-manual-compaction)
for the option meanings, supported deployment and version requirements,
authorization, job inspection, table defaults, and equivalent CLI/SDK examples.
### Preview manual compaction
```sql
EXPLAIN OPTIMIZE events REWRITE DATA WITH (max_source_rows = 1000000);
DESCRIBE JOB '<job_id>' FORMAT JSON;
```
The preview reports the selected source version, effective options, planned
work and continuation using the worker's planner without submitting a job.
`EXPLAIN ANALYZE` is unsupported. The JSON diagnostic includes reported progress
and a successful job's committed result. See [Compaction](/maintenance/compaction#compaction-jobs)
for durable SDK handles and CLI waiting.
## What to read next {#next}
<CardGroup cols={2}>
+6
View File
@@ -10,6 +10,12 @@ Use the `lancedb` command-line client to open an interactive SQL shell, run a
statement, or execute a SQL file. SQL requires a running deployment with an
[Arrow Flight SQL endpoint](/basics/sql#sql-is-remote).
This public client exposes `auth`, `profile`, and `sql`. Commands such as
`lancedb admin ...` and `lancedb job ...` require the Enterprise administrative
CLI from your deployment administrator; the public client archive and source
installation below do not include them. Use `lancedb sql --command` for SQL
statements supported by your deployment.
## Install
Download a CLI archive and `SHA256SUMS` from the
+1
View File
@@ -30,6 +30,7 @@ napi = { version = "3.15.0", default-features = false, features = [
"serde-json",
] }
chrono.workspace = true
serde.workspace = true
serde_json.workspace = true
napi-derive = "3.6.13"
# Prevent dynamic linking of lzma, which comes from datafusion
+267
View File
@@ -2662,3 +2662,270 @@ describe("lazy resource listings", () => {
});
}
});
describe("remote compaction job results", () => {
test.each([true, false])(
"reopens typed compaction result (counts=%s)",
async (counts) => {
await withMockDatabase(
(request, response) => {
expect(request.url).toBe("/v1/jobs/describe");
const result = JSON.parse(`{
"partial_commit": false,
"rows_succeeded": 12,
"rows_failed": 0,
"completion_percentage": 100
}`);
if (counts) {
Object.assign(
result,
JSON.parse(`{
"files_added": 1,
"files_removed": 3,
"fragments_added": 1,
"fragments_removed": 3
}`),
);
}
response.writeHead(200, { "Content-Type": "application/json" });
response.end(
`{"job_id":"compacting-job","job_type":"compact","job_state":"DONE","result":${JSON.stringify(result)}}`,
);
},
async (db) => {
const job =
await db.openJob<import("../lancedb").CompactionResult>(
"compacting-job",
);
const result = await job.wait();
expect(result.rowsSucceeded).toBe(12);
expect(result.moreWork).toBe(false);
expect(result.fragmentsRemoved).toBe(counts ? 3 : null);
},
);
},
);
});
describe("data prewarm typed results", () => {
test.each([null, {}])(
"rejects a missing typed outcome (%p)",
async (result) => {
await withMockDatabase(
(_request, response) => {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(
`{"job_id":"warming-job","job_type":"prewarm_page_cache","job_state":"DONE","result":${JSON.stringify(result)}}`,
);
},
async (db) => {
const job = await db.openJob("warming-job");
await expect(job.wait()).rejects.toThrow();
},
);
},
);
test.each([true, false])(
"reopens a result (counters=%s)",
async (counters) => {
await withMockDatabase(
(_request, response) => {
const result = JSON.parse(
counters
? '{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}'
: '{"table_version":42}',
);
response.writeHead(200, { "Content-Type": "application/json" });
response.end(
JSON.stringify({
["job_id"]: "warming-job",
["job_type"]: "prewarm_page_cache",
["job_state"]: "DONE",
progress: null,
["operation_progress"]: {
phase: "reading",
["executors_completed"]: 2,
},
result,
}),
);
},
async (db) => {
const job =
await db.openJob<import("../lancedb").PrewarmDataResult>(
"warming-job",
);
const result = await job.wait();
expect(result.tableVersion).toBe(42);
expect(result.executorsCompleted).toBe(counters ? 2 : null);
expect(result.bytesRead).toBeNull();
expect((await job.progress())?.executors_completed).toBe(2);
},
);
},
);
});
describe("job wait deadlines", () => {
function response(kind: string, done: boolean) {
const result =
kind === "compact"
? '{"partial_commit":false,"rows_succeeded":12,"rows_failed":0,"completion_percentage":100}'
: kind === "prewarm_page_cache"
? '{"table_version":42,"executors_targeted":2,"executors_completed":2}'
: "null";
return `{"job_id":"bounded-job","job_type":"${kind}","job_state":"${done ? "DONE" : "IN_PROGRESS"}","result":${done ? result : "null"}}`;
}
test.each(["compact", "prewarm_page_cache", "create_index"])(
"%s stops polling at timeout, resumes, and reopens",
async (kind) => {
let done = false;
let describes = 0;
const progress: JobProgress[] = [];
await withMockDatabase(
(request, res) => {
expect(request.url).toBe("/v1/jobs/describe");
describes++;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(response(kind, done));
},
async (db) => {
const fallback = setTimeout(() => {
done = true;
}, 1000);
try {
const job = await db.openJob("bounded-job");
await expect(
job.wait({ timeoutMs: 50, onProgress: (p) => progress.push(p) }),
).rejects.toThrow(/bounded-job.*continues/);
expect(job.state).toBe("running");
await new Promise((resolve) => setImmediate(resolve));
const requestsAtTimeout = describes;
const updatesAtTimeout = progress.length;
await new Promise((resolve) => setTimeout(resolve, 350));
expect(describes).toBe(requestsAtTimeout);
expect(progress).toHaveLength(updatesAtTimeout);
done = true;
const result = await job.wait({
timeoutMs: 1000,
onProgress: (p) => progress.push(p),
});
await new Promise((resolve) => setImmediate(resolve));
expect(progress.some((p) => p.state === "finished")).toBe(true);
expect(job.state).toBe("finished");
expect(result).toEqual(
kind === "compact"
? expect.objectContaining({ rowsSucceeded: 12 })
: kind === "prewarm_page_cache"
? expect.objectContaining({ tableVersion: 42 })
: undefined,
);
// Existing callback-only and argument-free calls remain supported.
expect(await job.wait((p) => progress.push(p))).toEqual(result);
expect(await job.wait()).toEqual(result);
const reopened = await db.openJob("bounded-job");
expect(await reopened.wait({ timeoutMs: 1000 })).toEqual(result);
} finally {
clearTimeout(fallback);
}
},
);
},
);
it("bounds a pending HTTP response and permits a later wait", async () => {
let slow = false;
let requests = 0;
await withMockDatabase(
(request, res) => {
expect(request.url).toBe("/v1/jobs/describe");
requests++;
const send = () => {
if (!res.destroyed) {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(response("prewarm_page_cache", slow));
}
};
if (slow) setTimeout(send, 300);
else send();
},
async (db) => {
const job = await db.openJob("bounded-job");
slow = true;
await expect(job.wait({ timeoutMs: 50 })).rejects.toThrow("continues");
expect(job.state).toBe("running");
const stoppedAt = requests;
await new Promise((resolve) => setTimeout(resolve, 350));
expect(requests).toBe(stoppedAt);
const result = await job.wait({ timeoutMs: 1000 });
expect(result).toEqual(expect.objectContaining({ tableVersion: 42 }));
},
);
});
it("accepts zero timeout and validates options before polling", async () => {
let requests = 0;
let done = false;
await withMockDatabase(
(_request, res) => {
requests++;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(response("compact", done));
},
async (db) => {
const fallback = setTimeout(() => {
done = true;
}, 1000);
try {
const job = await db.openJob("bounded-job");
for (const timeoutMs of [
-1,
1.5,
Number.NaN,
Number.POSITIVE_INFINITY,
Number.MAX_SAFE_INTEGER + 1,
"10",
true,
]) {
await expect(
job.wait({ timeoutMs: timeoutMs as number }),
).rejects.toThrow("nonnegative safe integer");
}
await expect(job.wait({ timeout: 10 } as never)).rejects.toThrow(
"Unknown job wait option",
);
await expect(job.wait({ onProgress: 7 } as never)).rejects.toThrow(
"onProgress must be a function",
);
await expect(job.wait(10 as never)).rejects.toThrow("options object");
expect(requests).toBe(1);
await expect(job.wait({ timeoutMs: 0 })).rejects.toThrow("Timeout");
} finally {
clearTimeout(fallback);
}
},
);
});
test.each(["FAILED", "CANCELLED"])(
"preserves a %s outcome when a timeout is configured",
async (state) => {
await withMockDatabase(
(_request, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
`{"job_id":"bounded-job","job_type":"compact","job_state":"${state}"}`,
);
},
async (db) => {
const job = await db.openJob("bounded-job");
await expect(job.wait({ timeoutMs: 1000 })).rejects.toThrow(
state === "FAILED" ? /failed/i : /cancelled/i,
);
},
);
},
);
});
+100 -5
View File
@@ -4678,15 +4678,94 @@ describe.each(arrowVersions)(
];
const table = await db.createTable("prewarm_data_test", data);
// prewarmData is only supported in LanceDB Enterprise. We verify the call
// is wired through napi and surfaces the expected error for both
// arg shapes (undefined and string[]).
await expect(table.prewarmData()).rejects.toThrow(
"prewarm_data is currently only supported in LanceDB Enterprise",
"only supported on remote tables",
);
await expect(table.prewarmData(["text"])).rejects.toThrow(
"prewarm_data is currently only supported in LanceDB Enterprise",
"only supported on remote tables",
);
await expect(
table.prewarmData({
columns: ["text"],
filter: "text = 'alpha'",
concurrency: 2,
}),
).rejects.toThrow("only supported on remote tables");
});
test("prewarmData preserves argument forms and returns after submission", async () => {
const db = await connect(tmpDir.name);
const table = await db.createTable("prewarm_submission", [{ id: 1 }]);
const wait = jest.fn();
const submit = jest
.spyOn(table, "prewarmDataAsync")
.mockResolvedValue({ wait } as unknown as Awaited<
ReturnType<Table["prewarmDataAsync"]>
>);
const options = { columns: ["id"], filter: "id > 0", concurrency: 2 };
try {
await expect(table.prewarmData(options)).resolves.toBeUndefined();
expect(submit).toHaveBeenLastCalledWith(options);
await expect(table.prewarmData(["id"])).resolves.toBeUndefined();
expect(submit).toHaveBeenLastCalledWith({ columns: ["id"] });
await expect(table.prewarmData([])).resolves.toBeUndefined();
expect(submit).toHaveBeenLastCalledWith({ columns: [] });
await expect(table.prewarmData()).resolves.toBeUndefined();
expect(submit).toHaveBeenLastCalledWith(undefined);
expect(wait).not.toHaveBeenCalled();
} finally {
submit.mockRestore();
}
});
test("prewarmData validates options before submission", async () => {
const db = await connect(tmpDir.name);
const table = await db.createTable("prewarm_options", [{ id: 1 }]);
await expect(
table.prewarmData({ unsupported: 1 } as never),
).rejects.toThrow("Unsupported data prewarm option: unsupported");
for (const concurrency of [
0,
-1,
1.5,
Number.NaN,
Number.POSITIVE_INFINITY,
4294967296,
]) {
await expect(table.prewarmData({ concurrency })).rejects.toThrow(
"concurrency must be an integer",
);
}
});
test("prewarmDataAsync validates options and rejects local tables", async () => {
const db = await connect(tmpDir.name);
const table = await db.createTable("prewarm_job", [{ id: 1 }]);
await expect(table.prewarmDataAsync()).rejects.toThrow(
"only supported on remote tables",
);
await expect(
table.prewarmDataAsync({
columns: ["id"],
filter: "id > 0",
concurrency: 2,
}),
).rejects.toThrow("only supported on remote tables");
await expect(
table.prewarmDataAsync({ unsupported: 1 } as never),
).rejects.toThrow("Unsupported data prewarm option: unsupported");
for (const concurrency of [
0,
-1,
1.5,
Number.NaN,
Number.POSITIVE_INFINITY,
4294967296,
]) {
await expect(table.prewarmDataAsync({ concurrency })).rejects.toThrow(
"concurrency must be an integer",
);
}
});
test("full text index on list", async () => {
@@ -5791,3 +5870,19 @@ describe("computed columns", () => {
expect(rows.map((r) => r.doubled).sort()).toEqual([10, 2]);
});
});
describe("durable compaction validation", () => {
test("rejects local tables and unknown options", async () => {
const db = await connect(`memory://compaction-job-${Date.now()}`);
const table = await db.createTable("test", [{ id: 1 }]);
await expect(table.compactAsync()).rejects.toThrow(
"only supported on remote tables",
);
await expect(
table.compactAsync({ unrecognizedLimit: 1 } as never),
).rejects.toThrow("Unsupported compaction option");
await expect(
table.compactAsync({ targetRowsPerFragment: 0 }),
).rejects.toThrow("safe integer");
});
});
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
/** Actual committed outcome of one remote compaction job. */
export interface CompactionResult {
/** A bounded run left eligible work for another invocation. */
moreWork: boolean;
/** Some planned groups were not committed. */
partialCommit: boolean;
/** Live source rows in committed rewrite groups. */
rowsSucceeded: number;
/** Planned live rows not committed by this job. */
rowsFailed: number;
/** Percentage of planned live rows committed, from 0 to 100. */
completionPercentage: number;
/** Files added, including deletion files; null if an older worker omitted it. */
filesAdded: number | null;
/** Files removed, including deletion files; null if an older worker omitted it. */
filesRemoved: number | null;
/** Fragments added by committed rewrites; null if an older worker omitted it. */
fragmentsAdded: number | null;
/** Fragments removed by committed rewrites; null if an older worker omitted it. */
fragmentsRemoved: number | null;
}
/** @internal */
export function decodeCompactionResult(value: unknown): CompactionResult {
// The Rust typed-job decoder validates the wire payload before it reaches JS.
const result = value as Record<string, number | boolean | null>;
return {
moreWork: result.more_work as boolean,
partialCommit: result.partial_commit as boolean,
rowsSucceeded: result.rows_succeeded as number,
rowsFailed: result.rows_failed as number,
completionPercentage: result.completion_percentage as number,
filesAdded: (result.files_added as number | null) ?? null,
filesRemoved: (result.files_removed as number | null) ?? null,
fragmentsAdded: (result.fragments_added as number | null) ?? null,
fragmentsRemoved: (result.fragments_removed as number | null) ?? null,
};
}
+3 -3
View File
@@ -583,7 +583,7 @@ export abstract class Connection {
* result, failure and event history, so there is no separate
* connection-level call for any of them.
*/
abstract openJob(jobId: string): Promise<Job>;
abstract openJob<T = void>(jobId: string): Promise<Job<T>>;
/**
* Iterate lazily over server-side jobs across the database's tables.
@@ -1017,8 +1017,8 @@ export class LocalConnection extends Connection {
);
}
async openJob(jobId: string): Promise<Job> {
return new Job(await this.inner.openJob(jobId));
async openJob<T = void>(jobId: string): Promise<Job<T>> {
return new Job<T>(await this.inner.openJob(jobId));
}
listJobs(options: ListingOptions = {}): Listing<JobInfo> {
+6 -1
View File
@@ -118,7 +118,7 @@ export {
Job,
JobEventsOptions,
} from "./job";
export type { JobProgress, JobProgressCallback } from "./job";
export type { JobProgress, JobProgressCallback, JobWaitOptions } from "./job";
export {
AutoQuery,
@@ -175,6 +175,7 @@ export {
UpdateOptions,
OptimizeOptions,
CompactionOptions,
PrewarmDataOptions,
Version,
WriteProgress,
FtsToken,
@@ -664,3 +665,7 @@ export {
} from "./catalog";
export { Listing, ListingOptions } from "./listing";
export type { CompactionResult } from "./compaction";
export type { PrewarmDataResult } from "./prewarm";
+105 -11
View File
@@ -2,7 +2,9 @@
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { Table as ArrowTable, tableFromIPC } from "apache-arrow";
import { decodeCompactionResult } from "./compaction";
import { JobFailureInfo, Job as NativeJob } from "./native";
import { decodePrewarmDataResult } from "./prewarm";
/** Which of a job's events {@link Job.events} returns. */
export interface JobEventsOptions {
@@ -39,6 +41,31 @@ export interface JobProgress {
rows_remaining?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
rows_failed?: number | null;
/** Maintenance work observations; rewritten rows are not committed rows. */
// biome-ignore lint/style/useNamingConvention: server wire format
groups_planned?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
groups_completed?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
rows_rewritten?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
executors_targeted?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
executors_completed?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
executors_partial?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
executors_active?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
executors_failed?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
fragments_selected?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
ranges_completed?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
ranges_planned?: number | null;
// biome-ignore lint/style/useNamingConvention: server wire format
bytes_read?: number | null;
/** Execution identity and sample time used for client-side ETA derivation. */
// biome-ignore lint/style/useNamingConvention: server wire format
execution_epoch?: number | null;
@@ -54,6 +81,18 @@ export interface JobProgress {
/** Callback for progress snapshots observed while waiting for a job. */
export type JobProgressCallback = (progress: JobProgress) => void;
/** Client-side controls for waiting without cancelling the underlying job. */
export interface JobWaitOptions {
/**
* Maximum wait in milliseconds, including status requests and polling backoff.
* Must be a nonnegative safe integer. Omit to wait indefinitely; zero allows
* only an immediately ready result.
*/
timeoutMs?: number;
/** Observe progress using the same poller that waits for completion. */
onProgress?: JobProgressCallback;
}
/**
* A handle to an operation that may still be running.
*
@@ -71,11 +110,20 @@ export type JobProgressCallback = (progress: JobProgress) => void;
*
* @hideconstructor
*/
export class Job {
export class Job<T = void> {
private readonly inner: NativeJob;
constructor(inner: NativeJob) {
private readonly resultDecoder?: (value: unknown) => T;
constructor(inner: NativeJob, resultDecoder?: (value: unknown) => T) {
this.inner = inner;
this.resultDecoder =
resultDecoder ??
(inner.jobType === "prewarm_page_cache"
? (decodePrewarmDataResult as (value: unknown) => T)
: inner.jobType === "compact"
? (decodeCompactionResult as (value: unknown) => T)
: undefined);
}
/**
@@ -161,18 +209,64 @@ export class Job {
* synchronous observer: its return value is ignored and not awaited. If it
* throws, the error is logged with `console.warn` and waiting continues; a
* callback exception does not reject `wait`.
*
* Pass an options object to set a client-side timeout. Expiry rejects with an
* error and stops this wait, including pending status requests and backoff.
* The operation continues; use the same handle to wait again. Registry jobs
* can also be reopened with `Connection.openJob`; query IDs cannot.
*
* @example
* ```ts
* const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log });
* ```
*/
async wait(progressCallback?: JobProgressCallback): Promise<void> {
if (progressCallback === undefined) {
return this.inner.wait();
async wait(
optionsOrProgress?: JobWaitOptions | JobProgressCallback,
): Promise<T> {
const options: JobWaitOptions =
typeof optionsOrProgress === "function"
? { onProgress: optionsOrProgress }
: (optionsOrProgress ?? {});
if (typeof options !== "object" || Array.isArray(options)) {
throw new TypeError(
"wait expects an options object or a progress callback",
);
}
return this.inner.wait((progress) => {
try {
progressCallback(this.enrichProgress(progress));
} catch (error) {
console.warn("Job progress callback threw:", error);
for (const key of Object.keys(options)) {
if (key !== "timeoutMs" && key !== "onProgress") {
throw new TypeError(`Unknown job wait option: ${key}`);
}
});
}
const { timeoutMs, onProgress: progressCallback } = options;
if (
timeoutMs !== undefined &&
(!Number.isSafeInteger(timeoutMs) || timeoutMs < 0)
) {
throw new RangeError("timeoutMs must be a nonnegative safe integer");
}
if (
progressCallback !== undefined &&
typeof progressCallback !== "function"
) {
throw new TypeError("onProgress must be a function");
}
const callback =
progressCallback === undefined
? undefined
: (progress: Record<string, unknown>) => {
try {
progressCallback(this.enrichProgress(progress));
} catch (error) {
console.warn("Job progress callback threw:", error);
}
};
if (this.resultDecoder !== undefined) {
return this.resultDecoder(
await this.inner.waitResult(callback, timeoutMs),
);
}
await this.inner.wait(callback, timeoutMs);
return undefined as T;
}
/** Request cancellation. Cancelling a finished operation is a no-op. */
+35
View File
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
/** Reported executor work for a pinned snapshot; unavailable measurements stay null. */
export interface PrewarmDataResult {
/** The source snapshot captured by submission. */
tableVersion: number;
/** Reported executors targeted, or null when unavailable. */
executorsTargeted: number | null;
/** Executors that finished successfully or partially, or null when unavailable. */
executorsCompleted: number | null;
/** Subset of completed executors reporting partial warming, or null when unavailable. */
executorsPartial: number | null;
/** Reported fragments selected, or null when unavailable. */
fragmentsSelected: number | null;
/** Reported ranges completed, or null when unavailable. */
rangesCompleted: number | null;
/** Reported bytes read, or null when unavailable. */
bytesRead: number | null;
}
/** @internal */
export function decodePrewarmDataResult(value: unknown): PrewarmDataResult {
// Rust validates the typed wire result before handing it to JavaScript.
const result = value as Record<string, number | null>;
return {
tableVersion: result.table_version as number,
executorsTargeted: result.executors_targeted ?? null,
executorsCompleted: result.executors_completed ?? null,
executorsPartial: result.executors_partial ?? null,
fragmentsSelected: result.fragments_selected ?? null,
rangesCompleted: result.ranges_completed ?? null,
bytesRead: result.bytes_read ?? null,
};
}
+126 -19
View File
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { CompactionResult, decodeCompactionResult } from "./compaction";
import { PrewarmDataResult, decodePrewarmDataResult } from "./prewarm";
import {
Table as ArrowTable,
Data,
@@ -165,6 +168,16 @@ export interface UpdateOptions {
where: string;
}
/** Settings for submitting a durable remote data-cache prewarm job. */
export interface PrewarmDataOptions {
/** Lance field paths to warm; omitted or empty means every column. */
columns?: string[];
/** A single SQL predicate for conservative metadata pruning. */
filter?: string;
/** Positive per-executor concurrency, at most 4294967295. */
concurrency?: number;
}
/** Per-invocation compaction settings. Values must be safe integers. */
export interface CompactionOptions {
/** Positive target rows per output fragment; also affects candidate selection. */
@@ -562,22 +575,58 @@ export abstract class Table {
/**
* Prewarm one or more columns of data in the table.
*
* @param columns The columns to prewarm. If undefined, all columns are prewarmed.
*
* This will load the column data into the page cache so that future queries that
* read those columns avoid the initial cold-start latency. This call initiates
* prewarming and returns once the request is accepted; the warming itself may
* continue in the background. Calling it on already-prewarmed columns is a
* no-op on the server.
* continue in the background. Submission uses SQL PREWARM and needs Flight
* SQL connectivity. Use {@link prewarmDataAsync} to retain the job handle.
*
* Prewarming is generally useful for columns used in filters or projections.
* Large columns (e.g. high-dimensional vectors or binary data) may not be
* practical to prewarm.
*
* This feature is currently only supported in LanceDB Enterprise.
*
* @param options Columns, a metadata-pruning filter, and per-executor concurrency.
* Omitted or empty columns warm every column.
*
* @example
* await table.prewarmData({
* columns: ["payload"], filter: "quality > 0.7", concurrency: 4,
* });
*/
abstract prewarmData(options?: PrewarmDataOptions): Promise<void>;
/**
* Submit data prewarm using the columns-array form and return after acceptance.
* @param columns Columns to warm; omitted or empty means every column.
*/
abstract prewarmData(columns?: string[]): Promise<void>;
/**
* Submit data prewarm through SQL and return its durable warming-job handle.
*
* The table handle supplies the branch and namespace. Requires a compatible
* SQL PREWARM server and Flight SQL connectivity. Standard authorization
* requires table Select and database/namespace Usage. Status/wait use generic
* HTTP job APIs; events and cancellation retain their own privileges.
* No REST fallback or option-dropping retry is performed. Historical-version
* handles are unsupported; call `checkoutLatest()` first.
*
* Submission returns after acceptance. Use `job.wait()` for completion, or
* save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel
* the job. After `job.refresh()`, `job.spec.table_version` is the pinned version.
*
* @example
* const job = await table.prewarmDataAsync({
* columns: ["video"], filter: "quality > 0.7", concurrency: 4,
* });
* await job.wait();
*/
abstract prewarmDataAsync(
options?: PrewarmDataOptions,
): Promise<Job<PrewarmDataResult>>;
/**
* Waits for asynchronous indexing to complete on the table.
*
@@ -1209,6 +1258,28 @@ export abstract class Table {
* out state and the read_consistency_interval, if any, will apply.
*/
abstract restore(): Promise<void>;
/**
* Submit remote compaction and return its durable job after acceptance.
*
* Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires
* a compatible remote server and table Ownership plus parent Usage. Local and
* historical-version handles are unsupported. Existing optimize() behavior is unchanged.
* Waiting tracks the rewrite itself and returns actual row/file statistics.
* Missing result payloads are errors; older workers can omit file counts.
* Status, progress, events and cancellation reuse the generic HTTP job APIs.
* Reopen with db.openJob<CompactionResult>(job.id!). A wait timeout does not cancel work.
*
* @example
* const job = await table.compactAsync({ targetRowsPerFragment: 1000 });
* const result = await job.wait();
* console.log(result.rowsSucceeded, result.fragmentsRemoved);
*/
async compactAsync(
_options?: CompactionOptions,
): Promise<Job<CompactionResult>> {
throw new Error("compaction jobs are only supported on remote tables");
}
/**
* Optimize the on-disk data and indices for better performance.
*
@@ -1505,8 +1576,30 @@ export class LocalTable extends Table {
await this.inner.prewarmIndex(name);
}
async prewarmData(columns?: string[]): Promise<void> {
await this.inner.prewarmData(columns);
async prewarmData(options?: PrewarmDataOptions): Promise<void>;
async prewarmData(columns?: string[]): Promise<void>;
async prewarmData(
columnsOrOptions?: string[] | PrewarmDataOptions,
): Promise<void> {
await this.prewarmDataAsync(
Array.isArray(columnsOrOptions)
? { columns: columnsOrOptions }
: columnsOrOptions,
);
}
async prewarmDataAsync(
options?: PrewarmDataOptions,
): Promise<Job<PrewarmDataResult>> {
for (const key of Object.keys(options ?? {})) {
if (!["columns", "filter", "concurrency"].includes(key)) {
throw new Error(`Unsupported data prewarm option: ${key}`);
}
}
return new Job(
await this.inner.prewarmDataAsync(options),
decodePrewarmDataResult,
);
}
async waitForIndex(
@@ -1884,20 +1977,18 @@ export class LocalTable extends Table {
return this.inner.currentBranch() ?? null;
}
async compactAsync(
options?: CompactionOptions,
): Promise<Job<CompactionResult>> {
validateCompactionOptions(options);
return new Job(
await this.inner.compactAsync(options),
decodeCompactionResult,
);
}
async optimize(options?: Partial<OptimizeOptions>): Promise<OptimizeStats> {
// JavaScript callers can supply extra keys that TypeScript would reject.
// Refuse them before the native binding can silently discard a work limit.
const supported = new Set([
"targetRowsPerFragment",
"maxSourceRows",
"ioBufferSize",
"batchSize",
]);
for (const key of Object.keys(options?.compactionOptions ?? {})) {
if (!supported.has(key)) {
throw new Error(`Unsupported compaction option: ${key}`);
}
}
validateCompactionOptions(options?.compactionOptions);
return await this.inner.optimize(
options?.cleanupOlderThan?.getTime(),
options?.deleteUnverified,
@@ -2197,3 +2288,19 @@ function rowIdsToBigInts(rowIds: readonly (bigint | number)[]): bigint[] {
return BigInt(id);
});
}
function validateCompactionOptions(options?: CompactionOptions): void {
// JavaScript callers can supply extra keys that TypeScript would reject.
// Refuse them before the native binding can silently discard a work limit.
const supported = new Set([
"targetRowsPerFragment",
"maxSourceRows",
"ioBufferSize",
"batchSize",
]);
for (const key of Object.keys(options ?? {})) {
if (!supported.has(key)) {
throw new Error(`Unsupported compaction option: ${key}`);
}
}
}
+13 -1
View File
@@ -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
View File
@@ -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.
+60
View File
@@ -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,
+10
View File
@@ -645,6 +645,13 @@ class Table:
async def restore(self, version: Optional[Union[int, str]] = None): ...
async def prewarm_index(self, index_name: str) -> None: ...
async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ...
async def prewarm_data_async(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> Job: ...
async def list_indices(self) -> list[IndexConfig]: ...
async def tokenize(
self,
@@ -787,6 +794,9 @@ class Table:
async def update_field_metadata(
self, updates: list[dict[str, Any]]
) -> UpdateFieldMetadataResult: ...
async def compact_async(
self, compaction_options: Optional[Dict[str, Any]] = None
) -> Job: ...
async def optimize(
self,
*,
+37
View File
@@ -0,0 +1,37 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Results of durable remote compaction jobs."""
from dataclasses import dataclass, fields
import json
from typing import Optional
@dataclass(frozen=True)
class CompactionResult:
"""Actual committed outcome of one remote compaction invocation.
``rows_failed`` counts planned live rows that were not committed, including
partial progress. ``more_work`` means a bounded run left eligible work for
another invocation. File/fragment counts are None if an older worker did
not report them; they are never inferred from unrelated table versions.
File counts include deletion files as well as data files.
"""
partial_commit: bool
rows_succeeded: int
rows_failed: int
completion_percentage: float
more_work: bool = False
files_added: Optional[int] = None
files_removed: Optional[int] = None
fragments_added: Optional[int] = None
fragments_removed: Optional[int] = None
@classmethod
def from_json(cls, raw: str) -> "CompactionResult":
"""Decode a server result, ignoring additive fields from newer servers."""
value = json.loads(raw)
names = {field.name for field in fields(cls)}
return cls(**{key: item for key, item in value.items() if key in names})
+24 -1
View File
@@ -21,6 +21,8 @@ from lancedb.background_loop import LOOP
from . import _lancedb
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
from .functions import RefreshColumnResult
from .compaction import CompactionResult
from .prewarm import PrewarmDataResult
from .remote.errors import HttpError, RetryError
T = TypeVar("T")
@@ -148,6 +150,19 @@ def _job_progress_callback(progress, enrich):
planned = snapshot.get("rows_planned")
remaining = snapshot.get("rows_remaining")
computed = snapshot.get("rows_computed")
job_type = snapshot.get("job_type")
maintenance = job_type in ("compact", "prewarm_page_cache")
if job_type == "compact":
computed = snapshot.get("rows_rewritten")
remaining = None
if hasattr(progress, "unit"):
progress.unit = " rows"
elif job_type == "prewarm_page_cache":
planned = snapshot.get("executors_targeted")
computed = snapshot.get("executors_completed")
remaining = None
if hasattr(progress, "unit"):
progress.unit = " executors"
if isinstance(planned, int):
epoch = snapshot.get("execution_epoch")
reset = (isinstance(last_planned, int) and planned < last_planned) or (
@@ -173,7 +188,7 @@ def _job_progress_callback(progress, enrich):
if completed is not None:
if isinstance(planned, int):
completed = min(completed, planned)
if first_snapshot and completed < last_rows:
if (first_snapshot or maintenance) and completed < last_rows:
# The server may have started a new execution while a
# caller-owned bar retained its old position.
last_rows = completed
@@ -287,6 +302,10 @@ class AsyncJob(Generic[T]):
a caller-owned bar with the server's current completed rows and total;
later observations in a stable execution epoch use a high-water mark. A
new execution epoch or smaller plan resets the bar to that plan.
Maintenance jobs display reported rewritten rows or completed executors;
revised maintenance counters replace earlier retry observations. Totals
remain unknown until the server reports them. Rewritten rows describe
execution work, not committed compaction results.
``False`` preserves the original wait behavior.
For SQL-backed Function registration, progress shows the query's
@@ -841,4 +860,8 @@ def _typed_job(
def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
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":
return _typed_job(inner, PrewarmDataResult.from_json)
if inner.job_type == "compact":
return _typed_job(inner, CompactionResult.from_json)
return AsyncJob(inner)
+32
View File
@@ -0,0 +1,32 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Results of remote data-cache prewarm jobs."""
from dataclasses import dataclass, fields
import json
from typing import Optional
@dataclass(frozen=True)
class PrewarmDataResult:
"""Reported executor work for a pinned snapshot, not guaranteed cache residency.
Counts omitted by older workers remain None. I/O counts are unknown when
executors do not report them. Partial completions are a subset of completed
executors and may reflect cache pressure.
"""
table_version: int
executors_targeted: Optional[int] = None
executors_completed: Optional[int] = None
executors_partial: Optional[int] = None
fragments_selected: Optional[int] = None
ranges_completed: Optional[int] = None
bytes_read: Optional[int] = None
@classmethod
def from_json(cls, raw: str) -> "PrewarmDataResult":
value = json.loads(raw)
names = {field.name for field in fields(cls)}
return cls(**{key: item for key, item in value.items() if key in names})
+45 -3
View File
@@ -48,6 +48,7 @@ from lancedb.index import (
Bitmap,
LabelList,
)
from lancedb.prewarm import PrewarmDataResult
from lancedb.job import Job
from lancedb.functions import (
FunctionProvenance,
@@ -78,6 +79,7 @@ from ..table import (
BlobMode,
Branches,
CompactionOptions,
CompactionResult,
IndexStatistics,
Query,
Table,
@@ -1105,6 +1107,13 @@ class RemoteTable(Table):
)
pass
def compact_async(
self, *, compaction_options: Optional[CompactionOptions] = None
) -> Job[CompactionResult]:
return Job(
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
)
def optimize(
self,
*,
@@ -1433,7 +1442,13 @@ class RemoteTable(Table):
"""
return LOOP.run(self._table.prewarm_index(name))
def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
def prewarm_data(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> None:
"""Prewarm data for the table.
This is a hint to the database that the given columns will be accessed
@@ -1441,7 +1456,8 @@ class RemoteTable(Table):
Currently only supported in LanceDB Enterprise.
This call initiates prewarming and returns once the request is accepted.
It is idempotent and safe to call from multiple clients concurrently.
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
durable warming job, use ``prewarm_data_async()``.
This operation has a large upfront cost but can speed up future queries
that need to fetch the given columns. Large columns such as embeddings
@@ -1452,8 +1468,34 @@ class RemoteTable(Table):
----------
columns: list of str, optional
The columns to prewarm. If None, all columns are prewarmed.
filter: str, optional
A single SQL predicate for conservative metadata pruning.
concurrency: int, optional
Positive per-executor warming concurrency; omitted uses the server default.
Examples
--------
>>> table.prewarm_data( # doctest: +SKIP
... ["payload"], filter="quality > 0.7", concurrency=4)
"""
return LOOP.run(self._table.prewarm_data(columns))
return LOOP.run(
self._table.prewarm_data(columns, filter=filter, concurrency=concurrency)
)
def prewarm_data_async(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> Job[PrewarmDataResult]:
return Job(
LOOP.run(
self._table.prewarm_data_async(
columns, filter=filter, concurrency=concurrency
)
)
)
def wait_for_index(
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
+193 -6
View File
@@ -48,7 +48,9 @@ from ._blob import (
from .types import BlobMode
from lancedb.arrow import peek_reader
from lancedb.background_loop import LOOP, embedding_executor
from lancedb.prewarm import PrewarmDataResult
from lancedb.job import AsyncJob, Job, _typed_job
from lancedb.compaction import CompactionResult
from .dependencies import (
_check_for_hugging_face,
_check_for_lance,
@@ -2011,6 +2013,69 @@ class Table(ABC):
"""
raise NotImplementedError("create_index is not supported for this table type")
def prewarm_data(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> None:
"""Submit remote data prewarm and return after acceptance.
Omitted or empty ``columns`` warm all fields. ``filter`` is a single
SQL predicate for conservative metadata pruning; ``concurrency`` is
a positive per-executor integer, or omitted for the server default.
The table handle supplies the namespace and branch. Requires a
compatible SQL PREWARM server and Flight SQL connectivity.
The operation continues in the background. Use
[prewarm_data_async][lancedb.table.Table.prewarm_data_async] to retain
the job handle and wait for completion.
Examples
--------
>>> table.prewarm_data( # doctest: +SKIP
... ["payload"], filter="quality > 0.7", concurrency=4)
"""
self.prewarm_data_async(columns, filter=filter, concurrency=concurrency)
def prewarm_data_async(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> Job[PrewarmDataResult]:
"""Submit a remote data-cache prewarm and return its durable job.
Requires a compatible SQL PREWARM server and Flight SQL connectivity.
The table handle supplies the branch and namespace. ``columns`` uses
Lance field paths; an omitted/empty list warms all columns. ``filter``
is one SQL predicate for conservative metadata pruning, not a row scan.
``concurrency`` is a positive per-executor integer. Historical-version
handles are unsupported; call ``checkout_latest()`` first.
Submission requires table Select and database/namespace Usage under
Standard authorization. Status/wait use the generic HTTP job API;
events and cancellation have their own privileges. Unsupported servers
are not retried through REST or with settings removed.
Returns once accepted. ``job.wait()`` waits for warming to finish and
returns [PrewarmDataResult][lancedb.prewarm.PrewarmDataResult].
Save ``job.id`` to resume with ``db.open_job(id)``. A wait timeout does
not cancel the operation. After ``job.refresh()``,
``job.spec["table_version"]`` identifies the pinned source version.
Examples
--------
>>> job = table.prewarm_data_async( # doctest: +SKIP
... ["video"], filter="quality > 0.7", concurrency=4)
>>> job.wait() # doctest: +SKIP
"""
raise NotImplementedError(
"data prewarm jobs are only supported on remote tables"
)
def create_index_async(
self,
column: str,
@@ -3024,6 +3089,33 @@ class Table(ABC):
compaction for you automatically.
"""
def compact_async(
self, *, compaction_options: Optional[CompactionOptions] = None
) -> Job[CompactionResult]:
"""Submit remote compaction and return a durable job after acceptance.
Uses SQL OPTIMIZE with the table handle's branch and namespace. Supports
the four per-job settings in
[CompactionOptions][lancedb.table.CompactionOptions].
Requires a compatible remote server, table Ownership and parent Usage.
Local and historical-version handles are unsupported. Existing
``optimize()`` retains its return-on-submission behavior remotely.
``job.wait()`` waits for the actual rewrite and returns
[CompactionResult][lancedb.compaction.CompactionResult]. Partial/bounded
runs report uncommitted rows and ``more_work``; unknown file statistics
are None. Servers without a result payload raise an error rather than
returning fabricated zero statistics. Wait timeouts do not cancel work.
Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and
cancellation use generic HTTP job APIs and their existing permissions.
>>> job = table.compact_async( # doctest: +SKIP
... compaction_options={"target_rows_per_fragment": 1000})
>>> result = job.wait() # doctest: +SKIP
>>> print(result.rows_succeeded) # doctest: +SKIP
"""
raise NotImplementedError("compaction jobs are only supported on remote tables")
@abstractmethod
def optimize(
self,
@@ -4843,7 +4935,13 @@ class LanceTable(Table):
"""
return LOOP.run(self._table.prewarm_index(name))
def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
def prewarm_data(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> None:
"""
Prewarm data for the table.
@@ -4852,7 +4950,8 @@ class LanceTable(Table):
Currently only supported in LanceDB Enterprise.
This call initiates prewarming and returns once the request is accepted.
It is idempotent and safe to call from multiple clients concurrently.
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
durable warming job, use ``prewarm_data_async()``.
This operation has a large upfront cost but can speed up future queries
that need to fetch the given columns. Large columns such as embeddings
@@ -4863,8 +4962,34 @@ class LanceTable(Table):
----------
columns: list of str, optional
The columns to prewarm. If None, all columns are prewarmed.
filter: str, optional
A single SQL predicate for conservative metadata pruning.
concurrency: int, optional
Positive per-executor warming concurrency; omitted uses the server default.
Examples
--------
>>> table.prewarm_data( # doctest: +SKIP
... ["payload"], filter="quality > 0.7", concurrency=4)
"""
return LOOP.run(self._table.prewarm_data(columns))
return LOOP.run(
self._table.prewarm_data(columns, filter=filter, concurrency=concurrency)
)
def prewarm_data_async(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> Job[PrewarmDataResult]:
return Job(
LOOP.run(
self._table.prewarm_data_async(
columns, filter=filter, concurrency=concurrency
)
)
)
def wait_for_index(
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
@@ -5683,6 +5808,13 @@ class LanceTable(Table):
self.checkout_latest()
return stats
def compact_async(
self, *, compaction_options: Optional[CompactionOptions] = None
) -> Job[CompactionResult]:
return Job(
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
)
def optimize(
self,
*,
@@ -7324,7 +7456,13 @@ class AsyncTable:
"""
await self._inner.prewarm_index(name)
async def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
async def prewarm_data(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> None:
"""
Prewarm data for the table.
@@ -7333,7 +7471,8 @@ class AsyncTable:
Currently only supported in LanceDB Enterprise.
This call initiates prewarming and returns once the request is accepted.
It is idempotent and safe to call from multiple clients concurrently.
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
durable warming job, use ``prewarm_data_async()``.
This operation has a large upfront cost but can speed up future queries
that need to fetch the given columns. Large columns such as embeddings
@@ -7344,8 +7483,43 @@ class AsyncTable:
----------
columns: list of str, optional
The columns to prewarm. If None, all columns are prewarmed.
filter: str, optional
A single SQL predicate for conservative metadata pruning.
concurrency: int, optional
Positive per-executor warming concurrency; omitted uses the server default.
Examples
--------
>>> await table.prewarm_data( # doctest: +SKIP
... ["payload"], filter="quality > 0.7", concurrency=4)
"""
await self._inner.prewarm_data(columns)
await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency)
async def prewarm_data_async(
self,
columns: Optional[List[str]] = None,
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
) -> AsyncJob[PrewarmDataResult]:
"""Submit data prewarm and return a durable handle after acceptance.
See [Table.prewarm_data_async][lancedb.table.Table.prewarm_data_async]
for options, permissions, and compatibility. Awaiting this method does
not wait for warming; use ``await job.wait()`` for completion.
Examples
--------
>>> job = await table.prewarm_data_async( # doctest: +SKIP
... ["video"], filter="quality > 0.7", concurrency=4)
>>> await job.wait() # doctest: +SKIP
"""
return _typed_job(
await self._inner.prewarm_data_async(
columns, filter=filter, concurrency=concurrency
),
PrewarmDataResult.from_json,
)
async def wait_for_index(
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
@@ -9273,6 +9447,19 @@ class AsyncTable:
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
return self._inner.current_branch()
async def compact_async(
self, *, compaction_options: Optional[CompactionOptions] = None
) -> AsyncJob[CompactionResult]:
"""Submit remote compaction; await the returned job for actual results.
See [Table.compact_async][lancedb.table.Table.compact_async] for options,
permissions, completion semantics and compatibility requirements.
"""
return _typed_job(
await self._inner.compact_async(compaction_options),
CompactionResult.from_json,
)
async def optimize(
self,
*,
+128
View File
@@ -11,11 +11,139 @@ import numpy as np
import pyarrow as pa
import pytest
from lancedb import LanceDBConnection, function
from lancedb.compaction import CompactionResult
from lancedb.index import FTS
from lancedb.prewarm import PrewarmDataResult
# TODO: setup integ test mark and script
@pytest.fixture
def maintenance_connection_options():
uri = os.environ.get("LANCEDB_URI")
if not uri:
pytest.skip(
"Set LANCEDB_URI to a server supporting SQL maintenance job results"
)
assert uri.startswith("db://")
return {
"uri": uri,
"api_key": os.environ.get("LANCEDB_API_KEY"),
"region": os.environ.get("LANCEDB_REGION", "us-east-1"),
"host_override": os.environ.get("LANCEDB_HOST_OVERRIDE"),
"sql_host_override": os.environ.get("LANCEDB_SQL_HOST_OVERRIDE"),
}
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
@pytest.mark.parametrize("operation", ["compact", "prewarm", "prewarm_legacy"])
async def test_maintenance_job_result_and_reopen_against_server(
maintenance_connection_options, asynchronous, operation
):
"""Exercise real SQL receipts, workers and HTTP job results with matching versions.
Configure LANCEDB_URI, LANCEDB_API_KEY and the REST/Flight SQL endpoint
overrides for a writable database. Workers must publish maintenance results;
an unsupported server fails the contract rather than silently skipping it.
"""
if asynchronous:
connection = await lancedb.connect_async(**maintenance_connection_options)
else:
connection = lancedb.connect(**maintenance_connection_options)
async def call(method, *args, **kwargs):
result = method(*args, **kwargs)
return await result if asynchronous else result
name = f"maintenance_{uuid4().hex}"
created = False
expected = [{"id": i, "payload": i * 10} for i in range(16)]
timeout = timedelta(minutes=5)
try:
table = await call(
connection.create_table, name, pa.Table.from_pylist(expected[:4])
)
created = True
for start in (4, 8, 12):
await call(table.add, pa.Table.from_pylist(expected[start : start + 4]))
version = await table.version() if asynchronous else table.version
if operation == "compact":
job = await call(
table.compact_async,
compaction_options={
"target_rows_per_fragment": 100,
"batch_size": 128,
"io_buffer_size": 0,
},
)
elif operation == "prewarm_legacy":
assert (
await call(
table.prewarm_data,
["payload"],
filter="id >= 8",
concurrency=2,
)
is None
)
reader = await call(
connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"'
)
batches = await call(reader.read_all)
jobs = pa.Table.from_batches(batches) if asynchronous else batches
ids = [
row["job_id"]
for row in jobs.to_pylist()
if row["job_type"] == "prewarm_page_cache"
]
assert len(ids) == 1, jobs.to_pylist()
job = await call(connection.open_job, ids[0])
else:
job = await call(
table.prewarm_data_async,
["payload"],
filter="id >= 8",
concurrency=2,
)
assert job.id
progress = []
result = await call(job.wait, timeout=timeout, progress=progress.append)
assert any(snapshot["state"] == "finished" for snapshot in progress)
await call(job.refresh)
assert await call(job.status) == "finished"
if operation == "compact":
assert isinstance(result, CompactionResult)
assert job.job_type == "compact"
assert not result.partial_commit and result.rows_failed == 0
assert result.completion_percentage == 100
assert 0 <= result.rows_succeeded <= len(expected)
assert result.files_added is not None and result.files_removed is not None
else:
assert isinstance(result, PrewarmDataResult)
assert job.job_type == "prewarm_page_cache"
assert result.table_version == version == job.spec["table_version"]
assert job.spec["columns"] == ["payload"]
assert job.spec["concurrency"] == 2
assert result.fragments_selected > 0
assert result.executors_completed == result.executors_targeted
assert result.executors_partial == 0
assert result.bytes_read is None and result.ranges_completed is None
reopened = await call(connection.open_job, job.id)
assert await call(reopened.wait, timeout=timeout) == result
query = table.query() if asynchronous else table.search()
actual = await call(
query.select(["id", "payload"]).limit(len(expected) + 1).to_arrow
)
assert sorted(actual.to_pylist(), key=lambda row: row["id"]) == expected
finally:
try:
if created:
await call(connection.drop_table, name)
finally:
connection.close()
@pytest.mark.skipif(
not os.environ.get("LANCEDB_URI"), reason="Set LANCEDB_URI to a JSON FTS server"
)
+92
View File
@@ -1072,3 +1072,95 @@ async def test_stack_propagates_errors_and_rejects_local_handles(sync):
Job(None).stack("worker")
else:
await AsyncJob(None).stack("worker")
@pytest.mark.asyncio
@pytest.mark.parametrize(
"kind,planned_key,completed_key,unit",
[
("compact", "rows_planned", "rows_rewritten", " rows"),
(
"prewarm_page_cache",
"executors_targeted",
"executors_completed",
" executors",
),
],
)
async def test_maintenance_progress_bar_uses_operation_counters_and_handles_retry(
monkeypatch, kind, planned_key, completed_key, unit
):
tqdm_module = pytest.importorskip("tqdm.auto")
class Bar:
total = None
n = 0
unit = " rows"
closed = False
def update(self, delta):
self.n += delta
def close(self):
self.closed = True
bar = Bar()
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
class MaintenanceJob:
id = "maintenance-job"
job_type = kind
async def wait(self, progress):
progress({"job_type": kind, "phase": "planning"})
assert bar.total is None
progress({"job_type": kind, planned_key: 4, completed_key: 2})
assert bar.n == 2
# Older responses can omit an epoch; revised observations still
# replace the previous attempt's displayed work.
progress({"job_type": kind, planned_key: 4, completed_key: 1})
assert bar.n == 1
progress({"job_type": kind, planned_key: 4, completed_key: 4})
assert await AsyncJob(MaintenanceJob()).wait(progress=True) is None
assert bar.n == 4
assert bar.total == 4
assert bar.unit == unit
assert bar.closed
@pytest.mark.asyncio
@pytest.mark.parametrize("known_empty", [False, True])
async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals(
monkeypatch, known_empty
):
tqdm_module = pytest.importorskip("tqdm.auto")
class Bar:
total = None
n = 0
unit = " rows"
def update(self, delta):
self.n += delta
def close(self):
pass
bar = Bar()
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
class PrewarmJob:
id = "prewarm-job"
job_type = "prewarm_page_cache"
async def wait(self, progress):
snapshot = {"job_type": self.job_type, "phase": "succeeded"}
if known_empty:
snapshot.update(executors_targeted=0, executors_completed=0)
progress(snapshot)
assert await AsyncJob(PrewarmJob()).wait(progress=True) is None
assert bar.n == 0
assert bar.total == (0 if known_empty else None)
assert bar.unit == " executors"
+372 -2
View File
@@ -7408,10 +7408,10 @@ def _create_table_handler(request):
@contextlib.contextmanager
def _mock_remote_sql_connection(flight_server):
def _mock_remote_sql_connection(flight_server, handler=_create_table_handler):
"""Connection arguments for mock REST and Flight SQL servers."""
with http.server.ThreadingHTTPServer(
("127.0.0.1", 0), make_mock_http_handler(_create_table_handler)
("127.0.0.1", 0), make_mock_http_handler(handler)
) as rest_server:
rest_port = rest_server.server_address[1]
handle = start_server_thread(rest_server)
@@ -8054,3 +8054,373 @@ def test_exact_function_retries_fail_before_writing_to_older_servers():
with pytest.raises(NotImplementedError, match="server does not support"):
table.function_errors().summary()
assert writes == []
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("mode", ["job", "columns", "filtered", "defaults"])
async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mode):
flight = pytest.importorskip("pyarrow.flight")
polls = []
class PrewarmServer(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": ["warming-job"],
"table_version": pa.array([42], pa.uint64()),
}
)
)
def handler(request):
if request.path == "/v1/jobs/describe":
body = json.loads(
request.rfile.read(int(request.headers["Content-Length"]))
)
assert body == {"job_id": "warming-job"}
polls.append(body)
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(
json.dumps(
{
"job_id": "warming-job",
"job_type": "prewarm_page_cache",
"job_state": "DONE",
"creation_ms": 1,
"spec": {"table_version": 42},
"result": {
"table_version": 42,
"executors_targeted": 2,
"executors_completed": 2,
"fragments_selected": 4,
},
"operation_progress": {
"phase": "reading",
"executors_completed": 2,
"fragments_selected": 4,
},
}
).encode()
)
else:
# No operation-specific REST prewarm endpoint is accepted.
_create_table_handler(request)
server = PrewarmServer()
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}])
if mode == "columns":
assert await table.prewarm_data(["payload"]) is None
elif mode == "filtered":
assert (
await table.prewarm_data(
columns=["attrs.score"], filter="id >= 8", concurrency=4
)
is None
)
elif mode == "defaults":
assert await table.prewarm_data() is None
else:
job = await table.prewarm_data_async(
["attrs.score"], filter="id >= 8", concurrency=4
)
assert job.id == "warming-job"
assert not polls
assert (await job.wait()).table_version == 42
await job.refresh()
assert job.spec["table_version"] == 42
reopened = await db.open_job(job.id)
assert (await reopened.wait()).executors_completed == 2
assert (await job.progress())["executors_completed"] == 2
assert (await job.wait()).bytes_read is None
else:
db = lancedb.connect(**kwargs)
table = db.create_table("test", [{"id": 1}])
if mode == "columns":
assert table.prewarm_data(["payload"]) is None
elif mode == "filtered":
assert (
table.prewarm_data(
columns=["attrs.score"], filter="id >= 8", concurrency=4
)
is None
)
elif mode == "defaults":
assert table.prewarm_data() is None
else:
job = table.prewarm_data_async(
["attrs.score"], filter="id >= 8", concurrency=4
)
assert job.id == "warming-job"
assert not polls
assert job.wait().table_version == 42
job.refresh()
assert job.spec["table_version"] == 42
assert db.open_job(job.id).wait().executors_completed == 2
assert job.progress()["executors_completed"] == 2
assert job.wait().bytes_read is None
assert len(server.tickets) == 1
assert b"PREWARM" in server.tickets[0]
if mode != "job":
assert not polls
if mode == "columns":
assert b'"payload"' in server.tickets[0]
elif mode == "defaults":
assert b"SELECT *" in server.tickets[0]
else:
assert b'"attrs"."score"' in server.tickets[0]
assert b"concurrency = 4" in server.tickets[0]
assert b"id >= 8" in server.tickets[0]
@pytest.mark.parametrize(
"options",
[
{"filter": ""},
{"filter": "id > 0; DROP TABLE test"},
{"filter": "id > 0 LIMIT 1"},
{"concurrency": 0},
{"concurrency": -1},
{"concurrency": 2**32},
{"concurrency": True},
{"concurrency": 1.5},
],
)
@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"])
def test_remote_data_prewarm_validates_before_submission(options, method):
flight = pytest.importorskip("pyarrow.flight")
class UnusedServer(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)
raise AssertionError("invalid options must not submit SQL")
server = UnusedServer()
with _mock_remote_table_with_sql(server) as table:
with pytest.raises(ValueError):
getattr(table, method)(**options)
assert not server.tickets
def test_remote_data_prewarm_malformed_receipt_is_not_retried():
flight = pytest.importorskip("pyarrow.flight")
class MalformedServer(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": ["warming-job"]}))
server = MalformedServer()
with _mock_remote_table_with_sql(server) as table:
with pytest.raises(Exception, match="inspect jobs before retrying"):
table.prewarm_data_async()
assert len(server.tickets) == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"outcome",
[
"counts",
"legacy",
"partial",
"bounded",
"no_op",
"missing",
"FAILED",
"CANCELLED",
],
)
async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
flight = pytest.importorskip("pyarrow.flight")
polls = []
result = {
"partial_commit": False,
"rows_succeeded": 12,
"rows_failed": 0,
"completion_percentage": 100.0,
}
if outcome == "counts":
result.update(
files_added=1, files_removed=3, fragments_added=1, fragments_removed=3
)
if outcome == "partial":
result.update(
partial_commit=True,
rows_succeeded=8,
rows_failed=4,
completion_percentage=100 * 8 / 12,
)
if outcome == "bounded":
result.update(more_work=True)
if outcome == "no_op":
result.update(
rows_succeeded=0,
files_added=0,
files_removed=0,
fragments_added=0,
fragments_removed=0,
)
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": ["compacting-job"]}))
def handler(request):
if request.path != "/v1/jobs/describe":
return _create_table_handler(request)
body = json.loads(request.rfile.read(int(request.headers["Content-Length"])))
assert body == {"job_id": "compacting-job"}
polls.append(body)
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(
json.dumps(
{
"job_id": "compacting-job",
"job_type": "compact",
"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.compact_async(
compaction_options={"target_rows_per_fragment": 100}
)
assert job.id == "compacting-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],
):
await job.wait()
else:
stats = await job.wait()
reopened = await db.open_job(job.id)
assert await reopened.wait() == stats
else:
db = lancedb.connect(**kwargs)
table = db.create_table("test", [{"id": 1}])
job = table.compact_async(
compaction_options={"target_rows_per_fragment": 100}
)
assert job.id == "compacting-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],
):
job.wait()
else:
stats = job.wait()
assert db.open_job(job.id).wait() == stats
if outcome in ("counts", "legacy", "partial", "bounded", "no_op"):
from lancedb.compaction import CompactionResult
assert isinstance(stats, CompactionResult)
assert stats.rows_succeeded == (
0 if outcome == "no_op" else 8 if outcome == "partial" else 12
)
assert stats.rows_failed == (4 if outcome == "partial" else 0)
assert stats.partial_commit == (outcome == "partial")
assert stats.more_work == (outcome == "bounded")
assert stats.fragments_removed == (
3 if outcome == "counts" else 0 if outcome == "no_op" else None
)
assert len(server.tickets) == 1
assert b"OPTIMIZE" in server.tickets[0]
assert b"target_rows_per_fragment = 100" in server.tickets[0]
@pytest.mark.parametrize("ids", [[], [None], [""], ["a", "b"]])
def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids):
flight = pytest.importorskip("pyarrow.flight")
class Server(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.calls = 0
def do_get(self, context, ticket):
self.calls += 1
return flight.RecordBatchStream(
pa.table({"job_id": pa.array(ids, pa.string())})
)
server = Server()
with _mock_remote_sql_connection(server) as kwargs:
db = lancedb.connect(**kwargs)
table = db.create_table("test", [{"id": 1}])
with pytest.raises(Exception, match="inspect jobs before retrying"):
table.compact_async()
assert server.calls == 1
@pytest.mark.parametrize("method", ["compact_async", "optimize"])
@pytest.mark.parametrize(
"option",
["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"],
)
@pytest.mark.parametrize("value", [False, True])
def test_remote_compaction_rejects_boolean_budgets_without_submitting(
method, option, value
):
flight = pytest.importorskip("pyarrow.flight")
class UnusedServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.calls = 0
def do_get(self, context, ticket):
self.calls += 1
raise AssertionError("boolean compaction settings must not submit SQL")
server = UnusedServer()
with _mock_remote_table_with_sql(server) as table:
with pytest.raises(ValueError, match="must be an integer, not a bool"):
getattr(table, method)(compaction_options={option: value})
assert server.calls == 0
+19
View File
@@ -6414,3 +6414,22 @@ def test_fts_exist_ok_matches_quoted_default_name(mem_db):
table.create_index("`body-text`", config=FTS(), exist_ok=True)
assert table.version == before
assert len(table.list_indices()) == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"])
async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method):
if asynchronous:
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("prewarm", [{"id": 1}])
with pytest.raises(
NotImplementedError, match="only supported on remote tables"
):
await getattr(table, method)(filter="id > 0", concurrency=2)
else:
table = lancedb.connect(tmp_path).create_table("prewarm", [{"id": 1}])
with pytest.raises(
NotImplementedError, match="only supported on remote tables"
):
getattr(table, method)(filter="id > 0", concurrency=2)
+8
View File
@@ -902,6 +902,14 @@ impl Connection {
job.into_typed::<RefreshColumnResult>().infer_error()?,
))
}
Some("prewarm_page_cache") => Ok(crate::job::Job::new_typed(
job.into_typed::<lancedb::table::PrewarmDataResult>()
.infer_error()?,
)),
Some("compact") => Ok(crate::job::Job::new_typed(
job.into_typed::<lancedb::table::CompactionResult>()
.infer_error()?,
)),
_ => Ok(crate::job::Job::new(job)),
}
})
+51
View File
@@ -495,6 +495,16 @@ fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<Com
for (key, value) in options.iter() {
let key: String = key.extract()?;
// Python bool is an int subclass: never turn True into a one-row budget.
if matches!(
key.as_str(),
"target_rows_per_fragment" | "max_source_rows" | "io_buffer_size" | "batch_size"
) && value.is_instance_of::<PyBool>()
{
return Err(PyValueError::new_err(format!(
"{key} must be an integer, not a bool"
)));
}
match key.as_str() {
"target_rows_per_fragment" => {
parsed.target_rows_per_fragment = positive_u32(&value, &key)?
@@ -1885,6 +1895,24 @@ impl Table {
})
}
#[pyo3(signature = (columns=None, *, filter=None, concurrency=None))]
pub fn prewarm_data_async<'py>(
self_: PyRef<'py, Self>,
columns: Option<Vec<String>>,
filter: Option<String>,
concurrency: Option<&Bound<'py, PyAny>>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self_.inner_ref()?.clone();
let mut options =
lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default());
options.filter = filter;
options.concurrency = positive_u32_integer(concurrency, "concurrency")?;
future_into_py(self_.py(), async move {
let job = inner.prewarm_data_async(options).await.infer_error()?;
Ok(crate::job::Job::new_typed(job))
})
}
pub fn list_indices(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
@@ -2245,6 +2273,29 @@ impl Table {
})
}
/// Submit remote compaction and retain its durable job and actual result.
#[pyo3(signature = (compaction_options=None))]
pub fn compact_async<'py>(
self_: PyRef<'py, Self>,
compaction_options: Option<&Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self_.inner_ref()?.clone();
let target_specified = compaction_options
.map(|options| options.contains("target_rows_per_fragment"))
.transpose()?
.unwrap_or(false);
let options = parse_compaction_options(compaction_options)?;
let mut overrides =
lancedb::table::optimize::CompactionOverrides::try_from(options).infer_error()?;
if !target_specified {
overrides.target_rows_per_fragment = None;
}
future_into_py(self_.py(), async move {
let job = inner.compact_async(overrides).await.infer_error()?;
Ok(crate::job::Job::new_typed(job))
})
}
/// Optimize the on-disk data by compacting and pruning old data, for better performance.
#[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))]
pub fn optimize<'py>(
+179 -2
View File
@@ -6,6 +6,7 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::time::Duration;
use arrow_array::RecordBatch;
use async_trait::async_trait;
@@ -24,6 +25,48 @@ use crate::error::{Error, JobFailure, Result};
/// retry loop just to render progress.
pub type JobProgressCallback = Arc<Mutex<dyn FnMut(&JobDescription) + Send>>;
/// Client-side controls for waiting on a job. A timeout stops this wait without
/// cancelling the operation; keep the handle to wait again.
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct JobWaitOptions {
/// Maximum time to wait, including HTTP requests and polling backoff.
/// `None` waits indefinitely. Zero only permits an immediately ready result.
pub timeout: Option<Duration>,
progress: Option<JobProgressCallback>,
}
impl std::fmt::Debug for JobWaitOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JobWaitOptions")
.field("timeout", &self.timeout)
.field("progress", &self.progress.is_some())
.finish()
}
}
impl JobWaitOptions {
/// Wait indefinitely without a progress callback.
pub fn new() -> Self {
Self::default()
}
/// Bound this wait without cancelling the underlying job.
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
/// Observe the backend's existing poller. The callback should return promptly.
pub fn progress<F>(mut self, progress: F) -> Self
where
F: FnMut(&JobDescription) + Send + 'static,
{
self.progress = Some(Arc::new(Mutex::new(progress)));
self
}
}
/// Which of a job's events [`Job::events`] returns.
///
/// The handle already knows which job to ask about, so this narrows the
@@ -598,7 +641,7 @@ where
/// Returns [`crate::Error::JobFailed`] if the operation failed and
/// [`crate::Error::JobCancelled`] if it was cancelled.
pub async fn wait(&self) -> Result<T> {
self.wait_with_progress_opt(None).await
self.wait_with_options(JobWaitOptions::default()).await
}
/// Wait for the operation while observing progress from the backend's
@@ -609,10 +652,58 @@ where
where
F: FnMut(&JobDescription) + Send + 'static,
{
self.wait_with_progress_opt(Some(Arc::new(Mutex::new(progress))))
self.wait_with_options(JobWaitOptions::new().progress(progress))
.await
}
/// Wait with a client-side deadline and an optional progress callback.
///
/// Returns [`Error::Timeout`] when the deadline expires, including while a
/// status request or polling backoff is pending. This drops the wait future;
/// it does not cancel the operation or mark it failed. The same handle can
/// wait again. Registry jobs can also be reopened by ID; query IDs remain
/// connection-scoped and cannot be reopened as registry jobs.
///
/// ```no_run
/// # async fn example(job: &lancedb::Job) -> lancedb::Result<()> {
/// use std::time::Duration;
/// use lancedb::job::JobWaitOptions;
/// job.wait_with_options(JobWaitOptions::new()
/// .timeout(Duration::from_secs(60))
/// .progress(|description| println!("{}", description.state)))
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn wait_with_options(&self, options: JobWaitOptions) -> Result<T> {
let Some(timeout) = options.timeout else {
return self.wait_with_progress_opt(options.progress).await;
};
let deadline = tokio::time::Instant::now()
.checked_add(timeout)
.ok_or_else(|| Error::InvalidInput {
message: "job wait timeout is too large".to_string(),
})?;
tokio::time::timeout_at(deadline, self.wait_with_progress_opt(options.progress))
.await
.map_err(|_| {
let operation = self
.id()
.map(|id| format!("job {id:?}"))
.unwrap_or_else(|| "operation".to_string());
let resume = if self.id().is_some() && self.job_type().as_deref() != Some("query") {
"continue waiting on this handle or reattach with Connection::open_job"
} else {
"keep this handle to continue waiting"
};
Error::Timeout {
message: format!(
"{operation} still running after {timeout:?}; the operation continues; {resume}"
),
}
})?
}
async fn wait_with_progress_opt(&self, progress: Option<JobProgressCallback>) -> Result<T> {
match &self.inner {
JobInner::Handle { handle, decode } => {
@@ -838,6 +929,92 @@ mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn wait_timeout_preserves_local_task_and_typed_result() {
let job = Job::spawned(tokio::spawn(async {
tokio::time::sleep(Duration::from_secs(1)).await;
Ok(41_u64)
}))
.map(|value| value + 1);
let error = job
.wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(10)))
.await
.unwrap_err();
assert!(matches!(error, Error::Timeout { .. }));
assert!(error.to_string().contains("keep this handle"));
assert!(!error.to_string().contains("Connection::open_job"));
assert_eq!(job.state(), None);
assert_eq!(job.status().await.unwrap(), "running");
assert_eq!(
job.wait_with_options(JobWaitOptions::new()).await.unwrap(),
42
);
}
#[tokio::test(start_paused = true)]
async fn wait_timeout_keeps_query_handle_without_requesting_cancellation() {
use std::sync::atomic::{AtomicUsize, Ordering};
let cancellations = Arc::new(AtomicUsize::new(0));
let observed = cancellations.clone();
let id = Uuid::new_v4();
let job = Job::from_query_task(
id,
tokio::spawn(async {
tokio::time::sleep(Duration::from_secs(1)).await;
Ok(42_u64)
}),
move || {
observed.fetch_add(1, Ordering::SeqCst);
async { Ok(()) }
},
);
let error = job
.wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(10)))
.await
.unwrap_err();
assert!(matches!(error, Error::Timeout { .. }));
assert!(error.to_string().contains(&id.to_string()));
assert!(!error.to_string().contains("Connection::open_job"));
assert_eq!(cancellations.load(Ordering::SeqCst), 0);
assert_eq!(job.wait().await.unwrap(), 42);
}
#[tokio::test]
async fn wait_options_handle_zero_and_unrepresentable_deadlines() {
let job = Job::new_done();
job.wait_with_options(JobWaitOptions::new().timeout(Duration::ZERO))
.await
.unwrap();
assert!(matches!(
job.wait_with_options(JobWaitOptions::new().timeout(Duration::MAX))
.await,
Err(Error::InvalidInput { .. })
));
}
#[tokio::test]
async fn wait_options_preserve_operation_errors() {
let failed = Job::<u64>::spawned(tokio::spawn(async {
Err(Error::Runtime {
message: "original failure".into(),
})
}));
let error = failed
.wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1)))
.await
.unwrap_err();
assert!(matches!(error, Error::JobFailed { .. }));
assert!(error.to_string().contains("original failure"));
let cancelled = Job::<u64>::spawned(tokio::spawn(pending()));
cancelled.cancel().await.unwrap();
assert!(matches!(
cancelled
.wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1)))
.await,
Err(Error::JobCancelled { .. })
));
}
#[test]
fn local_typed_result_decode_errors_are_runtime_errors() {
assert!(matches!(
+21 -8
View File
@@ -411,14 +411,6 @@ impl RemoteDatabase {
read_consistency_interval: Option<std::time::Duration>,
parsed: super::client::ParsedDbUrl,
) -> Result<Self> {
let sql_client = SqlClient::new(
parsed.db_name.clone(),
parsed.db_prefix.clone(),
api_key.to_string(),
host_overrides.rest.clone(),
host_overrides.sql,
client_config.clone(),
);
let header_map = RestfulLanceDbClient::<Sender>::default_headers(
api_key,
region,
@@ -429,6 +421,27 @@ impl RemoteDatabase {
&client_config,
)?;
// Preserve the resolved source-account hint when table operations use SQL.
let mut sql_config = client_config.clone();
if let Some(account) = header_map.get("x-azure-storage-account-name") {
sql_config.extra_headers.insert(
"x-azure-storage-account-name".into(),
account
.to_str()
.map_err(|error| Error::InvalidInput {
message: error.to_string(),
})?
.into(),
);
}
let sql_client = SqlClient::new(
parsed.db_name.clone(),
parsed.db_prefix.clone(),
api_key.to_string(),
host_overrides.rest.clone(),
host_overrides.sql,
sql_config,
);
let namespace_headers: HashMap<String, String> = header_map
.iter()
.filter_map(|(k, v)| {
+107 -3
View File
@@ -116,6 +116,8 @@ pub(super) struct DescribeJobResponse {
#[serde(default)]
pub(super) progress: Option<serde_json::Value>,
#[serde(default)]
pub(super) operation_progress: Option<serde_json::Value>,
#[serde(default)]
pub(super) phase: Option<String>,
#[serde(default)]
pub(super) queue_reason: Option<String>,
@@ -160,7 +162,7 @@ impl DescribeJobResponse {
job_type: self.job_type,
state: JobState::from(self.job_state.as_str()).client_label(),
creation_ms: self.creation_ms,
progress: self.progress,
progress: self.operation_progress.or(self.progress),
phase: self.phase,
queue_reason: self.queue_reason,
waiting_for_job_id: self.waiting_for_job_id,
@@ -420,7 +422,7 @@ impl<S: HttpSend> JobHandle for RemoteJob<S> {
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -428,7 +430,7 @@ mod tests {
use crate::Result;
use crate::function::{FunctionVersion, RefreshColumnResult};
use crate::job::{Job, JobHandle, JobProgressCallback, TerminalResult};
use crate::job::{Job, JobHandle, JobProgressCallback, JobWaitOptions, TerminalResult};
use crate::remote::client::test_utils::client_with_handler;
use super::{DescribeJobResponse, RemoteJob};
@@ -441,6 +443,108 @@ mod tests {
include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json");
const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#;
#[tokio::test(start_paused = true)]
async fn timed_wait_stops_polling_and_can_resume_or_reopen_typed_maintenance_jobs() {
for job_type in ["compact", "prewarm_page_cache"] {
let done = Arc::new(AtomicBool::new(false));
let describes = Arc::new(AtomicUsize::new(0));
let complete = done.clone();
let seen = describes.clone();
let expected = if job_type == "compact" {
serde_json::json!({"partial_commit":false,"rows_succeeded":12,"rows_failed":0,"completion_percentage":100})
} else {
serde_json::json!({"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4})
};
let payload = expected.clone();
let client =
client_with_handler(move |request| {
assert_eq!(request.url().path(), "/v1/jobs/describe");
seen.fetch_add(1, Ordering::SeqCst);
let finished = complete.load(Ordering::SeqCst);
http::Response::builder().status(200).body(serde_json::json!({
"job_id":"bounded-job", "job_type":job_type,
"job_state":if finished {"DONE"} else {"IN_PROGRESS"},
"result":if finished {payload.clone()} else {serde_json::Value::Null},
}).to_string()).unwrap()
});
let handle = RemoteJob::new(client.clone(), "bounded-job".into());
let description = handle.describe().await.unwrap();
let job = Job::opened(Box::new(handle), description)
.into_typed::<serde_json::Value>()
.unwrap();
let observations = Arc::new(Mutex::new(Vec::new()));
let updates = observations.clone();
let options = JobWaitOptions::new()
.timeout(Duration::from_millis(50))
.progress(move |description| {
updates.lock().unwrap().push(description.state.clone())
});
// Bound a regression that accidentally ignores the wait deadline.
let eventual_completion = done.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(1)).await;
eventual_completion.store(true, Ordering::SeqCst);
});
let error = job.wait_with_options(options.clone()).await.unwrap_err();
assert!(matches!(error, crate::Error::Timeout { .. }));
assert!(error.to_string().contains("bounded-job"));
assert!(error.to_string().contains("Connection::open_job"));
assert_eq!(job.state().as_deref(), Some("running"));
assert_eq!(describes.load(Ordering::SeqCst), 2);
tokio::time::advance(Duration::from_secs(2)).await;
tokio::task::yield_now().await;
assert_eq!(
describes.load(Ordering::SeqCst),
2,
"timed-out poller must stop"
);
assert_eq!(*observations.lock().unwrap(), ["running"]);
done.store(true, Ordering::SeqCst);
let result = job
.wait_with_options(options.timeout(Duration::from_secs(1)))
.await
.unwrap();
assert_eq!(result, expected);
assert_eq!(*observations.lock().unwrap(), ["running", "finished"]);
let handle = RemoteJob::new(client, "bounded-job".into());
let description = handle.describe().await.unwrap();
let reopened = Job::opened(Box::new(handle), description)
.into_typed::<serde_json::Value>()
.unwrap();
assert_eq!(
reopened
.wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1)))
.await
.unwrap(),
result
);
}
}
#[tokio::test(start_paused = true)]
async fn one_wait_timeout_does_not_interrupt_another_waiter() {
let done = Arc::new(AtomicBool::new(false));
let complete = done.clone();
let client = client_with_handler(move |request| {
assert_eq!(request.url().path(), "/v1/jobs/describe");
http::Response::builder().status(200).body(serde_json::json!({
"job_state":if complete.load(Ordering::SeqCst) {"DONE"} else {"IN_PROGRESS"},
}).to_string()).unwrap()
});
let job = Job::new(Box::new(RemoteJob::new(client, "shared-job".into())));
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(100)).await;
done.store(true, Ordering::SeqCst);
});
let (short, long) = tokio::join!(
job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(50))),
job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))),
);
assert!(matches!(short, Err(crate::Error::Timeout { .. })));
long.unwrap();
assert_eq!(job.state().as_deref(), Some("finished"));
}
#[tokio::test]
async fn stack_preserves_availability_and_uses_the_selected_worker() {
for status in ["captured", "unsupported", "unavailable"] {
+51 -1
View File
@@ -12,7 +12,6 @@ use arrow_array::RecordBatch;
use arrow_flight::decode::FlightRecordBatchStream;
use arrow_flight::error::FlightError;
use arrow_flight::flight_service_client::FlightServiceClient;
#[cfg(test)]
use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt};
use arrow_flight::{
Action, CancelFlightInfoRequest, CancelFlightInfoResult, CancelStatus, FlightClient,
@@ -44,6 +43,8 @@ pub(super) use secret::SecretWriteOperation;
mod stream;
mod view;
const PREWARM_AZURE_HINT_CAPABILITY: &str = "lancedb.prewarm.azure_storage_account_name";
use stream::{StreamingQuery, StreamingQueryHandle, Submission};
const DEFAULT_SQL_PORT: u16 = 10025;
@@ -217,6 +218,55 @@ impl SqlClient {
}
}
/// Unknown headers are otherwise silently ignored by older SQL servers.
/// Probe only when a source-account hint is present, before submitting work.
pub(super) async fn execute_prewarm(&self, request: ExecuteQueryRequest) -> Result<Query> {
with_overall_timeout(
self.inner.overall_timeout()?,
"prewarm submission",
async {
validate_namespace_path(&request.default_namespace_path)?;
let request_id = Uuid::new_v4().to_string();
let headers = self
.inner
.headers(&request.default_namespace_path, &request_id)
.await?;
if headers.contains_key("x-azure-storage-account-name") {
let connection = self.inner.connection(&request_id).await?;
let mut client = client_with_headers(connection.client.clone(), &headers)?;
let command = CommandStatementQuery {
query: request.query.clone(),
transaction_id: None,
};
let descriptor = FlightDescriptor::new_cmd(command.as_any().encode_to_vec());
let read_timeout = resolve_timeout(
self.inner.client_config.timeout_config.read_timeout,
"LANCE_CLIENT_READ_TIMEOUT", Some(DEFAULT_READ_TIMEOUT),
)?.unwrap();
let info = tokio::time::timeout(read_timeout, client.get_flight_info(descriptor))
.await.map_err(|_| Error::Runtime { message: format!("SQL PREWARM capability check timed out (request_id={request_id})") })?
.map_err(|error| sql_flight_error(&request_id, &error))?;
let supported = info.try_decode_schema().ok().is_some_and(|schema| {
schema
.metadata()
.get(PREWARM_AZURE_HINT_CAPABILITY)
.map(String::as_str)
== Some("true")
});
if !supported {
return Err(Error::NotSupported {
message: format!(
"SQL PREWARM server cannot acknowledge the Azure storage-account hint (request_id={request_id}); upgrade the server. No execution request was sent."
),
});
}
}
self.execute(request).await
},
)
.await
}
pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result<Query> {
Ok(self
.execute_with_materialized_view_job_handle(request, false)
+408 -2
View File
@@ -143,6 +143,8 @@ struct TestSqlService {
result_overrides: Arc<std::sync::Mutex<HashMap<String, RecordBatch>>>,
materialized_view_job_handle_supported: bool,
optimize_error: Option<Status>,
prewarm_error: Option<Status>,
prewarm_azure_supported: bool,
/// How many exchange responses have been dropped, finished or not.
exchange_drops: Arc<AtomicUsize>,
result: RecordBatch,
@@ -318,6 +320,8 @@ impl Default for TestSqlService {
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())),
materialized_view_job_handle_supported: false,
optimize_error: None,
prewarm_error: None,
prewarm_azure_supported: false,
exchange_drops: Arc::new(AtomicUsize::new(0)),
result,
large_result,
@@ -352,9 +356,30 @@ impl FlightService for TestSqlService {
async fn get_flight_info(
&self,
_request: Request<FlightDescriptor>,
request: Request<FlightDescriptor>,
) -> std::result::Result<Response<FlightInfo>, Status> {
Err(Status::unimplemented("get_flight_info"))
self.capture_headers(request.metadata());
assert!(
request
.metadata()
.get("x-azure-storage-account-name")
.is_some()
);
let schema = if self.prewarm_azure_supported {
self.result
.schema()
.as_ref()
.clone()
.with_metadata(HashMap::from([(
"lancedb.prewarm.azure_storage_account_name".into(),
"true".into(),
)]))
} else {
self.result.schema().as_ref().clone()
};
Ok(Response::new(
FlightInfo::new().try_with_schema(&schema).unwrap(),
))
}
async fn poll_flight_info(
@@ -493,6 +518,11 @@ impl FlightService for TestSqlService {
{
return Err(error.clone());
}
if command.query.starts_with("PREWARM")
&& let Some(error) = &self.prewarm_error
{
return Err(error.clone());
}
if command.query == "SELECT rejected" {
return Err(Status::invalid_argument("invalid statement"));
}
@@ -4445,3 +4475,379 @@ async fn remote_optimize_branch_options_are_not_dropped() {
);
shutdown.send(()).unwrap();
}
fn prewarm_result() -> RecordBatch {
RecordBatch::try_from_iter([
(
"job_id",
Arc::new(StringArray::from(vec!["warming-job"])) as ArrayRef,
),
(
"table_version",
Arc::new(arrow_array::UInt64Array::from(vec![42])) as ArrayRef,
),
])
.unwrap()
}
#[tokio::test]
async fn remote_prewarm_data_returns_the_durable_job_without_polling() {
use crate::table::PrewarmDataOptions;
for branch in [None, Some("experiment"), Some("o'brien")] {
let service = TestSqlService {
adaptive: true,
result: prewarm_result(),
..Default::default()
};
let statements = service.statements.clone();
let headers = service.headers.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| -> http::Response<String> {
assert_eq!(request.url().path(), "/v1/jobs/describe");
let value: serde_json::Value =
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
assert_eq!(value["job_id"], "warming-job");
observed.fetch_add(1, Ordering::SeqCst);
http::Response::builder()
.status(200)
.body(
serde_json::json!({
"job_id":"warming-job", "job_type":"prewarm_page_cache", "job_state":"DONE",
"creation_ms":1,"spec":{"table_version":42},
"result":{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4},
"operation_progress":{"phase":"reading","executors_completed":2}})
.to_string(),
)
.unwrap()
});
let table = RemoteTable::new_with_sql_client(
client,
"analytics".into(),
"clip\"name".into(),
vec!["team".into(), "inner".into()],
"team$inner$clip\"name".into(),
Default::default(),
Some(sql),
)
.with_branch(branch.map(str::to_string));
let job = table
.prewarm_data_async(
PrewarmDataOptions::new()
.columns(["attrs.score", "`caption.text`", "attrs.score"])
.filter("quality > 0.7")
.concurrency(4),
)
.await
.unwrap();
assert_eq!(job.id(), Some("warming-job"));
assert_eq!(
polls.load(Ordering::SeqCst),
0,
"acceptance must not eagerly poll HTTP"
);
let branch_sql = branch
.map(|b| format!("branch = '{}', ", b.replace('\'', "''")))
.unwrap_or_default();
assert_eq!(
*statements.lock().unwrap(),
[format!(
"PREWARM WITH ({branch_sql}concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7"
)]
);
assert!(
headers
.lock()
.unwrap()
.iter()
.all(|h| h.namespace_path == "team$inner" && h.database == "analytics")
);
job.wait().await.unwrap();
assert_eq!(polls.load(Ordering::SeqCst), 1);
job.refresh().await.unwrap();
assert_eq!(job.spec().unwrap()["table_version"], 42);
shutdown.send(()).unwrap();
}
}
#[tokio::test]
async fn remote_legacy_prewarm_data_submits_sql_and_returns_on_acceptance() {
for columns in [None, Some(vec![]), Some(vec!["payload".into()])] {
let service = TestSqlService {
adaptive: true,
result: prewarm_result(),
..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(|r| -> http::Response<String> {
panic!(
"legacy prewarm must neither submit nor poll REST: {}",
r.url()
);
}),
"analytics".into(),
"clips".into(),
vec![],
"clips".into(),
Default::default(),
Some(sql),
);
table.prewarm_data(columns.clone()).await.unwrap();
let projection = if columns.as_ref().is_some_and(|c| !c.is_empty()) {
"\"payload\""
} else {
"*"
};
assert_eq!(
*statements.lock().unwrap(),
[format!("PREWARM AS SELECT {projection} FROM \"clips\"")]
);
shutdown.send(()).unwrap();
}
}
#[tokio::test]
async fn remote_prewarm_data_rejects_bad_receipts_without_resubmission() {
let service = TestSqlService {
adaptive: true,
..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(|r| -> http::Response<String> {
panic!("must not retry malformed receipt through REST: {}", r.url());
}),
"analytics".into(),
"clips".into(),
vec![],
"clips".into(),
Default::default(),
Some(sql),
);
let error = table.prewarm_data(None).await.unwrap_err();
assert!(error.to_string().contains("inspect jobs before retrying"));
assert_eq!(statements.lock().unwrap().len(), 1);
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn remote_prewarm_errors_preserve_diagnostics_and_never_fall_back() {
for (status, unsupported) in [
(
Status::invalid_argument("Unknown PREWARM option 'branch'"),
true,
),
(Status::permission_denied("source Select denied"), false),
(
Status::invalid_argument("ParserError: expected expression, found invalid_filter"),
false,
),
] {
let service = TestSqlService {
adaptive: true,
prewarm_error: Some(status),
..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(|r| -> http::Response<String> {
panic!("must not retry through REST: {}", r.url());
}),
"analytics".into(),
"clips".into(),
vec![],
"clips".into(),
Default::default(),
Some(sql),
);
let error = table.prewarm_data(None).await.unwrap_err();
assert_eq!(
matches!(error, Error::NotSupported { .. }),
unsupported,
"{error}"
);
assert_eq!(statements.lock().unwrap().len(), 1);
shutdown.send(()).unwrap();
}
}
#[tokio::test]
async fn remote_prewarm_requires_azure_ack_before_execution() {
for supported in [false, true] {
let service = TestSqlService {
adaptive: true,
result: prewarm_result(),
prewarm_azure_supported: supported,
..Default::default()
};
let statements = service.statements.clone();
let mut config = ClientConfig::default();
config.extra_headers.insert(
"x-azure-storage-account-name".into(),
"sourceaccount".into(),
);
let (sql, shutdown) = start_sql_service(service, config).await;
let table = RemoteTable::new_with_sql_client(
client_with_handler(|r| -> http::Response<String> {
panic!("must not use REST: {}", r.url());
}),
"analytics".into(),
"clips".into(),
vec![],
"clips".into(),
Default::default(),
Some(sql),
);
let result = table.prewarm_data(None).await;
assert_eq!(result.is_ok(), supported, "{result:?}");
assert_eq!(statements.lock().unwrap().len(), usize::from(supported));
shutdown.send(()).unwrap();
}
}
#[tokio::test]
async fn remote_prewarm_wait_surfaces_warming_job_failure_or_cancellation() {
for state in ["FAILED", "CANCELLED"] {
let service = TestSqlService {
adaptive: true,
result: prewarm_result(),
..Default::default()
};
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
let client = client_with_handler(move |r| -> http::Response<String> {
assert_eq!(r.url().path(), "/v1/jobs/describe");
http::Response::builder()
.status(200)
.body(
serde_json::json!({
"job_id":"warming-job","job_type":"prewarm_page_cache","job_state":state,
"creation_ms":1,"spec":{"table_version":42},
"result":{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4},
"operation_progress":{"phase":"reading","executors_completed":2}})
.to_string(),
)
.unwrap()
});
let table = RemoteTable::new_with_sql_client(
client,
"analytics".into(),
"clips".into(),
vec![],
"clips".into(),
Default::default(),
Some(sql),
);
let job = table.prewarm_data_async(Default::default()).await.unwrap();
assert_eq!(job.id(), Some("warming-job"));
let error = job.wait().await.unwrap_err();
if state == "FAILED" {
assert!(matches!(error, Error::JobFailed { .. }), "{error}");
} else {
assert!(matches!(error, Error::JobCancelled { .. }), "{error}");
}
shutdown.send(()).unwrap();
}
}
#[tokio::test]
async fn remote_prewarm_rejects_historical_checkout_without_submitting() {
let service = TestSqlService {
adaptive: true,
result: prewarm_result(),
..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(|r| -> http::Response<String> {
assert_eq!(r.url().path(), "/v1/table/clips/describe/");
http::Response::builder()
.status(200)
.body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string())
.unwrap()
}),
"analytics".into(),
"clips".into(),
vec![],
"clips".into(),
Default::default(),
Some(sql),
);
table.checkout(7).await.unwrap();
let error = table.prewarm_data(None).await.unwrap_err();
assert!(matches!(error, Error::NotSupported { .. }));
assert!(error.to_string().contains("historical version 7"));
assert!(statements.lock().unwrap().is_empty());
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn remote_compaction_tracks_registry_job_and_real_result() {
use crate::table::optimize::CompactionOverrides;
let service = TestSqlService {
adaptive: true,
result: RecordBatch::try_from_iter([(
"job_id",
Arc::new(StringArray::from(vec!["compacting-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");
let body: serde_json::Value =
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
assert_eq!(body["job_id"], "compacting-job");
observed.fetch_add(1, Ordering::SeqCst);
http::Response::builder()
.status(200)
.body(
serde_json::json!({
"job_id":"compacting-job","job_type":"compact","job_state":"DONE",
"result":{"partial_commit":false,"rows_succeeded":12,"rows_failed":0,
"completion_percentage":100.0,"files_added":1,"files_removed":3,
"fragments_added":1,"fragments_removed":3}})
.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("experiment".into()));
let job = table
.compact_async(CompactionOverrides {
target_rows_per_fragment: Some(100),
..Default::default()
})
.await
.unwrap();
assert_eq!(job.id(), Some("compacting-job"));
assert_eq!(polls.load(Ordering::SeqCst), 0);
let result = job.wait().await.unwrap();
assert_eq!(result.rows_succeeded, 12);
assert_eq!(result.fragments_removed, Some(3));
assert!(!result.more_work);
assert_eq!(
*statements.lock().unwrap(),
[
"OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'experiment', target_rows_per_fragment = 100)"
]
);
shutdown.send(()).unwrap();
}
+90 -80
View File
@@ -5,6 +5,7 @@ pub mod blobs;
pub mod insert;
mod ipc_stream;
mod optimize;
mod prewarm;
#[cfg(test)]
mod write_tests;
@@ -4098,19 +4099,10 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
options: crate::table::optimize::CompactionOverrides,
) -> Result<OptimizeStats> {
self.check_mutable().await?;
let compaction_options = optimize::compaction_sql_options(&options)?;
let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?;
let sql_client = self.sql_client.clone().ok_or_else(|| Error::NotSupported {
message: "SQL is unavailable for this remote table client".to_string(),
})?;
let mut statement = format!("OPTIMIZE {} REWRITE DATA", quote_sql_identifier(&self.name));
let mut sql_options = Vec::new();
if let Some(branch) = &self.branch {
sql_options.push(format!("branch = {}", quote_sql_string(branch)));
}
sql_options.extend(compaction_options);
if !sql_options.is_empty() {
statement.push_str(&format!(" WITH ({})", sql_options.join(", ")));
}
// `OptimizeStats` carries `lance::dataset::optimize` metric types that
// are not `Serialize`/`Deserialize`/`Clone`, which `Job<T>` requires,
// so the job itself only signals completion; the real (placeholder)
@@ -4127,6 +4119,42 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
prune: None,
})
}
async fn compact_async(
&self,
options: crate::table::optimize::CompactionOverrides,
) -> Result<Job<crate::table::CompactionResult>> {
self.check_mutable().await?;
let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?;
let client = self
.sql_client
.as_ref()
.ok_or_else(|| Error::NotSupported {
message: "compaction jobs require a Flight SQL endpoint".into(),
})?;
let query = client
.execute(crate::database::ExecuteQueryRequest {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
})
.await
.map_err(optimize::map_optimize_error)?;
let mut reader = query.reader().await.map_err(optimize::map_optimize_error)?;
let mut batches = Vec::new();
while let Some(batch) = reader
.try_next()
.await
.map_err(optimize::map_optimize_error)?
{
batches.push(batch);
}
let job_id = optimize::receipt(&batches)?;
Ok(Job::new_typed(Box::new(RemoteJob::new(
self.client.clone(),
job_id,
))))
}
async fn add_columns(
&self,
transforms: NewColumnTransform,
@@ -4728,20 +4756,53 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
}
async fn prewarm_data(&self, columns: Option<Vec<String>>) -> Result<()> {
let mut request = self.client.post(&format!(
"/v1/table/{}/page_cache/prewarm/",
self.identifier
));
let mut body = serde_json::json!({
"columns": columns.unwrap_or_default(),
});
self.apply_branch_body(&mut body);
request = request.json(&body);
let (request_id, response) = self.send(request, true).await?;
self.check_table_response(&request_id, response).await?;
self.prewarm_data_async(
crate::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()),
)
.await?;
Ok(())
}
async fn prewarm_data_async(
&self,
options: crate::table::PrewarmDataOptions,
) -> Result<Job<crate::table::PrewarmDataResult>> {
if let Some(version) = *self.version.read().await {
return Err(Error::NotSupported {
message: format!(
"SQL PREWARM does not support historical version {version}; use checkout_latest() to prewarm the current branch"
),
});
}
let statement = prewarm::statement(&self.name, self.branch.as_deref(), &options)?;
let client = self
.sql_client
.as_ref()
.ok_or_else(|| Error::NotSupported {
message: "data prewarm requires a Flight SQL endpoint and SQL PREWARM support"
.into(),
})?;
let query = client
.execute_prewarm(crate::database::ExecuteQueryRequest {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
})
.await
.map_err(prewarm::map_error)?;
let mut reader = query.reader().await.map_err(prewarm::map_error)?;
let mut batches = Vec::new();
while let Some(batch) = reader.try_next().await.map_err(prewarm::map_error)? {
batches.push(batch);
}
let (job_id, _table_version) = prewarm::receipt(&batches)?;
// Construct lazily: submission must not require an HTTP status round trip.
Ok(Job::new_typed(Box::new(RemoteJob::new(
self.client.clone(),
job_id,
))))
}
async fn table_definition(&self) -> Result<TableDefinition> {
let schema = self.schema().await?;
TableDefinition::try_from_rich_schema(schema)
@@ -13718,67 +13779,16 @@ mod tests {
}
#[tokio::test]
async fn test_prewarm_data() {
let table = Table::new_with_handler("my_table", |request| {
assert_eq!(request.method(), "POST");
assert_eq!(
request.url().path(),
"/v1/table/my_table/page_cache/prewarm/"
async fn test_prewarm_data_requires_sql_without_rest_fallback() {
let table = Table::new_with_handler("my_table", |request| -> http::Response<String> {
panic!(
"data prewarm must not submit through REST: {}",
request.url()
);
http::Response::builder().status(200).body("{}").unwrap()
});
table.prewarm_data(None).await.unwrap();
}
#[tokio::test]
async fn test_prewarm_data_with_columns() {
let table = Table::new_with_handler("my_table", |request| {
assert_eq!(request.method(), "POST");
assert_eq!(
request.url().path(),
"/v1/table/my_table/page_cache/prewarm/"
);
let body = request.body().unwrap().as_bytes().unwrap();
let body: serde_json::Value = serde_json::from_slice(body).unwrap();
assert_eq!(body["columns"], serde_json::json!(["col_a", "col_b"]));
http::Response::builder().status(200).body("{}").unwrap()
});
table
.prewarm_data(Some(vec!["col_a".into(), "col_b".into()]))
.await
.unwrap();
}
#[tokio::test]
async fn test_prewarm_data_sends_the_checked_out_branch() {
use lance::dataset::refs::Ref;
let table =
Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| {
match request.url().path() {
"/v1/table/my_table/branches/create/" => {
http::Response::builder().status(200).body("{}").unwrap()
}
"/v1/table/my_table/page_cache/prewarm/" => {
let body = request_body_json(&request);
assert_eq!(body["branch"], "dev");
assert_eq!(body["columns"], json!(["payload"]));
http::Response::builder()
.status(202)
.body(r#"{"job_id":"prewarm-job"}"#)
.unwrap()
}
path => panic!("unexpected request path: {path}"),
}
});
let branch = table
.create_branch("dev", Ref::Version(None, None))
.await
.unwrap();
branch
.prewarm_data(Some(vec!["payload".into()]))
.await
.unwrap();
let error = table.prewarm_data(None).await.unwrap_err();
assert!(matches!(error, Error::NotSupported { .. }));
assert!(error.to_string().contains("SQL"));
}
#[tokio::test]
+77
View File
@@ -4,6 +4,49 @@
//! Compaction options supported by the remote SQL submission protocol.
use crate::error::{Error, Result};
pub(super) fn statement(
table: &str,
branch: Option<&str>,
options: &crate::table::optimize::CompactionOverrides,
) -> Result<String> {
let mut settings = compaction_sql_options(options)?;
if let Some(branch) = branch {
settings.insert(0, format!("branch = {}", super::quote_sql_string(branch)));
}
let mut sql = format!(
"OPTIMIZE {} REWRITE DATA",
super::quote_sql_identifier(table)
);
if !settings.is_empty() {
sql.push_str(&format!(" WITH ({})", settings.join(", ")));
}
Ok(sql)
}
/// Submission can already have created work: reject ambiguous receipts without
/// retrying or confusing the SQL query's identity with the compaction job.
pub(super) fn receipt(batches: &[arrow_array::RecordBatch]) -> Result<String> {
use arrow_array::{Array, StringArray};
let invalid = || {
Error::Runtime { message: "OPTIMIZE did not return a single nonempty job_id receipt; inspect jobs before retrying because compaction may already have been submitted".into() }
};
if batches.iter().map(|batch| batch.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(|a| a.as_any().downcast_ref::<StringArray>())
.ok_or_else(invalid)?;
if ids.is_null(0) || ids.value(0).is_empty() {
return Err(invalid());
}
Ok(ids.value(0).into())
}
pub(super) fn compaction_sql_options(
options: &crate::table::optimize::CompactionOverrides,
) -> Result<Vec<String>> {
@@ -258,3 +301,37 @@ mod tests {
}
}
}
#[cfg(test)]
mod receipt_tests {
use super::*;
use arrow_array::{ArrayRef, RecordBatch, StringArray};
use std::sync::Arc;
#[test]
fn compaction_receipt_requires_one_unambiguous_registry_id() {
let batch = |ids: Vec<Option<&str>>| {
RecordBatch::try_from_iter([("job_id", Arc::new(StringArray::from(ids)) as ArrayRef)])
.unwrap()
};
assert_eq!(
receipt(&[batch(vec![Some("compacting-job")])]).unwrap(),
"compacting-job"
);
for batches in [
vec![],
vec![batch(vec![])],
vec![batch(vec![None])],
vec![batch(vec![Some("")])],
vec![batch(vec![Some("a"), Some("b")])],
vec![batch(vec![Some("a")]), batch(vec![Some("b")])],
] {
assert!(
receipt(&batches)
.unwrap_err()
.to_string()
.contains("inspect jobs before retrying")
);
}
}
}
+248
View File
@@ -0,0 +1,248 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! SQL submission and receipt validation for data-cache prewarm jobs.
use arrow_array::{Array, RecordBatch, StringArray, UInt64Array};
use datafusion_sql::sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Token};
use super::{quote_sql_identifier, quote_sql_string};
use crate::{Error, Result, table::PrewarmDataOptions};
pub(super) fn statement(
table: &str,
branch: Option<&str>,
options: &PrewarmDataOptions,
) -> Result<String> {
let invalid = |message: &str| Error::InvalidInput {
message: message.into(),
};
if options.concurrency == Some(0) {
return Err(invalid("prewarm concurrency must be greater than 0"));
}
if let Some(filter) = &options.filter {
if filter.trim().is_empty() {
return Err(invalid("prewarm filter must not be empty"));
}
let dialect = GenericDialect {};
let mut parser = Parser::new(&dialect)
.try_with_sql(filter)
.map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?;
parser
.parse_expr()
.map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?;
if parser.peek_token().token != Token::EOF {
return Err(invalid("prewarm filter must be a single SQL expression"));
}
}
let mut settings = Vec::new();
if let Some(branch) = branch {
if branch.trim().is_empty() {
return Err(invalid("prewarm branch must not be empty"));
}
settings.push(format!("branch = {}", quote_sql_string(branch)));
}
if let Some(concurrency) = options.concurrency {
settings.push(format!("concurrency = {concurrency}"));
}
let mut sql = "PREWARM".to_string();
if !settings.is_empty() {
sql.push_str(&format!(" WITH ({})", settings.join(", ")));
}
let mut columns = Vec::new();
for column in &options.columns {
let parts = lance::datatypes::parse_field_path(column)?;
let column = parts
.iter()
.map(|part| quote_sql_identifier(part))
.collect::<Vec<_>>()
.join(".");
if !columns.contains(&column) {
columns.push(column);
}
}
let projection = if columns.is_empty() {
"*".into()
} else {
columns.join(", ")
};
sql.push_str(&format!(
" AS SELECT {projection} FROM {}",
quote_sql_identifier(table)
));
if let Some(filter) = &options.filter {
sql.push_str(&format!(" WHERE {filter}"));
}
Ok(sql)
}
pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> {
let invalid = || {
Error::Runtime {
message: "PREWARM did not return a single (job_id, table_version) receipt; inspect jobs before retrying because work 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 id = batch
.column_by_name("job_id")
.and_then(|array| array.as_any().downcast_ref::<StringArray>())
.ok_or_else(invalid)?;
let version = batch
.column_by_name("table_version")
.and_then(|array| array.as_any().downcast_ref::<UInt64Array>())
.ok_or_else(invalid)?;
if id.is_null(0) || id.value(0).is_empty() || version.is_null(0) {
return Err(invalid());
}
Ok((id.value(0).into(), version.value(0)))
}
pub(super) fn map_error(error: Error) -> Error {
fn unsupported(error: &Error) -> Option<&Error> {
match error {
Error::Sql {
message, grpc_code, ..
} => {
let diagnostic = message.to_ascii_lowercase();
(*grpc_code == tonic::Code::Unimplemented as i32
|| (*grpc_code == tonic::Code::InvalidArgument as i32
&& (diagnostic.contains("found: prewarm")
|| diagnostic.contains("supported syntax: prewarm")
|| diagnostic.contains("unknown prewarm option"))))
.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!(
"Data prewarm requires a compatible SQL PREWARM server; upgrade the server. Requested options will not be removed and submission will not fall back to REST. Server diagnostic: {diagnostic}"
),
}
} else {
error
}
}
#[cfg(test)]
mod tests {
use super::*;
use arrow_schema::{DataType, Field, Schema};
use std::sync::Arc;
#[test]
fn quotes_paths_branch_and_filter_without_changing_options() {
let options = PrewarmDataOptions::new()
.columns(["attrs.score", "`caption.text`", "attrs.score"])
.filter("quality > 0.7 AND caption = 'it''s ready'")
.concurrency(4);
assert_eq!(
statement("clip\"name", Some("o'brien"), &options).unwrap(),
"PREWARM WITH (branch = 'o''brien', concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7 AND caption = 'it''s ready'"
);
assert_eq!(
statement("clips", None, &Default::default()).unwrap(),
"PREWARM AS SELECT * FROM \"clips\""
);
assert!(statement("clips", None, &PrewarmDataOptions::new().filter("-1 < id")).is_ok());
}
#[test]
fn rejects_invalid_inputs_before_submission() {
for options in [
PrewarmDataOptions::new().filter(""),
PrewarmDataOptions::new().filter("id > 0; DROP TABLE clips"),
PrewarmDataOptions::new().filter("id > 0 LIMIT 1"),
PrewarmDataOptions::new().filter("id >"),
PrewarmDataOptions::new().columns(["attrs..score"]),
PrewarmDataOptions::new().concurrency(0),
] {
assert!(statement("clips", None, &options).is_err(), "{options:?}");
}
}
fn batch(ids: Vec<Option<&str>>, versions: Vec<Option<u64>>) -> RecordBatch {
RecordBatch::try_from_iter([
(
"job_id",
Arc::new(StringArray::from(ids)) as arrow_array::ArrayRef,
),
(
"table_version",
Arc::new(UInt64Array::from(versions)) as arrow_array::ArrayRef,
),
])
.unwrap()
}
#[test]
fn receipt_requires_one_non_null_job_and_version() {
assert_eq!(
receipt(&[batch(vec![Some("job-1")], vec![Some(42)])]).unwrap(),
("job-1".into(), 42)
);
for batches in [
vec![],
vec![batch(vec![], vec![])],
vec![batch(vec![None], vec![Some(42)])],
vec![batch(vec![Some("")], vec![Some(42)])],
vec![batch(vec![Some("job")], vec![None])],
vec![batch(vec![Some("a"), Some("b")], vec![Some(1), Some(2)])],
vec![
batch(vec![Some("a")], vec![Some(1)]),
batch(vec![Some("b")], vec![Some(2)]),
],
vec![RecordBatch::new_empty(Arc::new(Schema::new(vec![
Field::new("wrong", DataType::Utf8, false),
])))],
] {
let error = receipt(&batches).unwrap_err().to_string();
assert!(error.contains("inspect jobs before retrying"), "{error}");
}
}
#[test]
fn compatibility_errors_preserve_permission_and_predicate_diagnostics() {
for (code, message, unsupported) in [
(
tonic::Code::InvalidArgument,
"ParserError: found: PREWARM",
true,
),
(
tonic::Code::InvalidArgument,
"Unknown PREWARM option 'branch'",
true,
),
(tonic::Code::PermissionDenied, "permission denied", false),
(
tonic::Code::InvalidArgument,
"ParserError: expected expression, found unsupported_filter",
false,
),
] {
let error = map_error(Error::Sql {
message: message.into(),
request_id: "prewarm-request".into(),
grpc_code: code as i32,
metadata: Default::default(),
});
assert_eq!(matches!(error, Error::NotSupported { .. }), unsupported);
assert!(error.to_string().contains(message));
assert!(error.to_string().contains("prewarm-request"));
}
}
}
+91 -2
View File
@@ -86,6 +86,9 @@ pub mod freshness;
pub mod function_column_status;
pub mod merge;
pub mod optimize;
pub use optimize::CompactionResult;
mod prewarm;
pub use prewarm::{PrewarmDataOptions, PrewarmDataResult};
pub(crate) mod primary_key;
pub mod query;
pub mod refresh;
@@ -688,6 +691,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
/// Currently only supported in LanceDB Enterprise.
/// If `columns` is `None`, all columns are prewarmed.
async fn prewarm_data(&self, columns: Option<Vec<String>>) -> Result<()>;
/// Submit a data-cache prewarm and return its durable job handle.
async fn prewarm_data_async(
&self,
_options: PrewarmDataOptions,
) -> Result<Job<PrewarmDataResult>> {
Err(Error::NotSupported {
message: "data prewarm jobs are only supported on remote tables".into(),
})
}
/// Get statistics about the index.
async fn index_stats(&self, index_name: &str) -> Result<Option<IndexStatistics>>;
/// Merge insert new records into the table.
@@ -881,6 +894,15 @@ 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 remote compaction and retain its durable job and actual outcome.
async fn compact_async(
&self,
_options: optimize::CompactionOverrides,
) -> Result<Job<CompactionResult>> {
Err(Error::NotSupported {
message: "compaction jobs are only supported on remote tables".into(),
})
}
/// Compact with optional fields, preserving remote policy inheritance.
async fn compact(&self, options: optimize::CompactionOverrides) -> Result<OptimizeStats> {
self.optimize(OptimizeAction::Compact {
@@ -2065,6 +2087,37 @@ impl Table {
self.inner.compact(options).await
}
/// Submit remote compaction and return its durable job after acceptance.
///
/// Uses SQL `OPTIMIZE ... REWRITE DATA` with the table handle's namespace
/// and branch. The four fields of [`optimize::CompactionOverrides`] retain
/// server defaults when omitted. Requires a compatible remote SQL server
/// and table Ownership plus database/namespace Usage under Standard authorization.
/// Historical-version and local handles are unsupported.
///
/// Unlike [`Self::optimize`], waiting on this handle waits for compaction
/// itself and returns actual [`CompactionResult`] values. Status, progress,
/// events, and cancellation use the generic HTTP job APIs. A timeout or
/// dropping the handle does not cancel work. Missing result payloads are
/// errors, never placeholder zero statistics. An older worker may omit
/// file counts, represented as `None`. Reopen with
/// `connection.open_job(id).await?.into_typed::<CompactionResult>()?`.
///
/// ```no_run
/// # async fn compact(table: &lancedb::Table) -> lancedb::Result<()> {
/// let job = table.compact_async(Default::default()).await?;
/// let result = job.wait().await?;
/// println!("Committed {} rows", result.rows_succeeded);
/// # Ok(())
/// # }
/// ```
pub async fn compact_async(
&self,
options: optimize::CompactionOverrides,
) -> Result<Job<CompactionResult>> {
self.inner.compact_async(options).await
}
/// Language-binding entry point retaining optional compaction fields.
#[doc(hidden)]
pub async fn optimize_full_with_overrides(
@@ -3090,8 +3143,9 @@ impl Table {
/// supported in LanceDB Enterprise.
///
/// This call initiates prewarming and returns once the request is accepted.
/// It is idempotent and safe to call from multiple clients concurrently —
/// calling it on already-prewarmed columns is a no-op on the server.
/// Remote tables use SQL PREWARM and require Flight SQL connectivity.
/// Use [`Self::prewarm_data_async`] to retain the durable job handle.
/// Repeated submissions can create distinct jobs; warming cached data is safe.
///
/// This operation has a large upfront cost but can speed up future queries
/// that need to fetch the given columns. Large columns such as embeddings
@@ -3103,6 +3157,41 @@ impl Table {
self.inner.prewarm_data(columns).await
}
/// Submit a durable data-cache prewarm job through SQL and return when accepted.
///
/// The handle tracks the warming job, rather than the SQL submission. Use
/// [`Job::wait`] to wait for warming to finish, or save [`Job::id`] and
/// reopen it through [`crate::Connection::open_job`]. A wait timeout or
/// dropping the handle does not cancel the job. Waiting returns the reported
/// [`PrewarmDataResult`]; unavailable measurements remain `None`.
///
/// Requires a compatible remote server with SQL PREWARM support and Flight
/// SQL connectivity. Under Standard authorization, submission requires
/// Select on the table and Usage on its database and namespace hierarchy.
/// Status and waiting use the generic HTTP job APIs; events and cancellation
/// retain their separate privileges. Unsupported servers are not retried
/// through REST or with requested settings removed. Local tables are unsupported.
/// Historical-version checkouts are unsupported; use `checkout_latest()` first.
/// After [`Job::refresh`], the pinned source version is in [`Job::spec`].
///
/// ```no_run
/// # async fn warm(table: &lancedb::Table) -> lancedb::Result<()> {
/// use lancedb::table::PrewarmDataOptions;
/// let job = table.prewarm_data_async(PrewarmDataOptions::new()
/// .columns(["video"])
/// .filter("quality > 0.7")
/// .concurrency(4)).await?;
/// job.wait().await?;
/// # Ok(())
/// # }
/// ```
pub async fn prewarm_data_async(
&self,
options: PrewarmDataOptions,
) -> Result<Job<PrewarmDataResult>> {
self.inner.prewarm_data_async(options).await
}
/// Poll until the columns are fully indexed. Will return Error::Timeout if the columns
/// are not fully indexed within the timeout.
pub async fn wait_for_index(
+39 -6
View File
@@ -32,6 +32,35 @@ pub use lance::dataset::optimize::{CompactionMode, CompactionOptions, IndexRemap
const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64;
/// Actual outcome of one remote compaction job, returned by its job handle.
///
/// A successful bounded run can leave more work for another invocation. A
/// partial commit reports uncommitted rows rather than inventing file counts.
/// File/fragment counts are unknown (`None`) when an older worker omitted them.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct CompactionResult {
/// A complete bounded plan left eligible work for a later invocation.
#[serde(default)]
pub more_work: bool,
/// Some planned groups were not committed.
pub partial_commit: bool,
/// Live source rows in committed rewrite groups.
pub rows_succeeded: u64,
/// Planned live rows not committed by this job.
pub rows_failed: u64,
/// Percentage of planned live rows committed, from 0 to 100.
pub completion_percentage: f64,
/// Files added by committed rewrites, including deletion files, when reported.
pub files_added: Option<u64>,
/// Files removed by committed rewrites, including deletion files, when reported.
pub files_removed: Option<u64>,
/// Fragments added by committed rewrites, when reported by the server.
pub fragments_added: Option<u64>,
/// Fragments removed by committed rewrites, when reported by the server.
pub fragments_removed: Option<u64>,
}
struct PrecomputedCompactionPlanner {
plan: Mutex<Option<CompactionPlan>>,
}
@@ -261,8 +290,11 @@ pub enum OptimizeAction {
/// options and custom `remap_options` return [`crate::Error::NotSupported`]
/// before submission. The server must support these SQL options; errors
/// from older servers are returned without dropping the settings.
/// The source-row budget admits whole tasks and may perform no work when
/// the first task exceeds it. Zero I/O buffer size disables byte-based I/O
/// The source-row budget admits whole tasks. On current Enterprise servers,
/// worker planning fails if the budget cannot admit the first useful task,
/// reporting its required live rows and source fragment count. Older servers
/// may instead finish without rewriting data in this case.
/// Zero I/O buffer size disables byte-based I/O
/// backpressure. Use a positive size to limit I/O read-ahead; this is not a
/// total-memory limit. Row targets, source-row budgets, and batch sizes must
/// be positive.
@@ -298,10 +330,11 @@ pub enum OptimizeAction {
/// # }
/// ```
///
/// A branch-scoped table handle compacts that branch. The branch is not
/// validated to exist before the job is submitted, so a nonexistent
/// branch fails the compaction job asynchronously rather than failing
/// this call.
/// A branch-scoped table handle compacts that branch. Current Enterprise
/// servers validate the table and branch through the service catalog before
/// creating the compaction job, so a nonexistent branch fails submission.
/// Older servers may accept submission and fail the compaction job
/// asynchronously instead.
Compact {
options: CompactionOptions,
remap_options: Option<Arc<dyn IndexRemapperOptions>>,
+118
View File
@@ -0,0 +1,118 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! Options for submitting a durable data-cache prewarm job.
/// Data prewarm settings for [`super::Table::prewarm_data_async`].
///
/// The table handle supplies the database, namespace, and branch. Omitted
/// columns warm all fields. The filter selects conservative metadata ranges;
/// it does not execute a row-filter scan or change the source data.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct PrewarmDataOptions {
/// Lance field paths, including nested paths such as `attrs.score`.
pub columns: Vec<String>,
/// An optional SQL predicate for metadata pruning.
pub filter: Option<String>,
/// Positive per-executor warming concurrency. Omit for the server default.
pub concurrency: Option<u32>,
}
impl PrewarmDataOptions {
/// Use server defaults and warm every column.
pub fn new() -> Self {
Self::default()
}
/// Select fields to warm. An empty collection selects all columns.
pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.columns = columns.into_iter().map(Into::into).collect();
self
}
/// Restrict warming using a single SQL predicate for metadata pruning.
pub fn filter(mut self, filter: impl Into<String>) -> Self {
self.filter = Some(filter.into());
self
}
/// Set positive per-executor warming concurrency.
pub fn concurrency(mut self, concurrency: u32) -> Self {
self.concurrency = Some(concurrency);
self
}
}
/// Reported outcome of a remote data-prewarm job. Counts describe executor work;
/// absent measurements remain unknown rather than being inferred as zero.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct PrewarmDataResult {
/// Source snapshot captured by the submitted prewarm.
pub table_version: u64,
/// Reported executors targeted; unknown on older workers.
pub executors_targeted: Option<u64>,
/// Executors that reached a successful or partial terminal state.
pub executors_completed: Option<u64>,
/// Subset of completed executors that reported partial warming.
pub executors_partial: Option<u64>,
/// Reported fragments selected; unknown on older workers.
pub fragments_selected: Option<u64>,
/// Reported ranges completed; unknown on older workers.
pub ranges_completed: Option<u64>,
/// Reported bytes read; unknown on older workers.
pub bytes_read: Option<u64>,
}
#[cfg(test)]
mod tests {
use super::*;
use arrow_schema::{DataType, Field, Schema};
use std::sync::Arc;
#[test]
fn result_preserves_zero_partial_and_unknown_measurements() {
let result: PrewarmDataResult = serde_json::from_value(serde_json::json!({
"table_version":42,"executors_targeted":2,"executors_completed":2,
"executors_partial":1,"ranges_completed":0,"extra":"ignored",
}))
.unwrap();
assert_eq!(result.executors_partial, Some(1));
assert_eq!(result.ranges_completed, Some(0));
assert_eq!(result.bytes_read, None);
assert!(serde_json::from_value::<PrewarmDataResult>(serde_json::json!({})).is_err());
assert!(
serde_json::from_value::<PrewarmDataResult>(
serde_json::json!({"table_version":42,"bytes_read":-1})
)
.is_err()
);
}
#[tokio::test]
async fn local_table_rejects_durable_data_prewarm() {
let db = crate::connect(&format!("memory://prewarm-{}", uuid::Uuid::new_v4()))
.execute()
.await
.unwrap();
let table = db
.create_empty_table(
"items",
Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])),
)
.execute()
.await
.unwrap();
let error = table
.prewarm_data_async(PrewarmDataOptions::new().filter("id > 0"))
.await
.unwrap_err();
assert!(matches!(error, crate::Error::NotSupported { .. }));
assert!(
error
.to_string()
.contains("only supported on remote tables")
);
}
}