mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(query): stream query results with optional total hits (#5354)
## Summary An Embedded query can stream one page of results and report how many visible rows matched before offset and limit. This adds Rust `execute_with_metadata`, Python sync and async `to_result`, and TypeScript `toResult`. The existing query terminals continue to use their existing execution paths. Tracking defaults to Off. An exact count returns `eq(N)`. A positive cap C returns `eq(N)` below C and `gte(C)` as soon as C matches are proven, including equality. TypeScript exposes counts as bigint. Counts use the same snapshot as the result batches. The accessor reports pending until the stream reaches successful EOF. Explicit counts can add work after the last batch, especially when full-text counting needs to scan visible text. Closing an unfinished result cancels execution. Stream and metadata failures retain interruption details, including the request ID. Embedded supports scalar and row-level lexical counts. Unordered FTS retains its existing top-k and scoring policy. Enterprise and unsupported query shapes return a typed error when a count is requested. ## Dependency #5352 merged Lance v16.0.0-beta.7 into main, including [Lance #11680](https://github.com/lance-format/lance/pull/11680). This PR uses that dependency and its lockfiles. ## Validation The Linux-tested revision `bc39ad7ac` and rebased revision `24f4e90c2` have the same Git tree. The only change in `6932b3082` is the Python namespace regression fixture, which now resolves the local table without the optional pylance package. The revised test passed on managed Linux with CPython 3.11.18 both with pylance and pandas installed and after removing both packages. Managed Linux runs used the unmodified manifests and lockfiles from #5352 and the published `pylance 16.0.0b7` wheel. - The Rust metadata suite passed 57 tests, with two existing ignores. Coverage includes unordered FTS plans, top-k scores, physical row addresses under pagination, pending-read cancellation, and interruption after the last batch. - Python query, remote and namespace suites passed 1,163 tests. One optional slow test requires PyTorch, which was unavailable on this VM. The Node query, remote, table and error suites passed 913 tests, with three experimental cases skipped. - Regression tests reproduced the failures on the previous revision and verified the fixes. Python sync reranking and namespace FTS preserve an explicit empty page. Python sync and async scans expose `_rowaddr` alongside the pre-pagination count. Explicit counts are rejected before TypeScript auto-search issues an Enterprise request or invokes a vector embedding provider. Python and Node retain the server's 1,063-row first batch in Off mode. - A custom Python namespace opened through the public API receives the same computed projection in Off mode as with `to_batches()`. A Node result interrupted after another SDK load retains its original error class and request ID. Both regressions were reproduced on the prior revision. - Workspace Clippy, formatting, Ruff, Biome, TypeScript checks, TypeDoc and strict MkDocs passed. All 287 generated TypeDoc files matched the committed files byte for byte.
This commit is contained in:
@@ -3,7 +3,13 @@
|
||||
|
||||
import * as tmp from "tmp";
|
||||
|
||||
import { type Table, connect } from "../lancedb";
|
||||
import {
|
||||
MetadataCancelledError,
|
||||
MetadataPendingError,
|
||||
type Table,
|
||||
UnsupportedMetadataError,
|
||||
connect,
|
||||
} from "../lancedb";
|
||||
import {
|
||||
Field,
|
||||
FixedSizeList,
|
||||
@@ -809,3 +815,75 @@ describe("IVF search effort", () => {
|
||||
).toThrow("search_effort must be finite and in [0, 1]");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Query result metadata", () => {
|
||||
let dir: tmp.DirResult;
|
||||
let table: Table;
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = tmp.dirSync({ unsafeCleanup: true });
|
||||
const db = await connect(dir.name);
|
||||
table = await db.createTable("docs", [
|
||||
{ id: 1, text: "cat", vector: [0, 0] },
|
||||
{ id: 2, text: "cat dog", vector: [0, 1] },
|
||||
{ id: 3, text: "dog", vector: [1, 0] },
|
||||
]);
|
||||
});
|
||||
|
||||
afterEach(() => dir.removeCallback());
|
||||
|
||||
it("keeps metadata pending until EOF and retains it after close", async () => {
|
||||
const result = await table
|
||||
.query()
|
||||
.limit(1)
|
||||
.toResult({ trackTotalHits: true });
|
||||
expect((await result.batches.next()).value.numRows).toEqual(1);
|
||||
expect(() => result.metadata()).toThrow(MetadataPendingError);
|
||||
expect(await result.finish()).toEqual({
|
||||
totalHits: { value: 3n, relation: "eq" },
|
||||
});
|
||||
await result.close();
|
||||
expect(result.metadata().totalHits?.value).toEqual(3n);
|
||||
expect(await (await table.query().toResult()).finish()).toEqual({});
|
||||
});
|
||||
|
||||
it("preserves ranking with a capped count and cancels on break", async () => {
|
||||
await table.createIndex("text", { config: Index.fts() });
|
||||
const query = table.query().fullTextSearch("cat dog").limit(1);
|
||||
const capped = await query.toResult({ trackTotalHits: 2n });
|
||||
expect(await capped.finish()).toEqual({
|
||||
totalHits: { value: 2n, relation: "gte" },
|
||||
});
|
||||
const early = await query.toResult({ trackTotalHits: true });
|
||||
for await (const batch of early.batches) {
|
||||
expect(batch.numRows).toEqual(1);
|
||||
break;
|
||||
}
|
||||
expect(() => early.metadata()).toThrow(MetadataCancelledError);
|
||||
await expect(
|
||||
table.vectorSearch([0, 0]).toResult({ trackTotalHits: true }),
|
||||
).rejects.toThrow(UnsupportedMetadataError);
|
||||
});
|
||||
|
||||
it("normalizes threshold boundaries and accepts the largest u64", async () => {
|
||||
const query = table.query().limit(1);
|
||||
for (const [cap, value, relation] of [
|
||||
[2n, 2n, "gte"],
|
||||
[3, 3n, "gte"],
|
||||
[4n, 3n, "eq"],
|
||||
[(1n << 64n) - 1n, 3n, "eq"],
|
||||
] as const) {
|
||||
const result = await query.toResult({ trackTotalHits: cap });
|
||||
expect((await result.finish()).totalHits).toEqual({ value, relation });
|
||||
}
|
||||
});
|
||||
|
||||
it.each([0n, -1, 0.5, Number.MAX_SAFE_INTEGER + 1, 1n << 64n])(
|
||||
"rejects invalid cap %s",
|
||||
async (cap) => {
|
||||
await expect(
|
||||
table.query().toResult({ trackTotalHits: cap }),
|
||||
).rejects.toThrow(RangeError);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -11,10 +11,14 @@ import {
|
||||
Connection,
|
||||
ConnectionOptions,
|
||||
HttpError,
|
||||
LanceError,
|
||||
MetadataCancelledError,
|
||||
MetadataPendingError,
|
||||
OAuthConfig,
|
||||
OAuthFlowType,
|
||||
RetryError,
|
||||
TlsConfig,
|
||||
UnsupportedMetadataError,
|
||||
blob,
|
||||
connect,
|
||||
} from "../lancedb";
|
||||
@@ -29,6 +33,7 @@ import {
|
||||
makeArrowTable,
|
||||
tableToIPC,
|
||||
} from "../lancedb/arrow";
|
||||
import { installLanceErrorTranslation } from "../lancedb/errors";
|
||||
import {
|
||||
HeaderProvider,
|
||||
OAuthHeaderProvider,
|
||||
@@ -38,6 +43,8 @@ import { Index } from "../lancedb/indices";
|
||||
import type { JobProgress } from "../lancedb/job";
|
||||
import { LocalTable } from "../lancedb/table";
|
||||
|
||||
type SdkExports = typeof import("../lancedb");
|
||||
|
||||
// Test-only header providers
|
||||
class CustomProvider extends HeaderProvider {
|
||||
getHeaders(): Record<string, string> {
|
||||
@@ -285,8 +292,10 @@ describe("remote connection", () => {
|
||||
);
|
||||
|
||||
it("reports unsupported operations with backend-neutral errors", async () => {
|
||||
let requests = 0;
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
requests++;
|
||||
expect(req.url).toBe("/v1/table/test/describe/");
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
@@ -311,7 +320,22 @@ describe("remote connection", () => {
|
||||
);
|
||||
},
|
||||
async (db) => {
|
||||
// The second open reuses the server version but starts with a cold schema cache.
|
||||
await db.openTable("test");
|
||||
const table = (await db.openTable("test")) as LocalTable;
|
||||
const requestsAfterOpen = requests;
|
||||
for (const trackTotalHits of [true, 10n]) {
|
||||
for (const query of [
|
||||
table.query(),
|
||||
table.search("dog"),
|
||||
table.search("dog", "vector"),
|
||||
]) {
|
||||
await expect(query.toResult({ trackTotalHits })).rejects.toThrow(
|
||||
UnsupportedMetadataError,
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(requests).toBe(requestsAfterOpen);
|
||||
await expect(table.delta(1)).rejects.toThrow(
|
||||
"table.delta is only supported on LanceDB Embedded tables",
|
||||
);
|
||||
@@ -334,6 +358,79 @@ describe("remote connection", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["interrupted", "closed", "interrupted after SDK reload"])(
|
||||
"preserves the query result terminal state after a batch: %s",
|
||||
async (outcome) => {
|
||||
const serverBatch = makeArrowTable(
|
||||
Array.from({ length: 1063 }, (_, id) => ({ id })),
|
||||
);
|
||||
const ipc = tableToIPC(serverBatch, "stream");
|
||||
let requestId: string | undefined;
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
if (req.url?.endsWith("/describe/")) {
|
||||
res.writeHead(200).end(
|
||||
JSON.stringify({
|
||||
version: 7,
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "id", type: { type: "double" }, nullable: true },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else if (req.url?.endsWith("/query/")) {
|
||||
req.resume();
|
||||
requestId = String(req.headers["x-request-id"]);
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/vnd.apache.arrow.stream",
|
||||
"x-lancedb-version": "7",
|
||||
});
|
||||
res.write(ipc.subarray(0, -8));
|
||||
if (outcome !== "closed") res.end();
|
||||
} else {
|
||||
res.writeHead(404).end();
|
||||
}
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("test");
|
||||
const result = await table.query().toResult();
|
||||
expect((await result.next()).value.numRows).toBe(serverBatch.numRows);
|
||||
expect(() => result.metadata()).toThrow(MetadataPendingError);
|
||||
if (outcome === "interrupted after SDK reload") {
|
||||
jest.isolateModules(() => {
|
||||
const reloaded = require("../lancedb") as SdkExports;
|
||||
expect(reloaded.LanceError).not.toBe(LanceError);
|
||||
});
|
||||
}
|
||||
const pending = result.next().finally(() => {
|
||||
if (outcome === "interrupted after SDK reload") {
|
||||
// Restore the shared native prototypes for later tests in this file.
|
||||
installLanceErrorTranslation(require("../lancedb/native.js"));
|
||||
}
|
||||
});
|
||||
if (outcome === "closed") {
|
||||
const cancelled = expect(pending).rejects.toThrow(
|
||||
MetadataCancelledError,
|
||||
);
|
||||
await result.close();
|
||||
await cancelled;
|
||||
expect(() => result.metadata()).toThrow(MetadataCancelledError);
|
||||
} else {
|
||||
await expect(pending).rejects.toBeInstanceOf(LanceError);
|
||||
expect(requestId).toBeTruthy();
|
||||
const details = { code: "ResponseInterrupted", requestId };
|
||||
await expect(pending).rejects.toMatchObject(details);
|
||||
await result.close();
|
||||
expect(() => result.metadata()).toThrow(
|
||||
expect.objectContaining(details),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects nprobes(0) before sending a query", async () => {
|
||||
const requests: string[] = [];
|
||||
await withMockDatabase(
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
TableDelta,
|
||||
TableDeltaReader,
|
||||
TagContents,
|
||||
UnsupportedMetadataError,
|
||||
VectorQuery,
|
||||
blob,
|
||||
connect,
|
||||
@@ -2535,6 +2536,61 @@ describe("automatic search schema consistency", () => {
|
||||
tmpDir.removeCallback();
|
||||
});
|
||||
|
||||
it("rejects explicit counts before preparing embeddings and counts automatic FTS", async () => {
|
||||
const db = await connect(tmpDir.name, { readConsistencyInterval: 0 });
|
||||
const table = await db.createTable("docs", [{ text: "dog" }], {
|
||||
schema: embeddingSchema(),
|
||||
});
|
||||
const parse = jest.spyOn(getRegistry(), "parseFunctions");
|
||||
const embed = jest.spyOn(
|
||||
SchemaRefreshEmbedding.prototype,
|
||||
"computeQueryEmbeddings",
|
||||
);
|
||||
try {
|
||||
const auto = table.search("dog").limit(1);
|
||||
const vector = table.search("dog", "vector").limit(1);
|
||||
for (const query of [auto, vector]) {
|
||||
for (const trackTotalHits of [true, 1n]) {
|
||||
await expect(query.toResult({ trackTotalHits })).rejects.toThrow(
|
||||
UnsupportedMetadataError,
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(parse).not.toHaveBeenCalled();
|
||||
expect(embed).not.toHaveBeenCalled();
|
||||
for (const query of [auto, vector]) {
|
||||
const off = await query.toResult({ trackTotalHits: false });
|
||||
expect((await off.next()).value?.numRows).toBe(1);
|
||||
expect(await off.finish()).toEqual({});
|
||||
expect((await query.toArray())[0].text).toBe("dog");
|
||||
}
|
||||
expect(embed).toHaveBeenCalledTimes(2);
|
||||
|
||||
const replacement = await db.createTable(
|
||||
"docs",
|
||||
[{ text: "dog fish" }, { text: "dog dog" }],
|
||||
{ mode: "overwrite" },
|
||||
);
|
||||
await replacement.createIndex("text", { config: Index.fts() });
|
||||
const exact = await auto.toResult({ trackTotalHits: true });
|
||||
expect((await exact.next()).value?.numRows).toBe(1);
|
||||
expect((await exact.finish()).totalHits).toEqual({
|
||||
value: 2n,
|
||||
relation: "eq",
|
||||
});
|
||||
const capped = await auto.toResult({ trackTotalHits: 1n });
|
||||
expect((await capped.finish()).totalHits).toEqual({
|
||||
value: 1n,
|
||||
relation: "gte",
|
||||
});
|
||||
expect(embed).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
parse.mockRestore();
|
||||
embed.mockRestore();
|
||||
db.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the schema refreshed from another connection", async () => {
|
||||
const first = await connect(tmpDir.name, { readConsistencyInterval: 0 });
|
||||
const second = await connect(tmpDir.name, { readConsistencyInterval: 0 });
|
||||
|
||||
Reference in New Issue
Block a user