mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(python)!: preserve input order for take offsets (#5140)
## Summary Add an opt-in `preserve_order` flag to sync and async `take_offsets`. It exposes the existing Rust `TakeRestoreExec` ordering path and carries the flag through `QueryRequest`, `PyQueryRequest`, and the Python `Query` model. ## Behavior - Default `preserve_order=False` keeps the existing incremental, unspecified-order behavior. - `preserve_order=True` returns found rows in input order, including repeated offsets. - Missing non-negative offsets keep filter semantics and are omitted; negative offsets remain rejected by the existing `u64` contract. - Rust take queries apply `limit`/`offset` after order and repetition are restored. Python take builders and Query conversion do not expose pagination. - An explicit `order_by` conflicts with offset `preserve_order` and raises clearly. `take_row_ids` keeps its existing implicit ordering and explicit-sort behavior. - `__getitems__` is unchanged: it keeps its Python re-alignment and strict missing-offset (`ArrowIndexError`) behavior. ## Remote lookup The remote lookup sends only the deduplicated `_rowoffset IN (...)` filter and restores order/repetition client-side; there is no new wire field or backend extension. Namespace take queries stay on local execution, and RTE/LSM rejects the `_rowoffset` lookup loudly. ## Testing - Old reviewed head reproduced the serialization regression: `test_query_serialization_sync/async` failed because the Query model exposed `False` for an unset field. - Fixed by using `Optional[bool] = None` and mapping Rust `false` to absent in `PyQueryRequest`; explicit `True` still survives the actual round trip. - `python/tests/test_query.py`: 253 passed, 1 skipped. - Rust preserve-order tests: 3 passed; row-id/order-by tests: 27 passed. - Remote ordered Blob bytes, remote permutation, and Blob mode focused cases: 3 passed. - `cargo fmt --check`, `ruff format/check`, `py_compile`, and `git diff --check` passed. ## Migration `lancedb::query::QueryRequest` is a public non-`#[non_exhaustive]` struct. Downstream code that constructs it with an exhaustive struct literal must add `preserve_order: false` or use `..Default::default()`. The field is client-side metadata and is not sent over the remote protocol. Seekable Blob APIs, rollout, and ENT-4059 remain separate work. Refs OSS-2881 (non-closing).
This commit is contained in:
@@ -985,6 +985,7 @@ class Query:
|
||||
class TakeQuery:
|
||||
def select(self, columns: List[str]): ...
|
||||
def with_row_id(self): ...
|
||||
def preserve_order(self): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(self) -> RecordBatchStream: ...
|
||||
@@ -1092,6 +1093,7 @@ class PyQueryRequest:
|
||||
offset: Optional[int]
|
||||
take_offsets: Optional[List[int]]
|
||||
take_row_ids: Optional[List[int]]
|
||||
preserve_order: Optional[bool]
|
||||
filter: Optional[Union[str, bytes]]
|
||||
full_text_search: Optional[FullTextQuery]
|
||||
select: Optional[Union[str, List[str]]]
|
||||
|
||||
@@ -1186,6 +1186,9 @@ class Query(pydantic.BaseModel):
|
||||
# Row IDs whose requested order and duplicate occurrences must be restored.
|
||||
take_row_ids: Optional[List[int]] = None
|
||||
|
||||
# Restore take-offset duplicates in the exact input order.
|
||||
preserve_order: Optional[bool] = None
|
||||
|
||||
# if true, will only search the indexed data
|
||||
fast_search: Optional[bool] = None
|
||||
|
||||
@@ -1212,6 +1215,7 @@ class Query(pydantic.BaseModel):
|
||||
query.offset = req.offset
|
||||
query.take_offsets = req.take_offsets
|
||||
query.take_row_ids = req.take_row_ids
|
||||
query.preserve_order = req.preserve_order
|
||||
query.filter = req.filter
|
||||
query.full_text_query = req.full_text_search
|
||||
query.columns = req.select
|
||||
|
||||
@@ -1556,9 +1556,15 @@ class RemoteTable(Table):
|
||||
return LOOP.run(self._table.uri())
|
||||
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> LanceTakeQueryBuilder:
|
||||
builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
|
||||
builder = LanceTakeQueryBuilder(
|
||||
self._table.take_offsets(offsets, preserve_order=preserve_order)
|
||||
)
|
||||
if with_row_id:
|
||||
builder.with_row_id()
|
||||
return builder
|
||||
|
||||
@@ -2660,7 +2660,11 @@ class Table(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> LanceTakeQueryBuilder:
|
||||
"""
|
||||
Take a list of offsets from the table.
|
||||
@@ -2672,9 +2676,13 @@ class Table(ABC):
|
||||
Offsets are mostly useful for sampling as the set of all valid offsets is easily
|
||||
known in advance to be [0, len(table)).
|
||||
|
||||
No guarantees are made regarding the order in which results are returned.
|
||||
Repeated offsets produce repeated rows, which makes this method suitable for
|
||||
sampling with replacement.
|
||||
By default, no guarantees are made regarding the order in which results
|
||||
are returned. Repeated offsets produce repeated rows, which makes this
|
||||
method suitable for sampling with replacement. Set ``preserve_order=True``
|
||||
to return found rows in input order, including repeated offsets. Missing
|
||||
non-negative offsets are omitted. Negative offsets are rejected and are
|
||||
not Python-style relative indices. ``preserve_order`` cannot be combined
|
||||
with an explicit ``order_by``.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -2682,6 +2690,10 @@ class Table(ABC):
|
||||
The offsets to take.
|
||||
with_row_id: bool, default False
|
||||
If True, include the "_rowid" column in the results.
|
||||
preserve_order: bool, default False
|
||||
If True, return found rows in input order. Rust take queries apply
|
||||
limit/offset after restoration; Python take builders and Query
|
||||
conversion do not expose pagination.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -4533,9 +4545,15 @@ class LanceTable(Table):
|
||||
return LOOP.run(self._table.version())
|
||||
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> LanceTakeQueryBuilder:
|
||||
builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
|
||||
builder = LanceTakeQueryBuilder(
|
||||
self._table.take_offsets(offsets, preserve_order=preserve_order)
|
||||
)
|
||||
if with_row_id:
|
||||
builder.with_row_id()
|
||||
return builder
|
||||
@@ -8449,10 +8467,18 @@ class AsyncTable:
|
||||
if query.take_offsets is not None or query.take_row_ids is not None:
|
||||
if query.take_offsets is not None and query.take_row_ids is not None:
|
||||
raise ValueError("Only one of take_offsets and take_row_ids may be set")
|
||||
if query.preserve_order is True and query.take_offsets is None:
|
||||
raise ValueError("preserve_order only supports take_offsets")
|
||||
if query.preserve_order is True and query.order_by:
|
||||
raise ValueError(
|
||||
"preserve_order cannot be combined with an explicit order_by"
|
||||
)
|
||||
take_query = (
|
||||
self.take_row_ids(query.take_row_ids)
|
||||
if query.take_row_ids is not None
|
||||
else self.take_offsets(query.take_offsets)
|
||||
else self.take_offsets(
|
||||
query.take_offsets, preserve_order=query.preserve_order is True
|
||||
)
|
||||
)
|
||||
if query.columns is not None:
|
||||
columns = query.columns
|
||||
@@ -9662,7 +9688,11 @@ class AsyncTable:
|
||||
await self._inner.restore(version)
|
||||
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> AsyncTakeQuery:
|
||||
"""
|
||||
Take a list of offsets from the table.
|
||||
@@ -9674,8 +9704,12 @@ class AsyncTable:
|
||||
Offsets are mostly useful for sampling as the set of all valid offsets is easily
|
||||
known in advance to be [0, len(table)).
|
||||
|
||||
No guarantees are made regarding the order in which results are returned.
|
||||
Repeated offsets produce repeated rows.
|
||||
By default, no guarantees are made regarding the order in which results
|
||||
are returned. Repeated offsets produce repeated rows. Set
|
||||
``preserve_order=True`` to return found rows in input order, including
|
||||
repeated offsets. Missing non-negative offsets are omitted. Negative
|
||||
offsets are rejected and are not Python-style relative indices.
|
||||
``preserve_order`` cannot be combined with an explicit ``order_by``.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -9683,6 +9717,10 @@ class AsyncTable:
|
||||
The offsets to take.
|
||||
with_row_id: bool, default False
|
||||
If True, include the "_rowid" column in the results.
|
||||
preserve_order: bool, default False
|
||||
If True, return found rows in input order. Rust take queries apply
|
||||
limit/offset after restoration; Python take builders and Query
|
||||
conversion do not expose pagination.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -9691,6 +9729,8 @@ class AsyncTable:
|
||||
offsets.
|
||||
"""
|
||||
query = AsyncTakeQuery(self._inner.take_offsets(offsets), self)
|
||||
if preserve_order:
|
||||
query._inner.preserve_order()
|
||||
if with_row_id:
|
||||
query.with_row_id()
|
||||
return query
|
||||
|
||||
@@ -1017,6 +1017,11 @@ def test_take_queries_honor_blob_mode():
|
||||
1: b"one",
|
||||
2: b"two",
|
||||
}
|
||||
ordered = table.take_offsets([1, 0], preserve_order=True).to_arrow(
|
||||
blob_mode="bytes"
|
||||
)
|
||||
assert ordered["id"].to_pylist() == [2, 1]
|
||||
assert ordered["image"].to_pylist() == [b"two", b"one"]
|
||||
assert [
|
||||
row["image"] for row in table.take_row_ids([0]).to_list(blob_mode="bytes")
|
||||
] == [b"one"]
|
||||
|
||||
@@ -975,6 +975,10 @@ async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async):
|
||||
|
||||
df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes")
|
||||
assert set(df["blob"]) == {b"two", b"three"}
|
||||
ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas(
|
||||
blob_mode="bytes"
|
||||
)
|
||||
assert ordered["blob"].tolist() == [b"three", b"two"]
|
||||
|
||||
|
||||
def test_order_by_plain_query(mem_db):
|
||||
@@ -2815,6 +2819,86 @@ def test_take_queries(tmp_path):
|
||||
assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17]
|
||||
|
||||
|
||||
def test_take_offsets_preserve_order_sync(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("test", pa.table({"idx": range(4)}))
|
||||
table.add(pa.table({"idx": range(4, 8)}))
|
||||
table.delete("idx IN (1, 6)")
|
||||
requested = [5, 0, 5, 2, 99, 4, 0]
|
||||
expected = [7, 0, 7, 3, 5, 0]
|
||||
|
||||
actual = (
|
||||
table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow()
|
||||
)
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == expected
|
||||
|
||||
batches = list(
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_batches(max_batch_length=1)
|
||||
)
|
||||
assert all(batch.num_rows <= 1 for batch in batches)
|
||||
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
||||
|
||||
# The default path keeps its unspecified-order behavior.
|
||||
default = table.take_offsets(requested).select(["idx"]).to_arrow()
|
||||
assert sorted(default["idx"].to_pylist()) == sorted(expected)
|
||||
|
||||
assert table.take_offsets(requested).to_query_object().preserve_order is None
|
||||
query = (
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_query_object()
|
||||
)
|
||||
assert query.preserve_order is True
|
||||
assert table._execute_query(query).read_all()["idx"].to_pylist() == expected
|
||||
|
||||
empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow()
|
||||
assert empty.num_rows == 0
|
||||
assert empty.column_names == ["idx"]
|
||||
|
||||
query.order_by = [ColumnOrdering(column_name="idx")]
|
||||
with pytest.raises(
|
||||
ValueError, match="preserve_order cannot be combined with an explicit order_by"
|
||||
):
|
||||
table._execute_query(query)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_take_offsets_preserve_order_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test", pa.table({"idx": range(4)}))
|
||||
await table.add(pa.table({"idx": range(4, 8)}))
|
||||
await table.delete("idx IN (1, 6)")
|
||||
requested = [5, 0, 5, 2, 99, 4, 0]
|
||||
expected = [7, 0, 7, 3, 5, 0]
|
||||
|
||||
actual = (
|
||||
await table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_arrow()
|
||||
)
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == expected
|
||||
|
||||
reader = (
|
||||
await table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_batches(max_batch_length=1)
|
||||
)
|
||||
batches = [batch async for batch in reader]
|
||||
assert all(batch.num_rows <= 1 for batch in batches)
|
||||
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
||||
|
||||
query = (
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_query_object()
|
||||
)
|
||||
assert query.preserve_order is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty):
|
||||
@@ -2921,6 +3005,13 @@ def test_getitems(tmp_path):
|
||||
assert table.__getitems__(offsets) == pa.table({"idx": offsets})
|
||||
|
||||
|
||||
def test_getitems_rejects_missing_offsets(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)}))
|
||||
|
||||
with pytest.raises(pa.ArrowIndexError, match="out of bounds"):
|
||||
table.__getitems__([0, 99])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_timeout_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
|
||||
@@ -1404,6 +1404,12 @@ def test_remote_permutation_is_picklable():
|
||||
{"a": 2},
|
||||
{"a": 4},
|
||||
]
|
||||
assert table.take_offsets([0, 2, 0, 4], preserve_order=True).to_list() == [
|
||||
{"a": 0},
|
||||
{"a": 2},
|
||||
{"a": 0},
|
||||
{"a": 4},
|
||||
]
|
||||
|
||||
permutation = Permutation.identity(table)
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
@@ -6083,14 +6089,26 @@ def blob_remote_table(
|
||||
if requests is not None:
|
||||
requests.append(("query", body))
|
||||
columns = body.get("columns")
|
||||
assert columns in (
|
||||
take_offsets_query = isinstance(columns, list) and "_rowoffset" in columns
|
||||
assert take_offsets_query or columns in (
|
||||
None,
|
||||
["id", "image"],
|
||||
["id"],
|
||||
["image"],
|
||||
{"payload": "image"},
|
||||
)
|
||||
if isinstance(columns, dict):
|
||||
if take_offsets_query:
|
||||
response_table = blob_query_response_table().append_column(
|
||||
"_rowoffset", pa.array(range(3), type=pa.uint64())
|
||||
)
|
||||
response_table = response_table.select(
|
||||
[name for name in columns if name != "_rowid"]
|
||||
)
|
||||
if body.get("with_row_id", False):
|
||||
response_table = response_table.append_column(
|
||||
"_rowid", blob_query_response_table()["_rowid"]
|
||||
)
|
||||
elif isinstance(columns, dict):
|
||||
response_table = blob_query_response_table().select(["image", "_rowid"])
|
||||
response_table = response_table.rename_columns(["payload", "_rowid"])
|
||||
if not body.get("with_row_id", False):
|
||||
@@ -6725,6 +6743,18 @@ def test_remote_blob_fetch_accepts_metadata_free_query_table(api):
|
||||
handle.close()
|
||||
|
||||
|
||||
def test_remote_take_offsets_preserve_order_with_blob_bytes():
|
||||
with blob_remote_table() as table:
|
||||
hits = (
|
||||
table.take_offsets([2, 0, 2], preserve_order=True)
|
||||
.select(["id", "image"])
|
||||
.to_arrow(blob_mode="bytes")
|
||||
)
|
||||
|
||||
assert hits["id"].to_pylist() == [3, 1, 3]
|
||||
assert hits["image"].to_pylist() == [b"gamma", b"alpha", b"gamma"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
|
||||
def test_remote_blob_fetch_from_query_result_keeps_query_snapshot(api):
|
||||
requests = []
|
||||
|
||||
Reference in New Issue
Block a user