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
+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
{