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
+130
View File
@@ -85,3 +85,133 @@ def test_blob_array(with_pylance):
text=True,
)
assert result.returncode == 0, result.stderr
@pytest.mark.parametrize("with_pylance", [False, True])
def test_blob_uri_array(with_pylance):
if with_pylance:
pytest.importorskip("lance")
# Use fresh processes so each extension class can own Arrow's registry.
script = textwrap.dedent(
"""\
import importlib.abc
import pathlib
import sys
import tempfile
if sys.argv[1] == "False":
class MissingLance(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
if fullname == "lance" or fullname.startswith("lance."):
raise ModuleNotFoundError(fullname, name="lance")
sys.meta_path.insert(0, MissingLance())
import lancedb
import pyarrow as pa
from lancedb import BasePath, blob_uri_array
from lancedb.schema import blob
if sys.argv[1] == "True":
from lance import DatasetBasePath
from lance.blob import BlobType
else:
from lancedb.schema import _FallbackBlobType as BlobType
DatasetBasePath = None
schema = pa.schema([blob("video")])
array = blob_uri_array(
["s3://bucket/a.mp4", None, "b.mp4"],
positions=[0, None, None],
sizes=[4, None, None],
)
assert isinstance(array, pa.ExtensionArray)
assert type(array.type) is BlobType
assert array.type == schema.field("video").type
assert array.storage.to_pylist() == [
{"data": None, "uri": "s3://bucket/a.mp4", "position": 0, "size": 4},
None,
{"data": None, "uri": "b.mp4", "position": None, "size": None},
]
whole = blob_uri_array(iter(["s3://bucket/a.mp4"]))
assert whole.storage.to_pylist() == [
{"data": None, "uri": "s3://bucket/a.mp4", "position": None, "size": None}
]
checks = [
(lambda: blob_uri_array(["u"], positions=[0]), "provided together"),
(
lambda: blob_uri_array(["u"], positions=[0, 0], sizes=[1, 1]),
"same length",
),
(
lambda: blob_uri_array(["u"], sizes=[1, 1], positions=[0, 0]),
"same length",
),
(
lambda: blob_uri_array(["u"], positions=[0], sizes=[None]),
"both position and size",
),
(lambda: blob_uri_array(["u"], positions=[0], sizes=[0]), "positive"),
(lambda: blob_uri_array(["u"], positions=[-1], sizes=[1]), "non-negative"),
(lambda: blob_uri_array([None], positions=[0], sizes=[1]), "None but"),
(lambda: blob_uri_array(["u"], positions=[0], sizes=[2**64]), "uint64"),
(lambda: blob_uri_array([b"u"]), "must be a string"),
]
for call, fragment in checks:
try:
call()
except (TypeError, ValueError, OverflowError) as error:
assert fragment in str(error), (fragment, error)
else:
raise AssertionError(f"accepted invalid input: {fragment}")
try:
BasePath("s3://bucket", id=0)
except ValueError as error:
assert "id=None" in str(error)
else:
raise AssertionError("accepted explicit id=0")
# The public create route must accept the helper and register the base
# in the same commit as the data, with or without pylance.
root = pathlib.Path(tempfile.mkdtemp())
base_dir = root / "videos"
base_dir.mkdir()
payload = b"0123456789abcdef"
clip = base_dir / "clip.mp4"
clip.write_bytes(payload)
db = lancedb.connect(root / "db")
field = blob("video").with_metadata({"lancedb:logical_type": "mp4"})
table_schema = pa.schema([pa.field("id", pa.int64()), field])
videos = blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
batch = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=table_schema
)
if DatasetBasePath is not None:
bases = [DatasetBasePath(path=base_dir.as_uri(), name="source")]
else:
bases = [BasePath(path=base_dir.as_uri(), name="source")]
table = db.create_table("videos", data=batch, initial_bases=bases)
assert table.version == 1
assert (
table.schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
)
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
assert table.fetch_blobs("video", row_ids).to_pylist() == [payload[:6]]
assert table.fetch_blob_ranges(
"video", [(row_ids[0].as_py(), 1, 3)]
).to_pylist() == [payload[1:4]]
if DatasetBasePath is not None:
base_paths = table.to_lance().base_paths()
assert base_paths[1].path == base_dir.as_uri()
assert base_paths[1].is_dataset_root is False
if sys.argv[1] == "False":
assert "lance" not in sys.modules
"""
)
result = subprocess.run(
[sys.executable, "-c", script, str(with_pylance)],
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr