mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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:
@@ -1328,7 +1328,8 @@ def test_versioning_tags(tmp_db):
|
||||
# --8<-- [start:versioning_tags]
|
||||
# Create a tag pointing at a specific version
|
||||
table.tags.create("baseline", 1)
|
||||
table.tags.create("with-edits", table.version)
|
||||
# Omit version to tag the version this handle currently shows.
|
||||
table.tags.create("with-edits")
|
||||
|
||||
# List all tags on this table
|
||||
print(table.tags.list())
|
||||
@@ -1343,6 +1344,9 @@ def test_versioning_tags(tmp_db):
|
||||
table.checkout("baseline")
|
||||
print(table.version)
|
||||
|
||||
# A checked-out handle tags the older version it shows, not the latest.
|
||||
table.tags.create("baseline-checkout")
|
||||
|
||||
# Delete a tag (does not delete the underlying version)
|
||||
table.tags.delete("with-edits")
|
||||
|
||||
@@ -1350,6 +1354,7 @@ def test_versioning_tags(tmp_db):
|
||||
table.checkout_latest()
|
||||
# --8<-- [end:versioning_tags]
|
||||
assert table.version == 3
|
||||
assert table.tags.get_version("baseline-checkout") == 2
|
||||
assert "baseline" in table.tags.list()
|
||||
assert "with-edits" not in table.tags.list()
|
||||
|
||||
@@ -1387,8 +1392,15 @@ def test_branches(tmp_db):
|
||||
# Fork an isolated, writable branch from main's latest version.
|
||||
# `create` returns a table handle scoped to the new branch.
|
||||
branch = table.branches.create("exp")
|
||||
|
||||
# Fork from a tag. `from_tag` is keyword-only and cannot be combined with
|
||||
# `from_ref` or `from_version`.
|
||||
table.tags.create("baseline", 1)
|
||||
tag_branch = table.branches.create("exp-from-tag", from_tag="baseline")
|
||||
# --8<-- [end:branch_create]
|
||||
|
||||
assert tag_branch.count_rows() == 3
|
||||
|
||||
# --8<-- [start:branch_write]
|
||||
# Writes land on the branch handle only; main is left untouched.
|
||||
branch.add([{"id": 4, "author": "Lancelot", "quote": "For the realm!"}])
|
||||
@@ -1414,6 +1426,8 @@ def test_branches(tmp_db):
|
||||
|
||||
assert table.count_rows() == 3
|
||||
assert "exp" not in table.branches.list()
|
||||
assert "exp-from-tag" in table.branches.list()
|
||||
table.branches.delete("exp-from-tag")
|
||||
|
||||
# Setup: a branch with row results that we want to apply to main.
|
||||
candidate = table.branches.create("candidate")
|
||||
|
||||
@@ -1379,17 +1379,27 @@ async fn main() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// --8<-- [start:branch_create]
|
||||
use lancedb::table::Ref;
|
||||
|
||||
// --8<-- [start:branch_create]
|
||||
// Fork an isolated, writable branch from main's latest version.
|
||||
// `create_branch` returns a table handle scoped to the new branch.
|
||||
let branch = branches_table
|
||||
.create_branch("exp", Ref::Version(None, None))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Fork from a tag. A tag keeps its branch and version.
|
||||
let mut tags = branches_table.tags().await.unwrap();
|
||||
tags.create("baseline", 1).await.unwrap();
|
||||
let tag_branch = branches_table
|
||||
.create_branch("exp-from-tag", Ref::Tag("baseline".to_string()))
|
||||
.await
|
||||
.unwrap();
|
||||
// --8<-- [end:branch_create]
|
||||
|
||||
assert_eq!(tag_branch.count_rows(None).await.unwrap(), 3);
|
||||
|
||||
// --8<-- [start:branch_write]
|
||||
// Writes land on the branch handle only; main is left untouched.
|
||||
branch
|
||||
@@ -1428,6 +1438,14 @@ async fn main() {
|
||||
|
||||
assert_eq!(branches_table.count_rows(None).await.unwrap(), 3);
|
||||
assert!(!branches_table.list_branches().await.unwrap().contains_key("exp"));
|
||||
assert!(
|
||||
branches_table
|
||||
.list_branches()
|
||||
.await
|
||||
.unwrap()
|
||||
.contains_key("exp-from-tag")
|
||||
);
|
||||
branches_table.delete_branch("exp-from-tag").await.unwrap();
|
||||
|
||||
// Setup: a branch with row results that we want to apply to main.
|
||||
let candidate = branches_table
|
||||
|
||||
@@ -1742,6 +1742,11 @@ page).
|
||||
The tags API supports the standard CRUD operations (create, list, update, delete),
|
||||
plus checking out by tag name.
|
||||
|
||||
In Python, `tags.create()` accepts an optional `version`. If you omit it, the
|
||||
tag uses the version the table handle currently shows. That includes a handle
|
||||
checked out to an older version, so pass `version` explicitly when the tag must
|
||||
not depend on the handle's checkout state.
|
||||
|
||||
<CodeGroup>
|
||||
<CodeBlock filename="Python" language="Python" icon="python">
|
||||
{VersioningTags}
|
||||
|
||||
@@ -30,7 +30,7 @@ export const PyAlterVectorColumn = "data = [\n {\n \"id\": 1,\n
|
||||
|
||||
export const PyBatchDataInsertion = "import pyarrow as pa\n\ndef make_batches():\n for i in range(5): # Create 5 batches\n yield pa.RecordBatch.from_arrays(\n [\n pa.array([[3.1, 4.1], [5.9, 26.5]], pa.list_(pa.float32(), 2)),\n pa.array([f\"item{i * 2 + 1}\", f\"item{i * 2 + 2}\"]),\n pa.array([float((i * 2 + 1) * 10), float((i * 2 + 2) * 10)]),\n ],\n [\"vector\", \"item\", \"price\"],\n )\n\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n pa.field(\"item\", pa.utf8()),\n pa.field(\"price\", pa.float32()),\n ]\n)\n# Create table with batches\ntable_name = \"batch_ingestion_example\"\ntable = db.create_table(table_name, make_batches(), schema=schema, mode=\"overwrite\")\n";
|
||||
|
||||
export const PyBranchCreate = "# Fork an isolated, writable branch from main's latest version.\n# `create` returns a table handle scoped to the new branch.\nbranch = table.branches.create(\"exp\")\n";
|
||||
export const PyBranchCreate = "# Fork an isolated, writable branch from main's latest version.\n# `create` returns a table handle scoped to the new branch.\nbranch = table.branches.create(\"exp\")\n\n# Fork from a tag. `from_tag` is keyword-only and cannot be combined with\n# `from_ref` or `from_version`.\ntable.tags.create(\"baseline\", 1)\ntag_branch = table.branches.create(\"exp-from-tag\", from_tag=\"baseline\")\n";
|
||||
|
||||
export const PyBranchDelete = "# Delete the branch and its branch-local history. Data on main is safe.\ntable.branches.delete(\"exp\")\n";
|
||||
|
||||
@@ -136,7 +136,7 @@ export const PyVersioningListAllVersions = "versions = table.list_versions()\nfo
|
||||
|
||||
export const PyVersioningRollback = "table.restore(version_after_mod)\nversions = table.list_versions()\nversion_count_after_rollback = len(versions)\nprint(f\"Total number of versions after rollback: {version_count_after_rollback}\")\n";
|
||||
|
||||
export const PyVersioningTags = "# Create a tag pointing at a specific version\ntable.tags.create(\"baseline\", 1)\ntable.tags.create(\"with-edits\", table.version)\n\n# List all tags on this table\nprint(table.tags.list())\n\n# Look up the version a tag points at\nprint(table.tags.get_version(\"baseline\"))\n\n# Move an existing tag to a different version\ntable.tags.update(\"baseline\", 2)\n\n# Check out a version by tag name\ntable.checkout(\"baseline\")\nprint(table.version)\n\n# Delete a tag (does not delete the underlying version)\ntable.tags.delete(\"with-edits\")\n\n# Return to the latest version\ntable.checkout_latest()\n";
|
||||
export const PyVersioningTags = "# Create a tag pointing at a specific version\ntable.tags.create(\"baseline\", 1)\n# Omit version to tag the version this handle currently shows.\ntable.tags.create(\"with-edits\")\n\n# List all tags on this table\nprint(table.tags.list())\n\n# Look up the version a tag points at\nprint(table.tags.get_version(\"baseline\"))\n\n# Move an existing tag to a different version\ntable.tags.update(\"baseline\", 2)\n\n# Check out a version by tag name\ntable.checkout(\"baseline\")\nprint(table.version)\n\n# A checked-out handle tags the older version it shows, not the latest.\ntable.tags.create(\"baseline-checkout\")\n\n# Delete a tag (does not delete the underlying version)\ntable.tags.delete(\"with-edits\")\n\n# Return to the latest version\ntable.checkout_latest()\n";
|
||||
|
||||
export const PyVersioningUpdateData = "table.update(where=\"author='Richard'\", values={\"author\": \"Richard Daniel Sanchez\"})\nrows_after_update = table.count_rows(\"author = 'Richard Daniel Sanchez'\")\nprint(f\"Rows updated to Richard Daniel Sanchez: {rows_after_update}\")\n";
|
||||
|
||||
@@ -274,7 +274,7 @@ export const RsAlterColumnsWithExpression = "// For custom transforms, create a
|
||||
|
||||
export const RsAlterVectorColumn = "let old_dim = 384;\nlet new_dim = 1024;\nlet vector_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\n \"embedding\",\n DataType::FixedSizeList(\n Arc::new(Field::new(\"item\", DataType::Float32, true)),\n old_dim,\n ),\n true,\n ),\n]));\nlet vector_batch = RecordBatch::try_new(\n vector_schema.clone(),\n vec![\n Arc::new(Int64Array::from(vec![1])),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(\n vec![Some(vec![Some(0.1_f32); old_dim as usize])],\n old_dim,\n ),\n ),\n ],\n)\n.unwrap();\nlet vector_reader: Box<dyn RecordBatchReader + Send> =\n Box::new(RecordBatchIterator::new(vec![Ok(vector_batch)].into_iter(), vector_schema.clone()));\nlet vector_table = db\n .create_table(\"vector_alter_example\", vector_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n\n// Changing FixedSizeList dimensions (384 -> 1024) is not supported via alter_columns.\n// Use add_columns + drop_columns + alter_columns(rename) to replace the column.\nvector_table\n .add_columns(\n NewColumnTransform::SqlExpressions(vec![(\n \"embedding_v2\".to_string(),\n format!(\"arrow_cast(NULL, 'FixedSizeList({}, Float32)')\", new_dim),\n )]),\n None,\n )\n .await\n .unwrap();\nvector_table.drop_columns(&[\"embedding\"]).await.unwrap();\nvector_table\n .alter_columns(&[ColumnAlteration::new(\"embedding_v2\".to_string())\n .rename(\"embedding\".to_string())])\n .await\n .unwrap();\n";
|
||||
|
||||
export const RsBranchCreate = "// Fork an isolated, writable branch from main's latest version.\n// `create_branch` returns a table handle scoped to the new branch.\nlet branch = branches_table\n .create_branch(\"exp\", Ref::Version(None, None))\n .await\n .unwrap();\n";
|
||||
export const RsBranchCreate = "use lancedb::table::Ref;\n\n// Fork an isolated, writable branch from main's latest version.\n// `create_branch` returns a table handle scoped to the new branch.\nlet branch = branches_table\n .create_branch(\"exp\", Ref::Version(None, None))\n .await\n .unwrap();\n\n// Fork from a tag. A tag keeps its branch and version.\nlet mut tags = branches_table.tags().await.unwrap();\ntags.create(\"baseline\", 1).await.unwrap();\nlet tag_branch = branches_table\n .create_branch(\"exp-from-tag\", Ref::Tag(\"baseline\".to_string()))\n .await\n .unwrap();\n";
|
||||
|
||||
export const RsBranchDelete = "// Delete the branch and its branch-local history. Data on main is safe.\nbranches_table.delete_branch(\"exp\").await.unwrap();\n";
|
||||
|
||||
|
||||
@@ -127,8 +127,12 @@ small `quotes` table with three rows on `main`.
|
||||
### Create a branch {#create-a-branch}
|
||||
|
||||
Forking from `main` returns a table handle scoped to the new branch. `main` is
|
||||
the reserved default source, so `create` needs only a name; to fork from
|
||||
somewhere else, pass a branch name, a specific version, or both.
|
||||
the reserved default source, so `create` needs only a name. To fork from another
|
||||
branch, pass `from_ref`, optionally with `from_version`. In Python, use
|
||||
keyword-only `from_tag` to fork from a tag; it cannot be combined with
|
||||
`from_ref` or `from_version`. In Rust, pass `Ref::Tag` to `create_branch`. A
|
||||
tag carries its own branch and version, so the tag source forks from that exact
|
||||
snapshot.
|
||||
|
||||
<CodeGroup>
|
||||
<CodeBlock filename="Python" language="Python" icon="python">
|
||||
|
||||
@@ -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: ...
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -5813,6 +5813,60 @@ mod tests {
|
||||
assert_eq!(at2.count_rows(Some("i = 10".to_string())).await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_branch_from_tag_on_branch_with_same_version_as_main() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let uri = tmp_dir.path().to_str().unwrap();
|
||||
let conn = ConnectBuilder::new(uri)
|
||||
.read_consistency_interval(Duration::from_secs(0))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let table = conn
|
||||
.create_table("my_table", sample_rows(vec![0]))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let fork_point = table.version().await.unwrap();
|
||||
|
||||
// Advance exp and main to the same version number with different rows.
|
||||
let exp = table.create_branch("exp", fork_point).await.unwrap();
|
||||
exp.add(sample_rows(vec![10])).execute().await.unwrap();
|
||||
let exp_version = exp.version().await.unwrap();
|
||||
table.add(sample_rows(vec![100])).execute().await.unwrap();
|
||||
assert_eq!(exp_version, table.version().await.unwrap());
|
||||
|
||||
// Tag exp at that shared version number. The tag must keep exp's branch
|
||||
// identity, so forking from it sees exp's snapshot rather than main's
|
||||
// version with the same number.
|
||||
let mut tags = exp.tags().await.unwrap();
|
||||
tags.create("exp-v2", exp_version).await.unwrap();
|
||||
|
||||
let from_tag = table
|
||||
.create_branch(
|
||||
"from-tag",
|
||||
lance::dataset::refs::Ref::Tag("exp-v2".to_string()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(from_tag.current_branch().as_deref(), Some("from-tag"));
|
||||
assert_eq!(
|
||||
from_tag
|
||||
.count_rows(Some("i = 10".to_string()))
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
from_tag
|
||||
.count_rows(Some("i = 100".to_string()))
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_branch_name_validation() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user