Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions python/python/lance/lance/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ from datetime import timedelta
from pathlib import Path
from typing import (
Any,
BinaryIO,
Callable,
Dict,
Iterable,
Expand Down Expand Up @@ -332,6 +333,7 @@ class _Session:
metadata_cache_size_bytes: Optional[int] = None,
index_cache_backend: Optional[str | Dict[str, Any]] = None,
metadata_cache_backend: Optional[str | Dict[str, Any]] = None,
external_blob_fetcher: Optional[Callable[[str], BinaryIO]] = None,
) -> None:
"""Create a Lance session.

Expand All @@ -341,6 +343,10 @@ class _Session:
``index_cache_backend`` is mutually exclusive with
``index_cache_size_bytes``. ``metadata_cache_backend`` is mutually
exclusive with ``metadata_cache_size_bytes``.

``external_blob_fetcher`` is called with an absolute external blob URI
and must return a seekable binary file-like object. Lance reads that
object directly.
"""
...
def size_bytes(self) -> int: ...
Expand Down
28 changes: 28 additions & 0 deletions python/python/tests/test_blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -1781,6 +1781,34 @@ def test_blob_extension_write_external_ingest(tmp_path):
assert f.read() == b"hello"


@pytest.mark.parametrize("external_blob_mode", ["ingest", "reference"])
def test_blob_extension_external_fetcher(tmp_path, external_blob_mode):
blob_path = tmp_path / "external_blob.bin"
blob_path.write_bytes(b"hello")
missing_uri = (tmp_path / "missing.bin").as_uri()
fetched_uris = []

def fetch(uri):
fetched_uris.append(uri)
return blob_path.open("rb")

table = pa.table({"blob": lance.blob_array([missing_uri])})
ds = lance.write_dataset(
table,
tmp_path / f"test_ds_v2_external_{external_blob_mode}_fetcher",
data_storage_version="2.2",
external_blob_mode=external_blob_mode,
allow_external_blob_outside_bases=external_blob_mode == "reference",
session=lance.Session(external_blob_fetcher=fetch),
)

expected_before_read = [missing_uri] if external_blob_mode == "ingest" else []
assert fetched_uris == expected_before_read
with ds.take_blobs("blob", indices=[0])[0] as blob:
assert blob.read() == b"hello"
assert fetched_uris == [missing_uri]


def test_blob_extension_write_external_ingest_rejects_reference_only_options(tmp_path):
blob_path = tmp_path / "external_blob.bin"
blob_path.write_bytes(b"hello")
Expand Down
5 changes: 5 additions & 0 deletions python/python/tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ def test_cache_backend_uri_config():
assert session.index_cache_size_bytes() == 0


def test_external_blob_fetcher_must_be_callable():
with pytest.raises(ValueError, match="must be callable"):
lance.Session(external_blob_fetcher="not callable")


def test_cache_backend_dict_config():
session = lance.Session(
index_cache_backend={
Expand Down
160 changes: 156 additions & 4 deletions python/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@
// SPDX-FileCopyrightText: Copyright The Lance Authors

use std::collections::HashMap;
use std::fmt;
use std::ops::Range;
use std::sync::Arc;

use pyo3::exceptions::PyValueError;
use async_trait::async_trait;
use bytes::Bytes;
use futures::{StreamExt, future::BoxFuture};
use object_store::{Error as ObjectStoreError, path::Path};
use pyo3::exceptions::{PyIOError, PyValueError};
use pyo3::types::{PyAnyMethods, PyDict, PyDictMethods, PyString};
use pyo3::{Bound, PyAny, PyResult, pyclass, pymethods};
use pyo3::{Bound, Py, PyAny, PyErr, PyResult, Python, pyclass, pymethods};

use lance::session::{CacheSpec, Session as LanceSession};
use lance::session::{CacheSpec, ExternalBlobFetcher, Session as LanceSession};
use lance_core::cache::{BackendConfig, build_from_config, build_from_uri};
use lance_core::deepsize::{Context, DeepSizeOf};
use lance_io::traits::{ByteStream, Reader};

use crate::object_store::PyObjectStoreRegistry;
use crate::rt;
Expand All @@ -32,6 +40,9 @@ use crate::rt;
/// metadata_cache_backend : str or dict, optional
/// Custom metadata cache backend with the same format as
/// ``index_cache_backend``.
/// external_blob_fetcher : callable, optional
/// Called with an absolute external blob URI and must return a seekable
/// binary file-like object. Lance reads the returned object directly.
///
/// ``index_cache_backend`` is mutually exclusive with
/// ``index_cache_size_bytes``. ``metadata_cache_backend`` is mutually
Expand All @@ -48,6 +59,135 @@ impl Session {
}
}

struct PyExternalBlobFetcher {
fetcher: Py<PyAny>,
}

#[async_trait]
impl ExternalBlobFetcher for PyExternalBlobFetcher {
async fn fetch(&self, uri: &str) -> lance::Result<Box<dyn Reader>> {
let reader = Python::attach(|py| self.fetcher.call1(py, (uri,)))
.map_err(|error| lance::Error::external(Box::new(error)))?;
Ok(Box::new(PyExternalBlobReader {
reader: Arc::new(reader),
path: Path::from(uri),
}))
}
}

struct PyExternalBlobReader {
reader: Arc<Py<PyAny>>,
path: Path,
}

impl fmt::Debug for PyExternalBlobReader {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PyExternalBlobReader")
.field("path", &self.path)
.finish()
}
}

impl DeepSizeOf for PyExternalBlobReader {
fn deep_size_of_children(&self, _context: &mut Context) -> usize {
0
}
}

fn object_store_error(error: PyErr) -> ObjectStoreError {
ObjectStoreError::Generic {
store: "python external blob fetcher",
source: Box::new(error),
}
}

fn read_python_range(reader: &Py<PyAny>, range: Range<usize>) -> object_store::Result<Bytes> {
Python::attach(|py| {
reader.call_method1(py, "seek", (range.start, 0))?;
let data: Vec<u8> = reader
.call_method1(py, "read", (range.len(),))?
.extract(py)?;
if data.len() != range.len() {
return Err(PyIOError::new_err(format!(
"external blob reader returned {} bytes for range {}..{}; expected {}",
data.len(),
range.start,
range.end,
range.len()
)));
}
Ok(Bytes::from(data))
})
.map_err(object_store_error)
}

fn python_range_stream(reader: Arc<Py<PyAny>>, range: Range<usize>) -> ByteStream {
const CHUNK_SIZE: usize = 8 * 1024 * 1024;
let range_end = range.end;

futures::stream::try_unfold((reader, range.start), move |(reader, start)| async move {
if start >= range_end {
return Ok(None);
}
let end = start.saturating_add(CHUNK_SIZE).min(range_end);
let bytes = read_python_range(reader.as_ref(), start..end)?;
Ok(Some((bytes, (reader, end))))
})
.boxed()
}

impl Reader for PyExternalBlobReader {
fn path(&self) -> &Path {
&self.path
}

fn block_size(&self) -> usize {
8 * 1024 * 1024
}

fn io_parallelism(&self) -> usize {
1
}

fn size(&self) -> BoxFuture<'_, object_store::Result<usize>> {
Box::pin(async move {
Python::attach(|py| {
let current: usize = self.reader.call_method0(py, "tell")?.extract(py)?;
self.reader.call_method1(py, "seek", (0, 2))?;
let size = self.reader.call_method0(py, "tell")?.extract(py)?;
self.reader.call_method1(py, "seek", (current, 0))?;
Ok(size)
})
.map_err(object_store_error)
})
}

fn get_range(&self, range: Range<usize>) -> BoxFuture<'static, object_store::Result<Bytes>> {
let reader = self.reader.clone();
Box::pin(async move { read_python_range(reader.as_ref(), range) })
}

fn get_all(&self) -> BoxFuture<'_, object_store::Result<Bytes>> {
Box::pin(async move {
Python::attach(|py| {
self.reader.call_method1(py, "seek", (0, 0))?;
let data: Vec<u8> = self.reader.call_method0(py, "read")?.extract(py)?;
Ok(Bytes::from(data))
})
.map_err(object_store_error)
})
}

fn get_range_stream(
&self,
range: Range<usize>,
) -> BoxFuture<'_, object_store::Result<ByteStream>> {
let reader = self.reader.clone();
Box::pin(async move { Ok(python_range_stream(reader, range)) })
}
}

/// Turn a Python-supplied backend descriptor into an `Arc<dyn CacheBackend>`,
/// or return `Ok(None)` when the caller did not pass one.
///
Expand Down Expand Up @@ -170,13 +310,15 @@ impl Session {
index_cache_backend=None,
metadata_cache_backend=None,
store_registry=None,
external_blob_fetcher=None,
))]
fn create(
index_cache_size_bytes: Option<usize>,
metadata_cache_size_bytes: Option<usize>,
index_cache_backend: Option<Bound<'_, PyAny>>,
metadata_cache_backend: Option<Bound<'_, PyAny>>,
store_registry: Option<PyObjectStoreRegistry>,
external_blob_fetcher: Option<Bound<'_, PyAny>>,
) -> PyResult<Self> {
let index_cache = resolve_cache_spec(
"index_cache_backend",
Expand All @@ -191,8 +333,18 @@ impl Session {
metadata_cache_size_bytes,
)?;
let store_registry = store_registry.map(|r| r.inner).unwrap_or_default();
let session =
let mut session =
LanceSession::with_cache_backends(index_cache, metadata_cache, store_registry);
if let Some(fetcher) = external_blob_fetcher {
if !fetcher.is_callable() {
return Err(PyValueError::new_err(
"external_blob_fetcher must be callable",
));
}
session = session.with_external_blob_fetcher(Arc::new(PyExternalBlobFetcher {
fetcher: fetcher.unbind(),
}));
}
Ok(Self {
inner: Arc::new(session),
})
Expand Down
Loading
Loading