mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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:
@@ -915,6 +915,18 @@ with `search().with_row_id(True).to_arrow()` and pass the result to the fetch AP
|
||||
One missing or deleted row ID rejects the entire blob-read batch; the APIs do
|
||||
not return partial results.
|
||||
|
||||
Row positions are not row IDs. To read by position, call
|
||||
`take_offsets(offsets, with_row_id=True)` first and pass the resulting `_rowid`
|
||||
values; `fetch_blobs` remains row-ID based. A query result table that carries
|
||||
snapshot metadata keeps the snapshot that produced it on LanceDB Enterprise, so
|
||||
the fetched bytes or files stay pinned if the table changes. Metadata-free
|
||||
inputs, including legacy query responses and plain row-ID lists, are read from
|
||||
the table handle's current snapshot; keep the source unchanged between selection
|
||||
and fetching. Partial snapshot metadata fails explicitly. For `fetch_blob_files`,
|
||||
a snapshot-bound read also fails explicitly when the serving node cannot echo
|
||||
the immutable identity. The basic remote Blob API floor (server 0.5.0) does not
|
||||
by itself provide that echo capability.
|
||||
|
||||
Local and remote `BlobFile` handles prefetch 512 KiB for sequential reads by
|
||||
default. Pass `buffer_size=0` to `fetch_blob_files`, `open_blob_file`, or
|
||||
`open_blob_files` for sparse reads, or choose another window size in bytes.
|
||||
|
||||
@@ -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]]:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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():
|
||||
|
||||
+15
-1
@@ -2240,15 +2240,29 @@ impl Table {
|
||||
}
|
||||
|
||||
/// Open lazy blob handles for `row_ids` from blob v2 column `column`.
|
||||
#[pyo3(signature = (column, row_ids, buffer_size=None))]
|
||||
#[pyo3(signature = (column, row_ids, buffer_size=None, *, version=None, snapshot_identity=None))]
|
||||
pub fn fetch_blob_files(
|
||||
self_: PyRef<'_, Self>,
|
||||
column: String,
|
||||
row_ids: Vec<u64>,
|
||||
buffer_size: Option<usize>,
|
||||
version: Option<u64>,
|
||||
snapshot_identity: Option<String>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let inner = match (version, snapshot_identity) {
|
||||
(None, None) => inner,
|
||||
(Some(version), Some(identity)) => inner
|
||||
.query_snapshot_with_identity(version, &identity)
|
||||
.await
|
||||
.infer_error()?,
|
||||
_ => {
|
||||
return Err(PyValueError::new_err(
|
||||
"deferred blob reads require both query version and snapshot identity",
|
||||
));
|
||||
}
|
||||
};
|
||||
let handles = inner
|
||||
.fetch_blob_files(column.as_str(), &row_ids)
|
||||
.await
|
||||
|
||||
@@ -656,7 +656,9 @@ fn missing_blob_row_ids_error(column: &str, requested: usize, missing: &[u64]) -
|
||||
Error::InvalidInput {
|
||||
message: format!(
|
||||
"blob read for column '{column}' requested {requested} row ids but some \
|
||||
do not exist in the table{detail}; pass row ids collected from this table"
|
||||
do not exist in the table{detail}; pass row ids collected from this table. \
|
||||
If these were row positions, call take_offsets(offsets, with_row_id=True) \
|
||||
first and pass the resulting row ids"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1156,7 +1156,9 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!(
|
||||
"blob read for column '{column}' requested {} row ids but only {found} exist \
|
||||
in the table; pass row ids collected from this table",
|
||||
in the table; pass row ids collected from this table. If these were row \
|
||||
positions, call take_offsets(offsets, with_row_id=True) first and pass the \
|
||||
resulting row ids",
|
||||
unique_row_ids.len()
|
||||
),
|
||||
});
|
||||
@@ -1190,9 +1192,20 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/query/", self.identifier))
|
||||
.json(&body);
|
||||
// The query route opens the requested version and reports the identity of
|
||||
// the dataset it actually read. It does not validate the request identity,
|
||||
// so accept descriptors only after comparing the response echo.
|
||||
let request = if let Some(identity) = &self.expected_query_snapshot {
|
||||
request.header(QUERY_SNAPSHOT_HEADER, identity)
|
||||
} else {
|
||||
request
|
||||
};
|
||||
let (request_id, response) = self
|
||||
.send_with_freshness(request, true, read_snapshot.freshness)
|
||||
.await?;
|
||||
if response.status().is_success() {
|
||||
check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?;
|
||||
}
|
||||
let response_version = response
|
||||
.headers()
|
||||
.get(&VERSION_HEADER)
|
||||
@@ -2046,6 +2059,80 @@ mod tests {
|
||||
assert!(requests.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_blob_files_reject_unverified_descriptor_identity_before_values() {
|
||||
const EXPECTED: &str =
|
||||
"v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
|
||||
const OTHER: &str = "v1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
|
||||
for response_identity in [None, Some(OTHER)] {
|
||||
let range_requests = Arc::new(AtomicUsize::new(0));
|
||||
let captured_ranges = range_requests.clone();
|
||||
let table = RemoteTable::new_mock(
|
||||
"my_table".to_string(),
|
||||
move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path == "/v1/table/my_table/query/" {
|
||||
// Row 20 is NULL and row 40 is empty, so an unverified
|
||||
// result could escape without any payload request.
|
||||
assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], EXPECTED);
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(filter_row_ids(body["filter"].as_str().unwrap()), [20, 40]);
|
||||
let batch = RecordBatch::try_from_iter([
|
||||
(
|
||||
"image",
|
||||
Arc::new(descriptors(&[None, Some((BlobKind::Inline, 0))]))
|
||||
as Arc<dyn Array>,
|
||||
),
|
||||
(
|
||||
ROW_ID,
|
||||
Arc::new(UInt64Array::from_iter_values([20, 40])) as Arc<dyn Array>,
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
let mut body = Vec::new();
|
||||
let mut writer =
|
||||
arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema())
|
||||
.unwrap();
|
||||
writer.write(&batch).unwrap();
|
||||
writer.finish().unwrap();
|
||||
drop(writer);
|
||||
let mut response = http::Response::builder()
|
||||
.status(200)
|
||||
.header(VERSION_HEADER, "42");
|
||||
if let Some(identity) = response_identity {
|
||||
response = response.header(QUERY_SNAPSHOT_HEADER, identity);
|
||||
}
|
||||
return response.body(body).unwrap();
|
||||
}
|
||||
if path.starts_with("/v1/table/my_table/blob/") {
|
||||
captured_ranges.fetch_add(1, Ordering::SeqCst);
|
||||
panic!("descriptor verification must fail before any payload read");
|
||||
}
|
||||
panic!("unexpected path: {path}");
|
||||
},
|
||||
Some(Version::new(0, 5, 0)),
|
||||
);
|
||||
let snapshot = table
|
||||
.query_snapshot_with_identity(42, EXPECTED)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let error = snapshot
|
||||
.fetch_blob_files("image", &[20, 40])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("did not verify the query snapshot identity"),
|
||||
"{error}"
|
||||
);
|
||||
assert_eq!(range_requests.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_blob_ranges_accept_empty_requests_without_http() {
|
||||
let (table, requests) = mock_take_blob_table(vec![], Some("7"));
|
||||
|
||||
Reference in New Issue
Block a user