Repository navigation
Branching from historical commits - #1199
Conversation
aaj3f
left a comment
There was a problem hiding this comment.
This is really cool. All the capability re: branching is just getting cooler and cooler. Really want to start using it for things like provisional CAM output extensions to a dataset or with ITM-like ontology revisions as mergable, propositional branches
There was a problem hiding this comment.
Super super trivial, but given the other rename / concept changes e.g. with_previous_ref to with_parent, and previous_refs to parents, perhaps this should be MAX_PARENTS
| /// Verify `target` is reachable by walking parents from `source_head`, and | ||
| /// return its `t` value. | ||
| /// | ||
| /// Used by `create_branch` when a caller specifies a historical commit — we | ||
| /// only allow branching from commits on the source branch's ancestry. | ||
| /// Loads only the target commit's envelope (not its flakes) since we just | ||
| /// need `t` for the ancestry walk's stop condition. | ||
| async fn verify_ancestor<C: ContentStore + ?Sized>( | ||
| store: &C, | ||
| source_head: &CommitId, | ||
| target: &CommitId, | ||
| ) -> Result<i64> { | ||
| let target_envelope = load_commit_envelope_by_id(store, target) | ||
| .await | ||
| .map_err(|_| { | ||
| ApiError::NotFound(format!("commit {target} not found in source namespace")) | ||
| })?; | ||
|
|
||
| if source_head == target { | ||
| return Ok(target_envelope.t); | ||
| } | ||
|
|
||
| // Walk backward from source_head, stopping once we pass below target's t. | ||
| let stop_at = (target_envelope.t - 1).max(0); | ||
| let dag = collect_dag_cids(store, source_head, stop_at).await?; | ||
|
|
||
| if dag.iter().any(|(_, cid)| cid == target) { | ||
| Ok(target_envelope.t) | ||
| } else { | ||
| Err(ApiError::NotFound(format!( | ||
| "commit {target} is not an ancestor of source head {source_head}" | ||
| ))) | ||
| } | ||
| } |
There was a problem hiding this comment.
This is a question not a suggestion, but collect_dag_cids() follows all parent CIDs, right? not just the linear first-parent? Assuming that's correct, this all makes sense to me vis-a-vis your updates to docs and from the PR description, but just wondering if maybe some code-internal clarity is worth baking in (whether that be inline comment(s), additions to the signature doc comment). It's really cool (and load-bearing) for your work here that you can historically branch at a commit that's on any number of parent branches and not just on the linear branch, but just want to make sure wrong-headed assumptions aren't made moving forward when looking, for example, at this function's logic
Summary
Adds support for creating a branch at any historical commit on the source branch, not just its current HEAD. Exposed through the Rust API (
Fluree::create_branch), the CLI (fluree branch create --at <ref>), and the HTTP endpoint (POST /v1/fluree/branchwith anatfield). Includes several supporting refactors in the commit, ledger, and nameservice layers that the feature builds on top of.Motivation
Today, a new branch always starts at the source branch's current HEAD. This PR lets callers branch at an earlier point — useful for recovering to a known-good state, forking off an older release, or running what-if experiments from a past transaction. The commit must still be reachable from the source branch's HEAD (branching from unrelated history is rejected).
What's in this PR
Feature: historical commit branching
A new
CommitRefenum influree-db-api::ledger_viewdescribes the three user-facing ways to identify a commit — an exactCommitId, a hex-digest prefix (with optionalfluree:commit:/sha256:prefix stripping), or a transaction numbert.CommitRef::parseproduces the right variant from a user-supplied string, including multibase CID strings (e.g.,"bafybei…") which skip the lookup and go straight toExact.LedgerView::resolve_committurns aCommitRefinto a canonicalCommitIdagainst the view's indexes and novelty overlay. TheTandPrefixresolvers (moved out ofgraph_commit_builder.rssince they're now shared) both detect ambiguity — if a rebased ledger has multiple commits at the samet, the user gets an actionable error rather than a silent wrong answer.Fluree::create_branchgains a fourth parametersource_commit: Option<CommitRef>:None(default) → behaves exactly as before: branch starts at the source's HEAD and inherits its index (copied into the new branch's namespace).Some(ref)→ the ref is resolved, verified to be an ancestor of the source HEAD via a parent-walk, and becomes the new branch's starting commit. The index is not copied (the source's index reflects its current HEAD, not the historical branch point); the new branch replays from genesis on first query.A
CommitRefthat resolves to the source HEAD is collapsed to theNonepath so--at <head-cid>still produces an index copy rather than silently producing a slower branch than omitting--at.The nameservice
create_branchtrait method gains anat_commit: Option<(ContentId, i64)>parameter.Noneuses the source record's head info as before;Some((cid, t))uses the caller-supplied pair (ancestry verification is the caller's responsibility). All implementations (file,memory,storage_ns,dynamodb,notifying,proxy) are updated.Refactors bundled in
CommitRefstruct →CommitIdalias. The oldCommitRef { id: ContentId }wrapper provided no value beyond whatContentIdalready offered. It's removed; the new publicCommitRefname is reused by the enum. Wire format is preserved — the flag bit (0x02) and the length-prefixed CID encoding are unchanged; only internal symbol names shift (FLAG_PREVIOUS_REF→FLAG_PARENT,encode_commit_ref→encode_commit_id). Old commits deserialize fine.previous_refs→parents. On bothCommitandCommitEnvelope,Vec<CommitRef>becomesVec<CommitId>. Method renames:with_previous_ref→with_parent,previous_refs→parents. Terminology now matches standard DAG vocabulary.LedgerView/StagedLedgernaming swap. Two types were previously both calledLedgerView, one influree-db-ledger(staged-transaction overlay) and a related concept (CachedLedgerState) influree-db-api. Post-rename:fluree-db-ledger::StagedLedger= base + staged flakes, queryable before commit.fluree-db-api::LedgerView= read-only snapshot of a ledger at a point in time (Arc-shared fields, safe to hold across.await, ownsresolve_commit).The two concepts are now clearly distinct and the common
LedgerViewname goes to the snapshot type that user code actually interacts with.Tracking record field renames.
TrackingRecord.commit_ref/index_ref→commit_head/index_head, matching thehead_commit_id/head_index_idnaming inLedgerView.HTTP handler renames.
push_commit_ref/push_index_ref→push_commit_head/push_index_headfor the/nameservice/refs/:alias/{commit,index}endpoints.Public API changes
Rust
HTTP
Status codes:
201 Created— branch created.400 Bad Request— malformedatvalue (e.g.,"t:notanumber").404 Not Found— source branch missing, oratcommit not reachable from source HEAD.409 Conflict— branch already exists.CLI
--ataccepts the same forms as the HTTPatfield. Examples:Design decisions worth calling out
Historical branches replay from genesis. The source's current index reflects its current HEAD, which is strictly newer than the historical branch point. Pointing the new branch at it would give queries the wrong answers. Copying a matching historical index snapshot isn't free (and isn't always possible — old index roots may have been GC'd), so the design ships a conservative "no index, replay from genesis" strategy. Acceptable for small/medium histories; if replay cost matters for a given workload, a no-op transaction on the new branch forces an index rebuild.
Ancestry is verified before touching the nameservice.
verify_ancestorwalks parents backward from the source HEAD usingcollect_dag_cidswith a stop condition oftarget.t - 1, checking that the resolved commit appears in the walk. Short-circuits onsource_head == target. Only loads the target commit's envelope (not its flakes) since we just needt.CommitRef::Tdetects ambiguity. A rebased ledger leaves flakes from both the old and new chains in the POST index, so a naive "return the first match" resolver would silently return either commit — leading to a downstream "not an ancestor" error that doesn't point at the actual problem. The resolver now mirrors the prefix resolver's 0/1/N logic and returns an explicit ambiguous error pointing the user at using a full CID.Resolver is novelty-aware. Both resolvers use
range_*_with_overlay, so commits from transactions that haven't been indexed yet are still findable — the "commit then immediately branch at t:N" path works without forcing an indexer run.Test coverage
New tests:
fluree-db-api/tests/it_branch.rs— four new integration tests covering eachCommitRefvariant (Exact,T,Prefix) at happy path, plus rejection of a non-ancestor commit.fluree-db-server/tests/integration.rs— new HTTP integration test that drivesPOST /v1/fluree/branchwith"at": "t:2"and also asserts400for"t:notanumber".fluree-db-api/src/ledger_view.rs— unit testparse_full_multibase_cid_produces_exactlocking in the parse path for base32-multibase CID strings.Existing tests in
it_branch.rs,it_merge.rs,it_rebase.rs, andit_tutorial_end_to_end.rsupdated to passNonefor the newsource_commitparameter. All 17it_branchtests, the new unit test, and the server integration test pass.Backwards compatibility
0x02and the CID encoding stayed the same.Fluree::create_branchsignature changed. Callers must add aNoneargument. TheNameServicetrait gained a parameter; all in-tree impls updated. External impls ofNameServicewill need the same update.atfield is optional; existing clients are unaffected.--atflag is optional; existing invocations are unaffected.