feat(python): add tag-based branch creation and default tag versions (#5136)

Python `tags.create()` now defaults `version` to the handle's currently
visible version, including checked-out handles. Existing `from_ref` /
`from_version` branch selection and explicit tag versions keep their
current behavior.

`branches.create()` gains keyword-only `from_tag`, so a branch can fork
from a tag through the existing `Ref::Tag` path. This preserves the
tag's actual branch snapshot; resolving only its numeric version could
fork from `main` when both branches share a version number. `from_tag`
conflicts with `from_ref` / `from_version` are rejected before
`from_ref="main"` normalization.

When `from_ref` names a tag instead of a branch, the native
missing-branch failure keeps its classification and receives a static
`from_tag=` hint without another lookup. A missing version and an
ambiguous Enterprise 404 keep their original errors.

The Python sync and async APIs, PyO3 binding, stubs and docstrings are
updated together, with native Rust coverage for a tag on a branch that
shares main's numeric version. Node.js `fromTag` and optional `version`
will follow in a separate PR after this one.
This commit is contained in:
Xuanwo
2026-11-21 04:59:34 +08:00
committed by GitHub
parent 74239973c7
commit 668fb1e256
10 changed files with 382 additions and 23 deletions
+3 -1
View File
@@ -879,7 +879,7 @@ class Table:
class Tags:
async def list(self) -> Dict[str, Tag]: ...
async def get_version(self, tag: str) -> int: ...
async def create(self, tag: str, version: int): ...
async def create(self, tag: str, version: Optional[int] = None): ...
async def delete(self, tag: str): ...
async def update(self, tag: str, version: int): ...
@@ -890,6 +890,8 @@ class Branches:
name: str,
from_ref: Optional[str] = None,
from_version: Optional[int] = None,
*,
from_tag: Optional[str] = None,
) -> Table: ...
async def checkout(self, name: str, version: Optional[int] = None) -> Table: ...
async def delete(self, name: str) -> None: ...
+46 -9
View File
@@ -10250,6 +10250,26 @@ class FragmentSummaryStats:
p99: int
def _validate_branch_source(
from_ref: Optional[str],
from_version: Optional[int],
from_tag: Optional[str],
) -> None:
if from_tag is None:
return
conflicts = [
name
for name, value in (("from_ref", from_ref), ("from_version", from_version))
if value is not None
]
if conflicts:
raise ValueError(
"from_tag cannot be combined with "
+ " or ".join(conflicts)
+ "; pass only one source"
)
class Tags:
"""
Table tag manager.
@@ -10280,7 +10300,7 @@ class Tags:
"""
return LOOP.run(self._table.tags.get_version(tag))
def create(self, tag: str, version: int) -> None:
def create(self, tag: str, version: Optional[int] = None) -> None:
"""
Create a tag for a given table version.
@@ -10289,8 +10309,9 @@ class Tags:
tag: str,
The name of the tag to create. This name must be unique among all tag
names for the table.
version: int,
The table version to tag.
version: int, optional
The table version to tag. Defaults to the version visible to this
handle, including a checked-out version.
"""
LOOP.run(self._table.tags.create(tag, version))
@@ -10337,6 +10358,8 @@ class Branches:
name: str,
from_ref: Optional[str] = None,
from_version: Optional[int] = None,
*,
from_tag: Optional[str] = None,
) -> "Table":
"""Create a branch and return a handle scoped to it.
@@ -10348,9 +10371,13 @@ class Branches:
Source branch to fork from. Defaults to ``main``.
from_version: int, optional
A specific version on ``from_ref`` to fork from. Defaults to latest.
from_tag: str, optional
Source tag to fork from. Cannot be combined with ``from_ref`` or
``from_version``.
"""
_validate_branch_source(from_ref, from_version, from_tag)
async_table = LOOP.run(
self._table.branches.create(name, from_ref, from_version)
self._table.branches.create(name, from_ref, from_version, from_tag=from_tag)
)
return self._wrap(async_table)
@@ -10432,7 +10459,7 @@ class AsyncTags:
"""
return await self._table.tags.get_version(tag)
async def create(self, tag: str, version: int) -> None:
async def create(self, tag: str, version: Optional[int] = None) -> None:
"""
Create a tag for a given table version.
@@ -10441,8 +10468,9 @@ class AsyncTags:
tag: str,
The name of the tag to create. This name must be unique among all tag
names for the table.
version: int,
The table version to tag.
version: int, optional
The table version to tag. Defaults to the version visible to this
handle, including a checked-out version.
"""
await self._table.tags.create(tag, version)
@@ -10486,6 +10514,8 @@ class AsyncBranches:
name: str,
from_ref: Optional[str] = None,
from_version: Optional[int] = None,
*,
from_tag: Optional[str] = None,
) -> "AsyncTable":
"""Create a branch and return a handle scoped to it.
@@ -10497,12 +10527,19 @@ class AsyncBranches:
Source branch to fork from. Defaults to ``main``.
from_version: int, optional
A specific version on ``from_ref`` to fork from. Defaults to latest.
from_tag: str, optional
Source tag to fork from. Cannot be combined with ``from_ref`` or
``from_version``.
"""
_validate_branch_source(from_ref, from_version, from_tag)
# "main" and None are two spellings of the root branch in lance; normalize
# so from_ref="main" behaves identically to the default.
# so from_ref="main" behaves identically to the default. This must happen
# after validating from_tag conflicts so an explicit from_ref is not lost.
if from_ref == "main":
from_ref = None
inner = await self._table.branches.create(name, from_ref, from_version)
inner = await self._table.branches.create(
name, from_ref, from_version, from_tag=from_tag
)
return AsyncTable(inner)
async def checkout(self, name: str, version: Optional[int] = None) -> "AsyncTable":
+167
View File
@@ -1426,6 +1426,31 @@ def test_tags(mem_db: DBConnection):
)
def test_tags_create_defaults_to_visible_version(mem_db: DBConnection):
table = mem_db.create_table("test", data=[{"id": 1}])
table.add(data=[{"id": 2}])
table.tags.create("live")
assert table.tags.get_version("live") == 2
table.checkout(1)
table.tags.create("pinned")
assert table.tags.get_version("pinned") == 1
# An explicit version is independent of the version this handle shows.
table.tags.create("explicit", 2)
assert table.tags.get_version("explicit") == 2
# A tag checkout is still a visible version, not "latest".
table.checkout_latest()
table.add(data=[{"id": 3}])
assert table.version == 3
table.checkout("live")
assert table.version == 2
table.tags.create("tag-checkout")
assert table.tags.get_version("tag-checkout") == 2
@pytest.mark.asyncio
async def test_async_tags(mem_db_async: AsyncConnection):
table = await mem_db_async.create_table(
@@ -1480,6 +1505,34 @@ async def test_async_tags(mem_db_async: AsyncConnection):
)
@pytest.mark.asyncio
async def test_async_tags_create_defaults_to_visible_version(
mem_db_async: AsyncConnection,
):
table = await mem_db_async.create_table("test", data=[{"id": 1}])
await table.add(data=[{"id": 2}])
await table.tags.create("live")
assert await table.tags.get_version("live") == 2
await table.checkout(1)
await table.tags.create("pinned")
assert await table.tags.get_version("pinned") == 1
# An explicit version is independent of the version this handle shows.
await table.tags.create("explicit", 2)
assert await table.tags.get_version("explicit") == 2
# A tag checkout is still a visible version, not "latest".
await table.checkout_latest()
await table.add(data=[{"id": 3}])
assert await table.version() == 3
await table.checkout("live")
assert await table.version() == 2
await table.tags.create("tag-checkout")
assert await table.tags.get_version("tag-checkout") == 2
def test_branches(tmp_path):
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
table = db.create_table(
@@ -1519,6 +1572,62 @@ def test_branches(tmp_path):
assert "exp" not in table.branches.list()
def test_branches_create_from_tag(tmp_path):
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
table = db.create_table("test", data=[{"i": 0}])
exp = table.branches.create("exp")
exp.add([{"i": 10}])
exp_version = exp.version
exp.tags.create("exp-v2", exp_version)
# main reaches the same numeric version with different rows.
table.add([{"i": 100}])
assert table.version == exp_version
forked = table.branches.create("from-tag", from_tag="exp-v2")
assert forked.current_branch() == "from-tag"
assert forked.count_rows("i = 10") == 1
assert forked.count_rows("i = 100") == 0
def test_branches_create_from_tag_rejects_other_sources(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("test", data=[{"i": 0}])
table.tags.create("baseline")
# from_ref="main" must be rejected before it is normalized to the default.
with pytest.raises(ValueError, match="from_tag cannot be combined"):
table.branches.create("exp", from_ref="main", from_tag="baseline")
with pytest.raises(ValueError, match="from_tag cannot be combined"):
table.branches.create("exp", from_version=1, from_tag="baseline")
def test_branches_create_from_missing_ref_hint_applies_only_to_branches(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("test", data=[{"i": 0}])
base = table.branches.create("base")
base.add([{"i": 1}])
table.tags.create("baseline")
# A tag passed through from_ref is not a branch. Keep the original failure
# classification and add guidance without probing the ref a second time.
with pytest.raises(RuntimeError) as exc_info:
table.branches.create("exp", from_ref="baseline")
detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
assert "from_tag='baseline'" in detail
# An existing branch with an absent version is a version failure, not an
# unresolved branch, so it must not suggest from_tag.
with pytest.raises(RuntimeError) as exc_info:
table.branches.create("exp", from_ref="base", from_version=9999)
detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
assert "9999" in detail
assert "from_tag=" not in detail
def test_branch_handle_tracks_concurrent_writes(tmp_path):
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
table = db.create_table("t", [{"id": 1}])
@@ -1814,6 +1923,64 @@ async def test_async_branches(tmp_path):
assert "exp" not in await table.branches.list()
@pytest.mark.asyncio
async def test_async_branches_create_from_tag(tmp_path):
db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0))
table = await db.create_table("test", data=[{"i": 0}])
exp = await table.branches.create("exp")
await exp.add([{"i": 10}])
exp_version = await exp.version()
await exp.tags.create("exp-v2", exp_version)
# main reaches the same numeric version with different rows.
await table.add([{"i": 100}])
assert await table.version() == exp_version
forked = await table.branches.create("from-tag", from_tag="exp-v2")
assert forked.current_branch() == "from-tag"
assert await forked.count_rows("i = 10") == 1
assert await forked.count_rows("i = 100") == 0
@pytest.mark.asyncio
async def test_async_branches_create_from_tag_rejects_other_sources(tmp_path):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("test", data=[{"i": 0}])
await table.tags.create("baseline")
with pytest.raises(ValueError, match="from_tag cannot be combined"):
await table.branches.create("exp", from_ref="main", from_tag="baseline")
with pytest.raises(ValueError, match="from_tag cannot be combined"):
await table.branches.create("exp", from_version=1, from_tag="baseline")
@pytest.mark.asyncio
async def test_async_branches_create_from_missing_ref_hint_applies_only_to_branches(
tmp_path,
):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("test", data=[{"i": 0}])
base = await table.branches.create("base")
await base.add([{"i": 1}])
await table.tags.create("baseline")
with pytest.raises(RuntimeError) as exc_info:
await table.branches.create("exp", from_ref="baseline")
detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
assert "from_tag='baseline'" in detail
# An existing branch with an absent version is a version failure, not an
# unresolved branch, so it must not suggest from_tag.
with pytest.raises(RuntimeError) as exc_info:
await table.branches.create("exp", from_ref="base", from_version=9999)
detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
assert "9999" in detail
assert "from_tag=" not in detail
@pytest.mark.asyncio
async def test_async_open_table_with_branch_version(tmp_path):
db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0))
+64 -6
View File
@@ -36,7 +36,7 @@ use lancedb::table::{
};
use lancedb::tokenize as lancedb_tokenize;
use pyo3::{
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
Bound, FromPyObject, Py, PyAny, PyErr, PyRef, PyResult, Python,
exceptions::{PyRuntimeError, PyValueError},
pyclass, pyfunction, pymethods,
types::{
@@ -3261,9 +3261,14 @@ impl Tags {
})
}
pub fn create(self_: PyRef<Self>, tag: String, version: u64) -> PyResult<Bound<PyAny>> {
#[pyo3(signature = (tag, version=None))]
pub fn create(self_: PyRef<Self>, tag: String, version: Option<u64>) -> PyResult<Bound<PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let version = match version {
Some(version) => version,
None => inner.version().await.infer_error()?,
};
let mut tags = inner.tags().await.infer_error()?;
tags.create(tag.as_str(), version).await.infer_error()?;
Ok(())
@@ -3300,6 +3305,35 @@ impl Branches {
}
}
/// Add the from_tag hint to a native branch lookup failure.
///
/// The caller only invokes this for a native `NotFound`, which identifies an
/// unresolved branch path. A missing version is `VersionNotFound`, and a REST
/// 404 is an ambiguous `TableNotFound`, so neither gets the hint. The original
/// exception class and message are preserved apart from the added note.
fn add_from_tag_hint(error: PyErr, branch: &str) -> PyErr {
let hint = format!("If '{branch}' is a tag, pass from_tag='{branch}' instead of from_ref.");
Python::attach(|py| {
let value = error.value(py);
if value.hasattr("add_note").unwrap_or(false)
&& value.call_method1("add_note", (hint.clone(),)).is_ok()
{
return error;
}
// Python 3.10 has no BaseException.add_note. Native branch lookup
// failures are runtime errors with one string argument, so append the
// hint to that message without changing the exception class.
let Ok(args) = value.getattr("args") else {
return error;
};
let Ok(original) = args.get_item(0).and_then(|arg| arg.extract::<String>()) else {
return error;
};
let _ = value.setattr("args", (format!("{original}\n{hint}"),));
error
})
}
#[pymethods]
impl Branches {
pub fn list(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
@@ -3320,18 +3354,42 @@ impl Branches {
})
}
#[pyo3(signature = (name, from_ref=None, from_version=None))]
#[pyo3(signature = (name, from_ref=None, from_version=None, *, from_tag=None))]
pub fn create(
self_: PyRef<'_, Self>,
name: String,
from_ref: Option<String>,
from_version: Option<u64>,
from_tag: Option<String>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let from = Ref::Version(from_ref, from_version);
let table = inner.create_branch(&name, from).await.infer_error()?;
Ok(Table::new(table))
let from_branch = if from_tag.is_none() {
from_ref.clone()
} else {
None
};
let from = match from_tag {
Some(tag) => Ref::Tag(tag),
None => Ref::Version(from_ref, from_version),
};
match inner.create_branch(&name, from).await {
Ok(table) => Ok(Table::new(table)),
Err(error) => {
// A missing branch is a native NotFound. A missing version
// is VersionNotFound, and a remote 404 is an ambiguous
// TableNotFound, so only the native branch case hints.
let missing_branch = matches!(
&error,
lancedb::Error::Lance { source } if source.is_not_found()
);
let error = Err::<(), _>(error).infer_error().unwrap_err();
match from_branch {
Some(branch) if missing_branch => Err(add_from_tag_hint(error, &branch)),
_ => Err(error),
}
}
}
})
}