From feff86a08dd3f5df814ddf4c999ce45db2313bf7 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Wed, 2 Dec 2026 22:47:37 +0800 Subject: [PATCH] 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. --- docs/src/js/classes/AutoQuery.md | 43 ++ docs/src/js/classes/LanceError.md | 1 + docs/src/js/classes/MetadataCancelledError.md | 163 +++++++ docs/src/js/classes/MetadataPendingError.md | 163 +++++++ docs/src/js/classes/Query.md | 43 ++ docs/src/js/classes/QueryBase.md | 39 ++ docs/src/js/classes/QueryResult.md | 111 +++++ docs/src/js/classes/TakeQuery.md | 43 ++ .../js/classes/UnsupportedMetadataError.md | 459 ++++++++++++++++++ docs/src/js/classes/VectorQuery.md | 43 ++ docs/src/js/globals.md | 6 + docs/src/js/interfaces/QueryMetadata.md | 15 + docs/src/js/interfaces/TotalHits.md | 23 + docs/src/python/python.md | 42 ++ nodejs/__test__/query.test.ts | 80 ++- nodejs/__test__/remote.test.ts | 97 ++++ nodejs/__test__/table.test.ts | 56 +++ nodejs/lancedb/errors.ts | 6 + nodejs/lancedb/index.ts | 9 + nodejs/lancedb/query.ts | 156 ++++-- nodejs/lancedb/query_result.ts | 124 +++++ nodejs/lancedb/table.ts | 28 +- nodejs/src/error.rs | 1 + nodejs/src/iterator.rs | 55 +++ nodejs/src/query.rs | 68 ++- python/python/lancedb/_lancedb.pyi | 17 + python/python/lancedb/exceptions.py | 12 + python/python/lancedb/query.py | 113 +++++ python/python/lancedb/query_result.py | 205 ++++++++ python/python/lancedb/table.py | 34 +- python/python/tests/test_namespace.py | 47 ++ python/python/tests/test_query.py | 240 +++++++++ python/python/tests/test_remote_db.py | 134 ++++- python/src/error.rs | 6 + python/src/lib.rs | 2 + python/src/query.rs | 49 +- python/src/query_result.rs | 70 +++ rust/lancedb/src/error.rs | 5 + rust/lancedb/src/query.rs | 205 ++++++++ rust/lancedb/src/query/metadata.rs | 237 +++++++++ rust/lancedb/src/query/metadata_reader.rs | 92 ++++ rust/lancedb/src/remote/table/ipc_stream.rs | 45 ++ rust/lancedb/src/table/query.rs | 256 +++++++++- 43 files changed, 3540 insertions(+), 103 deletions(-) create mode 100644 docs/src/js/classes/MetadataCancelledError.md create mode 100644 docs/src/js/classes/MetadataPendingError.md create mode 100644 docs/src/js/classes/QueryResult.md create mode 100644 docs/src/js/classes/UnsupportedMetadataError.md create mode 100644 docs/src/js/interfaces/QueryMetadata.md create mode 100644 docs/src/js/interfaces/TotalHits.md create mode 100644 nodejs/lancedb/query_result.ts create mode 100644 python/python/lancedb/query_result.py create mode 100644 python/src/query_result.rs create mode 100644 rust/lancedb/src/query/metadata.rs create mode 100644 rust/lancedb/src/query/metadata_reader.rs diff --git a/docs/src/js/classes/AutoQuery.md b/docs/src/js/classes/AutoQuery.md index 311fc6a68..aeb4ed789 100644 --- a/docs/src/js/classes/AutoQuery.md +++ b/docs/src/js/classes/AutoQuery.md @@ -451,6 +451,49 @@ Empty results retain the query's output schema. *** +### toResult() + +```ts +toResult(options?): Promise +``` + +Stream one execution and read its metadata after successful exhaustion. +Tracking is off by default. Set `trackTotalHits` to `true` for an exact count +before offset and limit, or to a positive integer for a capped count. +At the cap, `totalHits.relation` is `"gte"`. + +Embedded supports counts for unfiltered scans, scans with deterministic scalar +filters, and row-level full-text searches for a single term or a positive OR +of terms with supported prefilters. Requesting a count on an Enterprise table +or an unsupported query, such as vector or hybrid search, throws +`UnsupportedMetadataError`. + +Counting can continue after the last data batch. Consume the iterator to EOF +or await `result.finish()` before calling `result.metadata()`. + +#### Parameters + +* **options?** + +* **options.trackTotalHits?**: `number` \| `bigint` \| `boolean` + +#### Returns + +`Promise`<[`QueryResult`](QueryResult.md)> + +#### Example + +```ts +const result = await table.query().limit(1).toResult({ trackTotalHits: 100n }); +const hits = (await result.finish()).totalHits; +``` + +#### Inherited from + +`StandardQueryBase.toResult` + +*** + ### useRTE() ```ts diff --git a/docs/src/js/classes/LanceError.md b/docs/src/js/classes/LanceError.md index 0b6ed3cab..579374fa4 100644 --- a/docs/src/js/classes/LanceError.md +++ b/docs/src/js/classes/LanceError.md @@ -56,6 +56,7 @@ try { - [`LanceRuntimeError`](LanceRuntimeError.md) - [`NotAComputedColumnError`](NotAComputedColumnError.md) - [`NotSupportedError`](NotSupportedError.md) +- [`UnsupportedMetadataError`](UnsupportedMetadataError.md) - [`ObjectStoreError`](ObjectStoreError.md) - [`OtherError`](OtherError.md) - [`RetryError`](RetryError.md) diff --git a/docs/src/js/classes/MetadataCancelledError.md b/docs/src/js/classes/MetadataCancelledError.md new file mode 100644 index 000000000..4025398a7 --- /dev/null +++ b/docs/src/js/classes/MetadataCancelledError.md @@ -0,0 +1,163 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / MetadataCancelledError + +# Class: MetadataCancelledError + +## Extends + +- `Error` + +## Constructors + +### new MetadataCancelledError() + +```ts +new MetadataCancelledError(message?): MetadataCancelledError +``` + +#### Parameters + +* **message?**: `string` + +#### Returns + +[`MetadataCancelledError`](MetadataCancelledError.md) + +#### Inherited from + +`Error.constructor` + +### new MetadataCancelledError() + +```ts +new MetadataCancelledError(message?, options?): MetadataCancelledError +``` + +#### Parameters + +* **message?**: `string` + +* **options?**: `ErrorOptions` + +#### Returns + +[`MetadataCancelledError`](MetadataCancelledError.md) + +#### Inherited from + +`Error.constructor` + +## Properties + +### cause? + +```ts +optional cause: unknown; +``` + +#### Inherited from + +`Error.cause` + +*** + +### message + +```ts +message: string; +``` + +#### Inherited from + +`Error.message` + +*** + +### name + +```ts +name: string; +``` + +#### Inherited from + +`Error.name` + +*** + +### stack? + +```ts +optional stack: string; +``` + +#### Inherited from + +`Error.stack` + +*** + +### prepareStackTrace()? + +```ts +static optional prepareStackTrace: (err, stackTraces) => any; +``` + +Optional override for formatting stack traces + +#### Parameters + +* **err**: `Error` + +* **stackTraces**: `CallSite`[] + +#### Returns + +`any` + +#### See + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Inherited from + +`Error.prepareStackTrace` + +*** + +### stackTraceLimit + +```ts +static stackTraceLimit: number; +``` + +#### Inherited from + +`Error.stackTraceLimit` + +## Methods + +### captureStackTrace() + +```ts +static captureStackTrace(targetObject, constructorOpt?): void +``` + +Create .stack property on a target object + +#### Parameters + +* **targetObject**: `object` + +* **constructorOpt?**: `Function` + +#### Returns + +`void` + +#### Inherited from + +`Error.captureStackTrace` diff --git a/docs/src/js/classes/MetadataPendingError.md b/docs/src/js/classes/MetadataPendingError.md new file mode 100644 index 000000000..5220219a5 --- /dev/null +++ b/docs/src/js/classes/MetadataPendingError.md @@ -0,0 +1,163 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / MetadataPendingError + +# Class: MetadataPendingError + +## Extends + +- `Error` + +## Constructors + +### new MetadataPendingError() + +```ts +new MetadataPendingError(message?): MetadataPendingError +``` + +#### Parameters + +* **message?**: `string` + +#### Returns + +[`MetadataPendingError`](MetadataPendingError.md) + +#### Inherited from + +`Error.constructor` + +### new MetadataPendingError() + +```ts +new MetadataPendingError(message?, options?): MetadataPendingError +``` + +#### Parameters + +* **message?**: `string` + +* **options?**: `ErrorOptions` + +#### Returns + +[`MetadataPendingError`](MetadataPendingError.md) + +#### Inherited from + +`Error.constructor` + +## Properties + +### cause? + +```ts +optional cause: unknown; +``` + +#### Inherited from + +`Error.cause` + +*** + +### message + +```ts +message: string; +``` + +#### Inherited from + +`Error.message` + +*** + +### name + +```ts +name: string; +``` + +#### Inherited from + +`Error.name` + +*** + +### stack? + +```ts +optional stack: string; +``` + +#### Inherited from + +`Error.stack` + +*** + +### prepareStackTrace()? + +```ts +static optional prepareStackTrace: (err, stackTraces) => any; +``` + +Optional override for formatting stack traces + +#### Parameters + +* **err**: `Error` + +* **stackTraces**: `CallSite`[] + +#### Returns + +`any` + +#### See + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Inherited from + +`Error.prepareStackTrace` + +*** + +### stackTraceLimit + +```ts +static stackTraceLimit: number; +``` + +#### Inherited from + +`Error.stackTraceLimit` + +## Methods + +### captureStackTrace() + +```ts +static captureStackTrace(targetObject, constructorOpt?): void +``` + +Create .stack property on a target object + +#### Parameters + +* **targetObject**: `object` + +* **constructorOpt?**: `Function` + +#### Returns + +`void` + +#### Inherited from + +`Error.captureStackTrace` diff --git a/docs/src/js/classes/Query.md b/docs/src/js/classes/Query.md index a4dd3c53f..89e7cdfdf 100644 --- a/docs/src/js/classes/Query.md +++ b/docs/src/js/classes/Query.md @@ -525,6 +525,49 @@ Empty results retain the query's output schema. *** +### toResult() + +```ts +toResult(options?): Promise +``` + +Stream one execution and read its metadata after successful exhaustion. +Tracking is off by default. Set `trackTotalHits` to `true` for an exact count +before offset and limit, or to a positive integer for a capped count. +At the cap, `totalHits.relation` is `"gte"`. + +Embedded supports counts for unfiltered scans, scans with deterministic scalar +filters, and row-level full-text searches for a single term or a positive OR +of terms with supported prefilters. Requesting a count on an Enterprise table +or an unsupported query, such as vector or hybrid search, throws +`UnsupportedMetadataError`. + +Counting can continue after the last data batch. Consume the iterator to EOF +or await `result.finish()` before calling `result.metadata()`. + +#### Parameters + +* **options?** + +* **options.trackTotalHits?**: `number` \| `bigint` \| `boolean` + +#### Returns + +`Promise`<[`QueryResult`](QueryResult.md)> + +#### Example + +```ts +const result = await table.query().limit(1).toResult({ trackTotalHits: 100n }); +const hits = (await result.finish()).totalHits; +``` + +#### Inherited from + +`StandardQueryBase.toResult` + +*** + ### useRTE() ```ts diff --git a/docs/src/js/classes/QueryBase.md b/docs/src/js/classes/QueryBase.md index 20ee8e558..f6bed6b21 100644 --- a/docs/src/js/classes/QueryBase.md +++ b/docs/src/js/classes/QueryBase.md @@ -258,6 +258,45 @@ Empty results retain the query's output schema. *** +### toResult() + +```ts +toResult(options?): Promise +``` + +Stream one execution and read its metadata after successful exhaustion. +Tracking is off by default. Set `trackTotalHits` to `true` for an exact count +before offset and limit, or to a positive integer for a capped count. +At the cap, `totalHits.relation` is `"gte"`. + +Embedded supports counts for unfiltered scans, scans with deterministic scalar +filters, and row-level full-text searches for a single term or a positive OR +of terms with supported prefilters. Requesting a count on an Enterprise table +or an unsupported query, such as vector or hybrid search, throws +`UnsupportedMetadataError`. + +Counting can continue after the last data batch. Consume the iterator to EOF +or await `result.finish()` before calling `result.metadata()`. + +#### Parameters + +* **options?** + +* **options.trackTotalHits?**: `number` \| `bigint` \| `boolean` + +#### Returns + +`Promise`<[`QueryResult`](QueryResult.md)> + +#### Example + +```ts +const result = await table.query().limit(1).toResult({ trackTotalHits: 100n }); +const hits = (await result.finish()).totalHits; +``` + +*** + ### withRowId() ```ts diff --git a/docs/src/js/classes/QueryResult.md b/docs/src/js/classes/QueryResult.md new file mode 100644 index 000000000..ad5500032 --- /dev/null +++ b/docs/src/js/classes/QueryResult.md @@ -0,0 +1,111 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / QueryResult + +# Class: QueryResult + +One execution with pull-driven batches and final metadata. + +## Implements + +- `AsyncIterableIterator`<`RecordBatch`> + +## Accessors + +### batches + +```ts +get batches(): AsyncIterableIterator> +``` + +#### Returns + +`AsyncIterableIterator`<`RecordBatch`<`any`>> + +## Methods + +### \[asyncIterator\]() + +```ts +asyncIterator: AsyncIterableIterator> +``` + +#### Returns + +`AsyncIterableIterator`<`RecordBatch`<`any`>> + +#### Implementation of + +`AsyncIterableIterator.[asyncIterator]` + +*** + +### close() + +```ts +close(): Promise +``` + +#### Returns + +`Promise`<`void`> + +*** + +### finish() + +```ts +finish(): Promise +``` + +#### Returns + +`Promise`<[`QueryMetadata`](../interfaces/QueryMetadata.md)> + +*** + +### metadata() + +```ts +metadata(): QueryMetadata +``` + +Access the successful terminal metadata without polling the stream. + +#### Returns + +[`QueryMetadata`](../interfaces/QueryMetadata.md) + +*** + +### next() + +```ts +next(): Promise, any>> +``` + +#### Returns + +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>> + +#### Implementation of + +`AsyncIterableIterator.next` + +*** + +### return() + +```ts +return(): Promise, any>> +``` + +#### Returns + +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>> + +#### Implementation of + +`AsyncIterableIterator.return` diff --git a/docs/src/js/classes/TakeQuery.md b/docs/src/js/classes/TakeQuery.md index 459f34998..6c3299d16 100644 --- a/docs/src/js/classes/TakeQuery.md +++ b/docs/src/js/classes/TakeQuery.md @@ -277,6 +277,49 @@ Empty results retain the query's output schema. *** +### toResult() + +```ts +toResult(options?): Promise +``` + +Stream one execution and read its metadata after successful exhaustion. +Tracking is off by default. Set `trackTotalHits` to `true` for an exact count +before offset and limit, or to a positive integer for a capped count. +At the cap, `totalHits.relation` is `"gte"`. + +Embedded supports counts for unfiltered scans, scans with deterministic scalar +filters, and row-level full-text searches for a single term or a positive OR +of terms with supported prefilters. Requesting a count on an Enterprise table +or an unsupported query, such as vector or hybrid search, throws +`UnsupportedMetadataError`. + +Counting can continue after the last data batch. Consume the iterator to EOF +or await `result.finish()` before calling `result.metadata()`. + +#### Parameters + +* **options?** + +* **options.trackTotalHits?**: `number` \| `bigint` \| `boolean` + +#### Returns + +`Promise`<[`QueryResult`](QueryResult.md)> + +#### Example + +```ts +const result = await table.query().limit(1).toResult({ trackTotalHits: 100n }); +const hits = (await result.finish()).totalHits; +``` + +#### Inherited from + +[`QueryBase`](QueryBase.md).[`toResult`](QueryBase.md#toresult) + +*** + ### useRTE() ```ts diff --git a/docs/src/js/classes/UnsupportedMetadataError.md b/docs/src/js/classes/UnsupportedMetadataError.md new file mode 100644 index 000000000..d59bb2398 --- /dev/null +++ b/docs/src/js/classes/UnsupportedMetadataError.md @@ -0,0 +1,459 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / UnsupportedMetadataError + +# Class: UnsupportedMetadataError + +The requested final metadata is unavailable for this query. + +## Extends + +- [`LanceError`](LanceError.md) + +## Constructors + +### new UnsupportedMetadataError() + +```ts +new UnsupportedMetadataError(message, options?): UnsupportedMetadataError +``` + +#### Parameters + +* **message**: `string` + +* **options?**: [`LanceErrorOptions`](../interfaces/LanceErrorOptions.md) + +#### Returns + +[`UnsupportedMetadataError`](UnsupportedMetadataError.md) + +#### Inherited from + +[`LanceError`](LanceError.md).[`constructor`](LanceError.md#constructors) + +## Properties + +### cause? + +```ts +optional cause: unknown; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`cause`](LanceError.md#cause) + +*** + +### code + +```ts +readonly code: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`code`](LanceError.md#code) + +*** + +### columnName? + +```ts +readonly optional columnName: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`columnName`](LanceError.md#columnname) + +*** + +### connectFailures? + +```ts +readonly optional connectFailures: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`connectFailures`](LanceError.md#connectfailures) + +*** + +### databaseName? + +```ts +readonly optional databaseName: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`databaseName`](LanceError.md#databasename) + +*** + +### errorCode? + +```ts +readonly optional errorCode: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`errorCode`](LanceError.md#errorcode) + +*** + +### functionName? + +```ts +readonly optional functionName: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`functionName`](LanceError.md#functionname) + +*** + +### grpcCode? + +```ts +readonly optional grpcCode: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`grpcCode`](LanceError.md#grpccode) + +*** + +### indexName? + +```ts +readonly optional indexName: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`indexName`](LanceError.md#indexname) + +*** + +### jobId? + +```ts +readonly optional jobId: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`jobId`](LanceError.md#jobid) + +*** + +### jobRequestId? + +```ts +readonly optional jobRequestId: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`jobRequestId`](LanceError.md#jobrequestid) + +*** + +### maxConnectFailures? + +```ts +readonly optional maxConnectFailures: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`maxConnectFailures`](LanceError.md#maxconnectfailures) + +*** + +### maxReadFailures? + +```ts +readonly optional maxReadFailures: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`maxReadFailures`](LanceError.md#maxreadfailures) + +*** + +### maxRequestFailures? + +```ts +readonly optional maxRequestFailures: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`maxRequestFailures`](LanceError.md#maxrequestfailures) + +*** + +### message + +```ts +message: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`message`](LanceError.md#message) + +*** + +### name + +```ts +name: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`name`](LanceError.md#name) + +*** + +### namespacePath? + +```ts +readonly optional namespacePath: string[]; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`namespacePath`](LanceError.md#namespacepath) + +*** + +### path? + +```ts +readonly optional path: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`path`](LanceError.md#path) + +*** + +### phase? + +```ts +readonly optional phase: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`phase`](LanceError.md#phase) + +*** + +### readFailures? + +```ts +readonly optional readFailures: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`readFailures`](LanceError.md#readfailures) + +*** + +### requestFailures? + +```ts +readonly optional requestFailures: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`requestFailures`](LanceError.md#requestfailures) + +*** + +### requestId? + +```ts +readonly optional requestId: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`requestId`](LanceError.md#requestid) + +*** + +### resourceKind? + +```ts +readonly optional resourceKind: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`resourceKind`](LanceError.md#resourcekind) + +*** + +### resourceName? + +```ts +readonly optional resourceName: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`resourceName`](LanceError.md#resourcename) + +*** + +### retryable? + +```ts +readonly optional retryable: boolean; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`retryable`](LanceError.md#retryable) + +*** + +### sqlJobId? + +```ts +readonly optional sqlJobId: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`sqlJobId`](LanceError.md#sqljobid) + +*** + +### stack? + +```ts +optional stack: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`stack`](LanceError.md#stack) + +*** + +### statusCode? + +```ts +readonly optional statusCode: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`statusCode`](LanceError.md#statuscode) + +*** + +### tableName? + +```ts +readonly optional tableName: string; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`tableName`](LanceError.md#tablename) + +*** + +### code + +```ts +readonly static code: "UnsupportedMetadata" = "UnsupportedMetadata"; +``` + +#### Overrides + +[`LanceError`](LanceError.md).[`code`](LanceError.md#code-1) + +*** + +### prepareStackTrace()? + +```ts +static optional prepareStackTrace: (err, stackTraces) => any; +``` + +Optional override for formatting stack traces + +#### Parameters + +* **err**: `Error` + +* **stackTraces**: `CallSite`[] + +#### Returns + +`any` + +#### See + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces + +#### Inherited from + +[`LanceError`](LanceError.md).[`prepareStackTrace`](LanceError.md#preparestacktrace) + +*** + +### stackTraceLimit + +```ts +static stackTraceLimit: number; +``` + +#### Inherited from + +[`LanceError`](LanceError.md).[`stackTraceLimit`](LanceError.md#stacktracelimit) + +## Methods + +### captureStackTrace() + +```ts +static captureStackTrace(targetObject, constructorOpt?): void +``` + +Create .stack property on a target object + +#### Parameters + +* **targetObject**: `object` + +* **constructorOpt?**: `Function` + +#### Returns + +`void` + +#### Inherited from + +[`LanceError`](LanceError.md).[`captureStackTrace`](LanceError.md#capturestacktrace) diff --git a/docs/src/js/classes/VectorQuery.md b/docs/src/js/classes/VectorQuery.md index d269a2c81..9e9b7a32c 100644 --- a/docs/src/js/classes/VectorQuery.md +++ b/docs/src/js/classes/VectorQuery.md @@ -836,6 +836,49 @@ Empty results retain the query's output schema. *** +### toResult() + +```ts +toResult(options?): Promise +``` + +Stream one execution and read its metadata after successful exhaustion. +Tracking is off by default. Set `trackTotalHits` to `true` for an exact count +before offset and limit, or to a positive integer for a capped count. +At the cap, `totalHits.relation` is `"gte"`. + +Embedded supports counts for unfiltered scans, scans with deterministic scalar +filters, and row-level full-text searches for a single term or a positive OR +of terms with supported prefilters. Requesting a count on an Enterprise table +or an unsupported query, such as vector or hybrid search, throws +`UnsupportedMetadataError`. + +Counting can continue after the last data batch. Consume the iterator to EOF +or await `result.finish()` before calling `result.metadata()`. + +#### Parameters + +* **options?** + +* **options.trackTotalHits?**: `number` \| `bigint` \| `boolean` + +#### Returns + +`Promise`<[`QueryResult`](QueryResult.md)> + +#### Example + +```ts +const result = await table.query().limit(1).toResult({ trackTotalHits: 100n }); +const hits = (await result.finish()).totalHits; +``` + +#### Inherited from + +`StandardQueryBase.toResult` + +*** + ### useRTE() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 08c534513..e01dd3785 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -56,6 +56,8 @@ - [MatchQuery](classes/MatchQuery.md) - [MaterializedView](classes/MaterializedView.md) - [MergeInsertBuilder](classes/MergeInsertBuilder.md) +- [MetadataCancelledError](classes/MetadataCancelledError.md) +- [MetadataPendingError](classes/MetadataPendingError.md) - [MultiMatchQuery](classes/MultiMatchQuery.md) - [NativeJsHeaderProvider](classes/NativeJsHeaderProvider.md) - [NotAComputedColumnError](classes/NotAComputedColumnError.md) @@ -69,6 +71,7 @@ - [PhraseQuery](classes/PhraseQuery.md) - [Query](classes/Query.md) - [QueryBase](classes/QueryBase.md) +- [QueryResult](classes/QueryResult.md) - [RetryError](classes/RetryError.md) - [Scannable](classes/Scannable.md) - [SchemaError](classes/SchemaError.md) @@ -84,6 +87,7 @@ - [Tags](classes/Tags.md) - [TakeQuery](classes/TakeQuery.md) - [TimeoutError](classes/TimeoutError.md) +- [UnsupportedMetadataError](classes/UnsupportedMetadataError.md) - [VectorColumnOptions](classes/VectorColumnOptions.md) - [VectorQuery](classes/VectorQuery.md) @@ -186,6 +190,7 @@ - [PrewarmDataResult](interfaces/PrewarmDataResult.md) - [PrewarmPruningSummary](interfaces/PrewarmPruningSummary.md) - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) +- [QueryMetadata](interfaces/QueryMetadata.md) - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) - [RTreeOptions](interfaces/RTreeOptions.md) @@ -217,6 +222,7 @@ - [TokenCacheOptions](interfaces/TokenCacheOptions.md) - [TokenResponse](interfaces/TokenResponse.md) - [TokenizeOptions](interfaces/TokenizeOptions.md) +- [TotalHits](interfaces/TotalHits.md) - [UpdateFieldMetadataResult](interfaces/UpdateFieldMetadataResult.md) - [UpdateOptions](interfaces/UpdateOptions.md) - [UpdateResult](interfaces/UpdateResult.md) diff --git a/docs/src/js/interfaces/QueryMetadata.md b/docs/src/js/interfaces/QueryMetadata.md new file mode 100644 index 000000000..a22e4cf5a --- /dev/null +++ b/docs/src/js/interfaces/QueryMetadata.md @@ -0,0 +1,15 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / QueryMetadata + +# Interface: QueryMetadata + +## Properties + +### totalHits? + +```ts +readonly optional totalHits: TotalHits; +``` diff --git a/docs/src/js/interfaces/TotalHits.md b/docs/src/js/interfaces/TotalHits.md new file mode 100644 index 000000000..51bda3986 --- /dev/null +++ b/docs/src/js/interfaces/TotalHits.md @@ -0,0 +1,23 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / TotalHits + +# Interface: TotalHits + +## Properties + +### relation + +```ts +readonly relation: "eq" | "gte"; +``` + +*** + +### value + +```ts +readonly value: bigint; +``` diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 8f6dff94a..39c8a7b3e 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -910,6 +910,37 @@ of raw SQL strings with [where][lancedb.query.LanceQueryBuilder.where] and ::: lancedb.query.Query +Use `query.to_result(track_total_hits=True)` to stream a page and read its exact +pre-pagination count after EOF. A positive integer up to `2**64 - 1` requests a +capped count. At the cap, `relation` is `"gte"`. Call `result.close()` or use a +context manager to cancel an unfinished read. + +Embedded scalar queries and supported row-level lexical queries can request counts. +A requested count on an unsupported plan raises +`lancedb.exceptions.UnsupportedMetadata` before yielding batches. The rich terminal +supports `with_row_address()` on plain Embedded scans. Each returned row's +`_rowaddr` identifies its physical fragment and offset in the query snapshot. +`with_fragments()` and `fragment_ids()` raise `UnsupportedMetadata`. +Before EOF, `metadata()` raises `MetadataPending`. +An early close raises `MetadataCancelled` on subsequent access. Stream failures +retain the underlying exception, including its request ID when supplied. An +explicit count can still take time or fail after the final data batch. For +example, a full-text query may scan visible text to establish the count. + +```python +with table.search().where("year >= 2020").limit(10).to_result(track_total_hits=100) as result: + for batch in result.batches: + print(batch.num_rows) + hits = result.metadata().total_hits + print(hits.relation, hits.value) # "gte", 100 if at least 100 rows match +``` + +::: lancedb.query_result.QueryResult + +::: lancedb.query_result.QueryMetadata + +::: lancedb.query_result.TotalHits + ::: lancedb.query.ColumnOrdering ::: lancedb.query.LanceQueryBuilder @@ -1469,6 +1500,17 @@ to return the entire (typically filtered) table. Vector searches return the rows nearest to a query vector and can be created with the [AsyncTable.vector_search][lancedb.table.AsyncTable.vector_search] method. +Use an async context manager to release an unfinished query when leaving the +loop early. Read the count after the iterator reaches EOF. + +```python +async with await table.query().limit(10).to_result(track_total_hits=True) as result: + async for batch in result.batches: + print(batch.num_rows) + print(result.metadata().total_hits.value) +``` + +::: lancedb.query_result.AsyncQueryResult ::: lancedb.query.AsyncQuery options: diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts index 4ecc38451..6cf48ff52 100644 --- a/nodejs/__test__/query.test.ts +++ b/nodejs/__test__/query.test.ts @@ -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); + }, + ); +}); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 7e6b84e0a..f74537973 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -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 { @@ -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( diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index adbd9bfc3..f8830f884 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -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 }); diff --git a/nodejs/lancedb/errors.ts b/nodejs/lancedb/errors.ts index 672a5bd4a..b8298ab83 100644 --- a/nodejs/lancedb/errors.ts +++ b/nodejs/lancedb/errors.ts @@ -307,6 +307,11 @@ export class NotSupportedError extends LanceError { static override readonly code = "NotSupported"; } +/** The requested final metadata is unavailable for this query. */ +export class UnsupportedMetadataError extends LanceError { + static override readonly code = "UnsupportedMetadata"; +} + /** A local operation exceeded its time limit. */ export class TimeoutError extends LanceError { static override readonly code = "Timeout"; @@ -400,6 +405,7 @@ const ERROR_CLASSES = new Map([ ["ColumnAlreadyExists", ColumnAlreadyExistsError], ["NotAComputedColumn", NotAComputedColumnError], ["NotSupported", NotSupportedError], + ["UnsupportedMetadata", UnsupportedMetadataError], ["Timeout", TimeoutError], ["Runtime", LanceRuntimeError], ["CreateDir", CreateDirError], diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 52acfdc9f..9a57344c4 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -149,6 +149,14 @@ export type { FunctionProfileWaitOptions, } from "./profiling"; +export { + QueryResult, + QueryMetadata, + TotalHits, + MetadataPendingError, + MetadataCancelledError, +} from "./query_result"; + export { AutoQuery, ExecutableQuery, @@ -282,6 +290,7 @@ export { NotAComputedColumnError, NotAMaterializedViewError, NotSupportedError, + UnsupportedMetadataError, ObjectStoreError, OtherError, RetryError, diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 1000f8940..72c79a410 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -19,7 +19,7 @@ import { vectorFromArray, } from "./arrow"; import { isBlobDescriptorField, isBlobField } from "./blob"; -import { bindErrorTranslator } from "./errors"; +import { UnsupportedMetadataError, bindErrorTranslator } from "./errors"; import { Expr } from "./expr"; import { type IvfPqOptions } from "./indices"; import { @@ -34,6 +34,7 @@ import { TakeQuery as NativeTakeQuery, VectorQuery as NativeVectorQuery, } from "./native"; +import { QueryResult, normalizeTrackTotalHits } from "./query_result"; import { Reranker } from "./rerankers"; export async function* RecordBatchIterator( @@ -376,6 +377,8 @@ function addQueryVectorToNative( } } +type PrepareQuery = (trackTotalHits: boolean) => Promise; + /** Common methods supported by all query types * * @see {@link Query} @@ -388,6 +391,11 @@ export class QueryBase< > implements AsyncIterable { protected inner!: NativeQueryType | Promise; + /** @hidden */ + protected readonly deferred?: { + prepare: PrepareQuery; + calls: Array<(inner: NativeQueryType) => void>; + }; /** * @hidden @@ -400,8 +408,11 @@ export class QueryBase< protected constructor( inner?: NativeQueryType | Promise, blobContext?: QueryBlobContext, + prepare?: PrepareQuery, ) { - if (inner !== undefined) { + if (prepare) { + this.deferred = { prepare, calls: [] }; + } else if (inner !== undefined) { this.setInner( inner instanceof Promise ? inner : bindErrorTranslator(inner), ); @@ -423,7 +434,9 @@ export class QueryBase< * @hidden */ protected doCall(fn: (inner: NativeQueryType) => void) { - if (this.inner instanceof Promise) { + if (this.deferred) { + this.deferred.calls.push(fn); + } else if (this.inner instanceof Promise) { this.setInner( this.inner.then((inner) => { const bound = bindErrorTranslator(inner); @@ -441,7 +454,15 @@ export class QueryBase< * * @hidden */ - protected async getInner(): Promise { + protected async getInner(trackTotalHits = false): Promise { + if (this.deferred) { + const calls = [...this.deferred.calls]; + const inner = bindErrorTranslator( + await this.deferred.prepare(trackTotalHits), + ); + for (const call of calls) call(inner); + return inner; + } return this.inner; } @@ -566,6 +587,40 @@ export class QueryBase< ); } + /** + * Stream one execution and read its metadata after successful exhaustion. + * Tracking is off by default. Set `trackTotalHits` to `true` for an exact count + * before offset and limit, or to a positive integer for a capped count. + * At the cap, `totalHits.relation` is `"gte"`. + * + * Embedded supports counts for unfiltered scans, scans with deterministic scalar + * filters, and row-level full-text searches for a single term or a positive OR + * of terms with supported prefilters. Requesting a count on an Enterprise table + * or an unsupported query, such as vector or hybrid search, throws + * `UnsupportedMetadataError`. + * + * Counting can continue after the last data batch. Consume the iterator to EOF + * or await `result.finish()` before calling `result.metadata()`. + * + * @example + * const result = await table.query().limit(1).toResult({ trackTotalHits: 100n }); + * const hits = (await result.finish()).totalHits; + */ + async toResult(options?: { + trackTotalHits?: boolean | number | bigint; + }): Promise { + for (const field of Object.keys(options ?? {})) { + if (field !== "trackTotalHits") { + throw new UnsupportedMetadataError( + `Unknown query metadata option: ${field}`, + ); + } + } + const [track, cap] = normalizeTrackTotalHits(options?.trackTotalHits); + const query = await this.getInner(track); + return new QueryResult(await query.executeWithMetadata(track, cap)); + } + /** * Execute the query and return the results as an @see {@link AsyncIterator} * of @see {@link RecordBatch}. @@ -774,8 +829,9 @@ export class StandardQueryBase< constructor( inner?: NativeQueryType | Promise, blobContext?: QueryBlobContext, + prepare?: PrepareQuery, ) { - super(inner, blobContext); + super(inner, blobContext, prepare); } /** @@ -962,10 +1018,25 @@ export class VectorQuery extends StandardQueryBase { * @hidden */ constructor( - inner: NativeVectorQuery | Promise, + inner: + | NativeVectorQuery + | Promise + | PrepareQuery, blobContext?: QueryBlobContext, ) { - super(inner, blobContext); + super( + typeof inner === "function" ? undefined : inner, + blobContext, + typeof inner === "function" ? inner : undefined, + ); + } + + /** @hidden */ + protected override async getInner( + trackTotalHits = false, + ): Promise { + if (trackTotalHits) throw unsupportedVectorMetadata(); + return super.getInner(); } /** @@ -1234,7 +1305,7 @@ export class VectorQuery extends StandardQueryBase { (value) => ({ status: "fulfilled" as const, value }), (reason) => ({ status: "rejected" as const, reason }), ); - const res = (async () => { + const prepare = async () => { const inner = await this.getInner(); const outcome = await settledVector; if (outcome.status === "rejected") { @@ -1242,8 +1313,13 @@ export class VectorQuery extends StandardQueryBase { } addQueryVectorToNative(inner, outcome.value); return inner; - })(); - return new VectorQuery(res, this.blobContext); + }; + // A string vector search may still need to call an embedding provider. + // Keep that work behind the terminal operation even for batch queries. + return new VectorQuery( + this.deferred ? prepare : prepare(), + this.blobContext, + ); } else { this.doVectorCall((inner) => addQueryVectorToNative(inner, vector)); return this; @@ -1325,7 +1401,14 @@ export function createAutoQuery( }; }; - const createInner = async (): Promise => { + const createInner = async ( + trackTotalHits: boolean, + ): Promise => { + if (trackTotalHits && !table.isNative()) { + throw new UnsupportedMetadataError( + "total_hits is unavailable on Enterprise tables", + ); + } const route = await snapshotRoute(); if (route.embeddingMetadata === undefined) { const inner = route.table.query(); @@ -1333,6 +1416,7 @@ export function createAutoQuery( return inner; } + if (trackTotalHits) throw unsupportedVectorMetadata(); const metadata = route.embeddingMetadata; if (cachedPreparation?.metadata !== metadata) { cachedPreparation = { @@ -1358,6 +1442,27 @@ export function createAutoQuery( return new AutoQuery(createInner, { table, withRowId: false }); } +function unsupportedVectorMetadata(): UnsupportedMetadataError { + return new UnsupportedMetadataError( + "total_hits is unavailable for vector search", + ); +} + +/** @hidden */ +export function createEmbeddingQuery( + table: NativeTable, + getVector: () => Promise>, +): VectorQuery { + let vector: Promise> | undefined; + return new VectorQuery( + async () => { + vector ??= getVector(); + return nearestToNative(table.query(), await vector); + }, + { table, withRowId: false }, + ); +} + /** * A query that returns a subset of the rows in the table. * @@ -1395,37 +1500,12 @@ export class TakeQuery extends QueryBase { export class AutoQuery extends StandardQueryBase< NativeQuery | NativeVectorQuery > { - private readonly calls: Array< - (inner: NativeQuery | NativeVectorQuery) => void - > = []; - /** @hidden */ constructor( - private readonly createInner: () => Promise< - NativeQuery | NativeVectorQuery - >, + createInner: PrepareQuery, blobContext?: QueryBlobContext, ) { - super(undefined, blobContext); - } - - /** @hidden */ - protected override doCall( - fn: (inner: NativeQuery | NativeVectorQuery) => void, - ) { - this.calls.push(fn); - } - - /** @hidden */ - protected override async getInner(): Promise< - NativeQuery | NativeVectorQuery - > { - const calls = [...this.calls]; - const inner = await this.createInner(); - for (const call of calls) { - call(inner); - } - return inner; + super(undefined, blobContext, createInner); } } diff --git a/nodejs/lancedb/query_result.ts b/nodejs/lancedb/query_result.ts new file mode 100644 index 000000000..6be5a27dd --- /dev/null +++ b/nodejs/lancedb/query_result.ts @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { type RecordBatch, tableFromIPC } from "./arrow"; +import { bindErrorTranslator, materializeLanceError } from "./errors"; +import type { NativeQueryResult } from "./native"; + +export interface TotalHits { + readonly value: bigint; + readonly relation: "eq" | "gte"; +} + +export interface QueryMetadata { + readonly totalHits?: TotalHits; +} + +export class MetadataPendingError extends Error {} +export class MetadataCancelledError extends Error {} + +/** @hidden */ +export function normalizeTrackTotalHits( + value: boolean | number | bigint = false, +): [boolean, bigint?] { + if (typeof value === "boolean") return [value]; + if (typeof value === "number" && Number.isSafeInteger(value)) { + value = BigInt(value); + } + if ( + typeof value !== "bigint" || + value <= 0n || + value > 0xffff_ffff_ffff_ffffn + ) { + throw new RangeError( + "trackTotalHits must be a boolean, positive safe integer, or positive u64 bigint", + ); + } + return [true, value]; +} + +/** One execution with pull-driven batches and final metadata. */ +export class QueryResult implements AsyncIterableIterator { + private finalMetadata?: QueryMetadata; + private failure?: Error; + private reading = false; + + /** @hidden */ + constructor(private readonly native: NativeQueryResult) { + bindErrorTranslator(native); + } + + get batches(): AsyncIterableIterator { + return this; + } + + [Symbol.asyncIterator](): AsyncIterableIterator { + return this; + } + + async next(): Promise> { + if (this.failure) throw this.failure; + if (this.finalMetadata) return { done: true, value: undefined }; + if (this.reading) throw new Error("A batch read is already in progress"); + this.reading = true; + try { + const buffer = await this.native.nextBatch(); + if (this.failure) throw this.failure; + if (buffer) { + const { batches } = tableFromIPC(buffer); + if (batches.length !== 1) throw new Error("Expected one Arrow batch"); + return { done: false, value: batches[0] }; + } + const hits = this.native.totalHits(); + if (hits && hits.relation !== "eq" && hits.relation !== "gte") { + throw new Error("Unknown total_hits relation"); + } + this.finalMetadata = hits + ? { + totalHits: { + value: hits.value, + relation: hits.relation as "eq" | "gte", + }, + } + : {}; + return { done: true, value: undefined }; + } catch (error) { + const failure = materializeLanceError(error); + this.failure ??= + failure instanceof Error ? failure : new Error(String(failure)); + await this.native.close(); + throw this.failure; + } finally { + this.reading = false; + } + } + + /** Access the successful terminal metadata without polling the stream. */ + metadata(): QueryMetadata { + if (this.failure) throw this.failure; + if (!this.finalMetadata) + throw new MetadataPendingError("Query metadata is pending until EOF"); + return this.finalMetadata; + } + + async finish(): Promise { + while (!(await this.next()).done) { + // Discard each remaining batch. + } + return this.metadata(); + } + + async close(): Promise { + if (!this.finalMetadata && !this.failure) { + this.failure = new MetadataCancelledError( + "Query result was closed before EOF", + ); + } + await this.native.close(); + } + + async return(): Promise> { + await this.close(); + return { done: true, value: undefined }; + } +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 1efb2171b..ff0485c3e 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -178,6 +178,7 @@ import { TakeQuery, VectorQuery, createAutoQuery, + createEmbeddingQuery, instanceOfFullTextQuery, } from "./query"; import { sanitizeSchema, sanitizeType } from "./sanitize"; @@ -2147,22 +2148,17 @@ export class LocalTable extends Table { }); } - const queryPromise = this.getEmbeddingFunctions().then( - async (functions) => { - // TODO: Support multiple embedding functions - const embeddingFunc: EmbeddingFunctionConfig | undefined = functions - .values() - .next().value; - if (!embeddingFunc) { - return Promise.reject( - new Error("No embedding functions are defined in the table"), - ); - } - return await embeddingFunc.function.computeQueryEmbeddings(query); - }, - ); - - return this.query().nearestTo(queryPromise); + return createEmbeddingQuery(this.inner, async () => { + const functions = await this.getEmbeddingFunctions(); + // TODO: Support multiple embedding functions + const embeddingFunc: EmbeddingFunctionConfig | undefined = functions + .values() + .next().value; + if (!embeddingFunc) { + throw new Error("No embedding functions are defined in the table"); + } + return await embeddingFunc.function.computeQueryEmbeddings(query); + }); } vectorSearch(vector: IntoVector | MultiVector): VectorQuery { diff --git a/nodejs/src/error.rs b/nodejs/src/error.rs index 0e38043a2..a7b3c02c5 100644 --- a/nodejs/src/error.rs +++ b/nodejs/src/error.rs @@ -75,6 +75,7 @@ fn error_payload(err: &LanceError) -> String { fn error_code(err: &LanceError) -> &'static str { match err { + err if err.unsupported_metadata().is_some() => "UnsupportedMetadata", LanceError::InvalidTableName { .. } => "InvalidTableName", LanceError::InvalidInput { .. } => "InvalidInput", LanceError::TableNotFound { .. } => "TableNotFound", diff --git a/nodejs/src/iterator.rs b/nodejs/src/iterator.rs index 96d08c765..3c2f440eb 100644 --- a/nodejs/src/iterator.rs +++ b/nodejs/src/iterator.rs @@ -42,3 +42,58 @@ impl RecordBatchIterator { } } } + +/// A pull-driven result with interruptible reads and a final count. +#[napi] +pub struct NativeQueryResult { + reader: lancedb::query::metadata_reader::QueryResultReader, +} + +#[napi(object)] +pub struct NativeTotalHits { + pub value: BigInt, + pub relation: String, +} + +#[napi] +impl NativeQueryResult { + pub(crate) fn new(result: lancedb::query::QueryResult) -> Self { + Self { + reader: lancedb::query::metadata_reader::QueryResultReader::new(result), + } + } + + #[napi(catch_unwind)] + pub async fn next_batch(&self) -> napi::Result> { + let batch = self + .reader + .next() + .await + .map_err(|e| crate::error::convert_error(&e))?; + batch + .map(|b| { + batches_to_ipc_file(&[b]) + .map(Buffer::from) + .map_err(|e| crate::error::convert_error(&e)) + }) + .transpose() + } + + #[napi] + pub fn total_hits(&self) -> napi::Result> { + let metadata = self + .reader + .metadata() + .map_err(|e| napi::Error::from_reason(e.to_string()))?; + Ok(metadata.total_hits.as_ref().map(|hits| NativeTotalHits { + value: BigInt::from(hits.value), + relation: hits.relation.as_str().into(), + })) + } + + #[napi(catch_unwind)] + pub async fn close(&self) -> napi::Result<()> { + self.reader.close().await; + Ok(()) + } +} diff --git a/nodejs/src/query.rs b/nodejs/src/query.rs index 7b32f4f32..99f61282e 100644 --- a/nodejs/src/query.rs +++ b/nodejs/src/query.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use crate::error::NapiErrorExt; use crate::error::convert_error; -use crate::iterator::RecordBatchIterator; +use crate::iterator::{NativeQueryResult, RecordBatchIterator}; use crate::rerankers::{RerankHybridCallbackArgs, RerankVectorCallbackArgs, Reranker}; use crate::util::{parse_distance_type, schema_to_buffer}; use arrow_array::{ @@ -48,6 +48,25 @@ impl From for LanceDbColumnOrdering { } } +fn metadata_request( + track: bool, + cap: Option, +) -> napi::Result { + use lancedb::query::{MetadataRequest, TrackTotalHits}; + let mode = if let Some(cap) = cap { + let (negative, value, lossless) = cap.get_u64(); + let cap = std::num::NonZeroU64::new(value) + .filter(|_| !negative && lossless) + .ok_or_else(|| napi::Error::from_reason("trackTotalHits must be a positive u64"))?; + TrackTotalHits::UpTo(cap) + } else if track { + TrackTotalHits::Exact + } else { + TrackTotalHits::Off + }; + Ok(MetadataRequest::new().track_total_hits(mode)) +} + fn analyze_plan_options( distributed_metrics: Option, ) -> napi::Result { @@ -196,6 +215,22 @@ impl Query { schema_to_buffer(&schema) } + #[napi(catch_unwind)] + pub async fn execute_with_metadata( + &self, + track: bool, + cap: Option, + ) -> napi::Result { + let request = metadata_request(track, cap)?; + let options = QueryExecutionOptions::default().with_optional_max_batch_length(None); + let result = self + .inner + .execute_with_metadata(options, request) + .await + .default_error()?; + Ok(NativeQueryResult::new(result)) + } + #[napi(catch_unwind)] pub async fn execute( &self, @@ -437,6 +472,22 @@ impl VectorQuery { schema_to_buffer(&schema) } + #[napi(catch_unwind)] + pub async fn execute_with_metadata( + &self, + track: bool, + cap: Option, + ) -> napi::Result { + let request = metadata_request(track, cap)?; + let options = QueryExecutionOptions::default().with_optional_max_batch_length(None); + let result = self + .inner + .execute_with_metadata(options, request) + .await + .default_error()?; + Ok(NativeQueryResult::new(result)) + } + #[napi(catch_unwind)] pub async fn execute( &self, @@ -516,6 +567,21 @@ impl TakeQuery { schema_to_buffer(&schema) } + #[napi(catch_unwind)] + pub async fn execute_with_metadata( + &self, + track: bool, + cap: Option, + ) -> napi::Result { + let request = metadata_request(track, cap)?; + let result = self + .inner + .execute_with_metadata(Default::default(), request) + .await + .default_error()?; + Ok(NativeQueryResult::new(result)) + } + #[napi(catch_unwind)] pub async fn execute( &self, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 7a5dad12c..eb6f38710 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1087,6 +1087,11 @@ class TableDelta: async def deleted_row_ids(self) -> RecordBatchStream: ... async def list_transactions(self) -> List[Dict[str, Any]]: ... +class NativeQueryResult: + async def next_batch(self) -> Optional[pa.RecordBatch]: ... + def total_hits(self) -> Optional[tuple[int, Literal["eq", "gte"]]]: ... + async def close(self) -> None: ... + class Query: def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... @@ -1105,6 +1110,9 @@ class Query: def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... def scan_in_order(self, ordered: bool): ... async def output_schema(self) -> pa.Schema: ... + async def execute_with_metadata( + self, track: bool, cap: Optional[int] = None + ) -> NativeQueryResult: ... async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... @@ -1129,6 +1137,9 @@ class TakeQuery: def preserve_order(self): ... def use_rte(self, enable: bool): ... async def output_schema(self) -> pa.Schema: ... + async def execute_with_metadata( + self, track: bool, cap: Optional[int] = None + ) -> NativeQueryResult: ... async def execute(self) -> RecordBatchStream: ... async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] @@ -1159,6 +1170,9 @@ class FTSQuery: def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... async def count_rows(self) -> int: ... async def output_schema(self) -> pa.Schema: ... + async def execute_with_metadata( + self, track: bool, cap: Optional[int] = None + ) -> NativeQueryResult: ... async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... @@ -1177,6 +1191,9 @@ class FTSQuery: class VectorQuery: def ordered_results(self, ordered: bool) -> None: ... async def output_schema(self) -> pa.Schema: ... + async def execute_with_metadata( + self, track: bool, cap: Optional[int] = None + ) -> NativeQueryResult: ... async def execute(self) -> RecordBatchStream: ... async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] diff --git a/python/python/lancedb/exceptions.py b/python/python/lancedb/exceptions.py index e5f7c9a47..8c2533d00 100644 --- a/python/python/lancedb/exceptions.py +++ b/python/python/lancedb/exceptions.py @@ -92,3 +92,15 @@ class JobNotFoundError(ValueError): """Exception raised when opening a job the server does not have.""" pass + + +class UnsupportedMetadata(NotImplementedError): + """This execution cannot produce the requested metadata.""" + + +class MetadataPending(RuntimeError): + """The consumer has not observed successful end of stream.""" + + +class MetadataCancelled(RuntimeError): + """The result was closed before end of stream.""" diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 752736733..cf4336a10 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -7,6 +7,7 @@ import asyncio import math from abc import ABC, abstractmethod from concurrent.futures import ThreadPoolExecutor +from copy import copy from datetime import timedelta from enum import Enum from typing import ( @@ -43,6 +44,8 @@ from lancedb.background_loop import LOOP from . import __version__ from .arrow import AsyncRecordBatchReader from .dependencies import pandas as pd +from .exceptions import UnsupportedMetadata +from .query_result import AsyncQueryResult, QueryResult, _track_total_hits from .expr import Expr from .rerankers.base import Reranker from .rerankers.rrf import RRFReranker @@ -310,6 +313,25 @@ def _is_remote_query_table(table: Any) -> bool: return not async_table._inner._is_native() +def _result_tracking(value: bool | int, table: Any) -> tuple[bool, int | None]: + track, cap = _track_total_hits(value) + if track and table is not None and _is_remote_query_table(table): + # Blob projection preparation may fetch the schema over HTTP. + raise UnsupportedMetadata("total_hits is unavailable on LanceDB Enterprise") + return track, cap + + +def _validate_result_scan(query: LanceQueryBuilder | AsyncQueryBase) -> None: + if query._fragments is not None or query._fragment_ids is not None: + raise UnsupportedMetadata("to_result does not support fragment selection") + if query._with_row_address and ( + not isinstance(query, (LanceEmptyQueryBuilder, AsyncQuery)) + or query._table is None + or _is_remote_query_table(query._table) + ): + raise UnsupportedMetadata("row addresses require a plain Embedded scan") + + def _query_needs_lance_scanner(builder: Any) -> bool: """Whether the query sets options that to_arrow ignores.""" to_query_object = getattr(builder, "to_query_object", None) @@ -1631,6 +1653,61 @@ class LanceQueryBuilder(ABC): ) return flatten_columns(tbl, flatten).to_pandas(**kwargs) + def to_result(self, *, track_total_hits: bool | int = False) -> QueryResult: + """Stream one query and read its pre-pagination count after EOF. + + Use True for an exact count or a positive integer for a capped count. + Use the result as a context manager to cancel an unfinished read. + """ + from .table import LanceTable + + track, _ = _result_tracking(track_total_hits, self._table) + + _validate_result_scan(self) + if isinstance(self, LanceFtsQueryBuilder) and self._explicit_zero_limit: + # All result paths, including Python reranking and namespace pushdown, + # need the empty page. Keep legacy terminals on this builder reusable. + self = copy(self) + self._limit = 0 + if ( + isinstance(self, LanceHybridQueryBuilder) + or getattr(self, "_reranker", None) is not None + ): + if track: + raise UnsupportedMetadata( + "total_hits is unavailable for hybrid or rerank" + ) + if isinstance(self, (LanceHybridQueryBuilder, LanceFtsQueryBuilder)): + # These rankers already require the complete candidate set. + return QueryResult(self.to_arrow().to_reader()) + return QueryResult(self.to_batches()) + + request = self.to_query_object() + if isinstance( + self._table, LanceTable + ) and self._table._uses_python_query_pushdown(request): + if track: + raise UnsupportedMetadata( + "total_hits is unavailable for namespace pushdown" + ) + if isinstance(self, LanceFtsQueryBuilder): + self._table._ensure_no_legacy_fts_index() + sources, schema = self._prepare_blob_execution("lazy") + return QueryResult( + self._to_batches_prepared( + batch_size=None, + timeout=None, + blob_mode="lazy", + blob_sources=sources, + schema=schema, + ) + ) + return QueryResult(self.to_batches()) + if isinstance(self, LanceFtsQueryBuilder): + self._table._ensure_no_legacy_fts_index() + query = self._table._table._sync_query_to_async(request) + return QueryResult(LOOP.run(query.to_result(track_total_hits=track_total_hits))) + @abstractmethod def to_arrow( self, @@ -3068,6 +3145,7 @@ class LanceFtsQueryBuilder(_RankedResultOrder, LanceQueryBuilder): ): super().__init__(table) self._query = query + self._explicit_zero_limit = False self._phrase_query = False self._operator: Optional[FullTextOperator] = None # Deprecated compatibility parameter. Native FTS ordering is now @@ -3080,6 +3158,12 @@ class LanceFtsQueryBuilder(_RankedResultOrder, LanceQueryBuilder): self._fts_columns = fts_columns self._wand_factor = None + def limit(self, limit: int | None) -> Self: + # Legacy FTS terminals normalize zero to an unspecified limit. Preserve + # the explicit empty page for to_result(), where it still has a count. + self._explicit_zero_limit = limit == 0 + return super().limit(limit) + def wand_factor(self, wand_factor: Optional[float]) -> LanceFtsQueryBuilder: """Set the WAND factor for full text search. @@ -4497,6 +4581,29 @@ class AsyncQueryBase(object): self._fragment_ids = fragment_ids return self + async def to_result( + self, *, track_total_hits: bool | int = False + ) -> AsyncQueryResult: + """Stream one execution and read its final metadata after successful EOF. + + For example, `async with await query.to_result(track_total_hits=1000) as r` + exposes `r.batches` and the nonblocking accessor `r.metadata()`. + """ + track, cap = _result_tracking(track_total_hits, self._table) + _validate_result_scan(self) + if ( + isinstance(self, AsyncHybridQuery) + or getattr(self, "_reranker", None) is not None + ): + if track: + raise UnsupportedMetadata( + "total_hits is unavailable for hybrid or reranked queries" + ) + return AsyncQueryResult(None, await self.to_batches()) + if not self._blob_row_id_prepared: + await self._maybe_add_blob_row_id() + return AsyncQueryResult(await self._inner.execute_with_metadata(track, cap)) + async def to_batches( self, *, @@ -6549,6 +6656,12 @@ class BaseQueryBuilder(object): """ return LOOP.run(self._inner.output_schema()) + def to_result(self, *, track_total_hits: bool | int = False) -> QueryResult: + """Execute once and stream the result with optional final metadata.""" + return QueryResult( + LOOP.run(self._inner.to_result(track_total_hits=track_total_hits)) + ) + def to_batches( self, *, diff --git a/python/python/lancedb/query_result.py b/python/python/lancedb/query_result.py new file mode 100644 index 000000000..84fb46bef --- /dev/null +++ b/python/python/lancedb/query_result.py @@ -0,0 +1,205 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass +from typing import TYPE_CHECKING, Literal + +import pyarrow as pa + +from .background_loop import LOOP +from .exceptions import MetadataCancelled, MetadataPending + +if TYPE_CHECKING: + from ._lancedb import NativeQueryResult + from .arrow import AsyncRecordBatchReader + + +def _track_total_hits(value: bool | int) -> tuple[bool, int | None]: + if isinstance(value, bool): + return value, None + if not isinstance(value, int): + raise TypeError("track_total_hits must be a bool or a positive integer") + if not 0 < value < 2**64: + raise ValueError("track_total_hits must be between 1 and 2**64 - 1") + return True, value + + +@dataclass(frozen=True) +class TotalHits: + """Number of distinct visible rows matched before offset and limit.""" + + value: int + relation: Literal["eq", "gte"] + + +@dataclass(frozen=True) +class QueryMetadata: + """Final metadata for one successful execution.""" + + total_hits: TotalHits | None + + +class AsyncQueryResult: + """A single-use batch iterator with a nonblocking final metadata accessor.""" + + def __init__( + self, + native: NativeQueryResult | None, + legacy: AsyncRecordBatchReader | None = None, + ): + self._native = native + self._legacy = legacy + self._metadata: QueryMetadata | None = None + self._failure: BaseException | None = None + self._reading = False + + @property + def batches(self) -> AsyncQueryResult: + """Pull the next available Arrow batch from this execution.""" + return self + + def __aiter__(self): + return self + + async def __anext__(self) -> pa.RecordBatch: + if self._failure is not None: + raise self._failure + if self._metadata is not None: + raise StopAsyncIteration + if self._reading: + raise RuntimeError("A batch read is already in progress") + self._reading = True + try: + if self._native is not None: + batch = await self._native.next_batch() + if self._failure is not None: + raise self._failure + if batch is not None: + return batch + hits = self._native.total_hits() + else: + assert self._legacy is not None + try: + batch = await self._legacy.__anext__() + except StopAsyncIteration: + hits = None + else: + if self._failure is not None: + raise self._failure + return batch + if self._failure is not None: + raise self._failure + self._metadata = QueryMetadata(TotalHits(*hits) if hits else None) + except asyncio.CancelledError: + await self.close() + raise + except Exception as error: + if self._failure is None: + self._failure = error + await self.close() + raise self._failure + finally: + self._reading = False + raise StopAsyncIteration + + def metadata(self) -> QueryMetadata: + """Return final metadata, or raise MetadataPending before EOF.""" + if self._failure is not None: + raise self._failure + if self._metadata is None: + raise MetadataPending("Query metadata is pending until EOF") + return self._metadata + + async def finish(self) -> QueryMetadata: + """Drain remaining batches and return final metadata.""" + async for _ in self: + pass + return self.metadata() + + async def close(self) -> None: + """Cancel outstanding work and preserve any completed outcome.""" + if self._metadata is None and self._failure is None: + self._failure = MetadataCancelled("Query result was closed before EOF") + if self._native is not None: + await self._native.close() + self._legacy = None + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + await self.close() + + +class QueryResult: + """A synchronous batch iterator over one execution. Use as a context manager.""" + + def __init__(self, result: AsyncQueryResult | pa.RecordBatchReader): + self._result = result + self._metadata: QueryMetadata | None = None + self._failure: BaseException | None = None + + @property + def batches(self) -> QueryResult: + """Pull the next available Arrow batch from this execution.""" + return self + + def __iter__(self): + return self + + def __next__(self) -> pa.RecordBatch: + if isinstance(self._result, AsyncQueryResult): + try: + return LOOP.run(self._result.__anext__()) + except StopAsyncIteration: + raise StopIteration from None + if self._failure is not None: + raise self._failure + if self._metadata is not None: + raise StopIteration + try: + return next(self._result) + except StopIteration: + self._metadata = QueryMetadata(None) + self._result.close() + raise + except BaseException as error: + self._failure = error + self._result.close() + raise + + def metadata(self) -> QueryMetadata: + """Return final metadata, or raise MetadataPending before EOF.""" + if isinstance(self._result, AsyncQueryResult): + return self._result.metadata() + if self._failure is not None: + raise self._failure + if self._metadata is None: + raise MetadataPending("Query metadata is pending until EOF") + return self._metadata + + def finish(self) -> QueryMetadata: + """Drain remaining batches and return final metadata.""" + if isinstance(self._result, AsyncQueryResult): + return LOOP.run(self._result.finish()) + for _ in self: + pass + return self.metadata() + + def close(self) -> None: + """Cancel outstanding work and preserve any completed outcome.""" + if isinstance(self._result, AsyncQueryResult): + LOOP.run(self._result.close()) + else: + if self._metadata is None and self._failure is None: + self._failure = MetadataCancelled("Query result was closed before EOF") + self._result.close() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 273c8085a..6dec72aac 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -6515,6 +6515,19 @@ class LanceTable(Table): """ return LOOP.run(self._table.update(values, where=where, updates_sql=values_sql)) + def _uses_python_query_pushdown(self, query: Query) -> bool: + # Branch queries run locally: the server-side query protocol can't + # carry a branch yet. + # TODO: push down server-side once it can (with remote table support). + return ( + _should_push_down_query_table( + self._namespace_client, self._pushdown_operations + ) + and not self._route_pushdown_to_rust + and self.current_branch() is None + and not _requires_local_namespace_execution(query, self._table) + ) + def _execute_query( self, query: Query, @@ -6522,17 +6535,7 @@ class LanceTable(Table): batch_size: Optional[int] = None, timeout: Optional[timedelta] = None, ) -> pa.RecordBatchReader: - # Branch queries run locally: the server-side query protocol can't - # carry a branch yet. - # TODO: push down server-side once it can (with remote table support). - if ( - _should_push_down_query_table( - self._namespace_client, self._pushdown_operations - ) - and not self._route_pushdown_to_rust - and self.current_branch() is None - and not _requires_local_namespace_execution(query, self._table) - ): + if self._uses_python_query_pushdown(query): from lancedb.namespace import _execute_server_side_query table_id = self._namespace_path + [self.name] @@ -6579,14 +6582,7 @@ class LanceTable(Table): timeout: Optional[timedelta] = None, ) -> pa.Table: # Keep the Python namespace pushdown path, including its branch rule. - if ( - _should_push_down_query_table( - self._namespace_client, self._pushdown_operations - ) - and not self._route_pushdown_to_rust - and self.current_branch() is None - and not _requires_local_namespace_execution(query, self._table) - ): + if self._uses_python_query_pushdown(query): return self._execute_query(query, timeout=timeout).read_all() async_query = self._table._sync_query_to_async(query) diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 8329a71d6..70cefb3d6 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -2042,6 +2042,53 @@ class AttributeAccessNamespace(LanceNamespace): return self._inner.describe_table(request) +def test_query_result_uses_custom_namespace_route(tmp_path): + from lancedb.exceptions import UnsupportedMetadata + + lancedb.connect(tmp_path).create_table("t", data=[{"id": 1, "text": "dog"}]) + + class QueryNamespace(LanceNamespace): + def __init__(self): + self.requests = [] + + def namespace_id(self): + return f"query-result:{tmp_path}" + + def describe_table(self, request): + assert request.id == ["t"] + return DescribeTableResponse(location=str(tmp_path / "t.lance")) + + def query_table(self, request): + self.requests.append(request) + if request.full_text_query is not None: + return _ipc_file(pa.table({"id": [1]}).slice(0, request.k)) + assert request.columns.column_aliases == {"next_id": "id + 1"} + return _ipc_file(pa.table({"next_id": [2]})) + + namespace = QueryNamespace() + db = LanceNamespaceDBConnection( + namespace, namespace_client_pushdown_operations=["QueryTable"] + ) + table = db.open_table("t") + query = table.search().select({"next_id": "id + 1"}) + expected = query.to_batches().read_all() + with query.to_result() as result: + assert pa.Table.from_batches(list(result)).equals(expected) + assert result.metadata().total_hits is None + assert expected.to_pylist() == [{"next_id": 2}] + assert len(namespace.requests) == 2 + assert namespace.requests[0] == namespace.requests[1] + + empty = table.search("dog", query_type="fts").limit(0) + with empty.to_result() as result: + assert sum(batch.num_rows for batch in result) == 0 + assert namespace.requests[-1].k == 0 + for builder in (query, empty): + with pytest.raises(UnsupportedMetadata): + builder.to_result(track_total_hits=True) + assert len(namespace.requests) == 3 + + def test_python_namespace_attribute_access(tmp_path): pytest.importorskip("lance.namespace") root = str(tmp_path) diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index d2e560c21..47c4c7301 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -3622,3 +3622,243 @@ async def test_search_effort_invalid_async(table_async, hybrid, effort): query = query.nearest_to_text("dog") with pytest.raises(ValueError, match="search_effort must be finite and in"): query.search_effort(effort) + + +def test_query_result_metadata(tmp_db): + from lancedb.exceptions import MetadataCancelled, MetadataPending + from lancedb.query_result import QueryMetadata, TotalHits + + table = _fragment_query_table(tmp_db, "result_metadata") + query = table.search().where("id >= 2").limit(1) + with query.to_result(track_total_hits=True) as result: + batch = next(result.batches) + assert isinstance(batch, pa.RecordBatch) + assert batch.num_rows == 1 + with pytest.raises(MetadataPending): + result.metadata() + assert result.finish() == QueryMetadata(TotalHits(3, "eq")) + assert result.metadata() == QueryMetadata(TotalHits(3, "eq")) + + with query.to_result(track_total_hits=2) as result: + assert result.finish() == QueryMetadata(TotalHits(2, "gte")) + + with query.to_result(track_total_hits=True) as result: + next(result.batches) + with pytest.raises(MetadataCancelled): + result.metadata() + + with query.to_result() as result: + assert result.finish() == QueryMetadata(None) + assert isinstance(query.to_arrow(), pa.Table) + assert isinstance(query.to_list(), list) + + +@pytest.mark.parametrize("cap", [0, -1, 2**64, 1.5, "1"]) +def test_query_result_invalid_cap(tmp_db, cap): + table = tmp_db.create_table("result_cap", [{"id": 1}]) + with pytest.raises((TypeError, ValueError), match="track_total_hits"): + table.search().to_result(track_total_hits=cap) + + +@pytest.mark.asyncio +async def test_async_query_result_metadata(tmp_db_async): + from lancedb.exceptions import MetadataPending, UnsupportedMetadata + from lancedb.query_result import TotalHits + + table = await tmp_db_async.create_table("result_fts", _fragment_query_data()) + await table.create_index("text", config=FTS(with_position=False)) + query = table.query().nearest_to_text("one two", columns="text").limit(1) + async with await query.to_result(track_total_hits=True) as result: + batches = [batch async for batch in result.batches] + assert sum(batch.num_rows for batch in batches) == 1 + assert result.metadata().total_hits == TotalHits(2, "eq") + async with await table.query().limit(0).to_result(track_total_hits=True) as empty: + with pytest.raises(MetadataPending): + empty.metadata() + assert sum([batch.num_rows async for batch in empty]) == 0 + assert empty.metadata().total_hits == TotalHits(4, "eq") + with pytest.raises(UnsupportedMetadata): + await table.query().nearest_to([0.0, 0.0]).to_result(track_total_hits=True) + + +def test_query_result_sync_fts_empty_page(tmp_db): + from lancedb.query_result import TotalHits + + table = _fragment_query_table(tmp_db, "result_fts_empty") + table.create_index("text", config=FTS(with_position=False)) + query = table.search("one two", query_type="fts").limit(0) + assert query.to_arrow().num_rows == 2 + with query.to_result(track_total_hits=True) as result: + assert sum(batch.num_rows for batch in result.batches) == 0 + assert result.metadata().total_hits == TotalHits(2, "eq") + + +def test_query_result_sync_reranked_fts_empty_page(tmp_db): + from lancedb.exceptions import UnsupportedMetadata + + table = _fragment_query_table(tmp_db, "result_fts_empty_reranked") + table.create_index("text", config=FTS(with_position=False)) + ranker = RRFReranker() + query = table.search("one two", query_type="fts").select(["id"]).rerank(ranker) + query.limit(0) + with mock.patch.object(ranker, "rerank_fts", wraps=ranker.rerank_fts) as rerank: + with query.to_result() as empty: + assert sum(batch.num_rows for batch in empty) == 0 + assert empty.metadata().total_hits is None + rerank.assert_called_once() + candidates = rerank.call_args.args[1] + assert candidates.num_rows == 0 + assert {"id", "_score"} <= set(candidates.column_names) + with pytest.raises(UnsupportedMetadata): + query.to_result(track_total_hits=True) + rerank.assert_called_once() + + # The legacy FTS terminal on the same builder still treats zero as unset. + legacy = query.to_arrow() + assert sorted(legacy["id"].to_pylist()) == [1, 2] + assert "_relevance_score" in legacy.column_names + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_api", [False, True], ids=["sync", "async"]) +async def test_query_result_plain_scan_row_address(tmp_path, async_api): + from lancedb.exceptions import UnsupportedMetadata + from lancedb.query_result import TotalHits + + data = _fragment_query_data() + options = {"new_table_enable_stable_row_ids": "true"} + if async_api: + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("rows", data.slice(0, 2), storage_options=options) + await table.add(data.slice(2)) + query = table.query() + else: + db = lancedb.connect(tmp_path) + table = db.create_table("rows", data.slice(0, 2), storage_options=options) + table.add(data.slice(2)) + query = table.search() + query = ( + query.where("id >= 2") + .select(["id"]) + .scan_in_order() + .with_row_address() + .offset(1) + .limit(1) + ) + for tracking, hits in [ + (False, None), + (True, TotalHits(3, "eq")), + (2, TotalHits(2, "gte")), + ]: + if async_api: + async with await query.to_result(track_total_hits=tracking) as result: + batches = [batch async for batch in result] + else: + with query.to_result(track_total_hits=tracking) as result: + batches = list(result) + rows = pa.Table.from_batches(batches) + assert rows.to_pylist() == [{"id": 3, "_rowaddr": 1 << 32}] + assert rows["_rowaddr"].type == pa.uint64() + assert result.metadata().total_hits == hits + + if async_api: + ranked = table.query().nearest_to([0.0, 0.0]).with_row_address() + with pytest.raises(UnsupportedMetadata): + await ranked.to_result() + else: + ranked = table.search([0.0, 0.0]).with_row_address() + with pytest.raises(UnsupportedMetadata): + ranked.to_result() + restricted = query.fragment_ids([0]) + with pytest.raises(UnsupportedMetadata): + if async_api: + await restricted.to_result() + else: + restricted.to_result() + + +def test_query_result_off_preserves_pull_reader(tmp_db, monkeypatch): + from lancedb.exceptions import MetadataCancelled + + table = _fragment_query_table(tmp_db, "result_pull") + query = table.search() + monkeypatch.setattr(table, "_namespace_client", object()) + monkeypatch.setattr(table, "_pushdown_operations", {"QueryTable"}) + monkeypatch.setattr(table, "_route_pushdown_to_rust", False) + polled = [] + schema = pa.schema([("id", pa.int64())]) + + def batches(): + for i in range(3): + polled.append(i) + yield pa.record_batch([[i]], schema=schema) + + monkeypatch.setattr( + query, + "to_batches", + lambda: pa.RecordBatchReader.from_batches(schema, batches()), + ) + with query.to_result() as result: + assert not polled + assert next(result.batches).column(0).to_pylist() == [0] + assert polled == [0] + with pytest.raises(MetadataCancelled): + result.metadata() + + +@pytest.mark.parametrize("async_api", [False, True], ids=["sync", "async"]) +@pytest.mark.asyncio +async def test_query_result_cap_boundaries(tmp_path, async_api): + from lancedb.query_result import TotalHits + + data = pa.table({"id": [1, 2, 3]}) + if async_api: + db = await lancedb.connect_async(tmp_path) + query = (await db.create_table("rows", data)).query().limit(1) + else: + db = lancedb.connect(tmp_path) + query = db.create_table("rows", data).search().limit(1) + for cap, expected in ( + (2, TotalHits(2, "gte")), + (3, TotalHits(3, "gte")), + (4, TotalHits(3, "eq")), + (2**64 - 1, TotalHits(3, "eq")), + ): + if async_api: + async with await query.to_result(track_total_hits=cap) as result: + metadata = await result.finish() + else: + with query.to_result(track_total_hits=cap) as result: + metadata = result.finish() + assert metadata.total_hits == expected + with pytest.raises(ValueError, match="track_total_hits"): + if async_api: + await query.to_result(track_total_hits=2**64) + else: + query.to_result(track_total_hits=2**64) + + +def test_query_result_count_error_after_last_page_batch(tmp_path): + from lancedb.exceptions import MetadataPending + + db = lancedb.connect(tmp_path) + table = db.create_table("fallible_count", [{"id": 0}, {"id": 1}]) + table.add([{"id": 2}, {"id": 3}]) + query = table.search().where("id >= 0").limit(1) + with query.to_result(track_total_hits=True) as result: + assert next(result).num_rows == 1 + with pytest.raises(MetadataPending): + result.metadata() + # The result page is complete. Simulate loss of the test table's + # storage before the EOF poll opens the independent count traversal. + dataset = tmp_path / "fallible_count.lance" + offline = tmp_path / "offline" + dataset.rename(offline) + try: + with pytest.raises(RuntimeError) as failure: + next(result) + with pytest.raises(type(failure.value)) as metadata: + result.metadata() + assert metadata.value is failure.value + finally: + offline.rename(dataset) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 033f81714..d04584d50 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors import asyncio -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait import contextlib import copy from dataclasses import replace @@ -4716,8 +4716,11 @@ def streamed_query_table(write_body): yield db.open_table("test"), queries -@pytest.mark.parametrize("batch_size", [None, 0, 37, 1024]) -def test_query_sync_to_batches_yields_before_the_body_is_complete(batch_size): +@pytest.mark.parametrize( + ("batch_size", "use_result"), + [(None, False), (0, False), (37, False), (1024, False), (None, True)], +) +def test_query_sync_batches_yield_before_the_body_is_complete(batch_size, use_result): server_batch_sizes = [1063, 81] values = list(range(sum(server_batch_sizes))) row_ids = [(1 << 32) + 2 * value for value in values] @@ -4746,8 +4749,10 @@ def test_query_sync_to_batches_yields_before_the_body_is_complete(batch_size): with streamed_query_table(write_body) as (table, queries): query = table.search().select(["id"]).with_row_id(True) - reader = query.to_batches(batch_size=batch_size) - first_batch = reader.read_next_batch() + reader = ( + query.to_result() if use_result else query.to_batches(batch_size=batch_size) + ) + first_batch = next(reader) first_batch_read.set() received = [first_batch, *reader] @@ -4798,6 +4803,125 @@ def test_query_sync_interrupted_response_raises(abort): assert len(queries) == 1 +@pytest.mark.parametrize("sync_api", [False, True], ids=["async", "sync"]) +@pytest.mark.asyncio +async def test_query_result_rejects_enterprise_counts_without_requests(sync_api): + from lancedb.exceptions import UnsupportedMetadata + + requests = [] + + def handler(request): + requests.append(request.path) + if request.path == "/v1/table/test/describe/": + request.send_response(200) + request.end_headers() + request.wfile.write(b'{"version": 7, "schema": {"fields": []}}') + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + query = table.search() if sync_api else table._table.query() + # Clear the cached schema so an accidental describe is observable. + table.checkout_latest() + requests.clear() + for tracking in [True, 10]: + with pytest.raises(UnsupportedMetadata): + if sync_api: + query.to_result(track_total_hits=tracking) + else: + await query.to_result(track_total_hits=tracking) + assert requests == [] + + +@pytest.mark.parametrize("sync_api", [False, True], ids=["async", "sync"]) +@pytest.mark.asyncio +async def test_query_result_interruption_preserves_details(sync_api): + batch = pa.record_batch({"id": pa.array([1], pa.int32())}) + + def write_body(request): + request.end_headers() + request.wfile.write(_arrow_stream([batch])[:-8]) + + with streamed_query_table(write_body) as (table, queries): + if sync_api: + result = table.search().to_result() + assert next(result.batches)["id"].to_pylist() == [1] + with pytest.raises(ResponseInterruptedError) as read: + next(result.batches) + result.close() + else: + result = await table._table.query().to_result() + assert (await anext(result.batches))["id"].to_pylist() == [1] + with pytest.raises(ResponseInterruptedError) as read: + await anext(result.batches) + await result.close() + with pytest.raises(ResponseInterruptedError) as metadata: + result.metadata() + assert len(queries) == 1 + for error in [read.value, metadata.value]: + assert error.request_id == queries[0]["x-request-id"] + assert (error.batches, error.rows, error.table_version) == (1, 1, 7) + assert not error.is_transport_error + + +@pytest.mark.parametrize("sync_api", [False, True], ids=["async", "sync"]) +@pytest.mark.asyncio +async def test_query_result_close_interrupts_pending_read(sync_api): + from lancedb.exceptions import MetadataCancelled, MetadataPending + + release = threading.Event() + batch = pa.record_batch({"id": pa.array([1], pa.int32())}) + + def write_body(request): + request.end_headers() + request.wfile.write(_arrow_stream([batch])[:-8]) + request.wfile.flush() + release.wait(10) + + with streamed_query_table(write_body) as (table, _): + try: + if sync_api: + result = table.search().to_result() + assert next(result.batches).num_rows == 1 + # A competing read is rejected only once the first is in flight. + with ThreadPoolExecutor(max_workers=2) as pool: + readers = [pool.submit(next, result.batches) for _ in range(2)] + finished, pending = wait( + readers, timeout=3, return_when=FIRST_COMPLETED + ) + try: + assert len(finished) == len(pending) == 1 + with pytest.raises(RuntimeError, match="read is already"): + finished.pop().result() + with pytest.raises(MetadataPending): + result.metadata() + result.close() + with pytest.raises(MetadataCancelled): + pending.pop().result(timeout=3) + with pytest.raises(MetadataCancelled): + result.metadata() + finally: + release.set() + return + + result = await table._table.query().to_result() + assert (await anext(result.batches)).num_rows == 1 + pending = asyncio.create_task(anext(result.batches)) + await asyncio.sleep(0) + assert not pending.done() + with pytest.raises(MetadataPending): + result.metadata() + await asyncio.wait_for(result.close(), 3) + with pytest.raises(MetadataCancelled): + await asyncio.wait_for(pending, 3) + with pytest.raises(MetadataCancelled): + result.metadata() + finally: + release.set() + + @pytest.mark.parametrize("query_type", ["auto", "vector", "hybrid"]) @pytest.mark.parametrize("vector_column_name", [None, "embedding"]) def test_query_sync_text_embedding(query_type, vector_column_name): diff --git a/python/src/error.rs b/python/src/error.rs index 1ac9f7ac3..8306a6a30 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -26,6 +26,12 @@ impl PythonErrorExt for std::result::Result { match &self { Ok(_) => Ok(self.unwrap()), Err(err) => match err { + err if err.unsupported_metadata().is_some() => Python::attach(|py| { + let cls = py + .import(intern!(py, "lancedb.exceptions"))? + .getattr(intern!(py, "UnsupportedMetadata"))?; + Err(PyErr::from_value(cls.call1((err.to_string(),))?)) + }), LanceError::InvalidInput { .. } | LanceError::InvalidTableName { .. } | LanceError::NotAMaterializedView { .. } diff --git a/python/src/lib.rs b/python/src/lib.rs index c9f382090..daeb4d41d 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -37,6 +37,7 @@ pub mod oauth; pub mod otel; pub mod permutation; pub mod query; +mod query_result; pub mod runtime; pub mod session; pub mod sql; @@ -118,6 +119,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(_uses_sql_subquery_filter, m)?)?; m.add_function(wrap_pyfunction!(query::_share_hybrid_subquery_filter, m)?)?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/python/src/query.rs b/python/src/query.rs index f72de6613..51cc3a154 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -98,7 +98,7 @@ where Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) } -fn query_execution_options( +pub(crate) fn query_execution_options( max_batch_length: Option, timeout: Option, ) -> QueryExecutionOptions { @@ -760,6 +760,16 @@ impl Query { }) } + #[pyo3(signature = (track, cap=None))] + pub fn execute_with_metadata<'py>( + &self, + py: Python<'py>, + track: bool, + cap: Option, + ) -> PyResult> { + crate::query_result::execute_with_metadata(py, self.inner.clone(), track, cap) + } + #[pyo3(signature = (max_batch_length=None, timeout=None))] pub fn execute( self_: PyRef<'_, Self>, @@ -892,6 +902,16 @@ impl TakeQuery { }) } + #[pyo3(signature = (track, cap=None))] + pub fn execute_with_metadata<'py>( + &self, + py: Python<'py>, + track: bool, + cap: Option, + ) -> PyResult> { + crate::query_result::execute_with_metadata(py, self.inner.clone(), track, cap) + } + #[pyo3(signature = (max_batch_length=None, timeout=None))] pub fn execute( self_: PyRef<'_, Self>, @@ -1044,6 +1064,23 @@ impl FTSQuery { }) } + #[pyo3(signature = (track, cap=None))] + pub fn execute_with_metadata<'py>( + &self, + py: Python<'py>, + track: bool, + cap: Option, + ) -> PyResult> { + crate::query_result::execute_with_metadata( + py, + self.inner + .clone() + .full_text_search(self.fts_query_for_execution()), + track, + cap, + ) + } + #[pyo3(signature = (max_batch_length=None, timeout=None))] pub fn execute( self_: PyRef<'_, Self>, @@ -1333,6 +1370,16 @@ impl VectorQuery { }) } + #[pyo3(signature = (track, cap=None))] + pub fn execute_with_metadata<'py>( + &self, + py: Python<'py>, + track: bool, + cap: Option, + ) -> PyResult> { + crate::query_result::execute_with_metadata(py, self.inner.clone(), track, cap) + } + #[pyo3(signature = (max_batch_length=None, timeout=None))] pub fn execute( self_: PyRef<'_, Self>, diff --git a/python/src/query_result.rs b/python/src/query_result.rs new file mode 100644 index 000000000..b5bc07805 --- /dev/null +++ b/python/src/query_result.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::num::NonZeroU64; +use std::sync::Arc; + +use arrow::pyarrow::ToPyArrow; +use lancedb::query::metadata_reader::QueryResultReader; +use lancedb::query::{ExecutableQuery, MetadataRequest, TrackTotalHits}; +use pyo3::{Bound, PyAny, PyResult, Python, exceptions::PyRuntimeError, pyclass, pymethods}; + +use crate::{error::PythonErrorExt, runtime::future_into_py}; + +#[pyclass] +pub struct NativeQueryResult(Arc); + +pub fn execute_with_metadata( + py: Python<'_>, + query: Q, + track: bool, + cap: Option, +) -> PyResult> { + let mode = match (track, cap) { + (_, Some(cap)) => TrackTotalHits::UpTo(cap), + (true, None) => TrackTotalHits::Exact, + (false, None) => TrackTotalHits::Off, + }; + let request = MetadataRequest::new().track_total_hits(mode); + future_into_py(py, async move { + let result = query + .execute_with_metadata(crate::query::query_execution_options(None, None), request) + .await + .infer_error()?; + Ok(NativeQueryResult(Arc::new(QueryResultReader::new(result)))) + }) +} + +#[pymethods] +impl NativeQueryResult { + fn next_batch<'py>(&self, py: Python<'py>) -> PyResult> { + let reader = self.0.clone(); + future_into_py(py, async move { + let batch = reader.next().await.infer_error()?; + Python::attach(|py| { + batch + .map(|batch| batch.to_pyarrow(py).map(Bound::unbind)) + .transpose() + }) + }) + } + + fn total_hits(&self) -> PyResult> { + let metadata = self + .0 + .metadata() + .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; + Ok(metadata + .total_hits + .as_ref() + .map(|hits| (hits.value, hits.relation.as_str()))) + } + + fn close<'py>(&self, py: Python<'py>) -> PyResult> { + let reader = self.0.clone(); + future_into_py(py, async move { + reader.close().await; + Ok(()) + }) + } +} diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index f22384eb8..d2a3da2b0 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -709,6 +709,11 @@ impl Error { /// Copy supported errors without flattening sources retained by a shared plan /// or schema cache. pub(crate) fn clone_shared(&self) -> Option { + if let Self::Timeout { message } = self { + return Some(Self::Timeout { + message: message.clone(), + }); + } #[cfg(feature = "remote")] match self { Self::Http { diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index ce476866d..ba6f951a7 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -56,6 +56,13 @@ use crate::{ }; mod hybrid; +mod metadata; +#[doc(hidden)] +pub mod metadata_reader; +pub use lance::dataset::scanner::{ + HitRelation, MetadataRequest, QueryMetadata, TotalHits, TrackTotalHits, +}; +pub use metadata::{MetadataAccessError, MetadataHandle, QueryResult, UnsupportedMetadata}; pub(crate) mod wal_fusion; // WAL-PK-FUSION: delete with the module. pub(crate) const DEFAULT_TOP_K: usize = 10; @@ -831,6 +838,38 @@ pub trait ExecutableQuery { options: QueryExecutionOptions, ) -> impl Future> + Send; + /// Open a streaming result and publish the requested metadata at successful EOF. + /// + /// Exact and bounded counts refer to visible matching rows before pagination. + /// Unsupported queries fail at execution creation. The default implementation + /// supports an empty request by executing the ordinary query once. + /// + /// ``` + /// # use lancedb::query::{ExecutableQuery, MetadataRequest, TrackTotalHits}; + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// let fields = MetadataRequest::new().track_total_hits(TrackTotalHits::Exact); + /// let result = table.query().execute_with_metadata(Default::default(), fields).await?; + /// let total = result.finish().await?.total_hits.unwrap(); + /// # Ok(()) + /// # } + /// ``` + fn execute_with_metadata( + &self, + options: QueryExecutionOptions, + fields: MetadataRequest, + ) -> impl Future> + Send { + let stream = + (fields.total_hits == TrackTotalHits::Off).then(|| self.execute_with_options(options)); + async move { + let stream = stream + .ok_or_else(|| { + Error::metadata_unsupported("this query does not support total_hits") + })? + .await?; + Ok(QueryResult::from_batches(stream)) + } + } + /// Explain the plan for a query /// /// This will create a string representation of the plan that will be used to @@ -1336,6 +1375,23 @@ impl ExecutableQuery for Query { } } + async fn execute_with_metadata( + &self, + options: QueryExecutionOptions, + fields: MetadataRequest, + ) -> Result { + if fields.total_hits == TrackTotalHits::Off { + return Ok(QueryResult::from_batches( + self.execute_with_options(options).await?, + )); + } + let table = self + .parent + .as_native() + .ok_or_else(|| Error::metadata_unsupported("this table does not support total_hits"))?; + crate::table::query::execute_with_metadata(table, &self.request, options, fields).await + } + async fn explain_plan(&self, verbose: bool) -> Result { let query = AnyQuery::Query(self.request.clone()); self.parent.explain_plan(&query, verbose).await @@ -3966,6 +4022,155 @@ mod tests { assert!(saw_batch); } + #[tokio::test] + async fn metadata_pinned_stream_and_pagination() -> Result<()> { + let ids = vec![Some(1), Some(2), None, Some(3), Some(2)]; + let expected = ids.iter().filter(|id| id.is_some_and(|i| i >= 2)).count(); + let batch = RecordBatch::try_from_iter([("id", Arc::new(Int32Array::from(ids)) as _)])?; + let conn = connect("memory://sdk_query_result").execute().await?; + let table = conn.create_table("counts", batch.clone()).execute().await?; + let query = table + .query() + .only_if("id >= 2") + .offset(1) + .limit(1) + .with_row_address(true); + let exact = MetadataRequest::new().track_total_hits(TrackTotalHits::Exact); + let mut page = query + .execute_with_metadata(Default::default(), exact) + .await?; + let handle = page.metadata_handle(); + assert!(matches!( + handle.metadata(), + Err(MetadataAccessError::Pending) + )); + table.add(batch).execute().await?; + let first = page.try_next().await?.unwrap(); + assert_eq!(first.num_rows(), 1); + let addresses = first["_rowaddr"] + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(addresses.value(0), 3); + assert!(matches!( + handle.metadata(), + Err(MetadataAccessError::Pending) + )); + assert!(page.try_next().await?.is_none()); + let hits = handle.metadata().unwrap().total_hits.as_ref().unwrap(); + assert_eq!( + (hits.value, hits.relation), + (expected as u64, HitRelation::Exact) + ); + let subsequent = query + .execute_with_metadata(Default::default(), exact) + .await? + .finish() + .await?; + assert_eq!(subsequent.total_hits.unwrap().value, (expected * 2) as u64); + Ok(()) + } + + #[tokio::test] + async fn metadata_cap_boundaries() -> Result<()> { + let batch = + RecordBatch::try_from_iter([("id", Arc::new(Int32Array::from(vec![1, 2, 3])) as _)])?; + let conn = connect("memory://sdk_cap_boundaries").execute().await?; + let table = conn.create_table("counts", batch).execute().await?; + for (cap, value, relation) in [ + (2, 2, HitRelation::GreaterThanOrEqual), + (3, 3, HitRelation::GreaterThanOrEqual), + (4, 3, HitRelation::Exact), + (u64::MAX, 3, HitRelation::Exact), + ] { + let request = MetadataRequest::new().track_total_hits(TrackTotalHits::UpTo( + std::num::NonZeroU64::new(cap).unwrap(), + )); + let hits = table + .query() + .limit(1) + .execute_with_metadata(Default::default(), request) + .await? + .finish() + .await? + .total_hits + .unwrap(); + assert_eq!((hits.value, hits.relation), (value, relation)); + } + Ok(()) + } + + #[tokio::test] + async fn metadata_cancellation_deadline_and_off() -> Result<()> { + let tmp = tempdir().unwrap(); + let table = make_test_table(&tmp).await; + let fields = MetadataRequest::new().track_total_hits(TrackTotalHits::Exact); + let query = table.query().limit(1); + let mut first = query + .execute_with_metadata(Default::default(), fields) + .await?; + let handle = first.metadata_handle(); + assert!(first.try_next().await?.is_some()); + drop(first); + assert!(matches!( + handle.metadata(), + Err(MetadataAccessError::Cancelled) + )); + + let mut expired = query + .execute_with_metadata( + QueryExecutionOptions { + timeout: Some(Duration::ZERO), + ..Default::default() + }, + fields, + ) + .await?; + assert!(matches!( + expired.try_next().await, + Err(Error::Timeout { .. }) + )); + expired.close(); + assert!( + matches!(expired.metadata(), Err(MetadataAccessError::Failed(err)) if matches!(err.as_ref(), Error::Timeout { .. })) + ); + + let ordinary = query + .execute_with_metadata(Default::default(), MetadataRequest::new()) + .await? + .finish() + .await?; + assert!(ordinary.total_hits.is_none()); + let vector = table.query().nearest_to(&[0.1; 4])?; + assert!(matches!( + vector + .execute_with_metadata(Default::default(), fields) + .await, + Err(err) if err.unsupported_metadata().is_some() + )); + Ok(()) + } + + #[cfg(feature = "remote")] + #[tokio::test] + async fn metadata_enterprise_rejects_before_sending() { + let table = crate::remote::table::RemoteTable::new_mock( + "counts".into(), + |_| -> http::Response> { + panic!("unexpected request for unsupported metadata") + }, + None, + ); + let request = MetadataRequest::new().track_total_hits(TrackTotalHits::Exact); + let query = Query::new(Arc::new(table)); + assert!(matches!( + query + .execute_with_metadata(Default::default(), request) + .await, + Err(err) if err.unsupported_metadata().is_some() + )); + } + #[tokio::test] async fn test_execute_with_options() { let tmp_dir = tempdir().unwrap(); diff --git a/rust/lancedb/src/query/metadata.rs b/rust/lancedb/src/query/metadata.rs new file mode 100644 index 000000000..c98477c00 --- /dev/null +++ b/rust/lancedb/src/query/metadata.rs @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::fmt; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll, ready}; +use std::time::Duration; + +use arrow_array::RecordBatch; +use arrow_schema::SchemaRef; +use datafusion_common::DataFusionError; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use futures::{Stream, TryStreamExt}; +use lance::dataset::scanner; +use tokio::time::Sleep; + +use super::{QueryExecutionOptions, QueryMetadata}; +use crate::arrow::{RecordBatchStream, SendableRecordBatchStream, SimpleRecordBatchStream}; +use crate::utils::MaxBatchLengthStream; +use crate::{Error, Result}; + +/// The execution backend or predicate cannot certify the requested metadata. +#[derive(Debug, snafu::Snafu)] +#[snafu(display("Unsupported query metadata: {message}"))] +pub struct UnsupportedMetadata { + /// Which requirement prevents this execution from publishing a total. + pub message: String, +} + +impl Error { + pub(crate) fn metadata_unsupported(message: impl Into) -> Self { + Self::External { + source: Box::new(UnsupportedMetadata { + message: message.into(), + }), + } + } + + /// Return the typed reason when the backend cannot supply requested metadata. + pub fn unsupported_metadata(&self) -> Option<&UnsupportedMetadata> { + match self { + Self::External { source } => source.downcast_ref(), + _ => None, + } + } +} + +/// Why final metadata cannot be read. +#[derive(Debug, Clone)] +pub enum MetadataAccessError { + /// The consumer has not yet observed EOF. + Pending, + /// The result was closed or dropped before EOF. + Cancelled, + /// Execution terminated with this cause. + Failed(Arc), +} + +impl fmt::Display for MetadataAccessError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Pending => f.write_str("query metadata is pending"), + Self::Cancelled => f.write_str("query result was cancelled"), + Self::Failed(cause) => cause.fmt(f), + } + } +} + +impl std::error::Error for MetadataAccessError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Failed(cause) => Some(cause.as_ref()), + _ => None, + } + } +} + +/// A nonblocking view of one execution's terminal state. Keeping this handle +/// alive never keeps the scanner, its buffers, or a count traversal alive. +#[derive(Clone, Default)] +pub struct MetadataHandle(Arc>>); + +impl MetadataHandle { + /// Read the metadata published at EOF. + pub fn metadata(&self) -> std::result::Result<&QueryMetadata, MetadataAccessError> { + self.0 + .get() + .ok_or(MetadataAccessError::Pending)? + .as_ref() + .map_err(Clone::clone) + } +} + +/// A single open query. Poll it to consume batches, then read its metadata. +/// Dropping or closing the result releases the underlying execution. +pub struct QueryResult { + batches: Option, + schema: SchemaRef, + completion: MetadataHandle, + core_metadata: Option, + timeout: Option, + deadline: Option>>, +} + +impl QueryResult { + pub(super) fn from_batches(batches: SendableRecordBatchStream) -> Self { + Self { + schema: batches.schema(), + batches: Some(batches), + completion: MetadataHandle::default(), + core_metadata: None, + timeout: None, + deadline: None, + } + } + + pub(crate) fn from_embedded( + result: scanner::QueryResult, + options: QueryExecutionOptions, + ) -> Self { + let metadata = result.metadata_handle(); + let schema = result.schema(); + let stream = RecordBatchStreamAdapter::new( + schema.clone(), + result.map_err(|e| DataFusionError::External(Box::new(e))), + ); + let stream = + MaxBatchLengthStream::new_boxed(Box::pin(stream), options.max_batch_length as usize); + let mut result = Self::from_batches(Box::pin(SimpleRecordBatchStream::new( + stream.map_err(Error::from), + schema, + ))); + result.core_metadata = Some(metadata); + result.timeout = options.timeout; + result + } + + /// Output schema, available for empty results as well. + pub fn schema(&self) -> SchemaRef { + self.schema.clone() + } + + /// Get an independent, read-only completion handle. + pub fn metadata_handle(&self) -> MetadataHandle { + self.completion.clone() + } + + /// Read final metadata without advancing the stream. + pub fn metadata(&self) -> std::result::Result<&QueryMetadata, MetadataAccessError> { + self.completion.metadata() + } + + /// Cancel unfinished execution. Previously observed success or failure is preserved. + pub fn close(&mut self) { + self.batches = None; + self.core_metadata = None; + self.deadline = None; + let _ = self.completion.0.set(Err(MetadataAccessError::Cancelled)); + } + + /// Drain remaining rows and return final metadata. + pub async fn finish(mut self) -> Result { + while self.try_next().await?.is_some() {} + self.metadata().cloned().map_err(|err| Error::External { + source: Box::new(err), + }) + } + + fn fail(&mut self, error: Error) -> Poll>> { + let shared = Arc::new(error); + let _ = self + .completion + .0 + .set(Err(MetadataAccessError::Failed(shared.clone()))); + self.close(); + Poll::Ready(Some(Err(shared.clone_shared().unwrap_or_else(|| { + Error::External { + source: Box::new(shared), + } + })))) + } +} + +impl Drop for QueryResult { + fn drop(&mut self) { + self.close(); + } +} + +impl Stream for QueryResult { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.batches.is_none() { + return Poll::Ready(None); + } + if let Some(timeout) = self.timeout { + let sleep = self + .deadline + .get_or_insert_with(|| Box::pin(tokio::time::sleep(timeout))); + if timeout.is_zero() || sleep.as_mut().poll(cx).is_ready() { + return self.fail(Error::Timeout { + message: format!("Query timeout after {} ms", timeout.as_millis()), + }); + } + } + + match ready!(self.batches.as_mut().unwrap().as_mut().poll_next(cx)) { + Some(Ok(batch)) => Poll::Ready(Some(Ok(batch))), + Some(Err(error)) => self.fail(error), + None => { + let metadata = match &self.core_metadata { + Some(core) => match core.metadata() { + Ok(metadata) => metadata.clone(), + Err(error) => { + return self.fail(Error::External { + source: Box::new(error), + }); + } + }, + None => QueryMetadata::default(), + }; + let _ = self.completion.0.set(Ok(metadata)); + self.close(); + Poll::Ready(None) + } + } + } +} + +impl RecordBatchStream for QueryResult { + fn schema(&self) -> SchemaRef { + self.schema.clone() + } +} diff --git a/rust/lancedb/src/query/metadata_reader.rs b/rust/lancedb/src/query/metadata_reader.rs new file mode 100644 index 000000000..1460671a2 --- /dev/null +++ b/rust/lancedb/src/query/metadata_reader.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Pull-driven adapter for foreign runtimes which can cancel a pending read. + +use arrow_array::RecordBatch; +use futures::StreamExt; +use futures::future::{AbortHandle, Abortable}; +use tokio::sync::Mutex; + +use super::{MetadataAccessError, MetadataHandle, QueryMetadata, QueryResult}; +use crate::Result; + +pub struct QueryResultReader { + stream: Mutex>>, + abort: AbortHandle, + metadata: MetadataHandle, +} + +impl QueryResultReader { + pub fn new(result: QueryResult) -> Self { + let metadata = result.metadata_handle(); + let (abort, registration) = AbortHandle::new_pair(); + Self { + stream: Mutex::new(Some(Abortable::new(result, registration))), + abort, + metadata, + } + } + + pub async fn next(&self) -> Result> { + let mut slot = self.stream.lock().await; + // The polling future must own the execution so cancelling the foreign + // awaitable drops producers even while the reader is still referenced. + let Some(mut stream) = slot.take() else { + return Ok(None); + }; + let next = stream.next().await.transpose()?; + if next.is_some() { + *slot = Some(stream); + } + Ok(next) + } + + pub fn metadata(&self) -> std::result::Result<&QueryMetadata, MetadataAccessError> { + self.metadata.metadata() + } + + pub async fn close(&self) { + self.abort.abort(); + self.stream.lock().await.take(); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::task::Poll; + + use arrow_schema::Schema; + use futures::stream; + + use super::*; + use crate::arrow::SimpleRecordBatchStream; + + #[tokio::test] + async fn close_interrupts_an_inflight_read_while_a_handle_is_retained() { + let pending = SimpleRecordBatchStream::new(stream::pending(), Arc::new(Schema::empty())); + let reader = QueryResultReader::new(QueryResult::from_batches(Box::pin(pending))); + let mut read = Box::pin(reader.next()); + assert!(matches!(futures::poll!(&mut read), Poll::Pending)); + let (result, ()) = tokio::join!(read, reader.close()); + assert!(result.unwrap().is_none()); + assert!(matches!( + reader.metadata(), + Err(MetadataAccessError::Cancelled) + )); + } + + #[tokio::test] + async fn dropping_a_foreign_read_releases_the_pending_stream() { + let pending = SimpleRecordBatchStream::new(stream::pending(), Arc::new(Schema::empty())); + let reader = QueryResultReader::new(QueryResult::from_batches(Box::pin(pending))); + let mut read = Box::pin(reader.next()); + assert!(matches!(futures::poll!(&mut read), Poll::Pending)); + drop(read); + assert!(matches!( + reader.metadata(), + Err(MetadataAccessError::Cancelled) + )); + } +} diff --git a/rust/lancedb/src/remote/table/ipc_stream.rs b/rust/lancedb/src/remote/table/ipc_stream.rs index 08b3b1dea..bbd339644 100644 --- a/rust/lancedb/src/remote/table/ipc_stream.rs +++ b/rust/lancedb/src/remote/table/ipc_stream.rs @@ -678,6 +678,51 @@ mod tests { assert_eq!(server.queries.lock().unwrap().len(), 1); } + #[tokio::test] + async fn metadata_preserves_response_interruption_after_a_batch() { + use crate::query::{MetadataAccessError, MetadataRequest}; + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + let mut result = server + .table + .query() + .execute_with_metadata(Default::default(), MetadataRequest::new()) + .await + .unwrap(); + assert_eq!(ids(&result.try_next().await.unwrap().unwrap()), [0]); + assert!(matches!( + result.metadata(), + Err(MetadataAccessError::Pending) + )); + let error = result.try_next().await.unwrap_err(); + result.close(); + let Err(MetadataAccessError::Failed(cause)) = result.metadata() else { + panic!("expected terminal failure"); + }; + let queries = server.queries.lock().unwrap(); + assert_eq!(queries.len(), 1); + for error in [&error, cause.as_ref()] { + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("unexpected error {error:?}"); + }; + assert_eq!(request_id, &queries[0]["x-request-id"]); + assert_eq!((*batches, *rows, *table_version), (1, 1, Some(7))); + assert!(source.is::()); + } + } + /// Vector queries run through a DataFusion plan, which must keep the error's type. #[tokio::test] async fn vector_query_keeps_the_interruption_type() { diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 8e6c9a926..c5a3a9694 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -17,7 +17,8 @@ use crate::error::{Error, Result}; use crate::expr::expr_to_sql_string; use crate::index::scalar::{FtsQuery, Operator as FullTextOperator}; use crate::query::{ - DEFAULT_TOP_K, QueryExecutionOptions, QueryFilter, QueryRequest, Select, VectorQueryRequest, + DEFAULT_TOP_K, MetadataRequest, QueryExecutionOptions, QueryFilter, QueryRequest, QueryResult, + Select, VectorQueryRequest, }; use crate::utils::{MaxBatchLengthStream, TimeoutStream}; use arrow::array::{AsArray, FixedSizeListBuilder, Float32Builder}; @@ -115,17 +116,18 @@ pub async fn execute_query( execute_generic_query(table, &query, options).await } -async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> Result { - if !(table - .pushdown_operations - .contains(&NamespaceClientPushdownOperation::QueryTable) +fn allows_namespace_query(table: &NativeTable, query: &AnyQuery) -> bool { + table.pushdown_operations.contains(&NamespaceClientPushdownOperation::QueryTable) && table.namespace_client.is_some() && table.dataset.current_branch().is_none() // NsQueryTableRequest has no version field, so a pushed-down query would // read latest and ignore the pin. && table.dataset.time_travel_version().is_none() - && !requires_local_namespace_execution(query)) - { + && !requires_local_namespace_execution(query) +} + +async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> Result { + if !allows_namespace_query(table, query) { return Ok(false); } // An RTE write spec means reads auto-route through the LSM scanner in @@ -413,9 +415,6 @@ pub async fn create_plan( } let mut scanner: Scanner = ds_ref.scan(); - if !query.base.ordered_results { - scanner.ordered_results(false); - } if let (Some(query_vector), Some((column, _, element_type))) = (query_vector, vector_column) { let is_binary = matches!(element_type, DataType::UInt8); @@ -459,6 +458,43 @@ pub async fn create_plan( } } + let eligibility = configure_scanner( + table, + &ds_ref, + &query, + &mut scanner, + &options, + is_batch_query, + with_row_address, + ) + .await?; + + if let Some(eligibility) = eligibility { + // Planning can translate the bounds for ANN. The deferred scanner + // must start with the original bounds for its exact fallback. + let mut preview_scanner = scanner.clone(); + let preview = create_scanner_plan(&mut preview_scanner, schema, &query).await?; + return Ok(Arc::new(subquery_filter::SubqueryPrefilterExec::new( + eligibility, + scanner, + query, + preview, + ))); + } + create_scanner_plan(&mut scanner, schema, &query).await +} + +async fn configure_scanner( + table: &NativeTable, + ds_ref: &Arc, + query: &VectorQueryRequest, + scanner: &mut Scanner, + options: &QueryExecutionOptions, + is_batch_query: bool, + with_row_address: bool, +) -> Result>> { + scanner.ordered_results(query.base.ordered_results); + // For a batch query, `nearest` already applies k to each query vector. // Adding Scanner's global limit would truncate the combined result to k rows. if !is_batch_query { @@ -581,19 +617,78 @@ pub async fn create_plan( } } - if let Some(eligibility) = eligibility { - // Planning can translate the bounds for ANN. The deferred scanner - // must start with the original bounds for its exact fallback. - let mut preview_scanner = scanner.clone(); - let preview = create_scanner_plan(&mut preview_scanner, schema, &query).await?; - return Ok(Arc::new(subquery_filter::SubqueryPrefilterExec::new( - eligibility, - scanner, - query, - preview, - ))); + Ok(eligibility) +} + +pub(crate) async fn execute_with_metadata( + table: &NativeTable, + query: &QueryRequest, + options: QueryExecutionOptions, + fields: MetadataRequest, +) -> Result { + let query = AnyQuery::Query(query.clone()).canonicalized()?; + validate_scan_in_order(&query)?; + let request = query.base(); + request.check_filter()?; + if request.has_take() + || request.reranker.is_some() + || request.norm.is_some() + || request.prepared_subquery.is_some() + || subquery_filter::predicate(request.filter.as_ref()).is_some() + { + return Err(Error::metadata_unsupported( + "total_hits requires a row-level scan or lexical predicate", + )); } - create_scanner_plan(&mut scanner, schema, &query).await + let dataset = table.dataset.get().await?; + let uses_rte = match request.use_rte { + Some(enabled) => enabled, + None => dataset.mem_wal_index_details().await?.is_some(), + }; + if uses_rte { + return Err(Error::metadata_unsupported( + "total_hits is unavailable for RTE scans", + )); + } + if allows_namespace_query(table, &query) { + return Err(Error::metadata_unsupported( + "namespace query pushdown does not provide total_hits", + )); + } + let mut scanner = dataset.scan(); + let with_row_address = query.requests_row_address(); + let query = VectorQueryRequest::from_plain_query(request.clone()); + if configure_scanner( + table, + &dataset, + &query, + &mut scanner, + &options, + false, + with_row_address, + ) + .await? + .is_some() + { + return Err(Error::metadata_unsupported( + "total_hits is unavailable for cross-table subqueries", + )); + } + let result = scanner + .try_into_stream_with_metadata(fields) + .await + .map_err(|error| match error { + lance::dataset::scanner::MetadataExecutionError::UnsupportedMetadata(message) => { + Error::metadata_unsupported(message) + } + lance::dataset::scanner::MetadataExecutionError::Execution(source) => { + enrich_lance_field_not_found(source, dataset.schema()) + } + other => Error::External { + source: Box::new(other), + }, + })?; + Ok(QueryResult::from_embedded(result, options)) } async fn create_scanner_plan( @@ -1433,6 +1528,123 @@ mod tests { .collect() } + #[tokio::test] + async fn metadata_unordered_fts_preserves_ranked_page() -> Result<()> { + use crate::query::{HitRelation, TrackTotalHits}; + use std::num::NonZeroU64; + + fn scored_ids(batches: &[RecordBatch]) -> Vec<(i32, u32)> { + batches + .iter() + .flat_map(|batch| { + let ids = batch["id"].as_primitive::(); + let scores = batch["_score"].as_primitive::(); + ids.values() + .iter() + .zip(scores.values().iter()) + .map(|(&id, &score)| (id, score.to_bits())) + }) + .collect() + } + + // Equal document lengths and distinct term frequencies yield an unambiguous cutoff. + let text = [ + "dog fish fish fish", + "dog dog dog fish", + "dog dog dog dog", + "dog dog fish fish", + "fish fish fish fish", + ]; + let batch = RecordBatch::try_from_iter([ + ( + "id", + Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4])) as ArrayRef, + ), + ( + "text", + Arc::new(StringArray::from_iter_values(text)) as ArrayRef, + ), + ])?; + let db = crate::connect("memory://metadata_unordered_fts") + .execute() + .await?; + let table = db.create_table("docs", batch).execute().await?; + table + .create_index(&["text"], crate::index::Index::FTS(Default::default())) + .execute() + .await?; + let search = table + .query() + .full_text_search(FullTextSearchQuery::new("dog".into())); + let ranked = scored_ids(&search.execute().await?.try_collect::>().await?); + assert_eq!( + ranked.iter().map(|row| row.0).collect::>(), + [2, 1, 3, 0] + ); + + let native = table.as_native().unwrap(); + let dataset = native.dataset.get().await?; + for offset in [0, 1] { + let query = search + .clone() + .ordered_results(false) + .limit(2) + .offset(offset); + let request = AnyQuery::Query(query.current_request().clone()).canonicalized()?; + let request = VectorQueryRequest::from_plain_query(request.base().clone()); + let mut scanner = dataset.scan(); + let options = QueryExecutionOptions::default(); + assert!( + configure_scanner( + native, + &dataset, + &request, + &mut scanner, + &options, + false, + false + ) + .await? + .is_none() + ); + let plan = scanner.explain_plan(false).await?; + assert_eq!(plan.contains("output_order=heap"), offset == 0, "{plan}"); + + for (mode, hits) in [ + (TrackTotalHits::Off, None), + (TrackTotalHits::Exact, Some((4, HitRelation::Exact))), + ( + TrackTotalHits::UpTo(NonZeroU64::new(3).unwrap()), + Some((3, HitRelation::GreaterThanOrEqual)), + ), + ] { + let result = query + .execute_with_metadata( + options.clone(), + MetadataRequest::new().track_total_hits(mode), + ) + .await?; + let metadata = result.metadata_handle(); + let mut actual = scored_ids(&result.try_collect::>().await?); + let mut expected = ranked[offset..offset + 2].to_vec(); + if offset == 0 { + actual.sort_unstable(); + expected.sort_unstable(); + } + assert_eq!(actual, expected, "{mode:?}, offset={offset}"); + assert_eq!( + metadata + .metadata() + .unwrap() + .total_hits + .map(|h| (h.value, h.relation)), + hits + ); + } + } + Ok(()) + } + #[tokio::test] async fn test_parse_arrow_ipc_response_handles_file_and_stream() { use arrow_array::{Int32Array, RecordBatch};