Skip to content

Branching from historical commits - #1199

Merged
zonotope merged 22 commits into
mainfrom
feature/historical-branches
Apr 29, 2026
Merged

zonotope merged 22 commits into
mainfrom
feature/historical-branches

Conversation

@zonotope

Copy link
Copy Markdown
Contributor

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/branch with an at field). 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 CommitRef enum in fluree-db-api::ledger_view describes the three user-facing ways to identify a commit — an exact CommitId, a hex-digest prefix (with optional fluree:commit: / sha256: prefix stripping), or a transaction number t. CommitRef::parse produces the right variant from a user-supplied string, including multibase CID strings (e.g., "bafybei…") which skip the lookup and go straight to Exact.

LedgerView::resolve_commit turns a CommitRef into a canonical CommitId against the view's indexes and novelty overlay. The T and Prefix resolvers (moved out of graph_commit_builder.rs since they're now shared) both detect ambiguity — if a rebased ledger has multiple commits at the same t, the user gets an actionable error rather than a silent wrong answer.

Fluree::create_branch gains a fourth parameter source_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 CommitRef that resolves to the source HEAD is collapsed to the None path so --at <head-cid> still produces an index copy rather than silently producing a slower branch than omitting --at.

The nameservice create_branch trait method gains an at_commit: Option<(ContentId, i64)> parameter. None uses 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

CommitRef struct → CommitId alias. The old CommitRef { id: ContentId } wrapper provided no value beyond what ContentId already offered. It's removed; the new public CommitRef name 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 both Commit and CommitEnvelope, Vec<CommitRef> becomes Vec<CommitId>. Method renames: with_previous_ref → with_parent, previous_refs → parents. Terminology now matches standard DAG vocabulary.

LedgerView / StagedLedger naming swap. Two types were previously both called LedgerView, one in fluree-db-ledger (staged-transaction overlay) and a related concept (CachedLedgerState) in fluree-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, owns resolve_commit).

The two concepts are now clearly distinct and the common LedgerView name 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 the head_commit_id / head_index_id naming in LedgerView.

HTTP handler renames. push_commit_ref / push_index_ref → push_commit_head / push_index_head for the /nameservice/refs/:alias/{commit,index} endpoints.

Public API changes

Rust

// New
pub enum CommitRef {
    Exact(CommitId),
    Prefix(String),
    T(i64),
}

impl CommitRef {
    pub fn parse(s: &str) -> Result<Self>;
}

pub struct LedgerView { /* ... */ }
impl LedgerView {
    pub async fn resolve_commit(&self, commit_ref: CommitRef) -> Result<CommitId>;
    pub fn ledger_id(&self) -> Option<&str>;
    pub fn name(&self) -> Option<&str>;
    pub fn index_t(&self) -> i64;
    pub fn to_ledger_state(self) -> LedgerState;
}

// Changed signature — existing callers pass `None` for the new parameter
pub async fn Fluree::create_branch(
    &self,
    ledger_name: &str,
    new_branch: &str,
    source_branch: Option<&str>,
    source_commit: Option<CommitRef>,  // NEW
) -> Result<NsRecord>;

// Changed trait (NameService) — new parameter
async fn create_branch(
    &self,
    ledger_name: &str,
    new_branch: &str,
    source_branch: &str,
    at_commit: Option<(ContentId, i64)>,  // NEW
) -> Result<()>;

// Renamed
fluree_db_ledger::LedgerView → fluree_db_ledger::StagedLedger
LedgerView::stage(...) → StagedLedger::new(...)
fluree_db_api::CachedLedgerState → fluree_db_api::LedgerView
Commit::with_previous_ref(CommitRef) → Commit::with_parent(CommitId)
Commit.previous_refs: Vec<CommitRef> → Commit.parents: Vec<CommitId>
CommitEnvelope.previous_refs → CommitEnvelope.parents
TrackingRecord.commit_ref → TrackingRecord.commit_head
TrackingRecord.index_ref → TrackingRecord.index_head

// Removed (public)
pub struct CommitRef { pub id: ContentId }  // zero-value wrapper, replaced by CommitId alias

HTTP

POST /v1/fluree/branch
{
  "ledger": "mydb",
  "branch": "feature-x",
  "source": "main",          // optional, defaults to "main"
  "at": "t:5"                // NEW: optional; accepts "t:N", hex prefix, or full CID
}

Status codes:

  • 201 Created — branch created.
  • 400 Bad Request — malformed at value (e.g., "t:notanumber").
  • 404 Not Found — source branch missing, or at commit not reachable from source HEAD.
  • 409 Conflict — branch already exists.

CLI

fluree branch create <NAME> [--from <BRANCH>] [--at <COMMIT-REF>]

--at accepts the same forms as the HTTP at field. Examples:

fluree branch create rewind --at t:5
fluree branch create rewind --at 3dd028a7
fluree branch create rewind --at bafybei...

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_ancestor walks parents backward from the source HEAD using collect_dag_cids with a stop condition of target.t - 1, checking that the resolved commit appears in the walk. Short-circuits on source_head == target. Only loads the target commit's envelope (not its flakes) since we just need t.

CommitRef::T detects 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 each CommitRef variant (Exact, T, Prefix) at happy path, plus rejection of a non-ancestor commit.
  • fluree-db-server/tests/integration.rs — new HTTP integration test that drives POST /v1/fluree/branch with "at": "t:2" and also asserts 400 for "t:notanumber".
  • fluree-db-api/src/ledger_view.rs — unit test parse_full_multibase_cid_produces_exact locking in the parse path for base32-multibase CID strings.

Existing tests in it_branch.rs, it_merge.rs, it_rebase.rs, and it_tutorial_end_to_end.rs updated to pass None for the new source_commit parameter. All 17 it_branch tests, the new unit test, and the server integration test pass.

Backwards compatibility

  • Wire format — unchanged. Commit blobs written before this branch deserialize identically; the flag bit for parents stayed at 0x02 and the CID encoding stayed the same.
  • Rust API — Fluree::create_branch signature changed. Callers must add a None argument. The NameService trait gained a parameter; all in-tree impls updated. External impls of NameService will need the same update.
  • HTTP API — the new at field is optional; existing clients are unaffected.
  • CLI — the new --at flag is optional; existing invocations are unaffected.

@zonotope
zonotope requested review from aaj3f and bplatz April 24, 2026 15:27

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines 46 to 48

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +481 to +514
/// 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}"
)))
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@zonotope
zonotope merged commit c99f0b9 into main Apr 29, 2026
12 checks passed
@zonotope
zonotope deleted the feature/historical-branches branch April 29, 2026 16:15
@aaj3f aaj3f mentioned this pull request Apr 30, 2026
7 of 8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants