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:
Yang Cen
2026-12-02 22:47:37 +08:00
committed by GitHub
parent 623777389e
commit feff86a08d
43 changed files with 3540 additions and 103 deletions
+79 -1
View File
@@ -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);
},
);
});