feat(nodejs): add tag-based branch creation and default tag versions

This commit is contained in:
Xuanwo
2026-11-20 22:17:30 +00:00
parent 668fb1e256
commit da12202d48
13 changed files with 431 additions and 25 deletions
+31 -2
View File
@@ -64,6 +64,35 @@ with `status: "failed"` instead of throwing.
### create()
#### create(name, options)
```ts
create(name, options): Promise<Table>
```
Create a branch from a tag and return a handle scoped to it.
##### Parameters
* **name**: `string`
Name of the new branch.
* **options**: [`CreateBranchOptions`](../interfaces/CreateBranchOptions.md)
Named source. `fromTag` keeps the tag's branch and version.
##### Returns
`Promise`&lt;[`Table`](Table.md)&gt;
##### Example
```typescript
const branches = await table.branches();
const branch = await branches.create("exp", { fromTag: "baseline" });
```
#### create(name, fromRef, fromVersion)
```ts
create(
name,
@@ -73,7 +102,7 @@ create(
Create a branch and return a handle scoped to it.
#### Parameters
##### Parameters
* **name**: `string`
Name of the new branch.
@@ -84,7 +113,7 @@ Create a branch and return a handle scoped to it.
* **fromVersion?**: `number`
A specific version on `fromRef`. Defaults to latest.
#### Returns
##### Returns
`Promise`&lt;[`Table`](Table.md)&gt;
+9 -2
View File
@@ -6,6 +6,8 @@
# Class: Tags
Tags label table versions with human-readable names.
## Constructors
### new Tags()
@@ -23,14 +25,19 @@ new Tags(): Tags
### create()
```ts
create(tag, version): Promise<void>
create(tag, version?): Promise<void>
```
Create a tag for a table version.
Omit `version` to tag the version this handle currently shows,
including a checked-out version.
#### Parameters
* **tag**: `string`
* **version**: `number`
* **version?**: `null` \| `number`
#### Returns
+1
View File
@@ -79,6 +79,7 @@
- [CompactionStats](interfaces/CompactionStats.md)
- [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md)
- [ConnectionOptions](interfaces/ConnectionOptions.md)
- [CreateBranchOptions](interfaces/CreateBranchOptions.md)
- [CreateNamespaceOptions](interfaces/CreateNamespaceOptions.md)
- [CreateNamespaceResponse](interfaces/CreateNamespaceResponse.md)
- [CreateTableOptions](interfaces/CreateTableOptions.md)
@@ -0,0 +1,20 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / CreateBranchOptions
# Interface: CreateBranchOptions
Options for creating a branch from a named source.
## Properties
### fromTag
```ts
fromTag: string;
```
Tag to fork from. The tag keeps the branch and version it points to.
Cannot be combined with `fromRef` or `fromVersion`.
+17 -1
View File
@@ -853,7 +853,8 @@ test("versioning snippets (async)", async () => {
// Create a tag pointing at a specific version
await tags.create("baseline", 1);
await tags.create("with-edits", await tagsTable.version());
// Omit version to tag the version this handle currently shows.
await tags.create("with-edits");
// List all tags on this table
console.log(await tags.list());
@@ -868,12 +869,16 @@ test("versioning snippets (async)", async () => {
await tagsTable.checkout("baseline");
console.log(await tagsTable.version());
// A checked-out handle tags the older version it shows, not the latest.
await tags.create("baseline-checkout");
// Delete a tag (does not delete the underlying version)
await tags.delete("with-edits");
// Return to the latest version
await tagsTable.checkoutLatest();
// --8<-- [end:versioning_tags]
expect(await tags.getVersion("baseline-checkout")).toBe(2);
expect(await tagsTable.version()).toBe(3);
const remainingTags = await tags.list();
expect(remainingTags).toHaveProperty("baseline");
@@ -900,8 +905,18 @@ test("branch snippets (async)", async () => {
// Fork an isolated, writable branch from main's latest version.
// `create` returns a table handle scoped to the new branch.
const branch = await branches.create("exp");
// Fork from a tag. Pass `{ fromTag }` as the second argument; it cannot be
// combined with `fromRef` or `fromVersion`.
await (await table.tags()).create("baseline", 1);
const tagBranch = await branches.create("exp-from-tag", {
fromTag: "baseline",
});
// --8<-- [end:branch_create]
expect(tagBranch.currentBranch()).toBe("exp-from-tag");
expect(await tagBranch.countRows()).toBe(3);
// --8<-- [start:branch_write]
// Writes land on the branch handle only; main is left untouched.
await branch.add([{ id: 4, author: "Lancelot", quote: "For the realm!" }]);
@@ -928,6 +943,7 @@ test("branch snippets (async)", async () => {
// Delete the branch and its branch-local history. Data on main is safe.
await branches.delete("exp");
// --8<-- [end:branch_delete]
await branches.delete("exp-from-tag");
expect(await table.countRows()).toBe(3);
expect(await branches.list()).not.toHaveProperty("exp");
+4 -4
View File
@@ -1742,10 +1742,10 @@ 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.
In Python and TypeScript, `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">
+2 -2
View File
@@ -162,7 +162,7 @@ export const TsAlterColumnsWithExpression = "// For custom transforms, create a
export const TsAlterVectorColumn = "const oldDim = 384;\nconst newDim = 1024;\nconst vectorSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\n \"embedding\",\n new arrow.FixedSizeList(\n oldDim,\n new arrow.Field(\"item\", new arrow.Float16(), true),\n ),\n true,\n ),\n]);\nconst vectorData = lancedb.makeArrowTable(\n [{ id: 1, embedding: Array.from({ length: oldDim }, () => Math.random()) }],\n { schema: vectorSchema },\n);\nconst vectorTable = await db.createTable(\"vector_alter_example\", vectorData, {\n mode: \"overwrite\",\n});\n\n// Changing FixedSizeList dimensions (384 -> 1024) is not supported via alterColumns.\n// Use addColumns + dropColumns + alterColumns(rename) to replace the column.\nawait vectorTable.addColumns([\n {\n name: \"embedding_v2\",\n valueSql: `arrow_cast(NULL, 'FixedSizeList(${newDim}, Float16)')`,\n },\n]);\nawait vectorTable.dropColumns([\"embedding\"]);\nawait vectorTable.alterColumns([{ path: \"embedding_v2\", rename: \"embedding\" }]);\n";
export const TsBranchCreate = "// Fork an isolated, writable branch from main's latest version.\n// `create` returns a table handle scoped to the new branch.\nconst branch = await branches.create(\"exp\");\n";
export const TsBranchCreate = "// Fork an isolated, writable branch from main's latest version.\n// `create` returns a table handle scoped to the new branch.\nconst branch = await branches.create(\"exp\");\n\n// Fork from a tag. Pass `{ fromTag }` as the second argument; it cannot be\n// combined with `fromRef` or `fromVersion`.\nawait (await table.tags()).create(\"baseline\", 1);\nconst tagBranch = await branches.create(\"exp-from-tag\", {\n fromTag: \"baseline\",\n});\n";
export const TsBranchDelete = "// Delete the branch and its branch-local history. Data on main is safe.\nawait branches.delete(\"exp\");\n";
@@ -250,7 +250,7 @@ export const TsVersioningListAllVersions = "const allVersions = await table.list
export const TsVersioningRollback = "await table.checkout(versionAfterMod);\nawait table.restore();\nconst versionsAfterRollback = await table.listVersions();\nconst versionCountAfterRollback = versionsAfterRollback.length;\nconsole.log(\n `Total number of versions after rollback: ${versionCountAfterRollback}`,\n);\n";
export const TsVersioningTags = "const tags = await tagsTable.tags();\n\n// Create a tag pointing at a specific version\nawait tags.create(\"baseline\", 1);\nawait tags.create(\"with-edits\", await tagsTable.version());\n\n// List all tags on this table\nconsole.log(await tags.list());\n\n// Look up the version a tag points at\nconsole.log(await tags.getVersion(\"baseline\"));\n\n// Move an existing tag to a different version\nawait tags.update(\"baseline\", 2);\n\n// Check out a version by tag name\nawait tagsTable.checkout(\"baseline\");\nconsole.log(await tagsTable.version());\n\n// Delete a tag (does not delete the underlying version)\nawait tags.delete(\"with-edits\");\n\n// Return to the latest version\nawait tagsTable.checkoutLatest();\n";
export const TsVersioningTags = "const tags = await tagsTable.tags();\n\n// Create a tag pointing at a specific version\nawait tags.create(\"baseline\", 1);\n// Omit version to tag the version this handle currently shows.\nawait tags.create(\"with-edits\");\n\n// List all tags on this table\nconsole.log(await tags.list());\n\n// Look up the version a tag points at\nconsole.log(await tags.getVersion(\"baseline\"));\n\n// Move an existing tag to a different version\nawait tags.update(\"baseline\", 2);\n\n// Check out a version by tag name\nawait tagsTable.checkout(\"baseline\");\nconsole.log(await tagsTable.version());\n\n// A checked-out handle tags the older version it shows, not the latest.\nawait tags.create(\"baseline-checkout\");\n\n// Delete a tag (does not delete the underlying version)\nawait tags.delete(\"with-edits\");\n\n// Return to the latest version\nawait tagsTable.checkoutLatest();\n";
export const TsVersioningUpdateData = "await table.update({\n where: \"author = 'Richard'\",\n values: { author: \"Richard Daniel Sanchez\" },\n});\nconst rowsAfterUpdate = await table.countRows(\n \"author = 'Richard Daniel Sanchez'\",\n);\nconsole.log(`Rows updated to Richard Daniel Sanchez: ${rowsAfterUpdate}`);\n";
+4 -3
View File
@@ -130,9 +130,10 @@ 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 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.
`from_ref` or `from_version`. In TypeScript, pass `{ fromTag }` as the second
argument to `create`; it cannot be combined with `fromRef` or `fromVersion`. 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">
+105
View File
@@ -1382,6 +1382,111 @@ describe("remote connection", () => {
);
});
it("forks Enterprise branches from tags and defaults tag versions", async () => {
const requests: { path: string; body: Record<string, unknown> }[] = [];
await withMockDatabase(
(req, res) => {
const path = req.url ?? "";
if (path.endsWith("/branches/list/")) {
res.writeHead(200, { "Content-Type": "application/json" }).end(
JSON.stringify({
branches: {
exp: { parentVersion: 1, createAt: 1, manifestSize: 1 },
},
}),
);
return;
}
if (path.endsWith("/describe/")) {
res.writeHead(200, { "Content-Type": "application/json" }).end(
JSON.stringify({
name: "t",
version: 2,
schema: { fields: [] },
}),
);
return;
}
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
});
req.on("end", () => {
const body = raw ? JSON.parse(raw) : {};
requests.push({ path, body });
if (path.endsWith("/tags/version/")) {
res
.writeHead(200, { "Content-Type": "application/json" })
.end(JSON.stringify({ version: 3, branch: "base" }));
return;
}
if (path.endsWith("/tags/create/")) {
res
.writeHead(200, { "Content-Type": "application/json" })
.end("{}");
return;
}
if (path.endsWith("/branches/create/")) {
if (body["name"] === "missing") {
res
.writeHead(404, { "Content-Type": "application/json" })
.end(JSON.stringify({ message: "not found" }));
return;
}
res
.writeHead(200, { "Content-Type": "application/json" })
.end("{}");
return;
}
res.writeHead(404).end();
});
},
async (db) => {
const table = await db.openTable("t", undefined, { branch: "exp" });
await (await table.tags()).create("baseline");
const branches = await table.branches();
const fromTag = await branches.create("from-tag", {
fromTag: "baseline",
});
expect(fromTag.currentBranch()).toBe("from-tag");
// An Enterprise 404 is an ambiguous table-or-source failure, so the
// Embedded branch hint must not be appended based on its message.
const missing = await branches
.create("missing", { fromTag: "baseline" })
.then(
() => undefined,
(error: Error) => error,
);
expect(missing).toBeDefined();
expect(missing?.message).not.toContain("fromTag");
},
);
// Omitting the tag version resolves the handle's visible branch version.
expect(requests).toContainEqual({
path: "/v1/table/t/tags/create/",
body: {
tag: "baseline",
version: 2,
branch: "exp",
},
});
// A tag source uses the existing coordinate lookup and the normal
// branches/create body; there is no from_tag field on the wire.
expect(requests).toContainEqual({
path: "/v1/table/t/tags/version/",
body: { tag: "baseline" },
});
expect(requests).toContainEqual({
path: "/v1/table/t/branches/create/",
// biome-ignore lint/style/useNamingConvention: snake_case is the server wire format
body: { name: "from-tag", from_branch: "base", from_version: 3 },
});
});
it("sends FTS options to remote tables", async () => {
let createIndexBody: Record<string, unknown> | undefined;
+117
View File
@@ -4020,6 +4020,123 @@ describe("when dealing with tags", () => {
await table.add([{ id: 3n, vector: [0.5, 0.6] }]);
expect(await table.countRows()).toBe(2);
});
it("defaults create version to the handle's visible version", async () => {
const conn = await connect(tmpDir.name, {
readConsistencyInterval: 0,
});
const table = await conn.createTable("my_table", [{ id: 1 }]);
await table.add([{ id: 2 }]);
const tags = await table.tags();
await tags.create("live");
expect(await tags.getVersion("live")).toBe(2);
await table.checkout(1);
await tags.create("pinned");
expect(await tags.getVersion("pinned")).toBe(1);
// An explicit version is independent of the version this handle shows.
await tags.create("explicit", 2);
expect(await tags.getVersion("explicit")).toBe(2);
// A tag checkout is still a visible version, not "latest".
await table.checkoutLatest();
await table.add([{ id: 3 }]);
expect(await table.version()).toBe(3);
await table.checkout("live");
await tags.create("tag-checkout");
expect(await tags.getVersion("tag-checkout")).toBe(2);
});
});
describe("when dealing with branches", () => {
let tmpDir: tmp.DirResult;
beforeEach(() => {
tmpDir = tmp.dirSync({ unsafeCleanup: true });
});
afterEach(() => {
tmpDir.removeCallback();
});
it("forks from a tag on a branch with the same version as main", async () => {
const conn = await connect(tmpDir.name, {
readConsistencyInterval: 0,
});
const table = await conn.createTable("my_table", [{ i: 0 }]);
const branches = await table.branches();
const exp = await branches.create("exp");
await exp.add([{ i: 10 }]);
const expVersion = await exp.version();
await (await exp.tags()).create("exp-v2", expVersion);
// main reaches the same numeric version with different rows.
await table.add([{ i: 100 }]);
expect(await table.version()).toBe(expVersion);
const fromTag = await branches.create("from-tag", {
fromTag: "exp-v2",
});
expect(fromTag.currentBranch()).toBe("from-tag");
expect(await fromTag.countRows("i = 10")).toBe(1);
expect(await fromTag.countRows("i = 100")).toBe(0);
// The existing positional branch/version path keeps its ordering.
const positional = await branches.create("from-exp", "exp", expVersion);
expect(positional.currentBranch()).toBe("from-exp");
expect(await positional.countRows("i = 10")).toBe(1);
expect(await positional.countRows("i = 100")).toBe(0);
});
it("rejects fromTag combined with another source before main normalization", async () => {
const conn = await connect(tmpDir.name);
const table = await conn.createTable("my_table", [{ i: 0 }]);
await (await table.tags()).create("baseline");
const branches = await table.branches();
// fromRef="main" must not normalize the conflict away.
const mixedSources = { fromTag: "baseline", fromRef: "main" };
await expect(branches.create("conflict", mixedSources)).rejects.toThrow(
"fromTag cannot be combined",
);
// JavaScript callers can still pass the legacy version position.
const createWithLegacyVersion = branches.create.bind(branches) as (
name: string,
options: { fromTag: string },
fromVersion: number,
) => Promise<Table>;
await expect(
createWithLegacyVersion("conflict", { fromTag: "baseline" }, 1),
).rejects.toThrow("fromTag cannot be combined");
expect(await branches.list()).not.toHaveProperty("conflict");
});
it("hints at fromTag only for a missing Embedded branch", async () => {
const conn = await connect(tmpDir.name);
const table = await conn.createTable("my_table", [{ i: 0 }]);
const branches = await table.branches();
const base = await branches.create("base");
await base.add([{ i: 1 }]);
await (await table.tags()).create("baseline");
// A tag passed through fromRef keeps the original failure and gains a
// static hint without probing the ref again.
await expect(branches.create("missing", "baseline")).rejects.toThrow(
'branches.create("missing", { fromTag: "baseline" })',
);
// A missing version is not an unresolved branch, so it gets no hint.
const missingVersion = await branches
.create("missing-version", "base", 9999)
.then(
() => undefined,
(error: Error) => error,
);
expect(missingVersion?.message).toContain("9999");
expect(missingVersion?.message).not.toContain("fromTag");
});
});
/** Returns a Date strictly later than every instant observed before the call. */
+1
View File
@@ -164,6 +164,7 @@ export {
FunctionColumnStatus,
FunctionColumnVersionStatus,
Branches,
CreateBranchOptions,
BranchColumnSummary,
BranchColumnChange,
BranchIndexSummary,
+51 -1
View File
@@ -2297,6 +2297,17 @@ export interface CherryPickResult {
mainVersionAfter?: number;
}
/**
* Options for creating a branch from a named source.
*/
export interface CreateBranchOptions {
/**
* Tag to fork from. The tag keeps the branch and version it points to.
* Cannot be combined with `fromRef` or `fromVersion`.
*/
fromTag: string;
}
/**
* Branch manager for a {@link Table}.
*
@@ -2319,6 +2330,18 @@ export class Branches {
return await this.#inner.list();
}
/**
* Create a branch from a tag and return a handle scoped to it.
*
* @param name Name of the new branch.
* @param options Named source. `fromTag` keeps the tag's branch and version.
* @example
* ```typescript
* const branches = await table.branches();
* const branch = await branches.create("exp", { fromTag: "baseline" });
* ```
*/
async create(name: string, options: CreateBranchOptions): Promise<Table>;
/**
* Create a branch and return a handle scoped to it.
*
@@ -2330,8 +2353,35 @@ export class Branches {
name: string,
fromRef?: string,
fromVersion?: number,
): Promise<Table>;
async create(
name: string,
fromRefOrOptions?: string | CreateBranchOptions,
fromVersion?: number,
): Promise<Table> {
return new LocalTable(await this.#inner.create(name, fromRef, fromVersion));
if (typeof fromRefOrOptions === "object" && fromRefOrOptions !== null) {
// The public options shape only adds `fromTag`. Forward any runtime
// `fromRef`/`fromVersion` fields so the native check remains the single
// authority for rejecting mixed sources before `main` normalization.
const options = fromRefOrOptions as CreateBranchOptions & {
fromRef?: string;
fromVersion?: number;
};
if (typeof options.fromTag !== "string") {
throw new Error("branch source options must include fromTag");
}
return new LocalTable(
await this.#inner.create(
name,
options.fromRef,
fromVersion ?? options.fromVersion,
options.fromTag,
),
);
}
return new LocalTable(
await this.#inner.create(name, fromRefOrOptions, fromVersion),
);
}
/**
+69 -10
View File
@@ -20,7 +20,7 @@ use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use napi_derive::napi;
use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable};
use crate::error::NapiErrorExt;
use crate::error::{NapiErrorExt, convert_error};
use crate::index::Index;
use crate::job::JobFailureInfo;
use crate::merge::NativeMergeInsertBuilder;
@@ -2393,6 +2393,15 @@ pub struct BranchContents {
pub manifest_size: i64,
}
fn from_tag_hint(name: &str, tag: &str) -> String {
let name_literal = serde_json::Value::String(name.to_string()).to_string();
let tag_literal = serde_json::Value::String(tag.to_string()).to_string();
format!(
"If {tag_literal} is a tag, use branches.create({name_literal}, {{ fromTag: {tag_literal} }}) instead of fromRef."
)
}
/// Tags label table versions with human-readable names.
#[napi]
pub struct Tags {
inner: LanceDbTable,
@@ -2431,12 +2440,20 @@ impl Tags {
.default_error()
}
/// Create a tag for a table version.
///
/// Omit `version` to tag the version this handle currently shows,
/// including a checked-out version.
#[napi]
pub async unsafe fn create(&mut self, tag: String, version: i64) -> napi::Result<()> {
pub async unsafe fn create(&mut self, tag: String, version: Option<i64>) -> napi::Result<()> {
let version = match version {
Some(version) => version as u64,
None => self.inner.version().await.default_error()?,
};
let mut rust_tags = self.inner.tags().await.default_error()?;
rust_tags
.as_mut()
.create(tag.as_str(), version as u64)
.create(tag.as_str(), version)
.await
.default_error()
}
@@ -2494,7 +2511,18 @@ impl Branches {
name: String,
from_ref: Option<String>,
from_version: Option<i64>,
from_tag: Option<String>,
) -> napi::Result<Table> {
if from_tag.is_some() && (from_ref.is_some() || from_version.is_some()) {
return Err(napi::Error::from_reason(
"fromTag cannot be combined with fromRef or fromVersion; pass only one source",
));
}
let from_branch = if from_tag.is_none() {
from_ref.clone()
} else {
None
};
let from_ref = from_ref.filter(|b| b != "main");
let from_version = from_version
.map(|v| {
@@ -2503,13 +2531,27 @@ impl Branches {
})
})
.transpose()?;
let from = Ref::Version(from_ref, from_version);
let table = self
.inner
.create_branch(&name, from)
.await
.default_error()?;
Ok(Table::new(table))
let from = match from_tag {
Some(tag) => Ref::Tag(tag),
None => Ref::Version(from_ref, from_version),
};
match self.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 an Enterprise 404 is an ambiguous
// TableNotFound, so only the native branch case gets the hint.
let missing_branch = matches!(
&error,
lancedb::Error::Lance { source } if source.is_not_found()
);
let mut error = convert_error(&error);
if missing_branch && let Some(branch) = from_branch.as_deref() {
error.reason = format!("{}\n{}", error.reason, from_tag_hint(&name, branch));
}
Err(error)
}
}
}
#[napi]
@@ -2557,3 +2599,20 @@ impl Branches {
})
}
}
#[cfg(test)]
mod tests {
use super::from_tag_hint;
#[test]
fn from_tag_hint_uses_escaped_javascript_string_literals() {
assert_eq!(
from_tag_hint("exp", "baseline"),
r#"If "baseline" is a tag, use branches.create("exp", { fromTag: "baseline" }) instead of fromRef."#
);
assert_eq!(
from_tag_hint("branch\"name\\path", "tag\"name\\path"),
r#"If "tag\"name\\path" is a tag, use branches.create("branch\"name\\path", { fromTag: "tag\"name\\path" }) instead of fromRef."#
);
}
}