feat(python): open blob files by row offset (#5356)

Open seekable Blob files by row position with
`table.take_blob_files(column, offsets, *, buffer_size=None)` on
synchronous and asynchronous Embedded and Enterprise tables. Results
follow the requested order, duplicate offsets have independent cursors,
and NULL and empty values stay distinct. An invalid offset rejects the
entire batch.

Enterprise resolves positions and descriptors together and verifies one
snapshot across descriptor queries, location resolution, and
authenticated byte reads. Eligible ranges use the existing presigned
read path when the gateway advertises it.

Refs [OSS-2881](https://linear.app/lancedb/issue/OSS-2881).

## Validation

- On Enterprise 1.16.0, the same locked wheel passed both sync and async
reads of 1,025 distinct offsets after a deletion. The offsets matched an
independent ordered query, and the two descriptor chunks and subsequent
authenticated requests matched the pinned version and snapshot identity.
- Both APIs returned byte-for-byte matches for 37-byte proxy reads and a
32 MiB presigned object-store read. The large reads used zero gateway
byte requests. An independent range check returned two object-store HTTP
206 responses with matching physical ranges and bytes.
- The wheel passed 23 focused Python tests. The Rust library check and
all 81 Enterprise Blob module tests passed, including nested NULL and
strict snapshot echo cases.

Runtime evidence is from commit
`f56c359ba7874cd75c52169491166a941251510f` with Lance `16.0.0-beta.6`,
wheel SHA-256
`9abbbfe584513432547d237dcf7b684b479b35cad07c48cd9899d381f0e80423`. The
merge preview with `main` at `ff556729` is clean.
[#5352](https://github.com/lancedb/lancedb/pull/5352) updates the
integration dependencies to Lance `16.0.0-beta.7` and `object_store`
`0.14.2`. Those pins are outside the tested wheel's coverage.

The synthetic test table was removed from the catalog. Its physical
storage cleanup is tracked separately.
This commit is contained in:
Xuanwo
2026-12-02 12:47:38 +00:00
committed by GitHub
parent eea95c8778
commit 0a14761f0e
13 changed files with 1209 additions and 133 deletions
+1 -1
View File
@@ -96,7 +96,7 @@ def _normalize_blob_descriptor(value):
class BlobFile(io.RawIOBase):
"""Seekable lazy handle from :meth:`~lancedb.table.Table.fetch_blob_files`.
"""Seekable lazy handle for one blob value.
Bytes load on ``read``, ``read1``, ``read_range``, or ``read_ranges``, not
when the handle is opened. Range reads leave the cursor unchanged. Use
+7
View File
@@ -979,6 +979,13 @@ class Table:
version: Optional[int] = None,
snapshot_identity: Optional[str] = None,
) -> list[Optional[BlobFile]]: ...
async def take_blob_files(
self,
column: str,
offsets: Sequence[int],
*,
buffer_size: Optional[int] = None,
) -> list[Optional[BlobFile]]: ...
async def open_blob_file(
self, descriptor: str, buffer_size: Optional[int] = None
) -> BlobFile: ...
+12
View File
@@ -17,6 +17,7 @@ from typing import (
Iterable,
List,
Optional,
Sequence,
Union,
Literal,
overload,
@@ -1673,6 +1674,17 @@ class RemoteTable(Table):
self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
)
def take_blob_files(
self,
column: str,
offsets: Sequence[int],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
return LOOP.run(
self._table.take_blob_files(column, offsets, buffer_size=buffer_size)
)
def open_blob_file(
self,
descriptor: Union[dict, pa.StructScalar, None],
+67
View File
@@ -3086,6 +3086,44 @@ class Table(ABC):
resulting ``_rowid`` values.
"""
def take_blob_files(
self,
column: str,
offsets: Sequence[int],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
"""Open seekable Blob files by zero-based position in the visible snapshot.
Files follow input order, and repeated offsets have independent cursors.
A NULL value returns ``None``. A valid empty value returns a file with
``size() == 0``. A negative or out-of-range offset rejects the whole
batch. An empty sequence returns ``[]``.
Offsets refer to this snapshot's live rows. Their meaning can change
after deletions or compaction. Returned handles stay bound to the
selected snapshot, which must remain available until reads finish.
``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB).
Set it to 0 to disable read-ahead. Explicit range reads bypass the buffer.
Embedded supports Blob v1 and v2. Enterprise supports Blob V2 columns
on native tables and requires a gateway that verifies query snapshots.
Realtime/MemWAL tables are unsupported. When Enterprise direct Blob reads
are enabled, eligible ranges at or above the client's threshold may use
them. The client threshold defaults to 32 MiB.
```python
for video in table.take_blob_files("video", [5, 1, 5], buffer_size=0):
if video is not None:
with video:
header = video.read(4096)
```
"""
raise NotImplementedError(
"take_blob_files is not supported for this table type"
)
@abstractmethod
def open_blob_file(
self,
@@ -4995,6 +5033,17 @@ class LanceTable(Table):
self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
)
def take_blob_files(
self,
column: str,
offsets: Sequence[int],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
return LOOP.run(
self._table.take_blob_files(column, offsets, buffer_size=buffer_size)
)
def open_blob_file(
self,
descriptor: Union[dict, pa.StructScalar, None],
@@ -10532,6 +10581,24 @@ class AsyncTable:
)
return _wrap_blob_files(handles)
async def take_blob_files(
self,
column: str,
offsets: Sequence[int],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
"""Open seekable Blob files by position in the visible snapshot.
See [Table.take_blob_files][lancedb.table.Table.take_blob_files]. Use
``await file.aread()`` to read bytes asynchronously from a returned file.
"""
buffer_size = _validate_blob_buffer_size(buffer_size)
handles = await self._inner.take_blob_files(
column, offsets, buffer_size=buffer_size
)
return _wrap_blob_files(handles)
async def open_blob_file(
self,
descriptor: Union[dict, pa.StructScalar, None],
+60
View File
@@ -2133,6 +2133,63 @@ def test_fetch_blobs_rejects_non_blob_column():
table.fetch_blobs("id", [0])
def test_take_blob_files_by_live_offset():
table = _blob_table(
"blob_offsets",
[
{"id": 0, "image": b"deleted"},
{"id": 1, "image": b"alpha"},
{"id": 2, "image": None},
],
)
table.add([{"id": 3, "image": b""}, {"id": 4, "image": b"delta"}])
table.delete("id = 0")
first, null, empty, second, duplicate = table.take_blob_files(
"image", (3, 1, 2, 0, 3), buffer_size=0
)
assert null is None
with first, empty, second, duplicate:
assert first.read(2) == b"de"
assert duplicate.tell() == 0
assert duplicate.read() == b"delta"
assert first.read() == b"lta"
assert second.read() == b"alpha"
assert empty.size() == 0
assert empty.read() == b""
assert table.take_blob_files("image", []) == []
with pytest.raises(ValueError, match="is not a blob column"):
table.take_blob_files("id", [0])
with pytest.raises(ValueError, match="no column named 'missing'"):
table.take_blob_files("missing", [0])
with pytest.raises(ValueError, match="non-negative"):
table.take_blob_files("image", [0, -1])
with pytest.raises(ValueError, match="row offset 4 is out of range"):
table.take_blob_files("image", [0, 4])
with pytest.raises(ValueError, match="buffer_size must be non-negative"):
table.take_blob_files("image", [0], buffer_size=-1)
@pytest.mark.asyncio
async def test_async_take_blob_files_keep_the_snapshot_after_table_closes(tmp_path):
db = await lancedb.connect_async(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
table = await db.create_table("videos", schema=schema)
await table.add([{"id": 1, "video": b"first"}, {"id": 2, "video": b"second"}])
original_version = await table.version()
await table.delete("id = 1")
[latest] = await table.take_blob_files("video", [0])
await table.checkout(original_version)
[historical] = await table.take_blob_files("video", [0], buffer_size=8)
await table.checkout_latest()
table.close()
with latest, historical:
assert await latest.aread() == b"second"
assert await historical.aread() == b"first"
def test_legacy_v1_query_omits_auto_row_id():
table = _legacy_v1_table("legacy_v1")
hits = table.search().select(["legacy"]).limit(10).to_arrow()
@@ -2163,6 +2220,9 @@ def test_fetch_legacy_v1_blobs():
]
assert table.fetch_blobs("legacy", []).to_pylist() == []
assert table.fetch_blob_files("legacy", []) == []
[positional] = table.take_blob_files("legacy", [3])
with positional:
assert positional.read() == b"another fragment"
handles = table.fetch_blob_files("legacy", row_ids)
assert len(handles) == len(expected)
+49 -2
View File
@@ -18,8 +18,9 @@ from test_remote_db import (
@contextmanager
def remote_buffer_table(*, http_requests=None, truncate_first=False):
def remote_buffer_table(*, http_requests=None, truncate_first=False, by_offset=False):
payload = bytes(range(256)) * 4096
identity = "v1:" + "b" * 64
requests = []
def handler(request):
@@ -33,7 +34,12 @@ def remote_buffer_table(*, http_requests=None, truncate_first=False):
data = json.loads(
request.rfile.read(int(request.headers["Content-Length"]))
)
assert data["columns"] == ["image"]
if by_offset:
assert data["columns"] == ["image", "_rowoffset"]
assert data["with_row_id"] is True
assert "use_rte" not in data
else:
assert data["columns"] == ["image"]
table = blob_descriptor_take_table().slice(0, 1)
images = table["image"].combine_chunks()
images = pa.StructArray.from_arrays(
@@ -47,6 +53,8 @@ def remote_buffer_table(*, http_requests=None, truncate_first=False):
fields=list(images.type),
)
table = table.set_column(0, table.schema.field(0), images)
if by_offset:
table = table.append_column("_rowoffset", pa.array([0], pa.uint64()))
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, table.schema) as writer:
writer.write_table(table)
@@ -63,6 +71,10 @@ def remote_buffer_table(*, http_requests=None, truncate_first=False):
request.send_response(206)
request.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
request.send_header("Content-Length", str(len(body)))
if by_offset:
assert request.headers["x-lancedb-query-snapshot"] == identity
request.send_header("x-lancedb-query-snapshot", identity)
request.send_header("x-lancedb-version", "1")
request.end_headers()
request.wfile.write(body)
return
@@ -71,6 +83,9 @@ def remote_buffer_table(*, http_requests=None, truncate_first=False):
request.send_header("Content-Length", str(len(body)))
request.send_header("phalanx-version", "0.5.0")
request.send_header("x-lancedb-version", "1")
if by_offset and path.endswith("/query/"):
request.send_header("x-lancedb-query-version", "1")
request.send_header("x-lancedb-query-snapshot", identity)
request.end_headers()
request.wfile.write(body)
@@ -78,6 +93,38 @@ def remote_buffer_table(*, http_requests=None, truncate_first=False):
yield db.open_table("test"), payload, requests
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_enterprise_take_blob_files_buffer_size(use_async):
http_requests = []
with remote_buffer_table(by_offset=True, http_requests=http_requests) as (
table,
payload,
ranges,
):
take = table._table.take_blob_files if use_async else table.take_blob_files
before = len(http_requests)
for offsets, buffer_size, message in [
([0], -1, "buffer_size must be non-negative"),
([0, -1], None, "row offset -1 must be a non-negative"),
]:
with pytest.raises(ValueError, match=message):
result = take("image", offsets, buffer_size=buffer_size)
if use_async:
await result
assert len(http_requests) == before
result = take("image", [0], buffer_size=8)
[file] = await result if use_async else result
with file:
assert ranges == []
assert file.read(2) == payload[:2]
assert file.read(2) == payload[2:4]
assert ranges == [(0, 8)]
assert file.read_range(0, 1) == payload[:1]
assert ranges[-1] == (0, 1)
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("buffer_size", [None, 0, 8, 512 * 1024])
+51 -16
View File
@@ -1252,7 +1252,7 @@ impl From<lancedb::table::DropColumnsResult> for DropColumnsResult {
}
}
/// Lazy blob handle from ``Table.fetch_blob_files``.
/// Lazy, seekable blob handle.
#[pyclass(name = "BlobFile")]
pub struct PyBlobFile {
inner: Arc<BlobFile>,
@@ -1260,6 +1260,28 @@ pub struct PyBlobFile {
}
impl PyBlobFile {
async fn from_handles(
handles: Vec<Option<BlobFile>>,
buffer_size: Option<usize>,
) -> PyResult<Vec<Option<Self>>> {
if let Some(size) = buffer_size {
for file in handles.iter().flatten() {
file.set_buffer_size(size)
.await
.map_err(|e| blob_file_error("set_buffer_size", e))?;
}
}
Ok(handles
.into_iter()
.map(|handle| {
handle.map(|file| Self {
inner: Arc::new(file),
closed: AtomicBool::new(false),
})
})
.collect())
}
fn ensure_open(&self) -> PyResult<()> {
if self.closed.load(Ordering::Acquire) {
Err(PyRuntimeError::new_err("blob file is already closed"))
@@ -2336,22 +2358,35 @@ impl Table {
.fetch_blob_files(column.as_str(), &row_ids)
.await
.infer_error()?;
if let Some(size) = buffer_size {
for file in handles.iter().flatten() {
file.set_buffer_size(size)
.await
.map_err(|e| blob_file_error("set_buffer_size", e))?;
}
}
Ok(handles
.into_iter()
.map(|handle| {
handle.map(|file| PyBlobFile {
inner: Arc::new(file),
closed: AtomicBool::new(false),
})
PyBlobFile::from_handles(handles, buffer_size).await
})
}
/// Open lazy blob handles by row offset in the visible table snapshot.
#[pyo3(signature = (column, offsets, *, buffer_size=None))]
pub fn take_blob_files(
self_: PyRef<'_, Self>,
column: String,
offsets: Vec<i128>,
buffer_size: Option<usize>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
let offsets = offsets
.into_iter()
.map(|offset| {
u64::try_from(offset).map_err(|_| {
PyValueError::new_err(format!(
"row offset {offset} must be a non-negative 64-bit integer"
))
})
.collect::<Vec<_>>())
})
.collect::<PyResult<Vec<_>>>()?;
future_into_py(self_.py(), async move {
let handles = inner
.take_blob_files(column, &offsets)
.await
.infer_error()?;
PyBlobFile::from_handles(handles, buffer_size).await
})
}