feat(query): stream query results with optional total hits (#5354)

## Summary

An Embedded query can stream one page of results and report how many
visible rows matched before offset and limit. This adds Rust
`execute_with_metadata`, Python sync and async `to_result`, and
TypeScript `toResult`. The existing query terminals continue to use
their existing execution paths.

Tracking defaults to Off. An exact count returns `eq(N)`. A positive cap
C returns `eq(N)` below C and `gte(C)` as soon as C matches are proven,
including equality. TypeScript exposes counts as bigint. Counts use the
same snapshot as the result batches. The accessor reports pending until
the stream reaches successful EOF. Explicit counts can add work after
the last batch, especially when full-text counting needs to scan visible
text. Closing an unfinished result cancels execution. Stream and
metadata failures retain interruption details, including the request ID.

Embedded supports scalar and row-level lexical counts. Unordered FTS
retains its existing top-k and scoring policy. Enterprise and
unsupported query shapes return a typed error when a count is requested.

## Dependency

#5352 merged Lance v16.0.0-beta.7 into main, including [Lance
#11680](https://github.com/lance-format/lance/pull/11680). This PR uses
that dependency and its lockfiles.

## Validation

The Linux-tested revision `bc39ad7ac` and rebased revision `24f4e90c2`
have the same Git tree. The only change in `6932b3082` is the Python
namespace regression fixture, which now resolves the local table without
the optional pylance package. The revised test passed on managed Linux
with CPython 3.11.18 both with pylance and pandas installed and after
removing both packages. Managed Linux runs used the unmodified manifests
and lockfiles from #5352 and the published `pylance 16.0.0b7` wheel.

- The Rust metadata suite passed 57 tests, with two existing ignores.
Coverage includes unordered FTS plans, top-k scores, physical row
addresses under pagination, pending-read cancellation, and interruption
after the last batch.
- Python query, remote and namespace suites passed 1,163 tests. One
optional slow test requires PyTorch, which was unavailable on this VM.
The Node query, remote, table and error suites passed 913 tests, with
three experimental cases skipped.
- Regression tests reproduced the failures on the previous revision and
verified the fixes. Python sync reranking and namespace FTS preserve an
explicit empty page. Python sync and async scans expose `_rowaddr`
alongside the pre-pagination count. Explicit counts are rejected before
TypeScript auto-search issues an Enterprise request or invokes a vector
embedding provider. Python and Node retain the server's 1,063-row first
batch in Off mode.
- A custom Python namespace opened through the public API receives the
same computed projection in Off mode as with `to_batches()`. A Node
result interrupted after another SDK load retains its original error
class and request ID. Both regressions were reproduced on the prior
revision.
- Workspace Clippy, formatting, Ruff, Biome, TypeScript checks, TypeDoc
and strict MkDocs passed. All 287 generated TypeDoc files matched the
committed files byte for byte.
This commit is contained in:
Yang Cen
2026-12-02 22:47:37 +08:00
committed by GitHub
parent 623777389e
commit feff86a08d
43 changed files with 3540 additions and 103 deletions
+17
View File
@@ -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]
+12
View File
@@ -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."""
+113
View File
@@ -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,
*,
+205
View File
@@ -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()
+15 -19
View File
@@ -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)
+47
View File
@@ -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)
+240
View File
@@ -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)
+129 -5
View File
@@ -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):
+6
View File
@@ -26,6 +26,12 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
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 { .. }
+2
View File
@@ -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::<Query>()?;
m.add_class::<query_result::NativeQueryResult>()?;
m.add_class::<FTSQuery>()?;
m.add_class::<HybridQuery>()?;
m.add_class::<VectorQuery>()?;
+48 -1
View File
@@ -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<u32>,
timeout: Option<Duration>,
) -> 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<std::num::NonZeroU64>,
) -> PyResult<Bound<'py, PyAny>> {
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<std::num::NonZeroU64>,
) -> PyResult<Bound<'py, PyAny>> {
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<std::num::NonZeroU64>,
) -> PyResult<Bound<'py, PyAny>> {
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<std::num::NonZeroU64>,
) -> PyResult<Bound<'py, PyAny>> {
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>,
+70
View File
@@ -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<QueryResultReader>);
pub fn execute_with_metadata<Q: ExecutableQuery + Send + 'static>(
py: Python<'_>,
query: Q,
track: bool,
cap: Option<NonZeroU64>,
) -> PyResult<Bound<'_, PyAny>> {
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<Bound<'py, PyAny>> {
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<Option<(u64, &'static str)>> {
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<Bound<'py, PyAny>> {
let reader = self.0.clone();
future_into_py(py, async move {
reader.close().await;
Ok(())
})
}
}