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 <tomwangcn@users.noreply.github.com>
This commit is contained in:
Tomwang.eth
2026-12-01 17:29:44 +08:00
committed by GitHub
co-authored by tomwangcn
parent a85cb92ffd
commit 76c8bf335a
13 changed files with 424 additions and 52 deletions
+108
View File
@@ -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<string, string> = 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 }]);
+2 -1
View File
@@ -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,
+54 -4
View File
@@ -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<string, string>;
}
/**
* 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<Record<string, BranchContents>> {
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<Record<string, ListedBranchContents>> {
const branches = await this.#inner.list();
for (const contents of Object.values(branches)) {
exposeOwnAccessors(contents, [
"parentBranch",
"parentVersion",
"createAt",
"manifestSize",
"metadata",
]);
}
return branches;
}
/**
+82
View File
@@ -2746,7 +2746,87 @@ pub struct TagContents {
pub struct BranchContents {
pub parent_branch: Option<String>,
pub parent_version: i64,
/// Branch creation time in Unix seconds.
pub create_at: i64,
pub manifest_size: i64,
metadata: HashMap<String, String>,
}
#[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<string, string>")]
pub fn metadata(&self, env: Env) -> napi::Result<Object<'static>> {
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<String, String>) {
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,
},
)
})