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:
@@ -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