Merge branch 'merge-insert-source-stats' into merge-insert-source-stats-bindings

# Conflicts:
#	nodejs/src/merge.rs
#	python/python/lancedb/merge.py
This commit is contained in:
Will Jones
2026-11-16 18:28:26 +00:00
218 changed files with 27953 additions and 2913 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "lancedb-nodejs"
edition.workspace = true
version = "0.42.0-beta.10"
version = "0.42.0-beta.16"
publish = false
license.workspace = true
description.workspace = true
+644
View File
@@ -0,0 +1,644 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { createHash } from "crypto";
import { getEventListeners } from "events";
import { createReadStream } from "fs";
import * as http from "http";
import { AddressInfo } from "net";
import {
Table as ArrowTable,
Binary,
Field,
LargeBinary,
Struct,
Uint8,
Uint32,
Uint64,
Utf8,
tableToIPC,
vectorFromArray,
} from "apache-arrow";
import { BlobRangeRequest, Connection, Table, connect } from "../lancedb";
jest.setTimeout(30000);
const IDENTITY = `v1:${"a".repeat(64)}`;
const MIB = 1024 * 1024;
type Range = {
// biome-ignore lint/style/useNamingConvention: Matches the server JSON contract.
row_id: number;
offset: number;
length: number;
};
type Request = {
column: string;
branch: string | null;
version: number | null;
ranges: Range[];
identity?: string;
};
function payload(row: number, offset: number, length: number, version: number) {
const bytes = Buffer.alloc(length);
for (let i = 0; i < length; i++) {
bytes[i] = (row * 17 + ((offset + i) % 251) + version) % 251;
}
return bytes;
}
async function withRangeServer(
run: (db: Connection, calls: Request[], paths: string[]) => Promise<void>,
fault?: string | number,
capability: string | null = "1",
onStall?: (response: http.ServerResponse) => void,
) {
let takes = 0;
let rangeReads = 0;
const calls: Request[] = [];
const paths: string[] = [];
const server = http.createServer((req, res) => {
req.setTimeout(15000);
paths.push(req.url ?? "");
if (
req.url === "/v1/table/test/describe/" ||
req.url === "/v1/table/test/branches/list/"
) {
res.writeHead(200, {
"Content-Type": "application/json",
"phalanx-version": "1.13.0-beta.0",
...(req.url.endsWith("/describe/") && capability !== null
? { "x-lancedb-blob-ranges": capability }
: {}),
});
const response = req.url.endsWith("branches/list/")
? {
branches: {
experiment: {
parentBranch: null,
parentVersion: 1,
createAt: 1,
manifestSize: 1,
},
},
}
: { version: 8, schema: { fields: [] } };
res.end(JSON.stringify(response));
return;
}
if (capability !== "1" && req.method === "GET") {
const url = new URL(req.url!, "http://localhost");
expect(url.searchParams.get("branch")).toBe("experiment");
expect(url.searchParams.get("version")).toBe("3");
const [start, end] = req.headers.range!.slice(6).split("-").map(Number);
const bytes = Buffer.from("alpha").subarray(start, end + 1);
res.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/5`,
"Content-Length": bytes.length,
"x-lancedb-version": "3",
});
if (fault === "stall-read" && ++rangeReads === 1) {
// Withhold the rest of the body so native completion cannot win the abort.
res.write(bytes.subarray(0, 1));
onStall?.(res);
return;
}
res.end(bytes);
return;
}
expect(req.method).toBe("POST");
expect(req.url).toBe(
capability === "1"
? "/v1/table/test/fetch_blob_ranges/"
: "/v1/table/test/query/",
);
const chunks: Buffer[] = [];
let size = 0;
req.on("data", (chunk: Buffer) => {
size += chunk.length;
expect(size).toBeLessThanOrEqual(256 * 1024);
chunks.push(chunk);
});
req.on("end", () => {
if (capability !== "1") {
const body = JSON.parse(Buffer.concat(chunks).toString()) as {
branch: string;
version: number;
filter: string;
};
expect(body.branch).toBe("experiment");
expect(body.version).toBe(3);
takes++;
const ids = (body.filter.match(/\d+/g) ?? [])
.map(Number)
.filter((id) => [10, 20, 40].includes(id))
.reverse();
const descriptor = new Struct([
new Field("kind", new Uint8(), false),
new Field("position", new Uint64(), false),
new Field("size", new Uint64(), false),
new Field("blob_id", new Uint32(), false),
new Field("blob_uri", new Utf8(), false),
]);
const arrow = new ArrowTable({
image: vectorFromArray(
ids.map((id) =>
id === 20
? null
: {
kind: 0,
position: 0n,
size: id === 40 ? 0n : 5n,
// biome-ignore lint/style/useNamingConvention: Arrow descriptor field.
blob_id: 0,
// biome-ignore lint/style/useNamingConvention: Arrow descriptor field.
blob_uri: "",
},
),
descriptor,
),
_rowid: vectorFromArray(ids.map(BigInt), new Uint64()),
});
expect(takes).toBeGreaterThan(0);
res
.writeHead(200, {
"Content-Type": "application/vnd.apache.arrow.stream",
"x-lancedb-version": "3",
})
.end(tableToIPC(arrow, "stream"));
return;
}
const body = JSON.parse(Buffer.concat(chunks).toString()) as Request;
body.identity = req.headers["x-lancedb-query-snapshot"] as
| string
| undefined;
calls.push(body);
expect(body.column).toBe("image");
expect(body.branch).toBe("experiment");
expect(body.ranges.length).toBeLessThanOrEqual(1024);
expect(
body.ranges.reduce((sum, range) => sum + range.length, 0),
).toBeLessThanOrEqual(64 * MIB);
const version = body.version ?? (calls.length === 1 ? 7 : 8);
const failure =
calls.length > 1 || String(fault).startsWith("first-")
? fault
: undefined;
if (failure === "recreated" || failure === "gone") {
res
.writeHead(failure === "recreated" ? 400 : 404)
.end("query snapshot identity mismatch: source gone or replaced");
return;
}
if (failure === "stall" && calls.length === 2) {
res.writeHead(200, {
"Content-Type": "application/vnd.apache.arrow.stream",
"x-lancedb-version": "7",
"x-lancedb-query-snapshot": IDENTITY,
});
res.flushHeaders();
onStall?.(res);
return;
}
if (typeof failure === "number") {
res.writeHead(failure).end("ordinary server failure");
return;
}
if (failure === "disconnect") {
req.socket.destroy();
return;
}
let values = body.ranges.map((range) =>
range.row_id === 20
? null
: payload(range.row_id, range.offset, range.length, version),
);
if (failure === "count") values = [];
if (failure === "length") values = [Buffer.alloc(0)];
const arrow = new ArrowTable({
[failure === "column" ? "wrong" : "value"]: vectorFromArray(
values,
failure === "type" ? new Binary() : new LargeBinary(),
),
});
let ipc = tableToIPC(arrow, "stream");
if (failure === "eos") ipc = ipc.subarray(0, ipc.length - 8);
if (failure === "body") ipc = ipc.subarray(0, Math.floor(ipc.length / 2));
res.writeHead(200, {
"Content-Type": "application/vnd.apache.arrow.stream",
connection: "close",
"Content-Length": ipc.length + (failure === "transport" ? 10 : 0),
...(failure === "version" ? {} : { "x-lancedb-version": version }),
...(["missing-identity", "first-missing-identity"].includes(
String(failure),
)
? {}
: {
"x-lancedb-query-snapshot":
failure === "wrong-identity"
? `v1:${"b".repeat(64)}`
: failure === "first-invalid-identity"
? "broken"
: IDENTITY,
}),
});
// Fragment the generated IPC payload across actual HTTP writes.
for (let i = 0; i < ipc.length; i += 8192)
res.write(ipc.subarray(i, i + 8192));
res.end();
});
});
server.listen(0, "127.0.0.1");
await new Promise<void>((resolve) => server.once("listening", resolve));
const port = (server.address() as AddressInfo).port;
const db = await connect("db://dev", {
apiKey: "fake",
hostOverride: `http://127.0.0.1:${port}`,
clientConfig: {
retryConfig: { retries: 2, connectRetries: 2, readRetries: 2 },
blobRequestConcurrency: 1,
timeoutConfig: { timeout: 20 },
},
});
try {
await run(db, calls, paths);
} finally {
await new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
});
}
}
async function open(db: Connection, version?: number): Promise<Table> {
return db.openTable("test", [], { branch: "experiment", version });
}
describe("fetchBlobRanges", () => {
it.each([null, "0", "2"])(
"uses old routes before data requests for capability %s",
async (capability) => {
await withRangeServer(
async (db, calls, paths) => {
// Reopening exercises both the initial and cached database describe paths.
for (let i = 0; i < 2; i++) {
const table = await open(db, 3);
const requests = [
{ rowId: 10n, offset: 1n, length: 3n },
{ rowId: 20n, offset: 0n, length: 1n },
{ rowId: 40n, offset: 0n, length: 0n },
{ rowId: 10n, offset: 5n, length: 0n },
{ rowId: 10n, offset: 1n, length: 3n },
];
expect(await table.fetchBlobRanges("image", requests)).toEqual([
Buffer.from("lph"),
null,
Buffer.alloc(0),
Buffer.alloc(0),
Buffer.from("lph"),
]);
for (const row of [
{ rowId: 10n, offset: 4n, length: 2n },
{ rowId: 99n, offset: 0n, length: 1n },
])
await expect(
table.fetchBlobRanges("image", [row]),
).rejects.toThrow();
const before = paths.length;
expect(await table.fetchBlobRanges("image", [])).toEqual([]);
expect(paths).toHaveLength(before);
}
expect(calls).toHaveLength(0);
expect(paths.some((path) => path.includes("fetch_blob_ranges"))).toBe(
false,
);
},
undefined,
capability,
);
},
);
it("renegotiates advertised support when reopening a cached table", async () => {
await withRangeServer(async (db, calls) => {
for (let i = 0; i < 2; i++) {
const table = await open(db);
expect(
await table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0n, length: 1n },
]),
).toEqual([payload(10, 0, 1, i === 0 ? 7 : 8)]);
}
expect(calls).toHaveLength(2);
});
});
it("cancels an in-flight BlobFile read and leaves the handle usable", async () => {
let responseTimedOut = false;
let markStalled!: () => void;
const stalled = new Promise<void>((resolve) => {
markStalled = resolve;
});
let markDisconnected!: () => void;
const disconnected = new Promise<void>((resolve) => {
markDisconnected = resolve;
});
await withRangeServer(
async (db) => {
const table = await open(db, 3);
const [handle] = await table.fetchBlobFiles("image", [10n]);
const controller = new AbortController();
try {
const pending = handle!.readRange(0n, handle!.size(), {
signal: controller.signal,
});
const rejected = expect(pending).rejects.toMatchObject({
name: "AbortError",
});
await stalled;
controller.abort();
await rejected;
await disconnected;
expect(responseTimedOut).toBe(false);
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
expect(handle!.isClosed()).toBe(false);
expect(await handle!.tell()).toBe(0n);
// The single request permit must also be released by cancellation.
expect(await handle!.readRange(0n, 5n)).toEqual(Buffer.from("alpha"));
} finally {
controller.abort();
await handle!.close();
}
},
"stall-read",
null,
(response) => {
response.once("timeout", () => {
responseTimedOut = true;
});
response.once("close", markDisconnected);
markStalled();
},
);
});
it("cancels while waiting for a later response body and releases the only permit", async () => {
let markStalled!: () => void;
const stalled = new Promise<void>((resolve) => {
markStalled = resolve;
});
await withRangeServer(
async (db, calls) => {
const table = await open(db);
const controller = new AbortController();
const pending = table.fetchBlobRanges(
"image",
Array.from({ length: 2049 }, () => ({
rowId: 10n,
offset: 0n,
length: 1n,
})),
{ signal: controller.signal },
);
const rejected = expect(pending).rejects.toMatchObject({
name: "AbortError",
});
await stalled;
controller.abort();
await rejected;
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
expect(calls).toHaveLength(2);
expect(
await table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0n, length: 1n },
]),
).toEqual([payload(10, 0, 1, 8)]);
expect(calls).toHaveLength(3);
},
"stall",
"1",
() => markStalled(),
);
});
it.each([undefined, 3])(
"preserves order, nulls, duplicates and snapshot (checkout %s)",
async (version) => {
await withRangeServer(async (db, calls, paths) => {
const table = await open(db, version);
const requests: BlobRangeRequest[] = Array.from(
{ length: 1025 },
(_, i) => ({
rowId: i % 9 === 0 ? 20 : 10 + (i % 7),
offset: BigInt(i),
length: BigInt(i % 4),
}),
);
requests.push(
{ rowId: 10n, offset: 0n, length: 0n },
{ rowId: 10n, offset: 2n, length: 3n },
{ rowId: 10n, offset: 2n, length: 3n },
);
const result = await table.fetchBlobRanges("image", requests);
expect(result).toEqual(
requests.map((range) =>
Number(range.rowId) === 20
? null
: payload(
Number(range.rowId),
Number(range.offset),
Number(range.length),
version ?? 7,
),
),
);
expect(calls.map((body) => body.version)).toEqual([
version ?? null,
version ?? 7,
]);
expect(
await table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0n, length: 1n },
]),
).toEqual([payload(10, 0, 1, version ?? 8)]);
expect(calls[2].version).toBe(version ?? null);
expect(
paths.filter((path) => path.endsWith("fetch_blob_ranges/")),
).toHaveLength(3);
});
},
);
it("partitions the byte budget and reassembles one range larger than 64 MiB", async () => {
await withRangeServer(async (db, calls) => {
const table = await open(db);
const requests = [
{ rowId: 10n, offset: 3n, length: BigInt(65 * MIB) },
{ rowId: 30n, offset: 7n, length: 2n },
];
const result = await table.fetchBlobRanges("image", requests);
for (const [i, range] of requests.entries()) {
expect(result[i]?.length).toBe(Number(range.length));
expect(
createHash("sha256")
.update(result[i] as Buffer)
.digest("hex"),
).toBe(
createHash("sha256")
.update(
payload(
Number(range.rowId),
Number(range.offset),
Number(range.length),
7,
),
)
.digest("hex"),
);
}
expect(calls).toHaveLength(2);
expect(calls.map((body) => body.version)).toEqual([null, 7]);
});
});
it.each([
"type",
"column",
"count",
"length",
"eos",
"body",
"transport",
"version",
"disconnect",
401,
403,
404,
429,
500,
])("rejects the whole call after a later %s failure", async (fault) => {
await withRangeServer(async (db, calls, paths) => {
const table = await open(db);
await expect(
table.fetchBlobRanges(
"image",
Array.from({ length: 1025 }, () => ({
rowId: 10n,
offset: 0n,
length: 1n,
})),
),
).rejects.toThrow();
expect(calls).toHaveLength(2);
expect(
paths.every(
(path) =>
path.endsWith("describe/") ||
path.endsWith("branches/list/") ||
path.endsWith("fetch_blob_ranges/"),
),
).toBe(true);
}, fault);
});
it.each(["missing-identity", "wrong-identity", "recreated", "gone"])(
"retains original identity through row and byte partitions (%s)",
async (fault) => {
for (const huge of [false, true]) {
await withRangeServer(async (db, calls) => {
const table = await open(db);
const requests = huge
? [{ rowId: 10n, offset: 0n, length: BigInt(64 * MIB + 1) }]
: Array.from({ length: 1025 }, () => ({
rowId: 10n,
offset: 0n,
length: 1n,
}));
await expect(
table.fetchBlobRanges("image", requests),
).rejects.toThrow();
expect(calls.map((call) => call.identity)).toEqual([
undefined,
IDENTITY,
]);
expect(calls.map((call) => call.version)).toEqual([null, 7]);
}, fault);
}
},
);
it.each(["first-missing-identity", "first-invalid-identity"])(
"requires a first authoritative bulk identity (%s)",
async (fault) => {
await withRangeServer(async (db, calls, paths) => {
const table = await open(db);
const before = paths.length;
await expect(
table.fetchBlobRanges(
"image",
Array.from({ length: 1025 }, () => ({
rowId: 10n,
offset: 0n,
length: 1n,
})),
),
).rejects.toThrow(/snapshot identity/);
expect(calls).toHaveLength(1);
expect(paths).toHaveLength(before + 1);
}, fault);
},
);
it("validates integers, overflow and cancellation and leaves empty calls at zero I/O", async () => {
await withRangeServer(async (db, calls, paths) => {
const table = await open(db);
const before = paths.length;
expect(await table.fetchBlobRanges("image", [])).toEqual([]);
for (const request of [
{ rowId: -1, offset: 0n, length: 1n },
{ rowId: 1.5, offset: 0n, length: 1n },
{ rowId: Number.MAX_SAFE_INTEGER + 1, offset: 0n, length: 1n },
{ rowId: -1n, offset: 0n, length: 1n },
{ rowId: 1n << 64n, offset: 0n, length: 1n },
{ rowId: 10n, offset: -1n, length: 1n },
{ rowId: 10n, offset: 0n, length: -1n },
{ rowId: 10n, offset: 0n, length: 1n << 64n },
{ rowId: 20n, offset: (1n << 64n) - 1n, length: 1n },
]) {
await expect(
table.fetchBlobRanges("image", [request]),
).rejects.toThrow();
}
// Runtime type validation must also reject a number passed as an offset.
await expect(
table.fetchBlobRanges("image", [
{ rowId: 10n, offset: 0 as unknown as bigint, length: 1n },
]),
).rejects.toThrow();
const controller = new AbortController();
controller.abort(new Error("cancelled by caller"));
await expect(
table.fetchBlobRanges(
"image",
[{ rowId: 10n, offset: 0n, length: 1n }],
{ signal: controller.signal },
),
).rejects.toThrow("cancelled by caller");
expect(paths).toHaveLength(before);
expect(calls).toHaveLength(0);
});
});
it("records the loaded native artifact", async () => {
const artifacts = Object.keys(require.cache).filter(
(path) => path.endsWith(".node") && path.includes("lancedb"),
);
expect(artifacts.length).toBeGreaterThan(0);
for (const path of artifacts) {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
console.log(
`loaded native artifact=${path} sha256=${hash.digest("hex")}`,
);
}
});
});
+520 -10
View File
@@ -483,6 +483,222 @@ describe("remote connection", () => {
expect(insertRequests).toBe(2);
});
it.each([
{ status: 429, retries: undefined, attempts: 2 },
{ status: 429, retries: 0, attempts: 1 },
{ status: 504, retries: undefined, attempts: 1 },
{ status: 504, retries: 0, attempts: 1 },
])("applies per-call add retries: %j", async (scenario) => {
let attempts = 0;
await withMockDatabase(
(req, res) => {
if (req.url?.endsWith("/describe/")) {
res.writeHead(200).end(
JSON.stringify({
version: 1,
schema: {
fields: [
{ name: "id", type: { type: "int64" }, nullable: true },
],
},
}),
);
return;
}
expect(req.url).toContain("/insert/");
req.resume();
req.on("end", () => {
attempts++;
res
.writeHead(attempts === 1 ? scenario.status : 200)
.end('{"version":2}');
});
},
async (db) => {
const table = await db.openTable("items");
const result = table.add([{ id: 1n }], { retries: scenario.retries });
if (scenario.attempts === 2) {
await expect(result).resolves.toMatchObject({ version: 2 });
} else {
await expect(result).rejects.toThrow();
}
for (const retries of [-1, 256, 1.5]) {
await expect(table.add([{ id: 2n }], { retries })).rejects.toThrow(
"retries must be an integer between 0 and 255",
);
}
},
{
clientConfig: {
retryConfig: {
retries: 3,
statuses: [429, 504],
backoffFactor: 0,
backoffJitter: 0,
},
},
},
);
expect(attempts).toBe(scenario.attempts);
});
it.each(
[409, 429, 502, 503, 504].flatMap((status) =>
[undefined, 0, 2].flatMap((retries) =>
[[], ["analytics", "features"]].map((namespacePath) => ({
status,
retries,
namespacePath,
})),
),
),
)("applies per-call merge retries: %j", async (scenario) => {
let attempts = 0;
const identifier = [...scenario.namespacePath, "items"].join("$");
const succeeds =
[409, 429].includes(scenario.status) && scenario.retries !== 0;
await withMockDatabase(
(req, res) => {
const url = new URL(req.url ?? "", "http://localhost");
if (url.pathname === `/v1/table/${identifier}/describe/`) {
res.writeHead(200).end(
JSON.stringify({
version: 1,
schema: {
fields: [
{ name: "id", type: { type: "int64" }, nullable: true },
],
},
}),
);
return;
}
const chunks: Buffer[] = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
try {
expect(url.pathname).toBe(`/v1/table/${identifier}/merge_insert/`);
expect(url.searchParams.get("use_index")).toBe("false");
expect(req.headers["x-request-timeout-ms"]).toBe("10000");
// Rust compresses the batches; Arrow JS can inspect the schema without a codec.
const reader = RecordBatchReader.from(Buffer.concat(chunks)).open();
expect(reader.schema.fields.map((field) => field.name)).toEqual([
"id",
]);
} finally {
attempts++;
res
.writeHead(attempts === 1 ? scenario.status : 200)
.end('{"version":2}');
}
});
},
async (db) => {
const table = await db.openTable("items", scenario.namespacePath);
const merge = table
.mergeInsert("id")
.whenNotMatchedInsertAll()
.useIndex(false);
const result = merge.execute([{ id: 1n }], {
timeoutMs: 10_000,
retries: scenario.retries,
});
if (succeeds) {
await expect(result).resolves.toMatchObject({ version: 2 });
} else {
await expect(result).rejects.toThrow();
}
},
{
clientConfig: {
retryConfig: {
retries: 3,
statuses: [409, 429, 502, 503, 504],
backoffFactor: 0,
backoffJitter: 0,
},
},
},
);
expect(attempts).toBe(succeeds ? 2 : 1);
});
it("isolates merge retry overrides across reused builders and reads", async () => {
let attempts = 0;
let readAttempts = 0;
await withMockDatabase(
(req, res) => {
if (req.url?.endsWith("/describe/")) {
res.writeHead(200).end(
JSON.stringify({
version: 1,
schema: {
fields: [
{ name: "id", type: { type: "int64" }, nullable: true },
],
},
}),
);
return;
}
req.resume();
req.on("end", () => {
if (req.url?.endsWith("/count_rows/")) {
readAttempts++;
res.writeHead(readAttempts % 2 ? 429 : 200).end("1");
} else {
attempts++;
res
.writeHead([1, 2, 4, 6].includes(attempts) ? 429 : 200)
.end('{"version":2}');
expect(req.url).toContain("/merge_insert/");
}
});
},
async (db) => {
const table = await db.openTable("items");
const merge = table.mergeInsert("id").whenNotMatchedInsertAll();
for (const retries of [
-1,
256,
1.5,
Number.NaN,
Number.POSITIVE_INFINITY,
]) {
await expect(
merge.execute([{ id: 1n }], { retries }),
).rejects.toThrow("retries must be an integer between 0 and 255");
}
expect(attempts).toBe(0);
await expect(
merge.execute([{ id: 1n }], { retries: 0 }),
).rejects.toThrow();
expect(attempts).toBe(1);
await expect(merge.execute([{ id: 1n }])).resolves.toMatchObject({
version: 2,
});
await expect(
merge.execute([{ id: 1n }], { retries: 255 }),
).resolves.toMatchObject({ version: 2 });
expect(attempts).toBe(5);
await expect(table.countRows()).resolves.toBe(1);
expect(readAttempts).toBe(2);
await expect(
table
.mergeInsert("id")
.whenNotMatchedInsertAll()
.execute([{ id: 1n }]),
).resolves.toMatchObject({ version: 2 });
expect(attempts).toBe(7);
},
{
clientConfig: {
retryConfig: { retries: 3, backoffFactor: 0, backoffJitter: 0 },
},
},
);
});
it("should accept partial connection options", async () => {
await connect("db://test", {
apiKey: "fake",
@@ -647,6 +863,100 @@ describe("remote connection", () => {
]);
});
it("passes a pinned version and decodes Function scheduler status", async () => {
const queries: Record<string, string>[] = [];
await withMockDatabase(
(req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
if (url.pathname.endsWith("/describe/")) {
res.writeHead(200, { "Content-Type": "application/json" }).end(
JSON.stringify({
name: "docs",
version: 42,
schema: { fields: [] },
}),
);
return;
}
if (url.pathname === "/v1/table/docs/function_columns/status") {
queries.push(Object.fromEntries(url.searchParams.entries()));
res.writeHead(200, { "Content-Type": "application/json" }).end(
`[{
"column":"embedding",
"binding_id":"fb_01",
"function":{
"name":"embed",
"object_id":"embed",
"location":"objects/embed",
"version":"7",
"manifest_digest":"sha256:abc"
},
"table_version":42,
"rows":4,
"fresh":2,
"stale":2,
"never_computed":0,
"failed":0,
"last_refresh_job":{
"job_id":"job-cancelled",
"state":"cancelled",
"automatic":true,
"completed_at_millis":1790000002000
},
"last_failure_job":{
"job_id":"job-failed",
"state":"failed",
"automatic":true,
"completed_at_millis":1790000001000,
"failure":{
"phase":"finalize",
"message":"worker timed out",
"traceback":"Traceback: timeout",
"retryable":true,
"sql_job_id":"sql-job-7"
}
},
"auto_refresh":{
"enabled":true,
"interval_seconds":60,
"active_job_id":"job-queued",
"state":"queued",
"failure_streak":1,
"next_run_at_millis":null,
"next_run_at_reason":"job_queued_not_started"
}
}]`,
);
return;
}
res.writeHead(404).end();
},
async (db) => {
const table = await db.openTable("docs");
await table.checkout(42);
const status = await table.functionColumnStatus("embedding");
expect(status.tableVersion).toBe(42n);
expect(status.autoRefresh.state).toBe("queued");
expect(status.autoRefresh.activeJobId).toBe("job-queued");
expect(status.autoRefresh.failureStreak).toBe(1);
expect(status.autoRefresh.nextRunAtReason).toBe(
"job_queued_not_started",
);
expect(status.lastRefreshJob?.state).toBe("cancelled");
expect(status.lastRefreshJob?.failure).toBeUndefined();
expect(status.lastFailureJob?.jobId).toBe("job-failed");
expect(status.lastFailureJob?.failure).toEqual({
phase: "finalize",
message: "worker timed out",
traceback: "Traceback: timeout",
retryable: true,
sqlJobId: "sql-job-7",
});
},
);
expect(queries).toEqual([{ column: "embedding", version: "42" }]);
});
it("forwards refresh options to the backfill request", async () => {
const bodies: unknown[] = [];
await withMockDatabase(
@@ -682,6 +992,7 @@ describe("remote connection", () => {
const job = await table.refreshColumnAsync("embedding", {
where: "id % 2 = 0",
batchSize: 16,
publicationIntervalRows: 60,
maxConcurrency: 3,
gpuClass: "a10g",
gpuCount: 2,
@@ -694,6 +1005,18 @@ describe("remote connection", () => {
});
expect(job.id).toBe("j-9");
await table.refreshColumnAsync("embedding");
await table.refreshColumnAsync("embedding", {
publicationIntervalRows: undefined,
});
for (const publicationIntervalRows of [
1,
2 ** 32 + 1,
Number.MAX_SAFE_INTEGER,
]) {
await table.refreshColumnAsync("embedding", {
publicationIntervalRows,
});
}
await table.refreshColumnAsync("embedding", {
resourceBudget: {
cpuMillis: 8_000,
@@ -705,6 +1028,14 @@ describe("remote connection", () => {
maxConcurrency: true as unknown as number,
}),
).rejects.toThrow();
for (const publicationIntervalRows of [true, "60", 60n]) {
await expect(
table.refreshColumnAsync("embedding", {
publicationIntervalRows:
publicationIntervalRows as unknown as number,
}),
).rejects.toThrow();
}
// Invalid options reject before any request is sent.
for (const [options, message] of [
[{ maxFailedRows: -1 }, "maxFailedRows"],
@@ -712,6 +1043,22 @@ describe("remote connection", () => {
[{ where: " " }, "where"],
[{ maxFailedFraction: 2 }, "max_failed_fraction"],
[{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"],
[{ publicationIntervalRows: 0 }, "publicationIntervalRows"],
[{ publicationIntervalRows: -1 }, "publicationIntervalRows"],
[{ publicationIntervalRows: 1.5 }, "publicationIntervalRows"],
[{ publicationIntervalRows: Number.NaN }, "publicationIntervalRows"],
[
{ publicationIntervalRows: Number.POSITIVE_INFINITY },
"publicationIntervalRows",
],
[
{ publicationIntervalRows: Number.NEGATIVE_INFINITY },
"publicationIntervalRows",
],
[
{ publicationIntervalRows: Number.MAX_SAFE_INTEGER + 1 },
"publicationIntervalRows",
],
[{ maxConcurrency: 1.5 }, "maxConcurrency"],
[{ maxConcurrency: 0 }, "maxConcurrency"],
[{ maxConcurrency: -1 }, "maxConcurrency"],
@@ -789,6 +1136,42 @@ describe("remote connection", () => {
},
"resourceBudget.gpuCount",
],
[
{
supervisorResources: {
cpuMillis: 0,
memoryBytes: 1_024,
ephemeralStorageBytes: 2_048,
},
},
"supervisorResources.cpuMillis",
],
[
{
supervisorResources: {
cpuMillis: 1_000,
memoryBytes: 1_024,
ephemeralStorageBytes: 0,
},
},
"supervisorResources.ephemeralStorageBytes",
],
[
{
planningWorkers: {
resources: {
cpuMillis: 1_000,
memoryBytes: 1_024,
ephemeralStorageBytes: 2_048,
},
maxWorkers: 0,
rowsPerWorker: 100,
fragmentsPerWorker: 1,
},
},
"planningWorkers.maxWorkers",
],
[{ retryPolicy: { maxAttempts: 0 } }, "retry_policy.max_attempts"],
] as const) {
await expect(
table.refreshColumnAsync("embedding", options),
@@ -799,6 +1182,7 @@ describe("remote connection", () => {
expect(bodies).toEqual([
JSON.parse(
`{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16,
"publication_interval_rows": 60,
"max_concurrency": 3, "gpu_class": "a10g", "gpu_count": 2,
"error_policy": "skip",
"max_failed_fraction": 0.01, "max_failed_rows": 50,
@@ -806,6 +1190,14 @@ describe("remote connection", () => {
"max_executor_processes_per_worker": 2}`,
),
{ column: "embedding" },
{ column: "embedding" },
JSON.parse('{"column": "embedding", "publication_interval_rows": 1}'),
JSON.parse(
'{"column": "embedding", "publication_interval_rows": 4294967297}',
),
JSON.parse(
'{"column": "embedding", "publication_interval_rows": 9007199254740991}',
),
JSON.parse(
`{"column": "embedding",
"resource_budget": {
@@ -817,6 +1209,91 @@ describe("remote connection", () => {
]);
});
it("forwards structured Function refresh options and Node retry policy", async () => {
const bodies: unknown[] = [];
await withMockDatabase(
(req, res) => {
const path = req.url ?? "";
if (path.endsWith("/describe/")) {
res.writeHead(200, { "Content-Type": "application/json" }).end(
JSON.stringify({
name: "docs",
version: 1,
schema: { fields: [] },
}),
);
return;
}
if (path === "/v1/table/docs/backfill_column") {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
bodies.push(JSON.parse(body));
res
.writeHead(202, { "Content-Type": "application/json" })
.end('{"job_id": "j-structured"}');
});
return;
}
res.writeHead(404).end();
},
async (db) => {
const table = await db.openTable("docs");
const job = await table.refreshColumnAsync("embedding", {
supervisorResources: {
cpuMillis: 2_000,
memoryBytes: 4 * 1024 ** 3,
ephemeralStorageBytes: 10 * 1024 ** 3,
},
planningWorkers: {
resources: {
cpuMillis: 1_000,
memoryBytes: 2 * 1024 ** 3,
ephemeralStorageBytes: 5 * 1024 ** 3,
},
maxWorkers: 4,
rowsPerWorker: 100_000,
fragmentsPerWorker: 8,
},
retryPolicy: { transient: true },
});
expect(job.id).toBe("j-structured");
},
);
expect(bodies).toEqual([
{
column: "embedding",
["supervisor_resources"]: {
["cpu_millis"]: 2_000,
["memory_bytes"]: 4 * 1024 ** 3,
["ephemeral_storage_bytes"]: 10 * 1024 ** 3,
},
["planning_workers"]: {
resources: {
["cpu_millis"]: 1_000,
["memory_bytes"]: 2 * 1024 ** 3,
["ephemeral_storage_bytes"]: 5 * 1024 ** 3,
},
["max_workers"]: 4,
["rows_per_worker"]: 100_000,
["fragments_per_worker"]: 8,
},
["retry_policy"]: {
["max_attempts"]: 3,
["initial_backoff_seconds"]: 0.2,
["max_backoff_seconds"]: 30,
["exception_types"]: [],
["message_pattern"]: null,
["error_codes"]: [],
transient: true,
["honor_retry_after"]: true,
},
},
]);
});
it("surfaces JSON server errors from remote table operations", async () => {
await withMockDatabase(
(req, res) => {
@@ -1841,10 +2318,30 @@ describe("remote connection jobs surface", () => {
queue_reason: "Waiting for Function worker capacity",
});
const descriptions = [
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 3000, unknownFleet)}}`,
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 2000, knownFleet)}}`,
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(40, 60, 1000, unknownFleet)}}`,
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(60, 0, 0, unknownFleet)}}`,
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
20,
80,
3000,
unknownFleet,
)}}`,
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
20,
80,
2000,
knownFleet,
)}}`,
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
40,
60,
1000,
unknownFleet,
)}}`,
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(
60,
0,
0,
unknownFleet,
)}}`,
];
let describeCount = 0;
@@ -1916,12 +2413,24 @@ describe("remote connection jobs surface", () => {
it("does not derive ETA across a zero-rate, epoch, or pause boundary", async () => {
const now = Date.now();
const descriptions = [
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 5000}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 4000}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 3000}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 2000}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1500}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1000}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${
now - 5000
}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${
now - 4000
}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
now - 3000
}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
now - 2000
}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
now - 1500
}}}`,
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
now - 1000
}}}`,
];
await withMockDatabase(
@@ -2097,6 +2606,7 @@ describe("lazy resource listings", () => {
if (kind === "jobs") {
expect(url.pathname).toBe("/v1/jobs/list");
expect(request.body).toEqual({
database: "dev",
// biome-ignore lint/style/useNamingConvention: server wire format
page_token: token,
limit: 2,
@@ -0,0 +1,642 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { type Table, connect } from "../lancedb";
import {
Table as ArrowTable,
DataType,
Field,
Float32,
LargeBinary,
RecordBatch,
Schema,
Struct,
Uint8,
Uint32,
Uint64,
Utf8,
makeArrowTable,
tableToIPC,
vectorFromArray,
} from "../lancedb/arrow";
const IDENTITY_A = `v1:${"a".repeat(64)}`;
const IDENTITY_B = `v1:${"b".repeat(64)}`;
const image = new Field(
"image",
new Struct([
new Field("kind", new Uint8(), false),
new Field("position", new Uint64(), true),
new Field("size", new Uint64(), true),
new Field("blob_id", new Uint32(), false),
new Field("blob_uri", new Utf8(), false),
]),
true,
// Native descriptor scans replace the logical extension metadata.
new Map([
["lance-encoding:blob", "true"],
["lance-encoding:packed", "true"],
]),
);
const schema = new Schema([new Field("label", new Utf8(), false), image]);
const description = {
fields: [
{ name: "label", type: { type: "string" }, nullable: false },
{
name: "image",
nullable: true,
metadata: { "ARROW:extension:name": "lance.blob.v2" },
type: {
type: "struct",
fields: ["position", "size"].map((name) => ({
name,
type: { type: "uint64" },
nullable: true,
})),
},
},
],
};
type Request = {
path: string;
body: Record<string, unknown>;
raw: string;
identity: string | string[] | undefined;
};
interface ServerOptions {
queryBlob?: Field;
describeBlobName?: string | null;
nestedBlob?: boolean;
queryVersion?: string | null;
queryIdentity?: string | null;
echo?: string | null;
empty?: boolean;
values?: boolean;
advanceQueries?: boolean;
otherLegIdentity?: string | null;
otherLegVersion?: string;
}
// A real HTTP service: the query finishes on A, then the logical table changes
// before the deferred blob request. Recreating B reuses both version and row IDs.
async function withSnapshotServer(
change: "recreate" | "overwrite",
run: (table: Table, requests: Request[]) => Promise<void>,
options: ServerOptions = {},
) {
const requests: Request[] = [];
let changed = false;
const queryBlob = options.queryBlob ?? image;
const queryOutputSchema = options.nestedBlob
? new Schema([
schema.fields[0],
new Field("extra", new Struct([queryBlob]), true),
])
: new Schema([schema.fields[0], queryBlob]);
const server = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
try {
const raw = Buffer.concat(chunks).toString() || "{}";
const body = JSON.parse(raw);
const path = req.url ?? "";
const identity = req.headers["x-lancedb-query-snapshot"];
requests.push({ path, body, raw, identity });
res.setHeader("phalanx-version", "0.5.0");
if (path.endsWith("/describe/")) {
res.setHeader("content-type", "application/json");
res.end(
JSON.stringify({
version: changed && change === "overwrite" ? 2 : 1,
schema: {
fields: description.fields.flatMap((field) => {
if (field.name !== "image") return [field];
if (options.describeBlobName === null) return [];
return [
{ ...field, name: options.describeBlobName ?? "image" },
];
}),
},
}),
);
} else if (path.endsWith("/query/")) {
const vector = (body.vector?.length ?? 0) > 0;
const advanced = options.advanceQueries === true && changed;
const label = advanced ? "B" : "A";
const columns: [string, string][] =
body.columns === undefined
? queryOutputSchema.fields.map((field) => [
field.name,
field.name,
])
: Array.isArray(body.columns)
? body.columns.map((name: string) => [name, name])
: Object.entries(body.columns);
const queryFields = columns.map(([output, source]) =>
queryOutputSchema.fields
.find((field) => field.name === source)!
.clone({ name: output }),
);
if (body.with_row_id) {
queryFields.push(new Field("_rowid", new Uint64(), false));
}
if (vector || body.full_text_query) {
queryFields.push(
new Field(vector ? "_distance" : "_score", new Float32(), false),
);
}
// Forged IPC metadata must never substitute for authoritative headers.
const querySchema = new Schema(
queryFields,
new Map([
["lancedb:query_version", "999"],
["lancedb:query_snapshot", IDENTITY_B],
]),
);
const values = options.empty
? []
: options.values
? ["A", null, ""]
: [label];
const rows = values.map((value, index) => {
const row: Record<string, unknown> = {};
for (const [output, source] of columns) {
const descriptor =
value === null
? null
: {
kind: 0,
position: 0n,
size: BigInt(value.length),
// biome-ignore lint/style/useNamingConvention: Native Arrow field name.
blob_id: 0,
// biome-ignore lint/style/useNamingConvention: Native Arrow field name.
blob_uri: "",
};
row[output] =
source === "image"
? descriptor
: source === "extra"
? descriptor === null
? null
: { image: descriptor }
: label;
}
if (body.with_row_id) row._rowid = BigInt(index);
if (vector || body.full_text_query) {
row[vector ? "_distance" : "_score"] = 0.5;
}
return row;
});
const result =
rows.length === 0
? new ArrowTable(querySchema)
: new ArrowTable(
querySchema,
Object.fromEntries(
queryFields.map((field) => [
field.name,
vectorFromArray(
rows.map((row) => row[field.name]),
field.type,
),
]),
),
);
res.setHeader("content-type", "application/vnd.apache.arrow.stream");
const version =
vector && options.otherLegVersion !== undefined
? options.otherLegVersion
: options.queryVersion;
const snapshot =
vector && options.otherLegIdentity !== undefined
? options.otherLegIdentity
: options.queryIdentity;
res.setHeader("x-lancedb-version", "1");
if (version !== null) {
res.setHeader(
"x-lancedb-query-version",
version ?? (advanced ? "2" : "1"),
);
}
if (snapshot !== null) {
res.setHeader(
"x-lancedb-query-snapshot",
snapshot ?? (advanced ? IDENTITY_B : IDENTITY_A),
);
}
changed = true;
res.end(tableToIPC(result, "stream"));
} else if (path.endsWith("/fetch_blobs/")) {
const requestedVersion = /"version":([0-9]+)/.exec(raw)?.[1];
const readsOriginal =
change === "overwrite" &&
requestedVersion === (options.queryVersion ?? "1");
const actualIdentity = readsOriginal ? IDENTITY_A : IDENTITY_B;
// An older serving node may ignore the guard and answer successfully;
// its echo must still be verified before the client uses any bytes.
if (options.echo !== null) {
res.setHeader(
"x-lancedb-query-snapshot",
options.echo ?? actualIdentity,
);
}
res.setHeader("content-type", "application/vnd.apache.arrow.stream");
const payloads = options.values
? ["A", null, ""]
: [readsOriginal ? "A" : "B"];
res.end(
tableToIPC(
makeArrowTable(
(body.row_ids as number[]).map((id) => ({
[String(body.column)]:
payloads[id] === null ? null : Buffer.from(payloads[id]!),
})),
{
schema: new Schema([
new Field(String(body.column), new LargeBinary(), true),
]),
},
),
"stream",
),
);
} else {
res.writeHead(404).end(path);
}
} catch (error) {
res.writeHead(500).end(String(error));
}
});
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
try {
const db = await connect("db://dev", {
apiKey: "fake",
hostOverride: `http://127.0.0.1:${
(server.address() as AddressInfo).port
}`,
});
await run(await db.openTable("test"), requests);
} finally {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}
const fetchRequests = (requests: Request[]) =>
requests.filter((request) => request.path.endsWith("/fetch_blobs/"));
const queryRequests = (requests: Request[]) =>
requests.filter((request) => request.path.endsWith("/query/"));
const keepFtsReranker = {
async rerankHybrid(_query: string, _vector: RecordBatch, fts: RecordBatch) {
const fields = fts.schema.fields.map((field) =>
field.name === "_score"
? field.clone({ name: "_relevance_score" })
: field,
);
return new RecordBatch(
new Schema(fields, fts.schema.metadata),
fts.data.clone(new Struct(fields)),
);
},
};
describe("remote blob query snapshot", () => {
it.each([
image.clone({ metadata: new Map() }),
new Field(
"image",
new Struct(image.type.children.slice(1, 3)),
true,
image.metadata,
),
])(
"leaves plain structs and v1 descriptors unchanged: %s",
async (queryBlob) => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const result = await table.query().toArrow({ blobMode: "bytes" });
expect(DataType.isStruct(result.getChild("image")!.type)).toBe(true);
expect(result.toArray()[0].image.size).toBe(1n);
expect(fetchRequests(requests)).toHaveLength(0);
},
{ queryBlob },
);
},
);
it("still recognizes extension-marked Blob results", async () => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const rows = await table.query().toArray({ blobMode: "bytes" });
expect(Buffer.from(rows[0].image).toString()).toBe("A");
expect(fetchRequests(requests)).toHaveLength(1);
},
{
queryBlob: image.clone({
metadata: new Map([["ARROW:extension:name", "lance.blob.v2"]]),
}),
},
);
});
it.each([
[null, false],
[null, true],
["old_image", false],
["old_image", true],
] as const)(
"uses the query schema after cached blob %s changes (alias: %s)",
async (describeBlobName, alias) => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
expect(await table.blobColumns()).toEqual(
describeBlobName === null ? [] : [describeBlobName],
);
const query = table.query();
if (alias) query.select({ "photo.image": "image" });
const output = alias ? "photo.image" : "image";
const result = await query.toArrow({ blobMode: "bytes" });
expect(DataType.isLargeBinary(result.getChild(output)!.type)).toBe(
true,
);
expect(
result
.toArray()
.map((row) =>
row[output] === null
? null
: Buffer.from(row[output]).toString(),
),
).toEqual(["A", null, ""]);
expect(
result.schema.fields.some((field) => field.name === "_rowid"),
).toBe(false);
expect(queryRequests(requests)).toHaveLength(1);
expect(fetchRequests(requests)).toHaveLength(1);
expect(fetchRequests(requests)[0].body.column).toBe("image");
expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
},
{ describeBlobName, values: true },
);
},
);
it("maps nested query fields through literal aliases despite a stale schema", async () => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
expect(await table.blobColumns()).toEqual([]);
const rows = await table
.query()
.select({ "container.alias": "extra" })
.toArray({ blobMode: "bytes" });
expect(
rows.map((row) =>
row["container.alias"] === null
? null
: Buffer.from(row["container.alias"].image).toString(),
),
).toEqual(["A", null, ""]);
expect(queryRequests(requests)).toHaveLength(1);
expect(fetchRequests(requests)[0].body.column).toBe("extra.image");
expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
},
{ nestedBlob: true, describeBlobName: null, values: true },
);
});
it.each(["toArrow", "toArray"] as const)(
"%s rejects payloads from a recreated table with reused version and row IDs",
async (terminal) => {
await withSnapshotServer("recreate", async (table, requests) => {
await expect(
table.query()[terminal]({ blobMode: "bytes" }),
).rejects.toThrow(/snapshot identity/);
const [fetch] = fetchRequests(requests);
expect(fetch.body.version).toBe(1);
expect(fetch.body.row_ids).toEqual([0]);
expect(fetch.body.column).toBe("image");
expect(fetch.identity).toBe(IDENTITY_A);
});
},
);
it("keeps the producing snapshot after an overwrite without rerunning the query", async () => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const rows = await table.query().toArray({ blobMode: "bytes" });
expect(rows[0].label).toBe("A");
expect(Buffer.from(rows[0].image).toString()).toBe("A");
expect(queryRequests(requests)).toHaveLength(1);
const [fetch] = fetchRequests(requests);
expect(fetch.body.version).toBe(1);
expect(fetch.identity).toBe(IDENTITY_A);
expect(await table.version()).toBe(2);
const [latest] = await table.query().toArray({ blobMode: "bytes" });
expect(latest.label).toBe("B");
expect(Buffer.from(latest.image).toString()).toBe("B");
expect(fetchRequests(requests)[1].identity).toBe(IDENTITY_B);
},
{ advanceQueries: true },
);
});
it.each<ServerOptions>([
{ queryVersion: null },
{ queryVersion: "0" },
{ queryVersion: "18446744073709551616" },
{ queryVersion: "invalid" },
{ queryIdentity: null },
{ queryIdentity: "v2:unsupported" },
])("refuses bytes without authoritative capability %j", async (options) => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const [descriptor] = await table.query().toArray();
expect(descriptor.image.size).toBe(1n);
await expect(
table.query().toArray({ blobMode: "bytes" }),
).rejects.toThrow(/blobMode.*bytes.*requires.*snapshot/);
expect(fetchRequests(requests)).toHaveLength(0);
},
options,
);
});
it("rejects a serving node without the snapshot echo", async () => {
await withSnapshotServer(
"overwrite",
async (table) => {
await expect(
table.query().toArray({ blobMode: "bytes" }),
).rejects.toThrow(/snapshot identity/);
},
{ echo: null },
);
});
it("keeps aliases, NULL, empty bytes, and explicit row IDs", async () => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const query = table
.query()
.select({ caption: "label", "photo.image": "image" });
const rows = await query.withRowId().toArray({ blobMode: "bytes" });
expect(rows.map((row) => row._rowid)).toEqual([0n, 1n, 2n]);
expect(
rows.map((row) =>
row["photo.image"] === null
? null
: Buffer.from(row["photo.image"]).toString(),
),
).toEqual(["A", null, ""]);
expect(rows[0].caption).toBe("A");
expect(fetchRequests(requests)[0].body.column).toBe("image");
const [descriptor] = await query.toArray();
expect(descriptor["photo.image"].size).toBe(1n);
},
{ values: true },
);
});
it("preserves an empty bytes schema without fetching payloads", async () => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const result = await table.query().toArrow({ blobMode: "bytes" });
expect(result.numRows).toBe(0);
expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe(
true,
);
expect(result.schema.fields.map((field) => field.name)).toEqual([
"label",
"image",
]);
expect(fetchRequests(requests)).toHaveLength(0);
},
{ empty: true },
);
});
it("passes the query version without rounding through a JS number", async () => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
await table.query().toArray({ blobMode: "bytes" });
expect(fetchRequests(requests)[0].raw).toContain(
'"version":9007199254740993',
);
},
{ queryVersion: "9007199254740993" },
);
});
it.each(["vector", "hybrid"])(
"materializes the actual %s query entry point",
async (kind) => {
await withSnapshotServer("overwrite", async (table, requests) => {
const query = table.query().nearestTo([0.1, 0.2]);
if (kind === "hybrid") query.fullTextSearch("A");
const rows = await query.toArray({ blobMode: "bytes" });
expect(Buffer.from(rows[0].image).toString()).toBe("A");
expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A);
expect(queryRequests(requests)).toHaveLength(kind === "hybrid" ? 2 : 1);
});
},
);
it("allows scalar-only bytes queries on older servers", async () => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const [row] = await table
.query()
.select(["label"])
.toArray({ blobMode: "bytes" });
expect(row.label).toBe("A");
expect(Object.keys(row)).toEqual(["label"]);
expect(fetchRequests(requests)).toHaveLength(0);
// Row IDs are requested before the executed output schema is known,
// then hidden from scalar-only results without requiring capability.
expect(queryRequests(requests)[0].body.with_row_id).toBe(true);
},
{ queryIdentity: null, queryVersion: null },
);
});
it.each([false, true])(
"preserves snapshot proof across a custom reranker (empty: %s)",
async (empty) => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const result = await table
.query()
.nearestTo([0.1, 0.2])
.fullTextSearch("A")
.rerank(keepFtsReranker)
.toArrow({ blobMode: "bytes" });
expect(result.numRows).toBe(empty ? 0 : 1);
expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe(
true,
);
expect(fetchRequests(requests)).toHaveLength(empty ? 0 : 1);
},
{ empty },
);
},
);
it("does not trust a custom reranker's first-leg snapshot when the legs disagree", async () => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const query = table
.query()
.nearestTo([0.1, 0.2])
.fullTextSearch("A")
.rerank(keepFtsReranker);
await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow(
/snapshot/,
);
expect(fetchRequests(requests)).toHaveLength(0);
},
{ otherLegIdentity: IDENTITY_B },
);
});
it.each<ServerOptions>([
{ otherLegIdentity: IDENTITY_B },
{ otherLegIdentity: null },
{ otherLegVersion: "2" },
])(
"refuses hybrid bytes when its actual query legs disagree %j",
async (options) => {
await withSnapshotServer(
"overwrite",
async (table, requests) => {
const query = table.query().nearestTo([0.1, 0.2]).fullTextSearch("A");
await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow(
/snapshot/,
);
expect(fetchRequests(requests)).toHaveLength(0);
expect(await query.toArray()).toHaveLength(1);
},
options,
);
},
);
});
+2 -2
View File
@@ -282,7 +282,7 @@ maybeDescribe("DynamoDB Lock", () => {
});
it("can be used to configure a DynamoDB table for commit log", async () => {
const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`;
const uri = `s3+ddb://${bucket.name}/concurrent-appends?ddbTableName=${commitTable.name}`;
const db = await connect(uri, {
storageOptions: CONFIG,
readConsistencyInterval: 0,
@@ -307,7 +307,7 @@ maybeDescribe("DynamoDB Lock", () => {
});
it("clears dynamodb state after dropping all tables", async () => {
const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`;
const uri = `s3+ddb://${bucket.name}/drop-all-tables?ddbTableName=${commitTable.name}`;
const db = await connect(uri, {
storageOptions: CONFIG,
readConsistencyInterval: 0,
+72 -24
View File
@@ -938,7 +938,8 @@ describe("merge insert", () => {
.mergeInsert("a")
.whenMatchedUpdateAll()
.whenNotMatchedInsertAll()
.execute(newData, { timeoutMs: 10_000 });
.useIndex(false)
.execute(newData, { timeoutMs: 10_000, retries: 0 });
expect(mergeInsertRes).toHaveProperty("version");
expect(mergeInsertRes.version).toBe(2);
expect(mergeInsertRes.numInsertedRows).toBe(1);
@@ -3029,6 +3030,43 @@ describe("when dealing with blob columns", () => {
expect(bytes.map((b) => b?.toString())).toEqual(["new", "hi"]);
});
it("fetchBlobRanges reads local ranges with order, duplicates, nulls and validation", async () => {
const { table, rowIds } = await openBlobTable();
const [alphaId, betaId, nullId] = rowIds;
const requests = [
{ rowId: betaId, offset: 1n, length: 3n },
{ rowId: alphaId, offset: 0n, length: 2n },
{ rowId: nullId, offset: 0n, length: 1n },
{ rowId: alphaId, offset: 5n, length: 0n },
{ rowId: betaId, offset: 1n, length: 3n },
];
expect(await table.fetchBlobRanges("image", requests)).toEqual([
Buffer.from("eta"),
Buffer.from("al"),
null,
Buffer.alloc(0),
Buffer.from("eta"),
]);
expect(await table.fetchBlobRanges("image", [])).toEqual([]);
await expect(
table.fetchBlobRanges("image", [
{ rowId: alphaId, offset: 4n, length: 2n },
]),
).rejects.toThrow();
await expect(
table.fetchBlobRanges("image", [
{ rowId: (1n << 63n) - 1n, offset: 0n, length: 1n },
]),
).rejects.toThrow();
const controller = new AbortController();
expect(
await table.fetchBlobRanges("image", requests, {
signal: controller.signal,
}),
).toHaveLength(5);
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
});
it("discovers blob columns", async () => {
const { table } = await openBlobTable();
expect(await table.blobColumns()).toEqual(["image"]);
@@ -3244,29 +3282,6 @@ describe("when dealing with blob columns", () => {
expect(await handle!.read()).toEqual(alpha);
});
it("cancels an in-flight read", async () => {
const db = await connect(tmpDir.name);
const schema = new Schema([
new Field("id", new Int64(), true),
blob("payload", { inlineSizeThreshold: 0, dedicatedSizeThreshold: 1 }),
]);
const payload = Buffer.alloc(32 * 1024 * 1024, 7);
const table = await db.createTable("large_blobs", [{ id: 1n, payload }], {
schema,
});
const [row] = await table.query().withRowId().toArray();
const [handle] = await table.fetchBlobFiles("payload", [
row._rowid as bigint,
]);
const controller = new AbortController();
const pending = handle!.readRange(0n, handle!.size(), {
signal: controller.signal,
});
controller.abort();
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
expect(await handle!.readRange(0n, 4n)).toEqual(payload.subarray(0, 4));
});
it("toArrow returns blob bytes with blobMode bytes", async () => {
const { table, alpha, beta } = await openBlobTable();
const result = await table.query().toArrow({ blobMode: "bytes" });
@@ -5696,6 +5711,14 @@ describe("computed columns", () => {
await expect(
table.refreshColumnAsync("x", { errorPolicy: "skip" }),
).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh");
for (const refresh of [
() => table.refreshColumn("x", { publicationIntervalRows: 60 }),
() => table.refreshColumnAsync("x", { publicationIntervalRows: 60 }),
]) {
await expect(refresh()).rejects.toThrow(
"publication_interval_rows requires a LanceDB Enterprise refresh",
);
}
await expect(
table.refreshColumnAsync("x", { maxConcurrency: 4 }),
).rejects.toThrow("max_concurrency requires a LanceDB Enterprise refresh");
@@ -5704,6 +5727,31 @@ describe("computed columns", () => {
resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 },
}),
).rejects.toThrow("resource_budget requires a LanceDB Enterprise refresh");
await expect(
table.refreshColumn("x", {
supervisorResources: {
cpuMillis: 1_000,
memoryBytes: 1_024,
ephemeralStorageBytes: 2_048,
},
}),
).rejects.toThrow(
"supervisor_resources requires a LanceDB Enterprise refresh",
);
await expect(
table.refreshColumnAsync("x", {
planningWorkers: {
resources: {
cpuMillis: 1_000,
memoryBytes: 1_024,
ephemeralStorageBytes: 2_048,
},
maxWorkers: 2,
rowsPerWorker: 100,
fragmentsPerWorker: 1,
},
}),
).rejects.toThrow("planning_workers requires a LanceDB Enterprise refresh");
});
it("records Function errors only on remote tables", async () => {
+51 -1
View File
@@ -1,7 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { Field, LargeBinary, Struct, Uint64, Utf8 } from "apache-arrow";
import {
DataType,
Field,
LargeBinary,
Struct,
Uint64,
Utf8,
} from "apache-arrow";
import { BlobFile as NativeBlobFile } from "./native";
const BLOB_V2_EXTENSION_NAME = "lance.blob.v2";
@@ -178,6 +185,39 @@ export function isBlobField(field: Field): boolean {
return field.metadata?.get("ARROW:extension:name") === BLOB_V2_EXTENSION_NAME;
}
/** @ignore */
export function isBlobDescriptorField(field: Field): boolean {
// Native descriptor scans replace the logical extension metadata. Require
// both the encoding marker and the v2 layout to exclude v1 and plain structs.
if (
field.metadata?.get("lance-encoding:blob") !== "true" ||
!DataType.isStruct(field.type)
) {
return false;
}
const children = field.type.children;
const integers = [
["kind", 8],
["position", 64],
["size", 64],
["blob_id", 32],
] as const;
return (
children.length === 5 &&
integers.every(([name, width], index) => {
const child = children[index];
return (
child.name === name &&
DataType.isInt(child.type) &&
!child.type.isSigned &&
child.type.bitWidth === width
);
}) &&
children[4].name === "blob_uri" &&
DataType.isUtf8(children[4].type)
);
}
/**
* A lazy handle to blob bytes. Create one with {@link Table.fetchBlobFiles}.
*
@@ -305,6 +345,16 @@ export async function runWithSignal<T>(
}
}
/** One row-specific range for {@link Table.fetchBlobRanges}. */
export type BlobRangeRequest = {
/** A row ID from a query with row IDs enabled. */
rowId: bigint | number;
/** Byte offset from the beginning of the logical blob, as a uint64. */
offset: bigint;
/** Number of bytes to read, as a uint64. Zero returns an empty non-null value. */
length: bigint;
};
/** A half-open byte range `[start, end)` for {@link BlobFile.readRanges}. */
export type BlobRange = {
start: bigint;
+8
View File
@@ -57,6 +57,9 @@ export {
AddResult,
AddColumnsResult,
RefreshColumnOptions,
FunctionRefreshPlanningConfig,
FunctionRefreshPodResources,
FunctionRetryPolicy,
FunctionWorkerResourceBudget,
RefreshColumnResult,
FunctionErrors,
@@ -91,6 +94,7 @@ export type {
BlobInput,
BlobOptions,
BlobRange,
BlobRangeRequest,
BlobReadOptions,
BlobUri,
} from "./blob";
@@ -154,6 +158,10 @@ export {
export {
Table,
FunctionColumnAutoRefreshStatus,
FunctionColumnLastRefreshJob,
FunctionColumnStatus,
FunctionColumnVersionStatus,
Branches,
BranchColumnSummary,
BranchColumnChange,
+27 -1
View File
@@ -127,6 +127,14 @@ export class MergeInsertBuilder {
data: Data,
execOptions?: Partial<WriteExecutionOptions>,
): Promise<MergeResult> {
if (
execOptions?.retries !== undefined &&
(!Number.isInteger(execOptions.retries) ||
execOptions.retries < 0 ||
execOptions.retries > 255)
) {
throw new Error("retries must be an integer between 0 and 255");
}
let schema: Schema;
if (this.#schema instanceof Promise) {
schema = await this.#schema;
@@ -140,7 +148,7 @@ export class MergeInsertBuilder {
}
const buffer = await fromDataToBuffer(data, undefined, schema);
return await this.#native.execute(buffer);
return await this.#native.execute(buffer, execOptions?.retries);
}
}
@@ -156,6 +164,24 @@ export interface WriteExecutionOptions {
* first attempt will not be cancelled.
*
* When this is set, the timeout is enforced on all attempts, including the first.
* For remote tables this is sent as a server execution timeout. It does not
* extend HTTP read or proxy idle timeouts, or prove that a failed request did
* not commit.
*/
timeoutMs?: number;
/**
* Override the remote retry budget for this execution only (an integer from
* 0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after
* precommit conflicts (409) or rate limits (429). This does not change
* connection-wide/read budgets or local transaction conflict retries.
*
* By default, remote calls use the connection's `clientConfig.retryConfig`
* ({@link RetryConfig}). Its `statuses` (also set through
* `LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget;
* it never permits replay of ambiguous merge outcomes. In particular, 502,
* ordinary 503, and 504 are never replayed, even if configured. Reconcile table
* contents before manually repeating a merge whose commit outcome is unknown.
*/
retries?: number;
}
+65 -6
View File
@@ -17,6 +17,7 @@ import {
tableFromIPC,
vectorFromArray,
} from "./arrow";
import { isBlobDescriptorField, isBlobField } from "./blob";
import { Expr } from "./expr";
import { type IvfPqOptions } from "./indices";
import {
@@ -148,6 +149,34 @@ async function readBlobBytes(
);
}
// Discover descriptors from the executed query, not the live table's cached
// schema. Projection names are literal aliases; only source paths use dots.
function projectedBlobSources(
schema: Schema,
projection: [string, string][] | undefined,
): BlobSource[] {
const sources: BlobSource[] = [];
for (const field of schema.fields) {
const source =
projection?.find(([output]) => output === field.name)?.[1] ?? field.name;
const visit = (child: Field, path: string[]) => {
if (isBlobField(child) || isBlobDescriptorField(child)) {
sources.push({
output: field.name,
path,
source: [source, ...path].join("."),
});
} else if (DataType.isStruct(child.type)) {
for (const nested of child.type.children) {
visit(nested, [...path, nested.name]);
}
}
};
visit(field, []);
}
return sources;
}
function withBinaryColumns(
table: ArrowTable,
replacements: Map<Field, (Buffer | null)[]>,
@@ -257,8 +286,10 @@ export interface QueryExecutionOptions {
* bytes. Blobs inside lists keep their descriptors. Arbitrary projection
* expressions are not materialized as bytes.
*
* The rows and the bytes come from the same table version. If the table
* changes while the query runs, the query runs again, up to three times.
* The rows and bytes come from the same snapshot. Remote queries require
* authoritative query version and snapshot identity headers, verified again
* by the blob response. Older servers can still return `"descriptions"`.
* Local queries retry up to three times if the table changes while they run.
*
* @example
* ```ts
@@ -499,6 +530,34 @@ export class QueryBase<
if (context === undefined) {
return this.collect(options, false);
}
if (!context.table.isNative()) {
// Request row IDs in the same query so newly added Blob columns can be
// fetched without rerunning the query against a different snapshot.
const addRowId = !context.withRowId;
const table = await this.collect(options, addRowId);
const sources = projectedBlobSources(table.schema, context.projection);
if (sources.length === 0) {
return addRowId
? table.select(
table.schema.fields
.map((field) => field.name)
.filter((name) => name !== "_rowid"),
)
: table;
}
const version = table.schema.metadata.get("lancedb:query_version");
const identity = table.schema.metadata.get("lancedb:query_snapshot");
if (version === undefined || identity === undefined) {
throw new Error(
'blobMode "bytes" requires a trustworthy query snapshot: missing, invalid, or inconsistent x-lancedb-query-version or x-lancedb-query-snapshot. Upgrade every serving node, or use blobMode "descriptions".',
);
}
const snapshot = await context.table.querySnapshotWithIdentity(
version,
identity,
);
return readBlobBytes(table, sources, snapshot, addRowId);
}
for (let attempt = 1; ; attempt++) {
// The snapshot pins the bytes. The query runs on the live table, so an
// unchanged version afterwards proves it read the snapshot's version.
@@ -533,10 +592,10 @@ export class QueryBase<
for await (const batch of RecordBatchIterator(iterator)) {
batches.push(batch);
}
if (batches.length === 0) {
return tableFromIPC((await iterator).schema());
}
return new ArrowTable(batches);
// Read metadata from the executed stream, including empty results and
// query types whose individual batches do not carry the stream metadata.
const schema = tableFromIPC((await iterator).schema()).schema;
return new ArrowTable(schema, batches);
}
private blobBytesContext(
+200 -3
View File
@@ -17,7 +17,12 @@ import {
tableFromIPC,
} from "./arrow";
import { BlobFile, BlobReadOptions, runWithSignal } from "./blob";
import {
BlobFile,
BlobRangeRequest,
BlobReadOptions,
runWithSignal,
} from "./blob";
import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry";
import { IndexOptions } from "./indices";
import { Job } from "./job";
@@ -35,6 +40,7 @@ import {
FunctionErrorsOptions,
IndexConfig,
IndexStatistics,
JobFailureInfo,
Branches as NativeBranches,
OptimizeStats,
RTEStats,
@@ -136,6 +142,13 @@ export interface AddDataOptions {
* when the blob is read later.
*/
allowExternalBlobOutsideBases?: boolean;
/**
* Override the remote retry budget for this call (0 to 255). Zero disables
* retries, including multipart parts. Ambiguous commits are never replayed.
* Ignored by LanceDB Embedded.
*/
retries?: number;
}
export interface UpdateOptions {
@@ -258,6 +271,76 @@ export interface RTEWriteSpec {
writerConfigDefaults?: Record<string, string>;
}
/** Exact immutable Function revision attached to a table output. */
export interface FunctionColumnVersionStatus {
name: string;
namespacePath: string[];
objectId: string;
location: string;
version: string;
manifestDigest: string;
}
/** Latest matching refresh Job projected for a Function output. */
export interface FunctionColumnLastRefreshJob {
jobId: string;
state: string;
automatic?: boolean;
completedAtMillis?: bigint;
/** Structured failure details for a failed Job. */
failure?: JobFailureInfo;
}
/** Automatic-refresh projection for a Function output. */
export interface FunctionColumnAutoRefreshStatus {
enabled: boolean;
intervalSeconds?: bigint;
activeJobId?: string;
state:
| "disabled"
| "running"
| "queued"
| "ready"
| "up_to_date"
| "waiting_interval"
| "waiting_backoff"
| "blocked"
| "unobservable";
failureStreak: number;
effectiveCooldownMillis?: bigint;
blockedReason?:
| "table_has_mem_wal"
| "inputs_not_settled"
| "dependency_in_flight"
| "table_capacity"
| "cancelled"
| "preparation_backoff"
| "failure_threshold_reached"
| "binding_revision_missing";
nextRunAtMillis: bigint | null;
nextRunAtReason?: string;
}
/** Exact four-way status of one Function output at one table version. */
export interface FunctionColumnStatus {
column: string;
bindingId: string;
function: FunctionColumnVersionStatus;
tableVersion: bigint;
rows: bigint;
fresh: bigint;
stale: bigint;
neverComputed: bigint;
failed: bigint;
lastRefreshJob?: FunctionColumnLastRefreshJob;
/**
* Newest failed refresh Job. This remains present when `lastRefreshJob`
* is a later cancellation.
*/
lastFailureJob?: FunctionColumnLastRefreshJob;
autoRefresh: FunctionColumnAutoRefreshStatus;
}
/**
* A Table is a collection of Records in a LanceDB Database.
*
@@ -605,6 +688,31 @@ export abstract class Table {
options?: BlobReadOptions,
): Promise<(Buffer | null)[]>;
/**
* Materializes row-specific byte ranges at the table's current checkout.
* Preserves request order, duplicates, and nulls. Zero length returns an empty
* buffer for a non-null blob. Invalid ranges or missing rows reject the entire
* call. See {@link Table.fetchBlobs} for row-ID validity across versions.
*
* Remote tables use the batched endpoint when the server advertises support,
* splitting at 1024 ranges and 64 MiB, including individual larger ranges.
* Older servers use descriptor queries and BlobFile range reads. Both protocols
* use one exact branch and version. Errors from an advertised endpoint propagate
* without switching protocols. All output bytes occupy memory.
*
* @example
* ```ts
* const bytes = await table.fetchBlobRanges("image", [
* { rowId: 10n, offset: 0n, length: 1024n },
* ]);
* ```
*/
abstract fetchBlobRanges(
column: string,
requests: readonly BlobRangeRequest[],
options?: BlobReadOptions,
): Promise<(Buffer | null)[]>;
/**
* Opens lazy blob handles for `column` at the given row IDs using the
* table's current checkout.
@@ -723,12 +831,18 @@ export abstract class Table {
* `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
* `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
* and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
* `maxConcurrency`, `resourceBudget` and
* `maxExecutorProcessesPerWorker` size registered Function refreshes.
* `maxConcurrency`, `resourceBudget`, `supervisorResources`,
* `planningWorkers` and `maxExecutorProcessesPerWorker` size registered
* Function refreshes. `retryPolicy` overrides user-code retries only when
* repeating partial work is safe; set `maxAttempts: 1` to disable retries.
* `maxConcurrency` overrides the registered default for this logical
* execution only and is a positive integer; it is not an account-wide
* quota. A `resourceBudget` requires `cpuMillis` and
* `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function.
* `supervisorResources` and each `planningWorkers.resources` entry require
* positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`.
* `planningWorkers` also requires positive `maxWorkers`,
* `rowsPerWorker` and `fragmentsPerWorker`.
* The budget applies only to this explicit refresh and does not configure
* a later automatic refresh.
* `gpuCount` at the top level is the shorthand that preserves the
@@ -737,6 +851,11 @@ export abstract class Table {
* `resourceBudget` for registered Functions. All are LanceDB Enterprise
* only; a LanceDB Embedded refresh rejects every option other than
* `batchSize`, `gpuClass` and `gpuCount`.
* `publicationIntervalRows` opts into publishing completed Function split
* ranges once their accumulated unpublished rows reach the threshold.
* It must be a positive safe integer and requires non-Blob Function outputs.
* Omit it for whole-fragment publication. Publications can exceed the
* threshold, and remaining rows publish at completion.
* @example
* ```ts
* const job = await table.refreshColumnAsync("embedding", {
@@ -746,6 +865,7 @@ export abstract class Table {
* memoryBytes: 16 * 1024 ** 3,
* },
* maxConcurrency: 4,
* publicationIntervalRows: 10000,
* errorPolicy: "skip",
* maxFailedFraction: 0.01,
* rowTimeoutSeconds: 30,
@@ -780,6 +900,32 @@ export abstract class Table {
options?: FunctionErrorsOptions,
): Promise<FunctionErrors>;
/**
* Return exact freshness status for Function-backed output columns.
*
* All results describe one server table version. Omit `column` for every
* Function output. Rows already failed remain visible and do not prevent
* `waitFresh` from completing. A handle pinned to an exact version requests
* that version; a latest handle retains normal read-freshness behavior.
*/
abstract functionColumnStatuses(
column?: string,
): Promise<FunctionColumnStatus[]>;
/** Return exact freshness status for one Function-backed output column. */
abstract functionColumnStatus(column: string): Promise<FunctionColumnStatus>;
/**
* Poll until no stale or never-computed rows remain.
*
* Only HTTP 503 with the exact finalization-pending error code is retried;
* every other error propagates. Failed rows do not block completion.
*/
abstract waitFresh(
column: string,
timeoutSeconds?: number,
): Promise<FunctionColumnStatus>;
/**
* Recompute this table's contents from its materialized-view definition.
*
@@ -1217,6 +1363,14 @@ export class LocalTable extends Table {
}
async add(data: Data, options?: Partial<AddDataOptions>): Promise<AddResult> {
if (
options?.retries !== undefined &&
(!Number.isInteger(options.retries) ||
options.retries < 0 ||
options.retries > 255)
) {
throw new Error("retries must be an integer between 0 and 255");
}
const mode = options?.mode ?? "append";
const schema = await this.schema();
@@ -1239,6 +1393,7 @@ export class LocalTable extends Table {
mode,
progress,
options?.allowExternalBlobOutsideBases,
options?.retries,
);
}
@@ -1391,6 +1546,23 @@ export class LocalTable extends Table {
return values.map((value) => value ?? null);
}
async fetchBlobRanges(
column: string,
requests: readonly BlobRangeRequest[],
options?: BlobReadOptions,
): Promise<(Buffer | null)[]> {
const rowIds = rowIdsToBigInts(requests.map((request) => request.rowId));
const ranges = requests.map((request, i) => ({
rowId: rowIds[i],
offset: request.offset,
length: request.length,
}));
const values = await runWithSignal(options?.signal, (signal) =>
this.inner.fetchBlobRanges(column, ranges, signal),
);
return values.map((value) => value ?? null);
}
async fetchBlobFiles(
column: string,
rowIds: readonly (bigint | number)[],
@@ -1557,6 +1729,31 @@ export class LocalTable extends Table {
return await this.inner.functionErrors(options);
}
async functionColumnStatuses(
column?: string,
): Promise<FunctionColumnStatus[]> {
return (await this.inner.functionColumnStatuses(
column,
)) as FunctionColumnStatus[];
}
async functionColumnStatus(column: string): Promise<FunctionColumnStatus> {
return (await this.inner.functionColumnStatus(
column,
)) as FunctionColumnStatus;
}
async waitFresh(
column: string,
timeoutSeconds?: number,
): Promise<FunctionColumnStatus> {
validateNonNegativeInteger(timeoutSeconds, "timeoutSeconds");
return (await this.inner.waitForFunctionColumn(
column,
timeoutSeconds,
)) as FunctionColumnStatus;
}
async refreshMaterializedView(
sourceVersion?: number,
full?: boolean,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-darwin-arm64",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.16",
"os": ["darwin"],
"cpu": ["arm64"],
"main": "lancedb.darwin-arm64.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-gnu",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.16",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-musl",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.16",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-gnu",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.16",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-musl",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.16",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-arm64-msvc",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.16",
"os": [
"win32"
],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-x64-msvc",
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.16",
"os": ["win32"],
"cpu": ["x64"],
"main": "lancedb.win32-x64-msvc.node",
+1 -1
View File
@@ -11,7 +11,7 @@
"ann"
],
"private": false,
"version": "0.42.0-beta.10",
"version": "0.42.0-beta.16",
"main": "dist/index.js",
"exports": {
".": "./dist/index.js",
+40 -10
View File
@@ -21,6 +21,25 @@ pub struct BlobRange {
pub end: BigInt,
}
#[napi(object)]
pub struct BlobRangeRequest {
pub row_id: BigInt,
pub offset: BigInt,
pub length: BigInt,
}
impl BlobRangeRequest {
pub(crate) fn parse(self) -> napi::Result<lancedb::blob::BlobRangeRequest> {
let row_id = parse_u64(self.row_id, "row id")?;
let offset = parse_u64(self.offset, "offset")?;
let length = parse_u64(self.length, "length")?;
offset
.checked_add(length)
.ok_or_else(|| napi::Error::from_reason("blob range offset + length overflows u64"))?;
Ok(lancedb::blob::BlobRangeRequest::new(row_id, offset, length))
}
}
#[napi]
pub struct BlobFile {
inner: Arc<LanceBlobFile>,
@@ -205,14 +224,25 @@ pub fn parse_row_ids(row_ids: Vec<BigInt>) -> napi::Result<Vec<u64>> {
.collect()
}
pub fn copy_blob_buffers(array: LargeBinaryArray) -> Vec<Option<Buffer>> {
(0..array.len())
.map(|i| {
if array.is_null(i) {
None
} else {
Some(Buffer::from(array.value(i).to_vec()))
}
})
.collect()
pub fn copy_blob_buffers(array: LargeBinaryArray) -> napi::Result<Vec<Option<Buffer>>> {
let allocation_error =
|error| napi::Error::from_reason(format!("cannot allocate blob result: {error}"));
let mut result = Vec::new();
result
.try_reserve_exact(array.len())
.map_err(allocation_error)?;
for value in array.iter() {
let buffer = value
.map(|value| {
let mut bytes = Vec::new();
bytes
.try_reserve_exact(value.len())
.map_err(allocation_error)?;
bytes.extend_from_slice(value);
Ok::<_, napi::Error>(Buffer::from(bytes))
})
.transpose()?;
result.push(buffer);
}
Ok(result)
}
+16 -6
View File
@@ -138,12 +138,7 @@ impl Job {
/// Why the job failed, when it failed and the server reports a reason.
#[napi(getter)]
pub fn failure(&self) -> Option<JobFailureInfo> {
self.inner.failure().map(|failure| JobFailureInfo {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
})
self.inner.failure().map(Into::into)
}
/// This job's recorded lifecycle events, as an Arrow IPC stream buffer.
@@ -216,10 +211,25 @@ impl From<lancedb::database::JobInfo> for JobInfo {
/// The server's account of why a job failed.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct JobFailureInfo {
pub phase: Option<String>,
pub message: Option<String>,
/// User-code traceback, possibly truncated by the server.
pub traceback: Option<String>,
pub retryable: Option<bool>,
/// Isolated SQL job that raised this failure, when supplied by the server.
pub sql_job_id: Option<String>,
}
impl From<lancedb::error::JobFailure> for JobFailureInfo {
fn from(failure: lancedb::error::JobFailure) -> Self {
Self {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
sql_job_id: failure.sql_job_id,
}
}
}
+7 -2
View File
@@ -66,7 +66,7 @@ impl NativeMergeInsertBuilder {
}
#[napi(catch_unwind)]
pub async fn execute(&self, buf: Buffer) -> napi::Result<MergeResult> {
pub async fn execute(&self, buf: Buffer, retries: Option<u32>) -> napi::Result<MergeResult> {
let reader = ipc_file_to_batches(buf.to_vec()).map_err(|e| {
napi::Error::from_reason(format!("Failed to read IPC file: {}", convert_error(&e)))
})?;
@@ -88,7 +88,12 @@ impl NativeMergeInsertBuilder {
data.push(RecordBatch::new_empty(schema));
}
let this = self.clone();
let mut this = self.clone();
if let Some(retries) = retries {
let retries = u8::try_from(retries)
.map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?;
this.inner.retries(retries);
}
let res = this.inner.execute(data).await.map_err(|e| {
napi::Error::from_reason(format!(
+371 -6
View File
@@ -9,6 +9,8 @@ use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema};
use lancedb::table::{
AddDataMode, ColumnAlteration as LanceColumnAlteration,
FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken,
FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig,
FunctionRefreshPodResources as LanceFunctionRefreshPodResources,
FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref,
Table as LanceDbTable,
};
@@ -17,9 +19,10 @@ use napi::bindgen_prelude::*;
use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use napi_derive::napi;
use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable};
use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable};
use crate::error::NapiErrorExt;
use crate::index::Index;
use crate::job::JobFailureInfo;
use crate::merge::NativeMergeInsertBuilder;
use crate::query::{Query, TakeQuery, VectorQuery};
use crate::util::schema_to_buffer;
@@ -133,7 +136,7 @@ impl Table {
#[napi(
catch_unwind,
ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean"
ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean, retries?: number"
)]
pub async fn add(
&self,
@@ -141,6 +144,7 @@ impl Table {
mode: String,
progress_callback: Option<ProgressFn>,
allow_external_blob_outside_bases: Option<bool>,
retries: Option<u32>,
) -> napi::Result<AddResult> {
let batches = ipc_file_to_batches(buf.to_vec())
.map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?;
@@ -156,6 +160,11 @@ impl Table {
})
.collect::<Result<Vec<_>>>()?;
let mut op = self.inner_ref()?.add(batches);
if let Some(retries) = retries {
let retries = u8::try_from(retries)
.map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?;
op = op.retries(retries);
}
op = if mode == "append" {
op.mode(AddDataMode::Append)
@@ -342,6 +351,31 @@ impl Table {
Ok(Query::new(self.inner_ref()?.query()))
}
/// Whether this handle reads an in-process dataset.
#[napi]
pub fn is_native(&self) -> napi::Result<bool> {
Ok(self.inner_ref()?.as_native().is_some())
}
/// Constrain deferred blob reads by the producing query response.
#[napi(catch_unwind)]
pub async fn query_snapshot_with_identity(
&self,
version: String,
identity: String,
) -> napi::Result<Self> {
// Keep u64 query versions exact across the JavaScript boundary.
let version = version
.parse::<u64>()
.map_err(|_| napi::Error::from_reason("Invalid query snapshot version"))?;
let snapshot = self
.inner_ref()?
.query_snapshot_with_identity(version, &identity)
.await
.default_error()?;
Ok(Self::new(snapshot))
}
/// Return a read-only table handle pinned to the current query revision.
#[napi(catch_unwind)]
pub async fn query_snapshot(&self) -> napi::Result<Self> {
@@ -413,7 +447,32 @@ impl Table {
.fetch_blobs(column.as_str(), &row_ids)
.await
.default_error()?;
Ok(copy_blob_buffers(array))
copy_blob_buffers(array)
})
}
#[napi(catch_unwind)]
pub fn fetch_blob_ranges<'env>(
&self,
env: &'env Env,
column: String,
requests: Vec<BlobRangeRequest>,
signal: Option<AbortSignal>,
) -> napi::Result<PromiseRaw<'env, Vec<Option<Buffer>>>> {
let mut ranges = Vec::new();
ranges.try_reserve_exact(requests.len()).map_err(|error| {
napi::Error::from_reason(format!("cannot allocate blob range requests: {error}"))
})?;
for request in requests {
ranges.push(request.parse()?);
}
let table = self.inner_ref()?.clone();
spawn_abortable(env, signal, async move {
let array = table
.fetch_blob_ranges(column.as_str(), ranges)
.await
.default_error()?;
copy_blob_buffers(array)
})
}
@@ -534,6 +593,55 @@ impl Table {
Ok(errors.into())
}
#[napi(catch_unwind)]
pub async fn function_column_statuses(
&self,
column: Option<String>,
) -> napi::Result<Vec<FunctionColumnStatus>> {
let statuses = self
.inner_ref()?
.function_column_statuses(column.as_deref())
.await
.default_error()?;
Ok(statuses.into_iter().map(Into::into).collect())
}
#[napi(catch_unwind)]
pub async fn function_column_status(
&self,
column: String,
) -> napi::Result<FunctionColumnStatus> {
let status = self
.inner_ref()?
.function_column_status(&column)
.await
.default_error()?;
Ok(status.into())
}
#[napi(catch_unwind)]
pub async fn wait_for_function_column(
&self,
column: String,
timeout_seconds: Option<i64>,
) -> napi::Result<FunctionColumnStatus> {
let timeout = timeout_seconds
.map(|seconds| {
u64::try_from(seconds)
.map(std::time::Duration::from_secs)
.map_err(|_| {
napi::Error::from_reason("timeoutSeconds must be a non-negative integer")
})
})
.transpose()?;
let status = self
.inner_ref()?
.wait_for_function_column(&column, timeout)
.await
.default_error()?;
Ok(status.into())
}
#[napi(catch_unwind)]
pub async fn refresh_materialized_view(
&self,
@@ -1599,7 +1707,59 @@ pub struct FunctionWorkerResourceBudget {
pub gpu_count: Option<f64>,
}
fn resource_budget_integer(value: f64, name: &str) -> napi::Result<u64> {
/// CPU, memory, and ephemeral-storage limits for one Function refresh
/// control-plane pod.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionRefreshPodResources {
/// CPU limit in millicores; 1000 is one CPU.
pub cpu_millis: f64,
/// Memory limit in bytes.
pub memory_bytes: f64,
/// Ephemeral storage limit in bytes.
pub ephemeral_storage_bytes: f64,
}
/// Resources and sizing policy for the planning fleet of one registered
/// Function refresh.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionRefreshPlanningConfig {
/// CPU, memory, and ephemeral-storage limits for one planning worker.
pub resources: FunctionRefreshPodResources,
/// Maximum number of planning workers.
pub max_workers: f64,
/// Maximum rows assigned to one planning worker.
pub rows_per_worker: f64,
/// Maximum fragments assigned to one planning worker.
pub fragments_per_worker: f64,
}
/// Overrides retries of failed user-code calls for one refresh. Omitted
/// fields use the Function refresh defaults.
#[napi(object)]
#[derive(Clone, Debug, Default)]
pub struct FunctionRetryPolicy {
/// Total calls, including the first; 1 disables retries, maximum 100.
pub max_attempts: Option<u32>,
/// Initial exponential-backoff ceiling, in seconds.
pub initial_backoff_seconds: Option<f64>,
/// Maximum backoff, in seconds.
pub max_backoff_seconds: Option<f64>,
/// Exception class names, preferably qualified.
pub exception_types: Option<Vec<String>>,
/// Regular expression matched against the exception class and message.
pub message_pattern: Option<String>,
/// Structured provider error codes or HTTP status codes.
pub error_codes: Option<Vec<String>>,
/// Match connection/timeouts, HTTP 429/503, SlowDown and
/// ServiceUnavailable.
pub transient: Option<bool>,
/// Honor Retry-After within the configured maximum.
pub honor_retry_after: Option<bool>,
}
fn positive_safe_integer(value: f64, name: &str) -> napi::Result<u64> {
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
if !value.is_finite() || value.fract() != 0.0 || !(1.0..=MAX_SAFE_INTEGER).contains(&value) {
return Err(napi::Error::from_reason(format!(
@@ -1649,6 +1809,11 @@ pub struct RefreshColumnOptions {
pub where_clause: Option<String>,
/// Maximum rows per Function call; must be greater than zero.
pub batch_size: Option<u32>,
/// Row-count threshold for publishing completed Function split ranges.
/// Must be a positive safe integer. Omit for whole-fragment publication.
/// Actual publications can be larger; remaining rows publish at completion.
/// Requires LanceDB Enterprise with non-Blob Function outputs.
pub publication_interval_rows: Option<f64>,
/// Override the registered Function's maximum concurrent user-code calls
/// for this logical execution.
pub max_concurrency: Option<f64>,
@@ -1657,8 +1822,14 @@ pub struct RefreshColumnOptions {
/// Complete aggregate CPU and memory budget for a registered Function
/// refresh. `gpuCount` inside the budget defaults to zero.
pub resource_budget: Option<FunctionWorkerResourceBudget>,
/// CPU, memory, and ephemeral-storage limits for the refresh supervisor.
pub supervisor_resources: Option<FunctionRefreshPodResources>,
/// Resources and sizing for the refresh planning fleet.
pub planning_workers: Option<FunctionRefreshPlanningConfig>,
/// Positive aggregate GPU budget for Function workers.
pub gpu_count: Option<u32>,
/// Override retries of failed user-code calls for this refresh.
pub retry_policy: Option<FunctionRetryPolicy>,
/// `"fail"` (default) stops on a row error; `"skip"` writes null and
/// records the error, subject to the failure limits.
pub error_policy: Option<String>,
@@ -1685,6 +1856,10 @@ impl TryFrom<RefreshColumnOptions> for lancedb::table::RefreshColumnOptions {
let mut options = Self::default();
options.where_clause = value.where_clause;
options.batch_size = value.batch_size.map(|size| size as usize);
options.publication_interval_rows = value
.publication_interval_rows
.map(|rows| positive_safe_integer(rows, "publicationIntervalRows"))
.transpose()?;
options.max_concurrency = positive_u32(value.max_concurrency, "maxConcurrency")?;
options.gpu_class = value.gpu_class;
options.resource_budget = value
@@ -1692,14 +1867,94 @@ impl TryFrom<RefreshColumnOptions> for lancedb::table::RefreshColumnOptions {
.map(|budget| {
Ok::<_, napi::Error>(
LanceFunctionWorkerResourceBudget::new(
resource_budget_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?,
resource_budget_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?,
positive_safe_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?,
positive_safe_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?,
)
.with_gpu_count(resource_budget_gpu_count(budget.gpu_count)?),
)
})
.transpose()?;
options.supervisor_resources = value
.supervisor_resources
.map(|resources| {
Ok::<_, napi::Error>(LanceFunctionRefreshPodResources::new(
positive_safe_integer(resources.cpu_millis, "supervisorResources.cpuMillis")?,
positive_safe_integer(
resources.memory_bytes,
"supervisorResources.memoryBytes",
)?,
positive_safe_integer(
resources.ephemeral_storage_bytes,
"supervisorResources.ephemeralStorageBytes",
)?,
))
})
.transpose()?;
options.planning_workers = value
.planning_workers
.map(|planning| {
let resources = LanceFunctionRefreshPodResources::new(
positive_safe_integer(
planning.resources.cpu_millis,
"planningWorkers.resources.cpuMillis",
)?,
positive_safe_integer(
planning.resources.memory_bytes,
"planningWorkers.resources.memoryBytes",
)?,
positive_safe_integer(
planning.resources.ephemeral_storage_bytes,
"planningWorkers.resources.ephemeralStorageBytes",
)?,
);
let max_workers = usize::try_from(positive_safe_integer(
planning.max_workers,
"planningWorkers.maxWorkers",
)?)
.map_err(|_| napi::Error::from_reason("planningWorkers.maxWorkers is too large"))?;
Ok::<_, napi::Error>(LanceFunctionRefreshPlanningConfig::new(
resources,
max_workers,
positive_safe_integer(
planning.rows_per_worker,
"planningWorkers.rowsPerWorker",
)?,
positive_safe_integer(
planning.fragments_per_worker,
"planningWorkers.fragmentsPerWorker",
)?,
))
})
.transpose()?;
options.gpu_count = value.gpu_count;
options.retry_policy = value.retry_policy.map(|policy| {
let mut converted = lancedb::function::FunctionRetryPolicy::default();
if let Some(max_attempts) = policy.max_attempts {
converted.max_attempts = max_attempts;
}
if let Some(seconds) = policy.initial_backoff_seconds {
converted.initial_backoff_seconds = seconds;
}
if let Some(seconds) = policy.max_backoff_seconds {
converted.max_backoff_seconds = seconds;
}
if let Some(exception_types) = policy.exception_types {
converted.exception_types = exception_types;
}
if let Some(pattern) = policy.message_pattern {
converted.message_pattern = Some(pattern);
}
if let Some(error_codes) = policy.error_codes {
converted.error_codes = error_codes;
}
if let Some(transient) = policy.transient {
converted.transient = transient;
}
if let Some(honor_retry_after) = policy.honor_retry_after {
converted.honor_retry_after = honor_retry_after;
}
converted
});
options.error_policy = match value.error_policy.as_deref() {
None => None,
Some("fail") => Some(lancedb::function::FunctionErrorPolicy::Fail),
@@ -1799,6 +2054,116 @@ pub struct FunctionErrors {
pub truncated: bool,
}
/// One exact immutable Function revision attached to a table output.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnVersionStatus {
pub name: String,
pub namespace_path: Vec<String>,
pub object_id: String,
pub location: String,
pub version: String,
pub manifest_digest: String,
}
/// Latest matching refresh Job projected for a Function output.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnLastRefreshJob {
pub job_id: String,
pub state: String,
pub automatic: Option<bool>,
pub completed_at_millis: Option<BigInt>,
pub failure: Option<JobFailureInfo>,
}
impl From<lancedb::table::FunctionColumnLastRefreshJob> for FunctionColumnLastRefreshJob {
fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self {
Self {
job_id: job.job_id,
state: job.state,
automatic: job.automatic,
completed_at_millis: job.completed_at_millis.map(BigInt::from),
failure: job.failure.map(Into::into),
}
}
}
/// Automatic-refresh projection for a Function output.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnAutoRefreshStatus {
pub enabled: bool,
pub interval_seconds: Option<BigInt>,
pub active_job_id: Option<String>,
pub state: String,
pub failure_streak: u32,
pub effective_cooldown_millis: Option<BigInt>,
pub blocked_reason: Option<String>,
pub next_run_at_millis: Option<BigInt>,
pub next_run_at_reason: Option<String>,
}
/// Exact four-way status of one Function output at one table version.
#[napi(object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnStatus {
pub column: String,
pub binding_id: String,
pub function: FunctionColumnVersionStatus,
pub table_version: BigInt,
pub rows: BigInt,
pub fresh: BigInt,
pub stale: BigInt,
pub never_computed: BigInt,
pub failed: BigInt,
pub last_refresh_job: Option<FunctionColumnLastRefreshJob>,
pub last_failure_job: Option<FunctionColumnLastRefreshJob>,
pub auto_refresh: FunctionColumnAutoRefreshStatus,
}
impl From<lancedb::table::FunctionColumnStatus> for FunctionColumnStatus {
fn from(status: lancedb::table::FunctionColumnStatus) -> Self {
Self {
column: status.column,
binding_id: status.binding_id,
function: FunctionColumnVersionStatus {
name: status.function.name,
namespace_path: status.function.namespace_path,
object_id: status.function.object_id,
location: status.function.location,
version: status.function.version,
manifest_digest: status.function.manifest_digest,
},
table_version: BigInt::from(status.table_version),
rows: BigInt::from(status.rows),
fresh: BigInt::from(status.fresh),
stale: BigInt::from(status.stale),
never_computed: BigInt::from(status.never_computed),
failed: BigInt::from(status.failed),
last_refresh_job: status.last_refresh_job.map(Into::into),
last_failure_job: status.last_failure_job.map(Into::into),
auto_refresh: FunctionColumnAutoRefreshStatus {
enabled: status.auto_refresh.enabled,
interval_seconds: status.auto_refresh.interval_seconds.map(BigInt::from),
active_job_id: status.auto_refresh.active_job_id,
state: status.auto_refresh.state.as_str().to_string(),
failure_streak: status.auto_refresh.failure_streak,
effective_cooldown_millis: status
.auto_refresh
.effective_cooldown_millis
.map(BigInt::from),
blocked_reason: status
.auto_refresh
.blocked_reason
.map(|reason| reason.as_str().to_string()),
next_run_at_millis: status.auto_refresh.next_run_at_millis.map(BigInt::from),
next_run_at_reason: status.auto_refresh.next_run_at_reason,
},
}
}
}
impl From<lancedb::function::FunctionErrors> for FunctionErrors {
fn from(errors: lancedb::function::FunctionErrors) -> Self {
Self {