From 76c8bf335a44a4819c5eef82b67da985a9fec9fb Mon Sep 17 00:00:00 2001 From: "Tomwang.eth" Date: Tue, 1 Dec 2026 09:29:44 +0000 Subject: [PATCH] fix: expose branch create_at and metadata in branches.list() for node and python (#4914) Fixes #4849. **Problem** - TypeScript SDK: `Branches.list()` returned napi class instances whose fields live on the prototype, so `console.log`, spread and `JSON.stringify` showed `{}` (the exact symptom in the docs example). `create_at` and `metadata`, which Lance already stores for every branch, were not exposed at all. - Python SDK: the `Branches.list()` dicts also dropped `create_at` and `metadata`. **Change** - `nodejs/src/table.rs`: `BranchContents` stays a runtime napi class export and gains `create_at` (Unix seconds) and `metadata`, populated from the stored Lance branch contents. The `metadata` getter defines every key as an own enumerable data property (`napi_define_properties`), so keys like `__proto__` that ordinary map conversion would route to the prototype setter are preserved. - `nodejs/lancedb/table.ts`: the `Branches.list()` wrapper promotes all fields (`parentBranch`, `parentVersion`, `createAt`, `manifestSize`, `metadata`) to own enumerable properties on each returned instance by reusing the class getters and setters, so spread and `JSON.stringify` see them while `instanceof` keeps working. Its return type is `ListedBranchContents`, which guarantees `createAt` and `metadata`. - Public typing: the exported `BranchContents` type keeps its released shape (`parentBranch`/`parentVersion`/`manifestSize` only), so values and interfaces written against it stay assignable and extendable, including a view whose `createAt` is a `Date` and an interface that extends `BranchContents` with its own `metadata`. `ListedBranchContents extends BranchContents` adds `createAt` and `metadata` as required fields, and the exported `BranchContents` constructor value has its `prototype` typed as `BranchContents`, so the class value and `instanceof` checks are unchanged. - `python/src/table.rs`: `Branches.list()` dicts now include `create_at` and `metadata`. - Docs: regenerated TypeScript API reference for the new shape, and the branching guide now documents `createAt`/`create_at` (Unix seconds) and `metadata`. **Tests** - `nodejs/__test__/table.test.ts`: a branch whose stored ref file carries non-empty metadata (including a `__proto__` key) and a known creation time in Unix seconds is listed with both, as a `BranchContents` instance with own enumerable fields, surviving spread and a JSON round-trip with every metadata key intact. A second test covers the consumer type contracts with `tsc`: a released-shape value with an extra `createAt: Date` stays assignable to `BranchContents`, an interface extending `BranchContents` can declare its own `metadata` shape, the exported constructor's `prototype` is typed as `BranchContents`, and `branches.list()` results guarantee `createAt` and `metadata`. - `python/python/tests/test_table.py::test_branches`: same non-empty-metadata (with `__proto__`) and known-`create_at` coverage. - Verified locally on Linux x86_64: `tsc -b`, Biome checks, regenerated docs diff limited to the `BranchContents` pages, node branches suite (34 passed), python `test_branches` (4 passed, 1 skipped). --------- Co-authored-by: tomwangcn --- docs/src/js/classes/BranchContents.md | 43 ------- docs/src/js/classes/Branches.md | 7 +- docs/src/js/globals.md | 7 +- docs/src/js/interfaces/BranchContents.md | 47 ++++++++ .../src/js/interfaces/ListedBranchContents.md | 76 ++++++++++++ docs/src/js/variables/BranchContents.md | 22 ++++ docs/web/tables/branching.mdx | 5 +- nodejs/__test__/table.test.ts | 108 ++++++++++++++++++ nodejs/lancedb/index.ts | 3 +- nodejs/lancedb/table.ts | 58 +++++++++- nodejs/src/table.rs | 82 +++++++++++++ python/python/tests/test_table.py | 16 +++ python/src/table.rs | 2 + 13 files changed, 424 insertions(+), 52 deletions(-) delete mode 100644 docs/src/js/classes/BranchContents.md create mode 100644 docs/src/js/interfaces/BranchContents.md create mode 100644 docs/src/js/interfaces/ListedBranchContents.md create mode 100644 docs/src/js/variables/BranchContents.md diff --git a/docs/src/js/classes/BranchContents.md b/docs/src/js/classes/BranchContents.md deleted file mode 100644 index 47339d7ab..000000000 --- a/docs/src/js/classes/BranchContents.md +++ /dev/null @@ -1,43 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / BranchContents - -# Class: BranchContents - -## Constructors - -### new BranchContents() - -```ts -new BranchContents(): BranchContents -``` - -#### Returns - -[`BranchContents`](BranchContents.md) - -## Properties - -### manifestSize - -```ts -manifestSize: number; -``` - -*** - -### parentBranch? - -```ts -optional parentBranch: string; -``` - -*** - -### parentVersion - -```ts -parentVersion: number; -``` diff --git a/docs/src/js/classes/Branches.md b/docs/src/js/classes/Branches.md index 4e154e30f..b8b59ec81 100644 --- a/docs/src/js/classes/Branches.md +++ b/docs/src/js/classes/Branches.md @@ -158,11 +158,14 @@ Compare a branch against main without modifying either branch. ### list() ```ts -list(): Promise> +list(): Promise> ``` List all branches, mapping name to branch metadata. +Every entry always carries `createAt` (the branch creation time in Unix +seconds) and `metadata` (a string map), in addition to the fork source. + #### Returns -`Promise`<`Record`<`string`, [`BranchContents`](BranchContents.md)>> +`Promise`<`Record`<`string`, [`ListedBranchContents`](../interfaces/ListedBranchContents.md)>> diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 975419abd..08c534513 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -23,7 +23,6 @@ - [BlobFile](classes/BlobFile.md) - [BooleanQuery](classes/BooleanQuery.md) - [BoostQuery](classes/BoostQuery.md) -- [BranchContents](classes/BranchContents.md) - [Branches](classes/Branches.md) - [Catalog](classes/Catalog.md) - [ColumnAlreadyExistsError](classes/ColumnAlreadyExistsError.md) @@ -100,6 +99,7 @@ - [BloomFilterOptions](interfaces/BloomFilterOptions.md) - [BranchColumnChange](interfaces/BranchColumnChange.md) - [BranchColumnSummary](interfaces/BranchColumnSummary.md) +- [BranchContents](interfaces/BranchContents.md) - [BranchDiff](interfaces/BranchDiff.md) - [BranchIndexSummary](interfaces/BranchIndexSummary.md) - [BranchRowCountSummary](interfaces/BranchRowCountSummary.md) @@ -171,6 +171,7 @@ - [JobProgress](interfaces/JobProgress.md) - [JobWaitOptions](interfaces/JobWaitOptions.md) - [LanceErrorOptions](interfaces/LanceErrorOptions.md) +- [ListedBranchContents](interfaces/ListedBranchContents.md) - [ListingOptions](interfaces/ListingOptions.md) - [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md) - [MemtableStats](interfaces/MemtableStats.md) @@ -259,6 +260,10 @@ - [TableLike](type-aliases/TableLike.md) - [TokenizeTableOptions](type-aliases/TokenizeTableOptions.md) +## Variables + +- [BranchContents](variables/BranchContents.md) + ## Functions - [RecordBatchIterator](functions/RecordBatchIterator.md) diff --git a/docs/src/js/interfaces/BranchContents.md b/docs/src/js/interfaces/BranchContents.md new file mode 100644 index 000000000..962a517b4 --- /dev/null +++ b/docs/src/js/interfaces/BranchContents.md @@ -0,0 +1,47 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BranchContents + +# Interface: BranchContents + +Contents of a table branch. + +This is the shape released in 0.41.0. Newer fields exposed by +[Branches.list](../classes/Branches.md#list) are declared on [ListedBranchContents](ListedBranchContents.md) so that +values and interfaces written against the released shape remain assignable. + +## Extended by + +- [`ListedBranchContents`](ListedBranchContents.md) + +## Properties + +### manifestSize + +```ts +manifestSize: number; +``` + +Size in bytes of the branch's manifest file. + +*** + +### parentBranch? + +```ts +optional parentBranch: string; +``` + +Branch this branch was forked from. Absent for direct forks of `main`. + +*** + +### parentVersion + +```ts +parentVersion: number; +``` + +Version on the parent branch this branch was forked from. diff --git a/docs/src/js/interfaces/ListedBranchContents.md b/docs/src/js/interfaces/ListedBranchContents.md new file mode 100644 index 000000000..7ecca6abc --- /dev/null +++ b/docs/src/js/interfaces/ListedBranchContents.md @@ -0,0 +1,76 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / ListedBranchContents + +# Interface: ListedBranchContents + +Branch contents as returned by [Branches.list](../classes/Branches.md#list), with the newer +`createAt` and `metadata` fields guaranteed to be present. + +## Extends + +- [`BranchContents`](BranchContents.md) + +## Properties + +### createAt + +```ts +createAt: number; +``` + +Branch creation time in Unix seconds. + +*** + +### manifestSize + +```ts +manifestSize: number; +``` + +Size in bytes of the branch's manifest file. + +#### Inherited from + +[`BranchContents`](BranchContents.md).[`manifestSize`](BranchContents.md#manifestsize) + +*** + +### metadata + +```ts +metadata: Record; +``` + +Application-defined string metadata. + +*** + +### parentBranch? + +```ts +optional parentBranch: string; +``` + +Branch this branch was forked from. Absent for direct forks of `main`. + +#### Inherited from + +[`BranchContents`](BranchContents.md).[`parentBranch`](BranchContents.md#parentbranch) + +*** + +### parentVersion + +```ts +parentVersion: number; +``` + +Version on the parent branch this branch was forked from. + +#### Inherited from + +[`BranchContents`](BranchContents.md).[`parentVersion`](BranchContents.md#parentversion) diff --git a/docs/src/js/variables/BranchContents.md b/docs/src/js/variables/BranchContents.md new file mode 100644 index 000000000..ede7a8e87 --- /dev/null +++ b/docs/src/js/variables/BranchContents.md @@ -0,0 +1,22 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BranchContents + +# Variable: BranchContents + +```ts +BranchContents: () => BranchContents & object; +``` + +Runtime class of the branch contents returned by [Branches.list](../classes/Branches.md#list). +Returned instances pass `instanceof BranchContents` checks. + +## Type declaration + +### prototype + +```ts +prototype: BranchContents; +``` diff --git a/docs/web/tables/branching.mdx b/docs/web/tables/branching.mdx index 9edd7c669..15a7c2005 100644 --- a/docs/web/tables/branching.mdx +++ b/docs/web/tables/branching.mdx @@ -152,7 +152,10 @@ snapshot. Writes go through the branch handle and stay there: the `main` handle keeps reporting its original row count. Listing branches returns a mapping of each -branch name to its metadata, including the version it was forked from. +branch name to its metadata, including the version it was forked from. Each +entry also carries the branch creation time in Unix seconds (`createAt` in +TypeScript, `create_at` in Python) and a string map of application-defined +`metadata`. diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index a77c6b44e..9e5d74608 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -11,6 +11,7 @@ import { AutoQuery, type BlobInput, type BlobMode, + BranchContents, type CompactionOptions, Connection, MatchQuery, @@ -4362,6 +4363,113 @@ describe("when dealing with branches", () => { tmpDir.removeCallback(); }); + it("returns serializable BranchContents instances from list()", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("my_table", [{ i: 0 }]); + const branches = await table.branches(); + await branches.create("exp"); + + // No SDK writes branch metadata yet, so give the stored ref file + // non-empty metadata and a known creation time in Unix seconds. + const refPath = path.join( + tmpDir.name, + "my_table.lance", + "_refs", + "branches", + "exp.json", + ); + const stored = JSON.parse(fs.readFileSync(refPath, "utf8")); + stored.metadata = { owner: "test", ["__proto__"]: "kept" }; + stored.createAt = 1700000000; + fs.writeFileSync(refPath, JSON.stringify(stored)); + + const list = await branches.list(); + const exp = list["exp"]; + + // The runtime class export and instance identity are preserved. + expect(exp).toBeInstanceOf(BranchContents); + + // All fields are own enumerable properties, so spread and JSON + // serialization see them. + expect(Object.keys(exp)).toEqual( + expect.arrayContaining([ + "parentBranch", + "parentVersion", + "createAt", + "manifestSize", + "metadata", + ]), + ); + expect({ ...exp }.createAt).toBe(1700000000); + + const serialized = JSON.parse(JSON.stringify(list)); + expect(serialized["exp"].createAt).toBe(1700000000); + expect(serialized["exp"].metadata).toEqual({ + owner: "test", + ["__proto__"]: "kept", + }); + expect(serialized["exp"].manifestSize).toBeGreaterThan(0); + expect(serialized["exp"].parentBranch).toBeNull(); + + // `__proto__` survives the binding conversion as an own data property + // instead of being swallowed by the prototype setter. + const metadata = exp.metadata; + // The key did not go through the prototype setter ... + expect(Object.getPrototypeOf(metadata)).not.toBe("kept"); + // ... and exists as an own data property. + expect( + Object.getOwnPropertyDescriptor(metadata, "__proto__"), + ).toMatchObject({ value: "kept", enumerable: true, writable: true }); + const roundTripped = JSON.parse(JSON.stringify(metadata)); + expect( + Object.getOwnPropertyDescriptor(roundTripped, "__proto__")?.value, + ).toBe("kept"); + }); + + it("keeps the BranchContents type assignable from the released shape", async () => { + // Compile-time contract: values typed against 0.41.0/0.42.0-beta.x, which + // only exposed parentBranch/parentVersion/manifestSize, still satisfy the + // exported type. + const legacy: BranchContents = { + parentVersion: 3, + manifestSize: 128, + }; + expect(legacy.parentVersion).toBe(3); + expect(legacy.parentBranch).toBeUndefined(); + + // Callers may carry extra fields of any type: the released shape has no + // createAt/metadata, so nothing constrains them. + const view = { parentVersion: 1, manifestSize: 512, createAt: new Date() }; + const branch: BranchContents = view; + expect(branch.manifestSize).toBe(512); + + interface AnnotatedBranch extends BranchContents { + metadata: { priority: number }; + } + const annotated: AnnotatedBranch = { + parentVersion: 2, + manifestSize: 64, + metadata: { priority: 1 }, + }; + expect(annotated.metadata.priority).toBe(1); + + // The exported constructor's prototype stays typed as BranchContents. + const proto: BranchContents = BranchContents.prototype; + expect(typeof proto).toBe("object"); + + // branches.list() still guarantees both newer fields, in its return type + // and at runtime. + const conn = await connect(tmpDir.name); + const table = await conn.createTable("my_table", [{ i: 0 }]); + const branches = await table.branches(); + await branches.create("exp"); + const exp = (await branches.list())["exp"]; + const createAt: number = exp.createAt; + const metadata: Record = exp.metadata; + expect(createAt).toBeGreaterThan(0); + expect(metadata).toEqual({}); + }); + it("reads cross-branch tags without redirecting writes or restores", async () => { const conn = await connect(tmpDir.name, { readConsistencyInterval: 0 }); const main = await conn.createTable("tag_branch", [{ i: 0 }]); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 7aa8bd0eb..3ea261e39 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -54,7 +54,6 @@ export { FragmentSummaryStats, Tags, TagContents, - BranchContents, MergeResult, AddResult, AddColumnsResult, @@ -86,6 +85,8 @@ export { OAuthConfig as NativeOAuthConfig, } from "./native.js"; +export { BranchContents, ListedBranchContents } from "./table"; + export { makeArrowTable, makeJsonField, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index cad41fb48..a255df807 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -62,7 +62,6 @@ import { AddColumnsSql, AddResult, AlterColumnsResult, - BranchContents, DeleteResult, DropColumnsResult, FunctionErrors, @@ -74,6 +73,7 @@ import { IndexStatistics, JobFailureInfo, RecordBatchIterator as NativeBatchIterator, + BranchContents as NativeBranchContents, Branches as NativeBranches, DeltaRef as NativeDeltaRef, TableDelta as NativeTableDelta, @@ -2972,6 +2972,41 @@ class TableDeltaReaderImpl implements TableDeltaReader { } } +/** + * Contents of a table branch. + * + * This is the shape released in 0.41.0. Newer fields exposed by + * {@link Branches.list} are declared on {@link ListedBranchContents} so that + * values and interfaces written against the released shape remain assignable. + */ +export interface BranchContents { + /** Branch this branch was forked from. Absent for direct forks of `main`. */ + parentBranch?: string; + /** Version on the parent branch this branch was forked from. */ + parentVersion: number; + /** Size in bytes of the branch's manifest file. */ + manifestSize: number; +} + +/** + * Branch contents as returned by {@link Branches.list}, with the newer + * `createAt` and `metadata` fields guaranteed to be present. + */ +export interface ListedBranchContents extends BranchContents { + /** Branch creation time in Unix seconds. */ + createAt: number; + /** Application-defined string metadata. */ + metadata: Record; +} + +/** + * Runtime class of the branch contents returned by {@link Branches.list}. + * Returned instances pass `instanceof BranchContents` checks. + */ +export const BranchContents: (new () => BranchContents) & { + prototype: BranchContents; +} = NativeBranchContents; + /** * Branch manager for a {@link Table}. * @@ -2989,9 +3024,24 @@ export class Branches { this.#inner = bindErrorTranslator(inner); } - /** List all branches, mapping name to branch metadata. */ - async list(): Promise> { - return await this.#inner.list(); + /** + * List all branches, mapping name to branch metadata. + * + * Every entry always carries `createAt` (the branch creation time in Unix + * seconds) and `metadata` (a string map), in addition to the fork source. + */ + async list(): Promise> { + const branches = await this.#inner.list(); + for (const contents of Object.values(branches)) { + exposeOwnAccessors(contents, [ + "parentBranch", + "parentVersion", + "createAt", + "manifestSize", + "metadata", + ]); + } + return branches; } /** diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 536be3cd5..ecc393993 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -2746,7 +2746,87 @@ pub struct TagContents { pub struct BranchContents { pub parent_branch: Option, pub parent_version: i64, + /// Branch creation time in Unix seconds. + pub create_at: i64, pub manifest_size: i64, + metadata: HashMap, +} + +#[napi] +impl BranchContents { + /// Application-defined string metadata stored with the branch. + /// + /// Every key is preserved, including keys like `__proto__` that ordinary + /// object assignment would route to the prototype setter. + #[napi(getter, ts_return_type = "Record")] + pub fn metadata(&self, env: Env) -> napi::Result> { + let raw_env = env.raw(); + let mut raw_obj = std::ptr::null_mut(); + unsafe { + napi::check_status!( + napi::sys::napi_create_object(raw_env, &mut raw_obj), + "Failed to create metadata object" + )?; + } + for (key, value) in &self.metadata { + define_own_data_property(raw_env, raw_obj, key, value)?; + } + Ok(Object::from_raw(raw_env, raw_obj)) + } + + #[napi(setter)] + pub fn set_metadata(&mut self, metadata: HashMap) { + self.metadata = metadata; + } +} + +/// Defines `key` as an own enumerable data property holding `value`. +/// +/// napi-rs converts maps with `napi_set_property`, whose `[[Set]]` semantics +/// send a `__proto__` key to the prototype setter and drop it from the +/// object's own keys. `napi_define_properties` uses `[[DefineOwnProperty]]`, +/// which keeps every key. +fn define_own_data_property( + raw_env: napi::sys::napi_env, + raw_obj: napi::sys::napi_value, + key: &str, + value: &str, +) -> napi::Result<()> { + use napi::sys; + use std::ffi::CString; + use std::ptr; + + let key_c = + CString::new(key).map_err(|e| napi::Error::new(napi::Status::InvalidArg, e.to_string()))?; + unsafe { + let mut raw_value = ptr::null_mut(); + napi::check_status!( + sys::napi_create_string_utf8( + raw_env, + value.as_ptr().cast(), + value.len() as isize, + &mut raw_value + ), + "Failed to create metadata value" + )?; + let descriptor = sys::napi_property_descriptor { + utf8name: key_c.as_ptr(), + name: ptr::null_mut(), + method: None, + getter: None, + setter: None, + value: raw_value, + attributes: sys::PropertyAttributes::enumerable + | sys::PropertyAttributes::writable + | sys::PropertyAttributes::configurable, + data: ptr::null_mut(), + }; + napi::check_status!( + sys::napi_define_properties(raw_env, raw_obj, 1, &descriptor), + "Failed to define metadata property" + )?; + } + Ok(()) } fn from_tag_hint(name: &str, tag: &str) -> String { @@ -2922,7 +3002,9 @@ impl Branches { BranchContents { parent_branch: v.parent_branch, parent_version: v.parent_version as i64, + create_at: v.create_at as i64, manifest_size: v.manifest_size as i64, + metadata: v.metadata, }, ) }) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index b99a90df3..aae471070 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1996,6 +1996,22 @@ def test_branches(tmp_path): branches = table.branches.list() assert "exp" in branches assert branches["exp"]["parent_branch"] is None + assert branches["exp"]["create_at"] > 0 + assert branches["exp"]["metadata"] == {} + + # No SDK writes branch metadata yet, so give the stored ref file + # non-empty metadata and a known creation time in Unix seconds. + ref_path = tmp_path / "test.lance" / "_refs" / "branches" / "exp.json" + stored = json.loads(ref_path.read_text()) + stored["metadata"] = {"owner": "test", "__proto__": "kept"} + stored["createAt"] = 1700000000 + ref_path.write_text(json.dumps(stored)) + + branches = table.branches.list() + assert branches["exp"]["create_at"] == 1700000000 + # every metadata key survives, including "__proto__" + assert branches["exp"]["metadata"] == {"owner": "test", "__proto__": "kept"} + assert branches["exp"]["manifest_size"] > 0 # from_ref="main" is equivalent to the default table.branches.create("exp2", from_ref="main") diff --git a/python/src/table.rs b/python/src/table.rs index d4174e591..013b75785 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -3583,7 +3583,9 @@ impl Branches { let value = PyDict::new(py); value.set_item("parent_branch", contents.parent_branch)?; value.set_item("parent_version", contents.parent_version)?; + value.set_item("create_at", contents.create_at)?; value.set_item("manifest_size", contents.manifest_size)?; + value.set_item("metadata", contents.metadata)?; py_dict.set_item(name, value)?; } Ok(py_dict.unbind())