fix(python): preserve blob query snapshots and row-id guidance (#5129)

## Summary

- Preserve the query snapshot carried by a remote query result when
`fetch_blobs` or `fetch_blob_files` receives that result table, instead
of reading row IDs from the table's current snapshot.
- Send the expected `x-lancedb-query-snapshot` on the descriptor take
used by `fetch_blob_files` and verify the response echo before decoding
any descriptor. NULL and empty descriptors cannot escape unverified.
- Point missing `_rowid` and missing row-id errors at
`take_offsets(offsets, with_row_id=True)` for callers that have row
positions, while keeping the existing missing/deleted row-id details.
- Keep `fetch_blobs` row-ID based. Positional access and seekable
video/DataLoader handle design remain separate work aligned with
ENT-4059; this PR does not add `offsets=` or change that contract.
- Document the behavior and keep empty row-id requests at zero I/O.

## Compatibility

Server 0.5.0 is the basic remote Blob API floor. Snapshot-bound
descriptor reads need the actual query identity echo from the serving
node (Sophon #10211, present in tag v1.13.0). If identity cannot be
verified, `fetch_blob_files` fails explicitly instead of accepting
descriptors. Metadata-free row-id input keeps the existing
current-snapshot behavior. This does not claim production rollout or
real server testing.

## Testing

- `python/tests/test_blob.py`: 249 passed, 1 skipped
- `python/tests/test_remote_db.py -k blob`: 133 passed
- Rust remote blob-file unit tests: 13 passed
- `cargo check --features remote --tests --examples`
- `cargo fmt --all --check`, `ruff format` and `ruff check`

Refs OSS-2881 (non-closing).
This commit is contained in:
Xuanwo
2026-11-20 23:47:26 +08:00
committed by GitHub
parent d46754cad4
commit a2176f9bcd
10 changed files with 353 additions and 39 deletions
+65 -4
View File
@@ -7,7 +7,9 @@ from __future__ import annotations
import io
import operator
import re
from collections.abc import Awaitable, Callable, Iterable, Mapping
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional, Union
import pyarrow as pa
@@ -30,10 +32,47 @@ BLOB_MODE_TO_HANDLING = {
}
ROW_ID_FIELD_NAME = "_lance_row_id"
QUERY_VERSION_METADATA_KEY = b"lancedb:query_version"
QUERY_SNAPSHOT_METADATA_KEY = b"lancedb:query_snapshot"
FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
_POSITION_HELP = (
"If you only have row positions, call "
"table.take_offsets(offsets, with_row_id=True) first and pass the resulting "
"'_rowid' values."
)
def _remote_blob_snapshot(
schema: pa.Schema, *, operation: str = "blob_mode='bytes'"
) -> tuple[int, str]:
"""Validate the snapshot metadata a remote query attaches to its result."""
value = (schema.metadata or {}).get(QUERY_VERSION_METADATA_KEY, b"")
if not value.isdigit() or not 0 < int(value) < 2**64:
raise NotImplementedError(
f"{operation} requires a stable table snapshot: the query response "
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
"Upgrade the server and use a table without Realtime/MemWAL, or use "
"blob_mode='descriptions'."
)
identity = (schema.metadata or {}).get(QUERY_SNAPSHOT_METADATA_KEY, b"")
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
raise NotImplementedError(
f"{operation} requires a trustworthy query snapshot identity: "
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
"on every serving node, or use blob_mode='descriptions'."
)
return int(value), identity.decode("ascii")
@dataclass(frozen=True)
class _BlobRowIdSelection:
row_ids: list[int]
version: Optional[int] = None
snapshot_identity: Optional[str] = None
def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]:
if size is None:
@@ -376,7 +415,7 @@ def _hit_row_ids(tbl: pa.Table, blob_sources: dict[str, str]) -> list[int]:
raise ValueError(
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
f"field on blob columns {list(blob_sources)}. Call .with_row_id(True) "
"to fetch blob bytes for this query."
f"to fetch blob bytes for this query. {_POSITION_HELP}"
)
@@ -417,7 +456,8 @@ def read_row_ids_from_hits(hits: pa.Table, blob_column: str) -> list[int]:
raise ValueError(
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
f"field on blob column '{blob_column}'. Pass fresh blob query "
"results, call .with_row_id(True), or pass a list of row ids."
f"results, call .with_row_id(True), or pass a list of row ids. "
f"{_POSITION_HELP}"
)
@@ -638,11 +678,31 @@ def _walk_struct_fields(
return data_type
def _query_snapshot_for_blob_fetch(
schema: pa.Schema,
) -> Optional[tuple[int, str]]:
"""Use the query snapshot when a result table carries one.
A table without either metadata key came from a local table or a server
that cannot pin deferred reads, so row ids keep their existing
current-snapshot behavior.
"""
metadata = schema.metadata or {}
if not any(
key in metadata
for key in (QUERY_VERSION_METADATA_KEY, QUERY_SNAPSHOT_METADATA_KEY)
):
return None
return _remote_blob_snapshot(schema, operation="fetching blobs for a query result")
def _normalize_blob_row_ids(
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], blob_column: str
) -> list[int]:
) -> _BlobRowIdSelection:
snapshot = None
if isinstance(row_ids, pa.Table):
values = read_row_ids_from_hits(row_ids, blob_column)
snapshot = _query_snapshot_for_blob_fetch(row_ids.schema)
elif isinstance(row_ids, (pa.Array, pa.ChunkedArray)):
if not pa.types.is_integer(row_ids.type):
raise ValueError(
@@ -662,7 +722,8 @@ def _normalize_blob_row_ids(
if row_id < 0:
raise ValueError("row ids must be non-negative")
normalized.append(row_id)
return normalized
version, snapshot_identity = snapshot if snapshot else (None, None)
return _BlobRowIdSelection(normalized, version, snapshot_identity)
def _wrap_blob_files(handles: Iterable[object]) -> list[Optional[BlobFile]]:
+7 -1
View File
@@ -862,7 +862,13 @@ class Table:
requests: Sequence[Sequence[int]],
) -> pa.LargeBinaryArray: ...
async def fetch_blob_files(
self, column: str, row_ids: list[int], buffer_size: Optional[int] = None
self,
column: str,
row_ids: list[int],
buffer_size: Optional[int] = None,
*,
version: Optional[int] = None,
snapshot_identity: Optional[str] = None,
) -> list[Optional[BlobFile]]: ...
async def open_blob_file(
self, descriptor: str, buffer_size: Optional[int] = None
+1 -20
View File
@@ -4,7 +4,6 @@
from __future__ import annotations
import asyncio
import re
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
@@ -48,6 +47,7 @@ from ._blob import (
BLOB_MODE_TO_HANDLING,
FetchBlobsAsync,
FetchBlobsSync,
_remote_blob_snapshot,
blob_auto_row_id_for_scan,
blob_projection_sources,
blob_v2_projection_sources,
@@ -205,25 +205,6 @@ def _supports_blob_fetch(
)
def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]:
value = (schema.metadata or {}).get(b"lancedb:query_version", b"")
if not value.isdigit() or not 0 < int(value) < 2**64:
raise NotImplementedError(
"blob_mode='bytes' requires a stable table snapshot: the query response "
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
"Upgrade the server and use a table without Realtime/MemWAL, or use "
"blob_mode='descriptions'."
)
identity = (schema.metadata or {}).get(b"lancedb:query_snapshot", b"")
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
raise NotImplementedError(
"blob_mode='bytes' requires a trustworthy query snapshot identity: "
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
"on every serving node, or use blob_mode='descriptions'."
)
return int(value), identity.decode("ascii")
def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table:
"""Preserve a snapshot only when every query leg used the same identity."""
keys = (b"lancedb:query_version", b"lancedb:query_snapshot")
+31 -2
View File
@@ -2802,6 +2802,15 @@ class Table(ABC):
One missing or deleted row ID rejects the entire batch; no partial
results are returned.
A query result table that carries snapshot metadata keeps the snapshot
that produced it on LanceDB Enterprise. A query result without that
metadata, including a legacy query response, and a plain list are read
from the table's current snapshot; keep the source unchanged between
selection and fetching. Partial snapshot metadata is rejected. Row
positions are not row IDs: to read by position, call
``table.take_offsets(offsets, with_row_id=True)`` first and pass the
resulting ``_rowid`` values.
Blobs inside lists cannot be fetched by row id yet.
LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob
@@ -2868,6 +2877,17 @@ class Table(ABC):
row ids.
One missing or deleted row ID rejects the entire batch; no partial
handles are returned.
A query result table that carries snapshot metadata keeps the snapshot
that produced it on LanceDB Enterprise, so every returned handle reads
that snapshot. Metadata-free query results, including legacy server
responses, and plain lists are read from the table's current snapshot.
Partial snapshot metadata is rejected. A snapshot-bound handle fails
explicitly when the serving node cannot echo the query snapshot
identity; the 0.5.0 floor covers the basic remote Blob API but not that
echo. Row positions are not row IDs: call
``table.take_offsets(offsets, with_row_id=True)`` first and pass the
resulting ``_rowid`` values.
"""
@abstractmethod
@@ -9711,8 +9731,12 @@ class AsyncTable:
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
) -> pa.LargeBinaryArray:
selection = _normalize_blob_row_ids(row_ids, column)
return await self._inner.fetch_blobs(
column, _normalize_blob_row_ids(row_ids, column)
column,
selection.row_ids,
version=selection.version,
snapshot_identity=selection.snapshot_identity,
)
async def fetch_blob_ranges(
@@ -9738,8 +9762,13 @@ class AsyncTable:
See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files].
"""
buffer_size = _validate_blob_buffer_size(buffer_size)
selection = _normalize_blob_row_ids(row_ids, column)
handles = await self._inner.fetch_blob_files(
column, _normalize_blob_row_ids(row_ids, column), buffer_size
column,
selection.row_ids,
buffer_size=buffer_size,
version=selection.version,
snapshot_identity=selection.snapshot_identity,
)
return _wrap_blob_files(handles)
+16 -1
View File
@@ -1958,6 +1958,18 @@ def test_fetch_blob_apis_reject_missing_fragment_row_addr():
_assert_fetch_apis_reject_missing_row_ids(table, [1 << 32, live])
def test_fetch_blobs_missing_row_ids_suggest_take_offsets():
table = _blob_table(
"position_hint",
[{"id": i, "image": b"x"} for i in range(3)],
)
with pytest.raises(ValueError, match="take_offsets") as exc:
table.fetch_blobs("image", [10])
message = str(exc.value)
assert "first missing row ids: [10]" in message
assert "with_row_id=True" in message
def test_fetch_blob_apis_reject_deleted_row_ids():
table = _blob_table(
"deleted_rows",
@@ -2216,8 +2228,11 @@ def test_fetch_blobs_from_query_result_without_row_id_raises():
table = _blob_table("no_rowid", [{"id": 1, "image": b"x"}])
hits = table.search().select(["id"]).to_arrow()
assert "_rowid" not in hits.column_names
with pytest.raises(ValueError, match="_rowid"):
with pytest.raises(ValueError, match="take_offsets") as exc:
table.fetch_blobs("image", hits)
message = str(exc.value)
assert "with_row_id=True" in message
assert "list of row ids" in message
_HYBRID_BLOB_SCHEMA = pa.schema(
+115 -8
View File
@@ -6007,6 +6007,9 @@ def blob_descriptor_take_table():
)
_DEFAULT_DESCRIPTOR_IDENTITY = object()
@contextlib.contextmanager
def blob_remote_table(
*,
@@ -6022,6 +6025,7 @@ def blob_remote_table(
search_scores=False,
snapshot_supported=True,
identity_header="v1:" + "a" * 64,
descriptor_identity_header=_DEFAULT_DESCRIPTOR_IDENTITY,
verify_identity=True,
):
if state is None:
@@ -6066,6 +6070,11 @@ def blob_remote_table(
request.send_header(
"x-lancedb-version", str(BLOB_DESCRIBE_RESPONSE["version"])
)
if verify_identity and request.headers.get("x-lancedb-query-snapshot"):
request.send_header(
"x-lancedb-query-snapshot",
request.headers["x-lancedb-query-snapshot"],
)
request.end_headers()
request.wfile.write(chunk)
elif request.path == "/v1/table/test/query/":
@@ -6132,11 +6141,20 @@ def blob_remote_table(
request.send_header("x-lancedb-version", header)
if snapshot_supported:
request.send_header("x-lancedb-query-version", header)
identity = (
identity_header(body)
if callable(identity_header)
else identity_header
descriptor_query = body.get("filter", "").startswith("_rowid IN")
use_descriptor_identity = (
descriptor_query
and descriptor_identity_header
is not _DEFAULT_DESCRIPTOR_IDENTITY
)
if use_descriptor_identity:
identity = descriptor_identity_header
else:
identity = (
identity_header(body)
if callable(identity_header)
else identity_header
)
if identity is not None:
request.send_header("x-lancedb-query-snapshot", identity)
request.end_headers()
@@ -6684,13 +6702,102 @@ def test_remote_blob_file_matches_file_error_and_range_contract():
handle.read(1)
def test_remote_blob_fetch_accepts_query_table():
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
def test_remote_blob_fetch_accepts_metadata_free_query_table(api):
hits = pa.table({"_rowid": pa.array([10, 20, 30], type=pa.uint64())})
with blob_remote_table() as table:
blobs = table.fetch_blobs("image", hits)
with blob_remote_table(descriptor_identity_header=None) as table:
if api == "fetch_blobs":
assert table.fetch_blobs("image", hits).to_pylist() == [
b"alpha",
None,
b"gamma",
]
else:
handles = table.fetch_blob_files("image", hits)
try:
assert [
handle.read() if handle is not None else None for handle in handles
] == [b"alpha", None, b"gamma"]
finally:
for handle in handles:
if handle is not None:
handle.close()
assert blobs.to_pylist() == [b"alpha", None, b"gamma"]
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
def test_remote_blob_fetch_from_query_result_keeps_query_snapshot(api):
requests = []
state = {"version": 1}
with blob_remote_table(requests=requests, state=state) as table:
hits = table.search().select(["id", "image"]).limit(3).to_arrow()
assert hits.schema.metadata[b"lancedb:query_version"] == b"1"
table.add([{"id": 4, "image": b"new-version"}])
assert table.version == 2
if api == "fetch_blobs":
assert table.fetch_blobs("image", hits).to_pylist() == [
b"alpha",
None,
b"gamma",
]
fetches = [body for path, body in requests if path == "fetch_blobs"]
assert fetches
assert all(body["version"] == 1 for body in fetches)
else:
handles = table.fetch_blob_files("image", hits)
try:
assert [
handle.read() if handle is not None else None for handle in handles
] == [b"alpha", None, b"gamma"]
finally:
for handle in handles:
if handle is not None:
handle.close()
descriptor_queries = [
body
for path, body in requests
if path == "query" and body.get("filter", "").startswith("_rowid IN")
]
assert descriptor_queries
assert all(body["version"] == 1 for body in descriptor_queries)
@pytest.mark.parametrize("descriptor_identity", [None, "v1:" + "b" * 64])
def test_remote_blob_files_reject_unverified_descriptor_identity(descriptor_identity):
requested = "v1:" + "a" * 64
hits = pa.table(
{"_rowid": pa.array([20, 40], type=pa.uint64())}
).replace_schema_metadata(
{
b"lancedb:query_version": b"1",
b"lancedb:query_snapshot": requested.encode(),
}
)
requests = []
with blob_remote_table(
requests=requests, descriptor_identity_header=descriptor_identity
) as table:
with pytest.raises(
NotImplementedError, match="did not verify the query snapshot identity"
):
table.fetch_blob_files("image", hits)
assert not any(path.startswith("/v1/table/test/blob/") for path, _ in requests)
assert not any(path == "/v1/table/test/fetch_blobs/" for path, _ in requests)
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
def test_remote_blob_fetch_rejects_incomplete_query_snapshot(api):
requests = []
hits = pa.table(
{"_rowid": pa.array([10], type=pa.uint64())}
).replace_schema_metadata({b"lancedb:query_version": b"1"})
with blob_remote_table(requests=requests) as table:
with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"):
getattr(table, api)("image", hits)
assert not any(path == "fetch_blobs" for path, _ in requests)
def test_remote_blob_query_stashes_row_ids_for_fetch():