mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat!: add explicit scan order contract for local queries (#5138)
BREAKING CHANGE: `QueryRequest` now has a public `scan_in_order: Option<bool>` field. Existing code that constructs `QueryRequest` with an exhaustive struct literal must add `scan_in_order: None` to retain the previous backend default, or use `..Default::default()` where appropriate. Python defaults are unchanged: leaving `scan_in_order()` uncalled keeps `None`. ## Problem Plain Embedded LanceDB scans already use Lance's ordered scan on a fixed snapshot, but the storage-order contract was undocumented and callers had no way to require it. Explicit `order_by` sorts the whole result. Ranked, Enterprise, RTE/LSM, legacy scalar-index and namespace-pushdown paths cannot always preserve base manifest order. ## Behavior - `scan_in_order(true)` requires manifest order without adding a sort: fragments in manifest order, then rows in fragment order. - `true` disables scalar-index filter planning. Legacy scalar-index plans can materialize index rows in a different sequence, so filters are evaluated over the manifest-ordered scan instead. Filter semantics are unchanged, but the scan can read more data. Default filtered scans can still use those plans and may not preserve manifest order. - `scan_in_order(false)` permits the backend to scan unordered. It does **not** guarantee a different order; an explicit nonempty `order_by` still sorts. - Leaving the option unset preserves the backend default. The documented manifest-order default applies to an unfiltered base-only scan of a pinned Embedded table version. RTE tables scan the LSM by default and need `use_rte(false)` for the base-only guarantee. Enterprise and namespace-pushed scans have no order guarantee. - `true` conflicts with nonempty `order_by`, take queries, vector/full-text/hybrid/reranked queries, RTE/LSM reads, and Enterprise tables. These fail explicitly instead of silently dropping the requirement. Take conflict validation happens at the shared take-preparation boundary before offset or row-id selectors are stripped. - `with_fragments()` is rejected with `scan_in_order(true)` because fragment objects cannot be validated against the pinned dataset version. Use `fragment_ids()`, which resolves fragment ids from the manifest and preserves manifest order. Both sync and async pandas scanner paths share this rule. - Namespace `QueryTable` pushdown executes `true` against Embedded storage instead of dropping the order. The existing path preserves projection, filtering, limits, version/branch selection, and RTE routing; if Embedded storage cannot be read, the query fails. Supported entry points are plain Rust `Table::query()`, Python sync `table.search()` and async `table.query()`. The Python pandas scanner fast path forwards the option and disables scalar-index planning for explicit order. Existing takes and `with_fragments()` calls with `None` or `false` are unchanged. ## Validation - Rust: 6 `scan_in_order` tests, 32 take tests, 25 query-route tests. - Python: `test_query.py` and `test_namespace.py` 352 passed, 1 skipped against a matching extension. - Scoped `pytest --doctest-modules python/lancedb/query.py -k scan_in_order`: 2 passed. The Rust/Python examples create their own tables and are executable. - Regressions cover legacy 0.1 and stable BTREE tables with update and a filter admitting every row, across pinned versions before and after update; reversed `fragment_ids`; explicit `with_fragments()` rejection; and fixed-version multi-fragment reads with deletions, one-row batches, and limit/offset. No `SortExec` is added. - `cargo clippy --features remote --tests --examples`; `cargo fmt --check`; Ruff format/check; `git diff --check`. - Local checks ran on this branch. CI on this PR evaluates the merge with current `main`; no combined local binary validation is claimed here. Refs OSS-3109.
This commit is contained in:
@@ -972,6 +972,7 @@ class Query:
|
||||
def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ...
|
||||
def nearest_to_text(self, query: dict) -> FTSQuery: ...
|
||||
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(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
@@ -1129,6 +1130,7 @@ class PyQueryRequest:
|
||||
postfilter: Optional[bool]
|
||||
norm: Optional[str]
|
||||
order_by: Optional[List[ColumnOrdering]]
|
||||
scan_in_order: Optional[bool]
|
||||
|
||||
class CompactionStats:
|
||||
fragments_removed: int
|
||||
|
||||
@@ -510,8 +510,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally. Queries with a
|
||||
nonempty ``order_by`` execute locally and require the client to
|
||||
access the table storage.
|
||||
nonempty ``order_by`` or an explicit ``scan_in_order(True)``
|
||||
execute on the client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -1215,8 +1215,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally. Queries with a
|
||||
nonempty ``order_by`` execute locally and require the client to
|
||||
access the table storage.
|
||||
nonempty ``order_by`` or an explicit ``scan_in_order(True)``
|
||||
execute on the client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -1824,8 +1824,8 @@ def connect_namespace(
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally. Queries with a nonempty
|
||||
``order_by`` execute locally and require the client to access the
|
||||
table storage.
|
||||
``order_by`` or an explicit ``scan_in_order(True)`` execute on the
|
||||
client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -1917,8 +1917,8 @@ def connect_namespace_async(
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally. Queries with a nonempty
|
||||
``order_by`` execute locally and require the client to access the
|
||||
table storage.
|
||||
``order_by`` or an explicit ``scan_in_order(True)`` execute on the
|
||||
client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
|
||||
@@ -371,6 +371,10 @@ def _scanner_kwargs_for_query(
|
||||
"with_row_id": with_row_id if with_row_id is not None else query.with_row_id,
|
||||
"with_row_address": query.with_row_address,
|
||||
"fast_search": query.fast_search,
|
||||
"scan_in_order": query.scan_in_order,
|
||||
# Legacy scalar-index plans can reorder rows. Explicit storage order
|
||||
# evaluates filters over the manifest-ordered scan instead.
|
||||
"use_scalar_index": False if query.scan_in_order is True else None,
|
||||
"blob_handling": BLOB_MODE_TO_HANDLING[blob_mode],
|
||||
"fragments": fragments,
|
||||
}
|
||||
@@ -381,6 +385,12 @@ def _scanner_fragments_for_query(query: Query, dataset: Optional[Any]) -> Option
|
||||
if query.fragments is not None and query.fragment_ids is not None:
|
||||
raise ValueError("fragments and fragment_ids cannot both be set")
|
||||
if query.fragments is not None:
|
||||
if query.scan_in_order is True:
|
||||
raise ValueError(
|
||||
"scan_in_order(True) cannot validate with_fragments() against "
|
||||
"the scanned dataset version; use fragment_ids() to select "
|
||||
"fragments by manifest id"
|
||||
)
|
||||
return query.fragments
|
||||
if query.fragment_ids is None:
|
||||
return None
|
||||
@@ -1208,6 +1218,10 @@ class Query(pydantic.BaseModel):
|
||||
|
||||
order_by: Optional[List[ColumnOrdering]] = None
|
||||
|
||||
# Tri-state storage-order requirement: None preserves the backend default,
|
||||
# True requires manifest order, False allows an unordered scan.
|
||||
scan_in_order: Optional[bool] = None
|
||||
|
||||
@classmethod
|
||||
def from_inner(cls, req: PyQueryRequest) -> Self:
|
||||
query = cls()
|
||||
@@ -1241,6 +1255,7 @@ class Query(pydantic.BaseModel):
|
||||
query.postfilter = req.postfilter
|
||||
if req.order_by is not None:
|
||||
query.order_by = [ColumnOrdering(**o) for o in req.order_by]
|
||||
query.scan_in_order = req.scan_in_order
|
||||
if req.full_text_search is not None:
|
||||
query.full_text_query = FullTextSearchQuery(
|
||||
columns=None,
|
||||
@@ -1415,6 +1430,7 @@ class LanceQueryBuilder(ABC):
|
||||
self._approx_mode = None
|
||||
self._bypass_vector_index = None
|
||||
self._order_by = None
|
||||
self._scan_in_order = None
|
||||
|
||||
@deprecation.deprecated(
|
||||
deprecated_in="0.3.1",
|
||||
@@ -2023,7 +2039,9 @@ class LanceQueryBuilder(ABC):
|
||||
----------
|
||||
fragments : list[lance.Fragment]
|
||||
Fragments from ``table.to_lance().get_fragments()``. Pass fragments
|
||||
from the same dataset snapshot.
|
||||
from the same dataset snapshot. Use ``fragment_ids()`` instead when
|
||||
``scan_in_order(True)`` is set; fragment objects cannot be validated
|
||||
against the pinned dataset version.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -3082,6 +3100,52 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
def scan_in_order(self, ordered: bool = True) -> Self:
|
||||
"""Control whether an ordinary scan must preserve storage order.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ordered: bool, default True
|
||||
``True`` requires manifest order: fragments in manifest order, then
|
||||
rows in fragment order. ``False`` allows the backend to scan
|
||||
unordered. Leave the method uncalled to preserve the backend
|
||||
default.
|
||||
|
||||
An unfiltered plain base-only scan of an Embedded table, pinned to one
|
||||
dataset version, returns manifest order by default. RTE tables scan the
|
||||
LSM by default and do not provide this guarantee unless
|
||||
``use_rte(False)`` selects the base table. Explicit ``True`` also
|
||||
disables scalar-index filter planning, because legacy scalar-index plans
|
||||
can return a different sequence; default filtered scans can still use
|
||||
those plans and may not preserve manifest order. Filters still apply,
|
||||
but the scan can read more data. ``with_fragments()`` is not supported
|
||||
with ``True`` because fragment objects cannot be validated against the
|
||||
pinned dataset version; use ``fragment_ids()`` instead, which resolves
|
||||
ids from the manifest and remains ordered. Compaction, updates, or
|
||||
opening a newer version can change that order, so pin the table version
|
||||
when positions must remain stable across executions. An explicit
|
||||
``order_by()`` replaces manifest order with a global sort, and vector,
|
||||
full-text, hybrid, or reranked queries return ranked results; combining
|
||||
those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise
|
||||
tables and RTE/LSM reads raise ``NotImplementedError`` because they
|
||||
cannot uphold the order; set ``use_rte(False)`` to read the RTE base
|
||||
table in storage order. When ``QueryTable`` pushdown is enabled, the
|
||||
backend default may not preserve order; requesting ``True`` executes
|
||||
against Embedded storage instead, because the namespace request has no
|
||||
order field.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import lancedb
|
||||
>>> db = lancedb.connect("memory://")
|
||||
>>> table = db.create_table("scan_in_order", [{"id": 1}])
|
||||
>>> query = table.search().scan_in_order(True).select(["id"])
|
||||
>>> query.to_arrow()["id"].to_pylist()
|
||||
[1]
|
||||
"""
|
||||
self._scan_in_order = ordered
|
||||
return self
|
||||
|
||||
def to_query_object(self) -> Query:
|
||||
return Query(
|
||||
columns=self._columns,
|
||||
@@ -3094,6 +3158,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
|
||||
use_rte=self._use_rte,
|
||||
offset=self._offset,
|
||||
order_by=self._order_by,
|
||||
scan_in_order=self._scan_in_order,
|
||||
)
|
||||
|
||||
def output_schema(self) -> pa.Schema:
|
||||
@@ -4142,7 +4207,9 @@ class AsyncQueryBase(object):
|
||||
query types. Other terminals and remote tables raise
|
||||
``NotImplementedError`` before scanning instead of silently scanning
|
||||
the full table. Blob-specific ``to_pandas()`` fallbacks keep their
|
||||
existing validation errors.
|
||||
existing validation errors. Use ``fragment_ids()`` instead when
|
||||
``scan_in_order(True)`` is set; fragment objects cannot be validated
|
||||
against the pinned dataset version.
|
||||
"""
|
||||
self._fragments = fragments
|
||||
return self
|
||||
@@ -4866,6 +4933,55 @@ class AsyncQuery(AsyncStandardQuery):
|
||||
super().__init__(inner, table)
|
||||
self._inner = inner
|
||||
|
||||
def scan_in_order(self, ordered: bool = True) -> Self:
|
||||
"""Control whether an ordinary scan must preserve storage order.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ordered: bool, default True
|
||||
``True`` requires manifest order: fragments in manifest order, then
|
||||
rows in fragment order. ``False`` allows the backend to scan
|
||||
unordered. Leave the method uncalled to preserve the backend
|
||||
default.
|
||||
|
||||
An unfiltered plain base-only scan of an Embedded table, pinned to one
|
||||
dataset version, returns manifest order by default. RTE tables scan the
|
||||
LSM by default and do not provide this guarantee unless
|
||||
``use_rte(False)`` selects the base table. Explicit ``True`` also
|
||||
disables scalar-index filter planning, because legacy scalar-index plans
|
||||
can return a different sequence; default filtered scans can still use
|
||||
those plans and may not preserve manifest order. Filters still apply,
|
||||
but the scan can read more data. ``with_fragments()`` is not supported
|
||||
with ``True`` because fragment objects cannot be validated against the
|
||||
pinned dataset version; use ``fragment_ids()`` instead, which resolves
|
||||
ids from the manifest and remains ordered. Compaction, updates, or
|
||||
opening a newer version can change that order, so pin the table version
|
||||
when positions must remain stable across executions. An explicit
|
||||
``order_by()`` replaces manifest order with a global sort, and vector,
|
||||
full-text, hybrid, or reranked queries return ranked results; combining
|
||||
those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise
|
||||
tables and RTE/LSM reads raise ``NotImplementedError`` because they
|
||||
cannot uphold the order; set ``use_rte(False)`` to read the RTE base
|
||||
table in storage order. When ``QueryTable`` pushdown is enabled, the
|
||||
backend default may not preserve order; requesting ``True`` executes
|
||||
against Embedded storage instead, because the namespace request has no
|
||||
order field.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import asyncio
|
||||
>>> import lancedb
|
||||
>>> async def example():
|
||||
... db = await lancedb.connect_async("memory://")
|
||||
... table = await db.create_table("scan_in_order_async", [{"id": 1}])
|
||||
... query = table.query().scan_in_order(True).select(["id"])
|
||||
... return (await query.to_arrow())["id"].to_pylist()
|
||||
>>> asyncio.run(example())
|
||||
[1]
|
||||
"""
|
||||
self._inner.scan_in_order(ordered)
|
||||
return self
|
||||
|
||||
@classmethod
|
||||
def _query_vec_to_array(self, vec: Union[VEC, Tuple]):
|
||||
if isinstance(vec, list):
|
||||
|
||||
@@ -149,6 +149,9 @@ def _requires_local_namespace_execution(query: Query) -> bool:
|
||||
# The namespace QueryTable request has no order_by field. Pushing a
|
||||
# nonempty ordering down would drop it and return the wrong top-K rows.
|
||||
or bool(query.order_by)
|
||||
# An ordered scan is a local manifest-order guarantee. The request has
|
||||
# no scan-order field, so run it locally where storage is available.
|
||||
or query.scan_in_order is True
|
||||
or (
|
||||
query.full_text_query is not None
|
||||
and query.fast_search is True
|
||||
@@ -8529,6 +8532,8 @@ class AsyncTable:
|
||||
async_query = async_query.with_row_id()
|
||||
if query.order_by:
|
||||
async_query = async_query.order_by(query.order_by)
|
||||
if query.scan_in_order is not None:
|
||||
async_query = async_query.scan_in_order(query.scan_in_order)
|
||||
|
||||
if query.vector:
|
||||
async_query = async_query.nearest_to(query.vector).distance_range(
|
||||
|
||||
@@ -1789,6 +1789,31 @@ class TestPushdownOperations:
|
||||
assert result.column("id").to_pylist() == [1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
def test_lance_table_scan_in_order_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = lancedb.connect(str(tmp_path / "db"))
|
||||
table = db.create_table("hist", data=[{"id": 3}, {"id": 1}])
|
||||
table.add([{"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = table._execute_query(
|
||||
Query(
|
||||
limit=2,
|
||||
filter="id >= 1",
|
||||
columns=["id"],
|
||||
scan_in_order=True,
|
||||
)
|
||||
).read_all()
|
||||
|
||||
# The namespace request has no scan-order field. Local execution keeps
|
||||
# membership order, projection and limit; a dropped order or a sort
|
||||
# would return [1, 3] or [1, 2].
|
||||
assert result.column("id").to_pylist() == [3, 1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestAsyncPushdownOperations:
|
||||
@@ -1869,6 +1894,29 @@ class TestAsyncPushdownOperations:
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == [1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
async def test_async_table_scan_in_order_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = await lancedb.connect_async(str(tmp_path / "db"))
|
||||
table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}])
|
||||
await table.add([{"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = await table._execute_query(
|
||||
Query(
|
||||
limit=2,
|
||||
filter="id >= 1",
|
||||
columns=["id"],
|
||||
scan_in_order=True,
|
||||
)
|
||||
)
|
||||
|
||||
batches = await result.read_all()
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query_kwargs",
|
||||
[
|
||||
|
||||
@@ -1102,6 +1102,201 @@ def test_order_by_clears_with_none_and_empty_list(mem_db):
|
||||
assert query.order_by([]).to_query_object().order_by is None
|
||||
|
||||
|
||||
def test_scan_in_order_plain_query(tmp_db):
|
||||
table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]}))
|
||||
table.add(pa.table({"id": [2, 3]}))
|
||||
table.add(pa.table({"id": [4, 5]}))
|
||||
|
||||
fragments = table.to_lance().get_fragments()
|
||||
assert len(fragments) == 3, "the test needs real multi-fragment data"
|
||||
|
||||
version = table.version
|
||||
table.checkout(version)
|
||||
|
||||
default = table.search().select(["id"]).to_arrow()["id"].to_pylist()
|
||||
assert default == [0, 1, 2, 3, 4, 5]
|
||||
assert table.search().to_query_object().scan_in_order is None
|
||||
|
||||
ordered = table.search().scan_in_order().select(["id"]).to_arrow()
|
||||
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
||||
repeated = table.search().scan_in_order(True).select(["id"]).to_arrow()
|
||||
assert repeated.equals(ordered)
|
||||
|
||||
unordered = (
|
||||
table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist()
|
||||
)
|
||||
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
||||
|
||||
sorted_desc = (
|
||||
table.search()
|
||||
.scan_in_order(False)
|
||||
.order_by(("id", "desc"))
|
||||
.select(["id"])
|
||||
.to_arrow()["id"]
|
||||
.to_pylist()
|
||||
)
|
||||
assert sorted_desc == [5, 4, 3, 2, 1, 0]
|
||||
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
table.search().scan_in_order().order_by("id").to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection):
|
||||
table = await tmp_db_async.create_table(
|
||||
"scan_in_order_async", pa.table({"id": [0, 1]})
|
||||
)
|
||||
await table.add(pa.table({"id": [2, 3]}))
|
||||
await table.add(pa.table({"id": [4, 5]}))
|
||||
|
||||
assert len((await table.to_lance()).get_fragments()) == 3
|
||||
version = await table.version()
|
||||
await table.checkout(version)
|
||||
|
||||
ordered = await table.query().scan_in_order().select(["id"]).to_arrow()
|
||||
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
||||
assert table.query().to_query_object().scan_in_order is None
|
||||
|
||||
unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[
|
||||
"id"
|
||||
].to_pylist()
|
||||
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
||||
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
await table.query().scan_in_order().order_by("id").to_arrow()
|
||||
with pytest.raises(ValueError, match="ranked results"):
|
||||
await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ordered", [False, True])
|
||||
def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = tmp_db.create_table(
|
||||
f"scan_in_order_scanner_{ordered}",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
table.add(data.slice(2, 2))
|
||||
|
||||
query = table.search().select(["id", "blob"]).scan_in_order(ordered)
|
||||
|
||||
def fail_to_arrow(*args, **kwargs):
|
||||
raise AssertionError("scanner-backed pandas must not collect through to_arrow")
|
||||
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
|
||||
dataset = table.to_lance()
|
||||
dataset_cls = type(dataset)
|
||||
real_scanner = dataset_cls.scanner
|
||||
captured = {}
|
||||
|
||||
def capture_scanner(self, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return real_scanner(self, **kwargs)
|
||||
|
||||
monkeypatch.setattr(dataset_cls, "scanner", capture_scanner)
|
||||
|
||||
df = query.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
|
||||
assert captured["scan_in_order"] is ordered
|
||||
assert captured.get("use_scalar_index") is (False if ordered else None)
|
||||
assert sorted(df["id"].tolist()) == [1, 2, 3, 4]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("storage_version", ["legacy", "stable"])
|
||||
def test_scan_in_order_indexed_filter_preserves_manifest_order(
|
||||
tmp_path, storage_version
|
||||
):
|
||||
lance = pytest.importorskip("lance")
|
||||
data = pa.table({"id": list(range(20)), "value": list(range(20))})
|
||||
dataset = lance.write_dataset(
|
||||
data,
|
||||
tmp_path / "t.lance",
|
||||
data_storage_version=storage_version,
|
||||
max_rows_per_file=10,
|
||||
)
|
||||
dataset.create_scalar_index("value", "BTREE")
|
||||
version_before_update = dataset.version
|
||||
dataset.update({"value": "100"}, where="id = 0")
|
||||
|
||||
table = lancedb.connect(str(tmp_path)).open_table("t")
|
||||
for version in (version_before_update, dataset.version):
|
||||
table.checkout(version)
|
||||
base = table.search().scan_in_order(True).select(["id"]).limit(100)
|
||||
expected = base.to_arrow()["id"].to_pylist()
|
||||
actual = base.where("value < 1000").to_arrow()["id"].to_pylist()
|
||||
assert actual == expected
|
||||
|
||||
|
||||
def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = tmp_db.create_table(
|
||||
"scan_in_order_fragments",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
table.add(data.slice(2, 2))
|
||||
table.checkout(table.version)
|
||||
|
||||
fragments = table.to_lance().get_fragments()
|
||||
reversed_fragments = fragments[::-1]
|
||||
with pytest.raises(ValueError, match="use fragment_ids"):
|
||||
(
|
||||
table.search()
|
||||
.scan_in_order()
|
||||
.select(["id", "blob"])
|
||||
.with_fragments(reversed_fragments)
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
|
||||
# fragment_ids is already resolved from the manifest and stays ordered.
|
||||
df_by_id = (
|
||||
table.search()
|
||||
.scan_in_order()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(
|
||||
tmp_db_async,
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
"scan_in_order_fragments_async",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
await table.checkout(await table.version())
|
||||
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
reversed_fragments = fragments[::-1]
|
||||
with pytest.raises(ValueError, match="use fragment_ids"):
|
||||
await (
|
||||
table.query()
|
||||
.scan_in_order()
|
||||
.with_fragments(fragments[::-1])
|
||||
.select(["id", "blob"])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
|
||||
df_by_id = await (
|
||||
table.query()
|
||||
.scan_in_order()
|
||||
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
||||
.select(["id", "blob"])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
def test_order_by_rejects_invalid_input_early(mem_db):
|
||||
table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}])
|
||||
|
||||
|
||||
Reference in New Issue
Block a user