mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
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:
@@ -1022,11 +1022,16 @@ 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
|
||||
Use [`Table.take_blob_files`][lancedb.table.Table.take_blob_files] or
|
||||
[`AsyncTable.take_blob_files`][lancedb.table.AsyncTable.take_blob_files] to open
|
||||
files by zero-based row position in the table's visible snapshot. The result
|
||||
follows the requested order and gives every duplicate its own file cursor.
|
||||
Negative or out-of-range positions fail the entire call. Enterprise supports
|
||||
Blob V2 columns on native tables with a gateway that verifies query snapshots.
|
||||
|
||||
For row-ID based fetches, get `_rowid` from a query. 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`,
|
||||
@@ -1034,9 +1039,10 @@ 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.
|
||||
Embedded and Enterprise `BlobFile` handles prefetch 512 KiB for sequential reads
|
||||
by default. Pass `buffer_size=0` to `take_blob_files`, `fetch_blob_files`,
|
||||
`open_blob_file`, or `open_blob_files` for sparse reads, or choose another window
|
||||
size in bytes.
|
||||
Call `file.set_buffer_size(size)` to change it without moving the cursor;
|
||||
changing the size discards unused prefetched bytes. Explicit `read_range` and
|
||||
`read_ranges` calls always read exactly the requested intervals and leave the
|
||||
|
||||
@@ -795,7 +795,26 @@ Hybrid byte queries require matching snapshot provenance from both responses.
|
||||
|
||||
#### Read blobs on demand {#multimodal-read-blobs}
|
||||
|
||||
Query the rows you want and pass their `_rowid` values to a fetch method.
|
||||
When you have row positions, Python's `take_blob_files` opens seekable handles
|
||||
from the table's visible snapshot. This example reads the header at position 5
|
||||
and closes the file afterward.
|
||||
|
||||
```python
|
||||
[video] = table.take_blob_files("video", [5], buffer_size=0)
|
||||
if video is not None:
|
||||
with video:
|
||||
header = video.read(4096)
|
||||
```
|
||||
|
||||
Offsets are zero-based among live rows and may change when the table advances.
|
||||
Results follow the input order. Duplicate offsets have independent cursors,
|
||||
null blobs return `None`, and empty blobs return a file of size zero. A negative
|
||||
or out-of-range offset rejects the whole batch. On an async table, use
|
||||
`await table.take_blob_files(...)` and `await file.aread()` for asynchronous reads.
|
||||
Enterprise supports Blob V2 columns on native tables with a gateway that
|
||||
verifies query snapshots. Realtime/MemWAL tables are unsupported.
|
||||
|
||||
When selecting rows with a query, pass their `_rowid` values to a fetch method.
|
||||
`fetch_blob_files` opens a seekable handle and loads bytes only when you read.
|
||||
The Python example opens the JPEG from the ingest step and reads its EXIF
|
||||
Make tag with Pillow. TypeScript and Rust read the first bytes from the handle.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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: ...
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ use std::sync::Arc;
|
||||
use arrow_array::LargeBinaryArray;
|
||||
use arrow_array::builder::LargeBinaryBuilder;
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use lance::dataset::mem_wal::DatasetMemWalExt;
|
||||
use lance::dataset::{BlobRangeRequest as LanceBlobRangeRequest, Dataset, WriteParams};
|
||||
use lance_arrow::FieldExt;
|
||||
use lance_file::version::{ConcreteFileVersion, LanceFileVersion};
|
||||
@@ -861,6 +862,33 @@ pub(crate) async fn take_blob_files_aligned(
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(crate) async fn take_blob_files_by_offsets(
|
||||
dataset: &Arc<Dataset>,
|
||||
column: &str,
|
||||
offsets: &[u64],
|
||||
) -> Result<Vec<Option<BlobFile>>> {
|
||||
ensure_blob_column(dataset.schema(), column)?;
|
||||
if dataset.mem_wal_index_details().await?.is_some() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "take_blob_files does not support Realtime/MemWAL tables".into(),
|
||||
});
|
||||
}
|
||||
// Use the same dataset for validation and opening, including its deletions.
|
||||
let num_rows = dataset.count_rows(None).await? as u64;
|
||||
if let Some(offset) = offsets.iter().find(|&&offset| offset >= num_rows) {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!(
|
||||
"row offset {offset} is out of range for a snapshot with {num_rows} rows"
|
||||
),
|
||||
});
|
||||
}
|
||||
let handles = dataset.take_blobs_by_indices(offsets, column).await?;
|
||||
Ok(handles
|
||||
.into_iter()
|
||||
.map(|handle| handle.map(Into::into))
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -78,7 +78,7 @@ use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
|
||||
use datafusion_physical_plan::{ExecutionPlan, RecordBatchStream, SendableRecordBatchStream};
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use http::header::{ACCEPT, CONTENT_TYPE};
|
||||
use http::{HeaderName, StatusCode};
|
||||
use http::{HeaderMap, HeaderName, StatusCode};
|
||||
use lance::arrow::json::{JsonDataType, JsonSchema};
|
||||
use lance::dataset::refs::TagContents;
|
||||
use lance::dataset::scanner::DatasetRecordBatchStream;
|
||||
@@ -141,6 +141,20 @@ fn check_query_snapshot_response(
|
||||
}
|
||||
|
||||
const QUERY_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-query-version");
|
||||
|
||||
fn query_response_snapshot(headers: &HeaderMap) -> (Option<u64>, Option<&str>) {
|
||||
let version = headers
|
||||
.get(&QUERY_VERSION_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.filter(|version| *version > 0);
|
||||
let identity = headers
|
||||
.get(QUERY_SNAPSHOT_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.filter(|value| valid_query_snapshot_identity(value));
|
||||
(version, identity)
|
||||
}
|
||||
|
||||
/// Asks for stream framing, which is decoded as it arrives. Servers that do not
|
||||
/// stream query results ignore this and answer with file framing.
|
||||
const QUERY_ACCEPT: &str =
|
||||
@@ -1500,19 +1514,8 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
|
||||
// Legacy version headers are freshness watermarks, not proof that the
|
||||
// query and a later Blob read use the same immutable dataset.
|
||||
let query_version = response
|
||||
.headers()
|
||||
.get(&QUERY_VERSION_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.filter(|version| *version > 0);
|
||||
|
||||
let query_identity = response
|
||||
.headers()
|
||||
.get(QUERY_SNAPSHOT_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.filter(|value| valid_query_snapshot_identity(value))
|
||||
.map(str::to_owned);
|
||||
let (query_version, query_identity) = query_response_snapshot(response.headers());
|
||||
let query_identity = query_identity.map(str::to_owned);
|
||||
|
||||
let stream = match framing {
|
||||
ArrowIpcFraming::Stream => {
|
||||
@@ -3870,6 +3873,14 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
self.fetch_blob_files_impl(column, row_ids).await
|
||||
}
|
||||
|
||||
async fn take_blob_files(
|
||||
&self,
|
||||
column: &str,
|
||||
offsets: &[u64],
|
||||
) -> Result<Vec<Option<BlobFile>>> {
|
||||
self.take_blob_files_impl(column, offsets).await
|
||||
}
|
||||
|
||||
async fn open_blob_file(&self, descriptor: &crate::blob::BlobDescriptor) -> Result<BlobFile> {
|
||||
self.open_blob_file_impl(descriptor).await
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -913,6 +913,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
message: "fetch_blob_files is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Open lazy blob handles by row offset. See [`Table::take_blob_files`].
|
||||
async fn take_blob_files(
|
||||
&self,
|
||||
_column: &str,
|
||||
_offsets: &[u64],
|
||||
) -> Result<Vec<Option<BlobFile>>> {
|
||||
Err(Error::NotSupported {
|
||||
message: "take_blob_files is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Open a descriptor at its pinned source version. See [`Table::open_blob_file`].
|
||||
async fn open_blob_file(&self, _descriptor: &BlobDescriptor) -> Result<BlobFile> {
|
||||
Err(Error::NotSupported {
|
||||
@@ -1689,6 +1699,39 @@ impl Table {
|
||||
self.inner.fetch_blob_files(column.as_ref(), row_ids).await
|
||||
}
|
||||
|
||||
/// Open seekable Blob handles by zero-based position among the visible snapshot's rows.
|
||||
///
|
||||
/// Results follow `offsets` in order, with independent cursors for duplicates.
|
||||
/// NULL values return `None`, and valid empty values return a zero-length handle.
|
||||
/// An out-of-range offset rejects the whole batch. An empty slice returns no handles.
|
||||
/// Offsets can change across versions. The returned files stay bound to the
|
||||
/// snapshot selected at opening, and that snapshot must remain available for reads.
|
||||
///
|
||||
/// LanceDB Embedded supports Blob v1 and v2. LanceDB Enterprise requires
|
||||
/// Blob v2 on a native table and a gateway that verifies query snapshots.
|
||||
/// Realtime/MemWAL tables do not support this operation. When Enterprise
|
||||
/// direct Blob reads are enabled, eligible ranges at or above the client's
|
||||
/// threshold can use them. The client threshold defaults to 32 MiB.
|
||||
///
|
||||
/// ```
|
||||
/// # use lancedb::Table;
|
||||
/// # async fn read_header(table: &Table) -> lancedb::Result<()> {
|
||||
/// let files = table.take_blob_files("video", &[5, 1, 5]).await?;
|
||||
/// for file in files.into_iter().flatten() {
|
||||
/// let _header = file.read_range(0..file.size().min(4096)).await?;
|
||||
/// file.close().await?;
|
||||
/// }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn take_blob_files(
|
||||
&self,
|
||||
column: impl AsRef<str>,
|
||||
offsets: &[u64],
|
||||
) -> Result<Vec<Option<BlobFile>>> {
|
||||
self.inner.take_blob_files(column.as_ref(), offsets).await
|
||||
}
|
||||
|
||||
/// Open a seekable file from a SQL `blob_descriptor` result.
|
||||
///
|
||||
/// The descriptor carries its table version, branch, column and row identity.
|
||||
@@ -4920,6 +4963,18 @@ impl BaseTable for NativeTable {
|
||||
crate::blob::take_blob_files_aligned(&dataset, column, row_ids).await
|
||||
}
|
||||
|
||||
async fn take_blob_files(
|
||||
&self,
|
||||
column: &str,
|
||||
offsets: &[u64],
|
||||
) -> Result<Vec<Option<BlobFile>>> {
|
||||
if offsets.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let dataset = self.dataset.get().await?;
|
||||
crate::blob::take_blob_files_by_offsets(&dataset, column, offsets).await
|
||||
}
|
||||
|
||||
async fn open_blob_file(&self, descriptor: &BlobDescriptor) -> Result<BlobFile> {
|
||||
let dataset = self.dataset.get().await?;
|
||||
crate::blob::open_native_blob_file(&dataset, descriptor).await
|
||||
|
||||
Reference in New Issue
Block a user