Files
lancedb/docs/web/enterprise/cache-prewarm.mdx
T
Bruno Ramirez 16af729792 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.
2026-11-17 10:57:56 -08:00

215 lines
8.7 KiB
Plaintext

---
title: "Cache Prewarm"
sidebarTitle: "Cache Prewarm"
description: "Warm indexes at executor startup or submit on-demand jobs to populate the data page cache."
icon: "fire"
keywords: ["prewarm", "cache", "index cache", "data page cache", "startup"]
availability:
embedded: unavailable
enterprise: available
---
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.
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">
```mermaid
%%{init: {"theme": "base", "themeVariables": {
"background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8",
"primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8",
"edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px"
}}}%%
flowchart LR
List[("Configured list<br/>of tables to prewarm")]
Start["Plan executor starts<br/>(not ready — no queries served)"] --> Warm["Loads the configured<br/>tables' indexes into cache"]
List -.-> Warm
Warm --> Ready["Ready — joins the fleet,<br/>starts serving queries"]
classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8
classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8
class Warm,List accent
```
</div>
<div className="block dark:hidden">
```mermaid
%%{init: {"theme": "base", "themeVariables": {
"background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19",
"primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19",
"edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px"
}}}%%
flowchart LR
List[("Configured list<br/>of tables to prewarm")]
Start["Plan executor starts<br/>(not ready — no queries served)"] --> Warm["Loads the configured<br/>tables' indexes into cache"]
List -.-> Warm
Warm --> Ready["Ready — joins the fleet,<br/>starts serving queries"]
classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19
classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19
class Warm,List accent
```
</div>
## Why it matters {#why-it-matters}
Without prewarming, a fresh or restarted executor would fill its indexes
lazily, so the first queries it serves pay the cost of loading and
deserializing them from object storage. Holding the executor out of the
fleet until its configured tables are warm means every query it ever
serves gets a warm cache, so performance stays consistent through restarts
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 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 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.
</Card>
</CardGroup>