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
+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 () => {