feat: register blob bases during table creation (#5117)

## Summary

`create_table` / `create_empty_table` now accept registered storage
bases and the embedded opt-in for blob URIs outside them. A create with
data registers `initial_bases` in the same commit, so external Blob v2
references no longer need an empty create followed by `add`.

- Rust `CreateTableBuilder::initial_bases` /
`allow_external_blob_outside_bases`, with `BasePath` re-exported.
- PyO3 and Python sync/async create paths accept lightweight `BasePath`,
dicts, and duck-typed `lance.DatasetBasePath`; `id=None` lets Lance
assign an ID and explicit `0` or duplicate explicit IDs are rejected.
- `blob_uri_array` builds the standard four-field `lance.blob.v2` array
without pylance and keeps field metadata such as
`lancedb:logical_type=mp4`.
- Enterprise create rejects non-empty `initial_bases` and the true
opt-in before normalization, input iteration, or HTTP; empty/false
defaults remain an ordinary create.
- Native namespace create merges namespace and connection storage
options into the caller's store parameters instead of replacing them.
This is reconciled with #5114's refresh layering, so caller-scoped
options survive create, refresh, and reopen while namespace-vended
values keep their precedence.
- The outside-base opt-in applies to one write: setting it on create
does not carry over to a later `add()`.

## Validation

- `cargo fmt --all -- --check`, `cargo check --quiet --features remote
--tests --examples`, `cargo clippy --quiet --features remote --tests
--examples`.
- Rust: `blob_integration` 66 passed, `database::namespace` 23,
`connection::create_table` 16, `remote::db` 128.
- Python: `test_blob.py` 263 passed / 1 skipped, `test_blob_array.py` 4,
remote create 12, `test_db.py -k "pickle or create_table"` 15,
`test_namespace.py -k "pickle or refresh or create"` 29, `test_table.py
-k pickle` 8; ruff 0.9.9 and pyright from `python/`.
- `test_blob.py` also passes with pylance and pandas removed (177 passed
/ 87 skipped), matching the CI no-pylance suite. The lightweight and
dict create cases keep version, schema, reopen, and exact-range
assertions there; only the pylance-only manifest introspection moved
into the `DatasetBasePath` case.
- Rust and sync Python two-base probes assert that base 1's scoped
option fails its read while base 2 still returns exact bytes after
reopen. A separate async namespace test covers create and reopen with
exact ranges.
- `test_namespace_refresh_layers_caller_scoped_options` covers the
expired namespace seed: create-time `base_1.caller_scoped` survives
refresh, vended `timeout` is replaced (7s to 8s), fresh namespace values
appear, and reopen with the caller option returns exact blob range bytes
through the registered base.
- Updated `main` through #5127 (including #5114) is merged;
`rust/lancedb/src/database/namespace.rs` and `rust/lancedb/src/table.rs`
match `main`, and no #5114 code was stacked before it merged.

## Dependency note

The Lance dependency stays pinned at the `v15.0.0-beta.25` release on
`main`. With that pin, mixing an automatic base ID (`id=0`) and an
explicit non-zero ID may still collide; the approved upstream fix is
https://github.com/lance-format/lance/pull/11307. Use distinct explicit
non-zero IDs for multi-base creates, or automatic IDs for every base,
until a Lance release containing that fix is pinned. A failed mixed
create can leave the table name listed but unopenable; retrying with
distinct explicit IDs succeeds. Multi-base validation here uses explicit
IDs and bootstrap uses a single automatic ID, so the mixed-ID case is
not claimed as verified until a Lance release containing that fix is
pinned.
This commit is contained in:
Xuanwo
2026-11-20 22:17:47 +08:00
committed by GitHub
parent 85f966a9a9
commit d46754cad4
16 changed files with 1708 additions and 8 deletions
+152 -4
View File
@@ -20,6 +20,7 @@ use arrow::{
pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
};
use lancedb::{
BasePath,
connection::Connection as LanceConnection,
connection::NamespaceClientPushdownOperation,
database::namespace::LanceNamespaceDatabase,
@@ -30,9 +31,9 @@ use lancedb::{
};
use pyo3::{
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
exceptions::{PyRuntimeError, PyValueError},
exceptions::{PyRuntimeError, PyTypeError, PyValueError},
pyclass, pyfunction, pymethods,
types::{PyAnyMethods, PyDict, PyDictMethods, PyList},
types::{PyAnyMethods, PyBool, PyDict, PyDictMethods, PyList},
};
fn materialized_view_builder(
@@ -56,6 +57,139 @@ fn materialized_view_builder(
}
}
/// Parse `initial_bases` into Lance base paths.
///
/// Accepts LanceDB's lightweight `BasePath`, a mapping with the same keys, or
/// a duck-typed `lance.DatasetBasePath`. `None` maps to no bases. Object
/// attributes follow `DatasetBasePath`: a reported `id` of `0` means
/// automatic assignment, while a mapping that sets `id=0` explicitly is
/// rejected because `0` is reserved for unregistered blob URIs. Explicit
/// non-zero ids must be unique.
fn parse_initial_bases(initial_bases: Option<Bound<'_, PyAny>>) -> PyResult<Option<Vec<BasePath>>> {
let Some(value) = initial_bases else {
return Ok(None);
};
if value.is_none() {
return Ok(None);
}
let mut bases = Vec::new();
let mut explicit_ids: HashSet<u32> = HashSet::new();
for (index, item) in value.try_iter()?.enumerate() {
let item = item?;
let base = parse_base_path(&item, index)?;
if base.id != 0 && !explicit_ids.insert(base.id) {
return Err(PyValueError::new_err(format!(
"initial_bases[{index}] reuses base id {}; explicit ids must be unique",
base.id
)));
}
bases.push(base);
}
Ok(Some(bases))
}
fn parse_base_path(item: &Bound<'_, PyAny>, index: usize) -> PyResult<BasePath> {
let (path, name, is_dataset_root, id) = if let Ok(dict) = item.cast::<PyDict>() {
let path = required_string(dict.get_item("path")?, index, "path")?;
let name = optional_string(dict.get_item("name")?, index, "name")?;
let is_dataset_root =
optional_bool(dict.get_item("is_dataset_root")?, index, "is_dataset_root")?;
let id = match dict.get_item("id")? {
None => 0,
Some(value) if value.is_none() => 0,
Some(value) => {
let id = base_id(&value, index)?;
if id == 0 {
return Err(PyValueError::new_err(format!(
"initial_bases[{index}] sets id=0, which is reserved for unregistered \
blob URIs; pass id=None to let Lance assign an ID"
)));
}
id
}
};
(path, name, is_dataset_root, id)
} else {
let path = item.getattr("path").map_err(|_| {
PyTypeError::new_err(format!(
"initial_bases[{index}] must be a BasePath, dict, or DatasetBasePath"
))
})?;
let path = required_string(Some(path), index, "path")?;
let name = item.getattr("name").ok().filter(|value| !value.is_none());
let name = optional_string(name, index, "name")?;
let is_dataset_root = match item.getattr("is_dataset_root") {
Ok(value) if !value.is_none() => value.extract::<bool>().map_err(|_| {
PyTypeError::new_err(format!(
"initial_bases[{index}].is_dataset_root must be a bool"
))
})?,
_ => false,
};
let id = match item.getattr("id") {
Ok(value) if !value.is_none() => base_id(&value, index)?,
_ => 0,
};
(path, name, is_dataset_root, id)
};
if path.is_empty() {
return Err(PyValueError::new_err(format!(
"initial_bases[{index}].path must not be empty"
)));
}
Ok(BasePath::new(id, path, name, is_dataset_root))
}
fn required_string(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<String> {
let Some(value) = value else {
return Err(PyValueError::new_err(format!(
"initial_bases[{index}] is missing '{field}'"
)));
};
value.extract::<String>().map_err(|_| {
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
})
}
fn optional_string(
value: Option<Bound<'_, PyAny>>,
index: usize,
field: &str,
) -> PyResult<Option<String>> {
match value {
None => Ok(None),
Some(value) if value.is_none() => Ok(None),
Some(value) => value.extract::<String>().map(Some).map_err(|_| {
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
}),
}
}
fn optional_bool(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<bool> {
match value {
None => Ok(false),
Some(value) if value.is_none() => Ok(false),
Some(value) => value.extract::<bool>().map_err(|_| {
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a bool"))
}),
}
}
fn base_id(value: &Bound<'_, PyAny>, index: usize) -> PyResult<u32> {
if value.is_instance_of::<PyBool>() {
return Err(PyTypeError::new_err(format!(
"initial_bases[{index}].id must be a positive integer, not a bool"
)));
}
value.extract::<u32>().map_err(|_| {
PyValueError::new_err(format!(
"initial_bases[{index}].id must be a positive integer that fits in a u32"
))
})
}
#[pyclass]
pub struct Connection {
inner: Option<LanceConnection>,
@@ -311,7 +445,7 @@ impl Connection {
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None, allow_external_blob_outside_bases=false))]
pub fn create_table<'a>(
self_: PyRef<'a, Self>,
name: String,
@@ -321,11 +455,14 @@ impl Connection {
storage_options: Option<HashMap<String, String>>,
location: Option<String>,
namespace_client: Option<Py<PyAny>>,
initial_bases: Option<Bound<'_, PyAny>>,
allow_external_blob_outside_bases: bool,
) -> PyResult<Bound<'a, PyAny>> {
let inner = self_.get_inner()?.clone();
let py = self_.py();
let mode = Self::parse_create_mode_str(mode)?;
let initial_bases = parse_initial_bases(initial_bases)?;
let batches: Box<dyn arrow::array::RecordBatchReader + Send> =
Box::new(ArrowArrayStreamReader::from_pyarrow_bound(&data)?);
@@ -333,6 +470,12 @@ impl Connection {
let ns_path = namespace_path.clone().unwrap_or_default();
let mut builder = inner.create_table(name.clone(), batches).mode(mode);
if let Some(bases) = initial_bases {
builder = builder.initial_bases(bases);
}
if allow_external_blob_outside_bases {
builder = builder.allow_external_blob_outside_bases(true);
}
builder = builder.namespace(ns_path.clone());
if let Some(storage_options) = storage_options {
builder = builder.storage_options(storage_options);
@@ -359,7 +502,7 @@ impl Connection {
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None))]
pub fn create_empty_table<'a>(
self_: PyRef<'a, Self>,
name: String,
@@ -369,11 +512,13 @@ impl Connection {
storage_options: Option<HashMap<String, String>>,
location: Option<String>,
namespace_client: Option<Py<PyAny>>,
initial_bases: Option<Bound<'_, PyAny>>,
) -> PyResult<Bound<'a, PyAny>> {
let inner = self_.get_inner()?.clone();
let py = self_.py();
let mode = Self::parse_create_mode_str(mode)?;
let initial_bases = parse_initial_bases(initial_bases)?;
let schema = Schema::from_pyarrow_bound(&schema)?;
@@ -382,6 +527,9 @@ impl Connection {
.create_empty_table(name.clone(), Arc::new(schema))
.mode(mode);
if let Some(bases) = initial_bases {
builder = builder.initial_bases(bases);
}
builder = builder.namespace(ns_path.clone());
if let Some(storage_options) = storage_options {
builder = builder.storage_options(storage_options);