feat(sdk): support bound parameters in data prewarm (#5076)

Data prewarm methods accept filter expressions but cannot bind their
values, which forces applications to build literal SQL themselves. This
adds optional positional and named parameters to data-prewarm submission
and typed previews across Rust, Python, and TypeScript. Values use the
existing typed Arrow SQL transport and remain separate from the filter
text. Existing calls and job-handle behavior are preserved;
parameterized filters require a compatible LanceDB Enterprise server.

This was accomplished with the following changes:

- Add `PrewarmDataOptions::parameters(RecordBatch)` and forward the
batch through SQL submission and `EXPLAIN PREWARM` requests.
- Reuse Python's `QueryParameters` conversion for
synchronous/asynchronous, legacy/job-returning, and typed preview
methods.
- Add TypeScript positional-array, named-object, and explicit Arrow
parameter inputs, with safe scalar encoding and native IPC forwarding.
- Keep parameter values out of Rust option debug output and reject
invalid input before submission where possible.
- Add transport and codec regression tests, including injection-shaped
strings, typed Arrow values, legacy method forwarding, and typed preview
bindings.
- Document bound filters in the cache-prewarm guide with Python,
TypeScript, and Rust examples; update generic SQL parameter
documentation.

### Usage and behaviour

```python
job = table.prewarm_data_async(
    ["payload"], filter="id >= $minimum", parameters={"minimum": 1000}
)
job.wait()
```

```typescript
const job = await table.prewarmDataAsync({
  columns: ["payload"], filter: "id >= $1", parameters: [1000],
});
await job.wait();
```

Python accepts a sequence, mapping, or one-row Arrow batch/table.
TypeScript accepts scalar arrays/objects or one-row Arrow input; safe
integers and bigint use Int64, fractional numbers use Float64. Rust
accepts a one-row Arrow batch. Parameters bind filter values, while
table identity, branch, and concurrency keep their existing interfaces.
Submission-only methods also forward bindings and retain their existing
return behavior. Typed preview helpers accept the same parameters
without creating a job.

### Testing

Python prewarm Flight transport tests pass (65 cases), Embedded
compatibility tests pass (6 cases), and focused Node parameter/prewarm
tests pass (45 cases, including ten codec and native-boundary cases).
Earlier matching-server verification passed 57 Python/SQL scenarios, 14
Node scenarios, and Rust SDK checks, covering selective and empty plans,
typed values, authorization, pinned branches, legacy methods, and
injection-shaped strings. A bound job also survives a full runtime
restart. The guide submission examples were also verified in Python,
TypeScript, and Rust; the TypeScript example type-checks. Live-server
checks used filesystem storage.
This commit is contained in:
Bruno Ramirez
2026-11-18 11:07:32 -08:00
committed by GitHub
parent 3907a492c0
commit 23f9d5a741
22 changed files with 613 additions and 50 deletions
+5 -2
View File
@@ -679,7 +679,9 @@ with an unsupported-operation error.
#### Example
```ts
const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"});
const plan = await table.explainPrewarmData({
columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7},
});
console.log(plan.pruning.selectedFragments);
```
@@ -1221,7 +1223,8 @@ the job. After `job.refresh()`, `job.spec.table_version` is the pinned version.
```ts
const job = await table.prewarmDataAsync({
columns: ["video"], filter: "quality > 0.7", concurrency: 4,
columns: ["video"], filter: "quality > $minimum",
parameters: { minimum: 0.7 }, concurrency: 4,
});
await job.wait();
```
+2
View File
@@ -191,6 +191,8 @@
- [JobProgressCallback](type-aliases/JobProgressCallback.md)
- [MaterializedViewSelect](type-aliases/MaterializedViewSelect.md)
- [MultiVector](type-aliases/MultiVector.md)
- [QueryParameterValue](type-aliases/QueryParameterValue.md)
- [QueryParameters](type-aliases/QueryParameters.md)
- [RecordBatchLike](type-aliases/RecordBatchLike.md)
- [SchemaLike](type-aliases/SchemaLike.md)
- [TableLike](type-aliases/TableLike.md)
@@ -37,3 +37,13 @@ optional filter: string;
```
A single SQL predicate for conservative metadata pruning.
***
### parameters?
```ts
optional parameters: QueryParameters;
```
Typed positional or named filter values, sent separately from SQL.
@@ -0,0 +1,20 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / QueryParameterValue
# Type Alias: QueryParameterValue
```ts
type QueryParameterValue:
| string
| number
| bigint
| boolean
| Date
| Uint8Array
| null;
```
Scalar SQL values. Use a one-row Arrow table for explicit Arrow types.
@@ -0,0 +1,16 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / QueryParameters
# Type Alias: QueryParameters
```ts
type QueryParameters: readonly QueryParameterValue[] | Readonly<Record<string, QueryParameterValue>> | TableLike | RecordBatchLike;
```
Values for `$1`/`$name` placeholders, sent separately from SQL text.
Arrays bind by position; objects bind by name. Arrow columns bind both ways.
Safe integers and bigint use Int64; fractional numbers use Float64.
Arrow input preserves explicit types.
+54 -15
View File
@@ -14,7 +14,7 @@ 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
For startup index prewarm, you configure which tables to warm. Each
executor loads those tables' indexes before it joins the fleet. The executor
does not accept queries until startup prewarming finishes.
@@ -32,7 +32,7 @@ an idempotent hint that loads a built index into memory ahead of a query.
}}}%%
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"]
Start["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
@@ -52,7 +52,7 @@ flowchart LR
}}}%%
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"]
Start["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
@@ -91,7 +91,8 @@ The table handle determines the database, namespace, and branch in every SDK.
from datetime import timedelta
job = table.prewarm_data_async(
["video"], filter="quality > 0.7", concurrency=4
["video"], filter="quality > $minimum",
parameters={"minimum": 0.7}, concurrency=4
)
print(job.id)
result = job.wait(timeout=timedelta(minutes=10), progress=print)
@@ -105,7 +106,8 @@ db.open_job(job.id).wait()
```typescript
const job = await table.prewarmDataAsync({
columns: ["video"],
filter: "quality > 0.7",
filter: "quality > $1",
parameters: [0.7],
concurrency: 4,
});
console.log(job.id);
@@ -121,14 +123,20 @@ if (job.id !== null) {
<Tab title="Rust">
```rust
use std::time::Duration;
use std::sync::Arc;
use arrow_array::{ArrayRef, Float64Array, RecordBatch};
use lancedb::job::JobWaitOptions;
use lancedb::table::{PrewarmDataOptions, PrewarmDataResult};
let parameters = RecordBatch::try_from_iter([
("minimum", Arc::new(Float64Array::from(vec![0.7])) as ArrayRef),
])?;
let job = table
.prewarm_data_async(
PrewarmDataOptions::new()
.columns(["video"])
.filter("quality > 0.7")
.filter("quality > $minimum")
.parameters(parameters)
.concurrency(4),
)
.await?;
@@ -150,8 +158,22 @@ 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.
The TypeScript SDK exposes
`table.prewarmDataAsync({ columns, filter, parameters, concurrency })` with the
same lifecycle.
Pass `parameters` alongside a filter to bind positional `$1`/`$2` or named
`$name` values. Python accepts a sequence, mapping, or one-row Arrow batch/table;
TypeScript accepts a scalar array, named object, or one-row Arrow batch/table.
Rust accepts a one-row Arrow `RecordBatch`. Values travel separately from SQL
text, and table/column identifiers, branch, and concurrency retain their existing
interfaces. Existing literal filters continue to work without parameters.
Bound filters require an Enterprise server that supports parameterized PREWARM.
The server accepts up to 1,024 scalar parameters and 64 KiB of encoded Arrow IPC.
Missing, unused, malformed, oversized, and unsupported bindings fail before job
creation. TypeScript encodes safe integer numbers and bigint as Int64 and
fractional numbers as Float64; use Arrow input when an explicit type is needed.
Waiting returns a typed `PrewarmDataResult`: the pinned source version,
selected fragment count, targeted/completed executor counts, and partial
@@ -197,7 +219,7 @@ it creates no warming job and does not use the job-monitoring APIs.
from lancedb.prewarm import PrewarmDataPlan
plan: PrewarmDataPlan = table.explain_prewarm_data(
["payload"], filter="id >= 1000", concurrency=4
["payload"], filter="id >= $minimum", parameters={"minimum": 1000}, concurrency=4
)
print(plan.table_version)
print(plan.pruning.mode)
@@ -214,7 +236,8 @@ import type { PrewarmDataPlan } from "@lancedb/lancedb";
const plan: PrewarmDataPlan = await table.explainPrewarmData({
columns: ["payload"],
filter: "id >= 1000",
filter: "id >= $minimum",
parameters: { minimum: 1000 },
concurrency: 4,
});
console.log(plan.tableVersion);
@@ -225,13 +248,19 @@ console.log(plan.pruning.selectedRowRanges, plan.pruning.fallbackReason);
</Tab>
<Tab title="Rust">
```rust
use std::sync::Arc;
use arrow_array::{ArrayRef, Int64Array, RecordBatch};
use lancedb::table::{PrewarmDataOptions, PrewarmDataPlan};
let parameters = RecordBatch::try_from_iter([
("minimum", Arc::new(Int64Array::from(vec![1000])) as ArrayRef),
])?;
let plan: PrewarmDataPlan = table
.explain_prewarm_data(
PrewarmDataOptions::new()
.columns(["payload"])
.filter("id >= 1000")
.filter("id >= $minimum")
.parameters(parameters)
.concurrency(4),
)
.await?;
@@ -255,15 +284,25 @@ when reported. Pruning modes may expand in future server versions. A preview doe
resolves and plans its own source version. Unsupported servers fail explicitly
without falling back to text parsing or REST.
Python's SQL interface also accepts bindings for a preview without submitting a
warming job:
```python
plan = db.execute_query(
"EXPLAIN PREWARM AS SELECT video FROM clips WHERE quality > $minimum",
parameters={"minimum": 0.7},
).read_all()
```
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.
`prewarm_data(columns, filter=..., parameters=..., concurrency=...)` and
`prewarmData({ columns, filter, parameters, 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
@@ -280,6 +319,6 @@ already-cached data is safe. Index prewarm keeps its existing behavior.
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.
Where executors and query nodes sit in the serving fleet.
</Card>
</CardGroup>
+111
View File
@@ -0,0 +1,111 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { Int32, Table, tableFromIPC, vectorFromArray } from "../lancedb/arrow";
import { toParameterBuffer } from "../lancedb/sql";
import { LocalTable } from "../lancedb/table";
describe("SQL parameter encoding", () => {
test.each([false, true])(
"prewarm submission and preview forward typed bindings (named: %s)",
async (named) => {
const attack = "training' OR TRUE; DROP TABLE items; --";
const parameters = named ? { minimum: 42n, tag: attack } : [42n, attack];
const filter = named
? "id >= $minimum AND tag = $tag"
: "id >= $1 AND tag = $2";
const submission = jest.fn().mockResolvedValue({});
const preview = jest.fn().mockResolvedValue(
JSON.parse(`{
"table_version": 42,
"plan": "metadata preview",
"pruning": {
"mode": "zonemap_ranges",
"input_fragments": 3,
"selected_fragments": 1,
"pruned_fragments": 2,
"selected_row_ranges": 2
}
}`),
);
const table = new LocalTable({
prewarmDataAsync: submission,
explainPrewarmData: preview,
} as never);
await table.prewarmDataAsync({ filter, parameters });
const plan = await table.explainPrewarmData({ filter, parameters });
expect(plan.tableVersion).toBe(42);
expect(plan.pruning.selectedFragments).toBe(1);
for (const call of [submission, preview]) {
expect(call).toHaveBeenCalledTimes(1);
const options = call.mock.calls[0][0];
expect(options.filter).toBe(filter);
expect(options.filter).not.toContain(attack);
expect(Buffer.isBuffer(options.parameters)).toBe(true);
const batch = tableFromIPC(options.parameters);
expect(batch.schema.fields.map((field) => field.name)).toEqual(
named ? ["minimum", "tag"] : ["1", "2"],
);
expect(batch.getChildAt(0)?.get(0)).toBe(42n);
expect(batch.getChildAt(1)?.get(0)).toBe(attack);
}
},
);
test("positional and named bindings preserve values without SQL interpolation", async () => {
const attack = "training' OR TRUE; DROP TABLE items; --";
const date = new Date("2026-01-02T00:00:00Z");
const batch = tableFromIPC(
await toParameterBuffer([
42n,
attack,
null,
true,
date,
0.7,
new Uint8Array([1, 2]),
]),
);
expect(batch.schema.fields.map((field) => field.name)).toEqual([
"1",
"2",
"3",
"4",
"5",
"6",
"7",
]);
expect(batch.getChildAt(0)?.get(0)).toBe(42n);
expect(batch.getChildAt(1)?.get(0)).toBe(attack);
expect(batch.getChildAt(2)?.get(0)).toBeNull();
expect(batch.getChildAt(4)?.get(0)).toBe(date.getTime());
const named = tableFromIPC(
await toParameterBuffer({ minimum: 42n, tag: attack }),
);
expect(named.schema.fields.map((field) => field.name)).toEqual([
"minimum",
"tag",
]);
expect(named.getChild("tag")?.get(0)).toBe(attack);
});
test("explicit Arrow input preserves its types", async () => {
const input = new Table({ minimum: vectorFromArray([42], new Int32()) });
for (const parameters of [input, input.batches[0]]) {
const decoded = tableFromIPC(await toParameterBuffer(parameters));
expect(decoded.schema.fields[0].type.toString()).toBe("Int32");
expect(decoded.getChildAt(0)?.get(0)).toBe(42);
}
});
test.each([
[],
{ value: undefined },
{ value: 2 ** 53 },
{ value: 1n << 63n },
{ value: {} },
{ value: new Date("invalid") },
])("invalid parameters fail before submission: %p", async (parameters) => {
await expect(toParameterBuffer(parameters as never)).rejects.toThrow();
});
});
+5 -1
View File
@@ -4744,6 +4744,9 @@ describe.each(arrowVersions)(
await expect(table.explainPrewarmData()).rejects.toThrow(
"only supported on remote tables",
);
await expect(
table.explainPrewarmData({ filter: "id > $1", parameters: [1] }),
).rejects.toThrow("only supported on remote tables");
await expect(
table.explainPrewarmData({ unsupported: true } as never),
).rejects.toThrow("Unsupported data prewarm option");
@@ -4770,8 +4773,9 @@ describe.each(arrowVersions)(
await expect(
table.prewarmDataAsync({
columns: ["id"],
filter: "id > 0",
filter: "id > $1",
concurrency: 2,
parameters: [1],
}),
).rejects.toThrow("only supported on remote tables");
await expect(
+2
View File
@@ -673,3 +673,5 @@ export type {
PrewarmDataResult,
PrewarmPruningSummary,
} from "./prewarm";
export type { QueryParameters, QueryParameterValue } from "./sql";
+104
View File
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import {
Binary,
Bool,
type DataType,
Float64,
Int64,
Null,
RecordBatchFileWriter,
type RecordBatchLike,
Table,
type TableLike,
TimestampMillisecond,
Utf8,
vectorFromArray,
} from "./arrow";
import { sanitizeTable } from "./sanitize";
/** Scalar SQL values. Use a one-row Arrow table for explicit Arrow types. */
export type QueryParameterValue =
| string
| number
| bigint
| boolean
| Date
| Uint8Array
| null;
/** Values for `$1`/`$name` placeholders, sent separately from SQL text.
* Arrays bind by position; objects bind by name. Arrow columns bind both ways.
* Safe integers and bigint use Int64; fractional numbers use Float64.
* Arrow input preserves explicit types.
*/
export type QueryParameters =
| readonly QueryParameterValue[]
| Readonly<Record<string, QueryParameterValue>>
| TableLike
| RecordBatchLike;
/** @internal */
export async function toParameterBuffer(
parameters: QueryParameters,
): Promise<Buffer> {
let table: Table;
if (
"schema" in parameters &&
parameters.schema !== null &&
typeof parameters.schema === "object" &&
"fields" in parameters.schema
) {
const arrow = parameters as TableLike | RecordBatchLike;
table = sanitizeTable(
"batches" in arrow ? arrow : { schema: arrow.schema, batches: [arrow] },
);
} else {
const entries = Array.isArray(parameters)
? parameters.map((value, index) => [String(index + 1), value] as const)
: Object.entries(parameters);
const columns = Object.fromEntries(
entries.map(([name, input]) => {
let value = input;
let type: DataType;
if (value === null) type = new Null();
else if (typeof value === "string") type = new Utf8();
else if (typeof value === "boolean") type = new Bool();
else if (typeof value === "number") {
if (
!Number.isFinite(value) ||
(Number.isInteger(value) && !Number.isSafeInteger(value))
) {
throw new Error(
"Numeric parameters must be finite and integers must be safe; use bigint for Int64",
);
}
type = Number.isInteger(value) ? new Int64() : new Float64();
if (Number.isInteger(value)) value = BigInt(value);
} else if (typeof value === "bigint") {
if (value < -(1n << 63n) || value >= 1n << 63n) {
throw new Error("bigint parameters must fit Int64");
}
type = new Int64();
} else if (value instanceof Date && Number.isFinite(value.getTime())) {
type = new TimestampMillisecond();
} else if (value instanceof Uint8Array) type = new Binary();
else
throw new Error(
"Query parameters must be scalar values or a one-row Arrow table",
);
return [name, vectorFromArray([value], type)];
}),
);
table = new Table(columns);
}
if (table.numRows !== 1) {
throw new Error(
`Query parameters must contain exactly one row, got ${table.numRows}`,
);
}
return Buffer.from(
await RecordBatchFileWriter.writeAll(table).toUint8Array(),
);
}
+30 -7
View File
@@ -71,6 +71,7 @@ import {
instanceOfFullTextQuery,
} from "./query";
import { sanitizeType } from "./sanitize";
import { QueryParameters, toParameterBuffer } from "./sql";
import { IntoSql, toSQL } from "./util";
export { IndexConfig } from "./native";
export {
@@ -179,6 +180,8 @@ export interface PrewarmDataOptions {
columns?: string[];
/** A single SQL predicate for conservative metadata pruning. */
filter?: string;
/** Typed positional or named filter values, sent separately from SQL. */
parameters?: QueryParameters;
/** Positive per-executor concurrency, at most 4294967295. */
concurrency?: number;
}
@@ -624,7 +627,8 @@ export abstract class Table {
*
* @example
* const job = await table.prewarmDataAsync({
* columns: ["video"], filter: "quality > 0.7", concurrency: 4,
* columns: ["video"], filter: "quality > $minimum",
* parameters: { minimum: 0.7 }, concurrency: 4,
* });
* await job.wait();
*/
@@ -643,7 +647,9 @@ export abstract class Table {
* with an unsupported-operation error.
*
* @example
* const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"});
* const plan = await table.explainPrewarmData({
* columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7},
* });
* console.log(plan.pruning.selectedFragments);
*/
async explainPrewarmData(
@@ -1668,9 +1674,10 @@ export class LocalTable extends Table {
async prewarmDataAsync(
options?: PrewarmDataOptions,
): Promise<Job<PrewarmDataResult>> {
validatePrewarmDataOptions(options);
return new Job(
await this.inner.prewarmDataAsync(options),
await this.inner.prewarmDataAsync(
await toNativePrewarmDataOptions(options),
),
decodePrewarmDataResult,
);
}
@@ -1678,8 +1685,11 @@ export class LocalTable extends Table {
async explainPrewarmData(
options?: PrewarmDataOptions,
): Promise<PrewarmDataPlan> {
validatePrewarmDataOptions(options);
return decodePrewarmDataPlan(await this.inner.explainPrewarmData(options));
return decodePrewarmDataPlan(
await this.inner.explainPrewarmData(
await toNativePrewarmDataOptions(options),
),
);
}
async waitForIndex(
@@ -2399,9 +2409,22 @@ function validateCompactionOptions(options?: CompactionOptions): void {
}
}
async function toNativePrewarmDataOptions(options?: PrewarmDataOptions) {
validatePrewarmDataOptions(options);
return options === undefined
? undefined
: {
...options,
parameters:
options.parameters === undefined
? undefined
: await toParameterBuffer(options.parameters),
};
}
function validatePrewarmDataOptions(options?: PrewarmDataOptions): void {
for (const key of Object.keys(options ?? {})) {
if (!["columns", "filter", "concurrency"].includes(key)) {
if (!["columns", "filter", "concurrency", "parameters"].includes(key)) {
throw new Error(`Unsupported data prewarm option: ${key}`);
}
}
+16
View File
@@ -33,6 +33,7 @@ pub struct PrewarmDataOptions {
pub columns: Option<Vec<String>>,
pub filter: Option<String>,
pub concurrency: Option<f64>,
pub parameters: Option<Buffer>,
}
impl PrewarmDataOptions {
@@ -40,6 +41,21 @@ impl PrewarmDataOptions {
let mut options =
lancedb::table::PrewarmDataOptions::new().columns(self.columns.unwrap_or_default());
options.filter = self.filter;
if let Some(parameters) = self.parameters {
let mut batches = ipc_file_to_batches(parameters.to_vec())
.and_then(|reader| {
reader
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(Into::into)
})
.map_err(|error| napi::Error::from_reason(error.to_string()))?;
if batches.len() != 1 || batches[0].num_rows() != 1 {
return Err(napi::Error::from_reason(
"prewarm parameters must contain one row in one batch",
));
}
options.parameters = Some(batches.remove(0));
}
if let Some(value) = self.concurrency {
if !value.is_finite() || value.fract() != 0.0 || value < 1.0 || value > u32::MAX as f64
{
+2
View File
@@ -651,6 +651,7 @@ class Table:
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[pa.RecordBatch] = None,
) -> str: ...
async def prewarm_data_async(
self,
@@ -658,6 +659,7 @@ class Table:
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[pa.RecordBatch] = None,
) -> Job: ...
async def list_indices(self) -> list[IndexConfig]: ...
async def tokenize(
+5 -2
View File
@@ -1738,8 +1738,11 @@ class DBConnection(EnforceOverrides):
parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10],
)
Parameters are supported in queries, not in DDL or DML. With or
without parameters, the server chooses whether to stream rows on the
Parameters are supported in queries and, on compatible Enterprise servers,
scalar filter values in ``PREWARM`` and ``EXPLAIN PREWARM``. Support for
other statement types depends on the server.
With or without parameters, the server chooses whether to stream rows on the
initial call or return a polling continuation. The reader follows
either path transparently. Dropping an unread handle or its reader
stops a directly streamed query; deferred execution requires explicit
+15 -3
View File
@@ -24,6 +24,7 @@ from typing import (
import warnings
from lancedb import __version__
from lancedb.sql import QueryParameters
from lancedb._blob import BlobFile
from lancedb._lancedb import (
@@ -1452,6 +1453,7 @@ class RemoteTable(Table):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> None:
"""Prewarm data for the table.
@@ -1474,6 +1476,9 @@ class RemoteTable(Table):
The columns to prewarm. If None, all columns are prewarmed.
filter: str, optional
A single SQL predicate for conservative metadata pruning.
parameters: sequence, mapping, or one-row Arrow batch/table, optional
Scalar values for ``$1``/``$name`` placeholders in ``filter``.
Values are sent separately from SQL; requires server support.
concurrency: int, optional
Positive per-executor warming concurrency; omitted uses the server default.
@@ -1483,7 +1488,9 @@ class RemoteTable(Table):
... ["payload"], filter="quality > 0.7", concurrency=4)
"""
return LOOP.run(
self._table.prewarm_data(columns, filter=filter, concurrency=concurrency)
self._table.prewarm_data(
columns, filter=filter, concurrency=concurrency, parameters=parameters
)
)
def explain_prewarm_data(
@@ -1492,6 +1499,7 @@ class RemoteTable(Table):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> PrewarmDataPlan:
"""Preview prewarm without submitting a warming job.
@@ -1500,7 +1508,7 @@ class RemoteTable(Table):
"""
return LOOP.run(
self._table.explain_prewarm_data(
columns, filter=filter, concurrency=concurrency
columns, filter=filter, concurrency=concurrency, parameters=parameters
)
)
@@ -1510,11 +1518,15 @@ class RemoteTable(Table):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> Job[PrewarmDataResult]:
return Job(
LOOP.run(
self._table.prewarm_data_async(
columns, filter=filter, concurrency=concurrency
columns,
filter=filter,
concurrency=concurrency,
parameters=parameters,
)
)
)
+48 -13
View File
@@ -47,6 +47,7 @@ from ._blob import (
)
from .types import BlobMode
from lancedb.arrow import peek_reader
from lancedb.sql import QueryParameters, to_parameter_batch
from lancedb.background_loop import LOOP, embedding_executor
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
from lancedb.job import AsyncJob, Job, _typed_job
@@ -2019,6 +2020,7 @@ class Table(ABC):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> None:
"""Submit remote data prewarm and return after acceptance.
@@ -2037,7 +2039,9 @@ class Table(ABC):
>>> table.prewarm_data( # doctest: +SKIP
... ["payload"], filter="quality > 0.7", concurrency=4)
"""
self.prewarm_data_async(columns, filter=filter, concurrency=concurrency)
self.prewarm_data_async(
columns, filter=filter, concurrency=concurrency, parameters=parameters
)
def explain_prewarm_data(
self,
@@ -2045,13 +2049,15 @@ class Table(ABC):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> PrewarmDataPlan:
"""Preview data prewarm without creating a warming job.
Accepts the same columns, filter, and concurrency as ``prewarm_data_async``
and uses the table handle's namespace and branch. Requires LanceDB
Enterprise with structured SQL previews, table Select, and database/namespace
Usage. Historical-version and Embedded handles are unsupported.
Accepts the same columns, filter, parameters, and concurrency as
``prewarm_data_async`` and uses the table handle's namespace and branch.
Requires LanceDB Enterprise with structured SQL previews, table Select,
and database/namespace Usage. Historical-version and Embedded handles
are unsupported.
Returns the source version, readable plan, and conservative pruning summary.
Unknown metrics remain None; selected ranges are not exact matching rows.
@@ -2060,7 +2066,7 @@ class Table(ABC):
Examples
--------
>>> plan = table.explain_prewarm_data( # doctest: +SKIP
... ["video"], filter="quality > 0.7")
... ["video"], filter="quality > $minimum", parameters={"minimum": 0.7})
>>> print(plan.pruning.selected_fragments) # doctest: +SKIP
"""
raise NotImplementedError(
@@ -2073,6 +2079,7 @@ class Table(ABC):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> Job[PrewarmDataResult]:
"""Submit a remote data-cache prewarm and return its durable job.
@@ -2080,6 +2087,8 @@ class Table(ABC):
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.
``parameters`` binds ``$1``/``$name`` values using a sequence, mapping,
or one-row Arrow batch/table. Values are sent separately from SQL.
``concurrency`` is a positive per-executor integer. Historical-version
handles are unsupported; call ``checkout_latest()`` first.
@@ -2097,7 +2106,8 @@ class Table(ABC):
Examples
--------
>>> job = table.prewarm_data_async( # doctest: +SKIP
... ["video"], filter="quality > 0.7", concurrency=4)
... ["video"], filter="quality > $min", parameters={"min": 0.7},
... concurrency=4)
>>> job.wait() # doctest: +SKIP
"""
raise NotImplementedError(
@@ -4977,6 +4987,7 @@ class LanceTable(Table):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> None:
"""
Prewarm data for the table.
@@ -5000,6 +5011,9 @@ class LanceTable(Table):
The columns to prewarm. If None, all columns are prewarmed.
filter: str, optional
A single SQL predicate for conservative metadata pruning.
parameters: sequence, mapping, or one-row Arrow batch/table, optional
Scalar values for ``$1``/``$name`` placeholders in ``filter``.
Values are sent separately from SQL; requires server support.
concurrency: int, optional
Positive per-executor warming concurrency; omitted uses the server default.
@@ -5009,7 +5023,9 @@ class LanceTable(Table):
... ["payload"], filter="quality > 0.7", concurrency=4)
"""
return LOOP.run(
self._table.prewarm_data(columns, filter=filter, concurrency=concurrency)
self._table.prewarm_data(
columns, filter=filter, concurrency=concurrency, parameters=parameters
)
)
def explain_prewarm_data(
@@ -5018,6 +5034,7 @@ class LanceTable(Table):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> PrewarmDataPlan:
"""Preview prewarm without submitting a warming job.
@@ -5026,7 +5043,7 @@ class LanceTable(Table):
"""
return LOOP.run(
self._table.explain_prewarm_data(
columns, filter=filter, concurrency=concurrency
columns, filter=filter, concurrency=concurrency, parameters=parameters
)
)
@@ -5036,11 +5053,15 @@ class LanceTable(Table):
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> Job[PrewarmDataResult]:
return Job(
LOOP.run(
self._table.prewarm_data_async(
columns, filter=filter, concurrency=concurrency
columns,
filter=filter,
concurrency=concurrency,
parameters=parameters,
)
)
)
@@ -7532,6 +7553,7 @@ class AsyncTable:
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> None:
"""
Prewarm data for the table.
@@ -7555,6 +7577,9 @@ class AsyncTable:
The columns to prewarm. If None, all columns are prewarmed.
filter: str, optional
A single SQL predicate for conservative metadata pruning.
parameters: sequence, mapping, or one-row Arrow batch/table, optional
Scalar values for ``$1``/``$name`` placeholders in ``filter``.
Values are sent separately from SQL; requires server support.
concurrency: int, optional
Positive per-executor warming concurrency; omitted uses the server default.
@@ -7563,7 +7588,9 @@ class AsyncTable:
>>> await table.prewarm_data( # doctest: +SKIP
... ["payload"], filter="quality > 0.7", concurrency=4)
"""
await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency)
await self.prewarm_data_async(
columns, filter=filter, concurrency=concurrency, parameters=parameters
)
async def explain_prewarm_data(
self,
@@ -7571,6 +7598,7 @@ class AsyncTable:
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> PrewarmDataPlan:
"""Preview prewarm without submitting a warming job.
@@ -7579,7 +7607,10 @@ class AsyncTable:
"""
return PrewarmDataPlan.from_json(
await self._inner.explain_prewarm_data(
columns, filter=filter, concurrency=concurrency
columns,
filter=filter,
concurrency=concurrency,
parameters=to_parameter_batch(parameters),
)
)
@@ -7589,6 +7620,7 @@ class AsyncTable:
*,
filter: Optional[str] = None,
concurrency: Optional[int] = None,
parameters: Optional[QueryParameters] = None,
) -> AsyncJob[PrewarmDataResult]:
"""Submit data prewarm and return a durable handle after acceptance.
@@ -7604,7 +7636,10 @@ class AsyncTable:
"""
return _typed_job(
await self._inner.prewarm_data_async(
columns, filter=filter, concurrency=concurrency
columns,
filter=filter,
concurrency=concurrency,
parameters=to_parameter_batch(parameters),
),
PrewarmDataResult.from_json,
)
+84
View File
@@ -8212,6 +8212,8 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod
{"concurrency": 2**32},
{"concurrency": True},
{"concurrency": 1.5},
{"parameters": [1]},
{"filter": "id > $1", "parameters": pa.table({"1": [1, 2]})},
],
)
@pytest.mark.parametrize(
@@ -8236,6 +8238,88 @@ def test_remote_data_prewarm_validates_before_submission(options, method):
assert not server.tickets
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"]
)
@pytest.mark.parametrize("named", [False, True])
async def test_prewarm_bound_parameters_reach_flight(asynchronous, method, named):
flight = pytest.importorskip("pyarrow.flight")
attack = "training' OR TRUE; DROP TABLE items; --"
class ParameterServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.calls = []
def do_exchange(self, context, descriptor, reader, writer):
self.calls.append((descriptor.command, reader.read_all()))
if method == "explain_prewarm_data":
result = pa.table(
{
"plan_type": ["logical_plan"],
"plan": [
json.dumps(
{
"format_version": 1,
"table_version": 42,
"plan": "metadata preview",
"pruning": {
"mode": "zonemap_ranges",
"input_fragments": 3,
"selected_fragments": 1,
"pruned_fragments": 2,
"selected_row_ranges": 2,
},
}
)
],
}
)
else:
result = pa.table(
{
"job_id": ["bound-job"],
"table_version": pa.array([42], pa.uint64()),
}
)
writer.begin(result.schema)
writer.write_table(result)
writer.close()
server = ParameterServer()
with _mock_remote_sql_connection(server, _create_table_handler) as kwargs:
parameters = {"min": 8, "tag": attack} if named else [8, attack]
predicate = "id >= $min AND tag = $tag" if named else "id >= $1 AND tag = $2"
if asynchronous:
db = await lancedb.connect_async(**kwargs)
table = await db.create_table("test", [{"id": 1}])
result = await getattr(table, method)(
["payload"], filter=predicate, parameters=parameters
)
else:
db = lancedb.connect(**kwargs)
table = db.create_table("test", [{"id": 1}])
result = getattr(table, method)(
["payload"], filter=predicate, parameters=parameters
)
if method == "prewarm_data":
assert result is None
elif method == "explain_prewarm_data":
assert result.table_version == 42
assert result.pruning.selected_fragments == 1
else:
assert result.id == "bound-job"
((command, received),) = server.calls
assert b"PREWARM" in command and predicate.encode() in command
if method == "explain_prewarm_data":
assert b"EXPLAIN (FORMAT JSON) PREWARM" in command
assert attack.encode() not in command
assert received.column(0).to_pylist() == [8]
assert received.column(1).to_pylist() == [attack]
def test_remote_data_prewarm_malformed_receipt_is_not_retried():
flight = pytest.importorskip("pyarrow.flight")
+6 -2
View File
@@ -1895,17 +1895,19 @@ impl Table {
})
}
#[pyo3(signature = (columns=None, *, filter=None, concurrency=None))]
#[pyo3(signature = (columns=None, *, filter=None, concurrency=None, parameters=None))]
pub fn prewarm_data_async<'py>(
self_: PyRef<'py, Self>,
columns: Option<Vec<String>>,
filter: Option<String>,
concurrency: Option<&Bound<'py, PyAny>>,
parameters: Option<PyArrowType<arrow::record_batch::RecordBatch>>,
) -> 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.parameters = parameters.map(|parameters| parameters.0);
options.concurrency = positive_u32_integer(concurrency, "concurrency")?;
future_into_py(self_.py(), async move {
let job = inner.prewarm_data_async(options).await.infer_error()?;
@@ -1913,17 +1915,19 @@ impl Table {
})
}
#[pyo3(signature = (columns=None, *, filter=None, concurrency=None))]
#[pyo3(signature = (columns=None, *, filter=None, concurrency=None, parameters=None))]
pub fn explain_prewarm_data<'py>(
self_: PyRef<'py, Self>,
columns: Option<Vec<String>>,
filter: Option<String>,
concurrency: Option<&Bound<'py, PyAny>>,
parameters: Option<PyArrowType<arrow::record_batch::RecordBatch>>,
) -> 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.parameters = parameters.map(|parameters| parameters.0);
options.concurrency = positive_u32_integer(concurrency, "concurrency")?;
future_into_py(self_.py(), async move {
let plan = inner.explain_prewarm_data(options).await.infer_error()?;
+4 -1
View File
@@ -381,7 +381,10 @@ impl ExecuteQueryAsyncBuilder {
///
/// Every placeholder needs a value and every parameter must be used by a
/// placeholder. Parameters are supported in queries (`SELECT`, and
/// `EXPLAIN` of one), not in DDL or DML, nor in table-function arguments.
/// `EXPLAIN` of one) and, on compatible Enterprise servers, filter values in
/// `PREWARM` and `EXPLAIN PREWARM`. Prewarm bindings must be scalars.
/// Support for other statements depends on the server; table-function
/// arguments do not accept parameters.
/// Do not follow a named placeholder directly with `$`: `$a$` starts a
/// dollar-quoted string.
///
+2 -2
View File
@@ -4789,7 +4789,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
.execute_prewarm(crate::database::ExecuteQueryRequest {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
parameters: options.parameters,
})
.await
.map_err(prewarm::map_error)?;
@@ -4828,7 +4828,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
.execute_prewarm(crate::database::ExecuteQueryRequest {
query: statement,
default_namespace_path: self.namespace.clone(),
parameters: None,
parameters: options.parameters,
})
.await
.map_err(prewarm::map_explain_error)?;
+33
View File
@@ -20,6 +20,14 @@ pub(super) fn statement(
if options.concurrency == Some(0) {
return Err(invalid("prewarm concurrency must be greater than 0"));
}
if let Some(parameters) = &options.parameters {
if options.filter.is_none() {
return Err(invalid("prewarm parameters require a filter"));
}
if parameters.num_rows() != 1 {
return Err(invalid("prewarm parameters must contain exactly one row"));
}
}
if let Some(filter) = &options.filter {
if filter.trim().is_empty() {
return Err(invalid("prewarm filter must not be empty"));
@@ -293,6 +301,31 @@ mod tests {
assert!(plan(&[batch(&valid), batch(&valid)]).is_err());
}
#[test]
fn bound_values_are_never_rendered_into_sql() {
let value = "training' OR TRUE; DROP TABLE clips; --";
let parameters = RecordBatch::try_from_iter(vec![(
"tag",
Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef,
)])
.unwrap();
let options = PrewarmDataOptions::new()
.filter("tag = $tag")
.parameters(parameters);
let sql = statement("clips", Some("experiment"), &options).unwrap();
assert!(sql.ends_with("WHERE tag = $tag"));
assert!(!sql.contains(value));
assert!(!format!("{options:?}").contains(value));
assert!(
statement(
"clips",
None,
&PrewarmDataOptions::new().parameters(options.parameters.unwrap())
)
.is_err()
);
}
#[test]
fn quotes_paths_branch_and_filter_without_changing_options() {
let options = PrewarmDataOptions::new()
+39 -2
View File
@@ -3,22 +3,40 @@
//! Options, previews, and results for data-cache prewarm.
/// Data prewarm settings for [`super::Table::prewarm_data_async`].
/// Data prewarm settings for [`super::Table::prewarm_data_async`] and
/// [`super::Table::explain_prewarm_data`].
///
/// 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)]
#[derive(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>,
/// One row of typed filter values. Column i binds `$<i + 1>` and a
/// nonnumeric column name also binds `$name`. Requires server support.
pub parameters: Option<arrow_array::RecordBatch>,
/// Positive per-executor warming concurrency. Omit for the server default.
pub concurrency: Option<u32>,
}
impl std::fmt::Debug for PrewarmDataOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PrewarmDataOptions")
.field("columns", &self.columns)
.field("filter", &self.filter)
.field("concurrency", &self.concurrency)
.field(
"parameter_count",
&self.parameters.as_ref().map(|batch| batch.num_columns()),
)
.finish()
}
}
impl PrewarmDataOptions {
/// Use server defaults and warm every column.
pub fn new() -> Self {
@@ -37,6 +55,25 @@ impl PrewarmDataOptions {
self
}
/// Bind scalar filter values without interpolating them into SQL text.
///
/// ```
/// # use lancedb::table::PrewarmDataOptions;
/// # use arrow_array::{ArrayRef, Int64Array, RecordBatch};
/// # use std::sync::Arc;
/// let values = RecordBatch::try_from_iter(vec![(
/// "minimum", Arc::new(Int64Array::from(vec![100])) as ArrayRef,
/// )]).unwrap();
/// let options = PrewarmDataOptions::new()
/// .columns(["payload"])
/// .filter("id >= $minimum")
/// .parameters(values);
/// ```
pub fn parameters(mut self, parameters: arrow_array::RecordBatch) -> Self {
self.parameters = Some(parameters);
self
}
/// Set positive per-executor warming concurrency.
pub fn concurrency(mut self, concurrency: u32) -> Self {
self.concurrency = Some(concurrency);