Skip to content

Stamp branch-operation flakes on the target's clock and load state along the first-parent lineage - #1818

Merged
zonotope merged 19 commits into
mainfrom
fix/branch-workflow-t
Sep 15, 2026
Merged

zonotope merged 19 commits into
mainfrom
fix/branch-workflow-t

Conversation

@zonotope

@zonotope zonotope commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Fixes #1783

Problem

Every branch numbers its commits from its fork point, so feat t=2 and main t=2 are unrelated commits with the same number. Two paths let flakes stamped on one branch's clock land in another branch's state:

  • Staging. Merge transplanted source flakes verbatim, rebase replayed them verbatim, and revert and take-source built flakes with t: 0 trusting a restamp that only the normal write path performed. The commit builder passed them through. In-process novelty then held merge-time facts at branch-local t, and revert inversions at t=0.
  • Loading. The commit blob stores t once in its header, so a reload cannot carry skewed per-flake stamps. But every state-materializing walk (novelty load, @t: reads, index rebuild and incremental resolve, commit catch-up, graph-source watermarks) followed all parent edges, so after a merge it replayed the source branch's copied commits a second time with their own header t.

Every @t: read filters on flake.t <= to_t, so feat's t=2 commit surfaced at main@t:2: history below the merge point was rewritten and historical reads showed both values. Take-branch and take-source decisions exist only in the merge commit, so a restart also resurrected the flakes the strategy had dropped and HEAD itself changed. That last part is worse than the issue describes.

Fix

StagedLedger::new stamps every flake with base.t() + 1, inside the pass that already resolves graph ids, so ordinary commits pay no extra traversal. The stage.rs stamps stay: multi-operation transactions apply each op's flakes to a virtual novelty before any view exists.

State materialization walks the first-parent lineage. New collect_first_parent_cids, its split-mode variant, and a single-pass trace_first_parent_commits_by_id in core. A merge commit already carries the folded, strategy-resolved delta of the branch it merged, so its first-parent lineage is self-contained. The walk refuses a chain whose t fails to decrease. Reachability callers (common ancestors, blob copying, ancestry checks, drop, pack, verify, transfer, CLI sync and log, merge-preview listings) keep the all-parents walk.

Two regressions the restamp exposed, found in review and fixed here:

  • Folding a range collapsed same-fact histories. A merge or range revert lands at one t, and a same-t assert and retract of one fact resolves to retracted. The shared fold now nets per fact with the accumulator merge preview already uses, in Replay direction for merge and Undo for revert.
  • Take-source and take-branch wiped values both sides agreed on. The retraction builder now skips facts the winning side asserts in the same commit. Covers merge, revert, and rebase.

Semantics

A branch's state at any t is the fold of its own line of commits. A merge lands as one commit at the target's next t and never rewrites what came before it. This is the git contract (--first-parent) and is now stated in the branching cookbook.

Tests

  • it_branch_time_travel.rs: seven tests across merge, rebase, and revert, including two on a file-backed instance rebuilt from disk. All failed before the fix; reverting either half alone re-fails a distinct subset.
  • Five regression tests for the review findings in the merge, rebase, and revert suites, each observed failing before its fix.
  • Core unit tests for the first-parent walk: lineage, stop_at_t, streaming, and the non-decreasing-t guard.

Existing ledgers

Commit blobs need no migration. Novelty is correct on the next load. Index files built by the old code after a merge can still hold flakes stamped on the source branch's clock; fluree reindex rebuilds them. No index format bump, so that step is manual.

Out of scope

Three pre-existing defects confirmed during review, all on main today and each a separate design question:

  • fluree sync push fails after any general merge (all-parents bundle vs the receiver's contiguity check).
  • branch create --at rejects a merged-in commit whose branch-clock t exceeds the merge's t.
  • sibling-branch merges can pick a common ancestor on the wrong clock and drop the source's commits.

A flake's t is a position on its branch's clock, but the branch paths handed
StagedLedger::new flakes minted elsewhere: merge and rebase transplanted source
flakes verbatim, revert inverted historical flakes, and take-source retractions
were built with t: 0 trusting a restamp that only stage.rs ever performed.
build_commit passed them through unchanged, so novelty held merge-time facts at
branch-local t and revert inversions at t=0.

Stamp base.t() + 1 on every flake inside the pass from_flakes already makes to
resolve graph ids, so the normal write path pays no extra traversal. The
stage.rs stamps stay: multi-operation transactions apply each op's flakes to a
virtual novelty before any view exists, and that apply never rewrites t. A debug
assertion in build_commit pins that the two agree.

Drop invert_at(0) from revert in favor of plain invert(), and correct the
comments on invert_at and build_source_retractions that described the restamp
that never happened.
A merge commit already carries the folded delta of the branch it merged,
resolved by the conflict strategy. The loaders walked every parent edge anyway,
so after a merge they replayed the source branch's commits a second time. Those
commits are stamped on the source's clock
(each branch numbers from its fork point):, and every time-travel read filters
on flake t, so feat's t=2 commit surfaced at main@t:2: history below the merge
point was rewritten and historical reads showed both values. Take-branch and
take-source decisions live only in the merge commit, so a restart also
resurrected the flakes the strategy had dropped and HEAD itself changed.

Add collect_first_parent_cids, its split-mode variant, and
trace_first_parent_commits_by_id in core: follow parents[0] only, stop at
stop_at_t, no sort needed since t is contiguous on the lineage. The two commit
streams share one body. Switch every caller that rebuilds state or computes what
a branch changed on its own timeline: novelty load and the historical range
load, index rebuild and the incremental fallback walk, merge's source
collection, rebase's branch scan, revert's conflict scan, both novelty delta
functions, incremental commit catch-up, and the BM25 and vector watermark walks.
Catch-up previously fell back to a full reload after any merge because the DAG
count never matched the gap.

The DAG walkers keep their behavior for reachability: common ancestors, blob
copying, ancestry checks, drop, pack, verify, transfer, CLI sync and log, and
merge-preview summaries.

@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.

@zonotope the problem statement and the referenced issue (along with your PR body) make this make a lot of sense to me. I think on the whole I have very few notes (as human-Andrew). With that said, I haven't spent much time (if any) in the branch/merge sections of the code, and don't have tremendous design grasp on the implementation details beyond the stories they make possible. So, candidly, most of the review value I can offer is mostly Claude's own rigorous lower level checks. I do agree with the Claude review (posted below) that the PR body and the problems/fixes they mention don't match the commit history of the branch. Not sure if possibly there are some unpushed commits, as I'm not sure what else in the git history those could refer to in this branch or on main. In any event, approving with some suggestions below for investigation/reconsideration.

Claude review:

The two halves that are here are exactly what #1783 asked for and they hold up under every angle I could throw at them — both of my repros from the issue are fixed on a CLI built from this branch (and still reproduce on one built from main), rebase and single/range revert stamp correctly, take-source/take-branch resolve correctly, a second merge from the same branch, reindex, incremental index, and a fast-forward all read consistently at every --at, and turning off either half alone re-fails the distinct subset of the seven new tests the body describes (three for the restamp, five for the walk). The first-parent classification of every walker matches my own pass over core/ledger/api/novelty/indexer, and the fast-forward arm isn't a hole since a branch numbers from its fork point. I'm requesting changes for one reason: the branch on GitHub isn't the branch the description describes. The netting fix, the winner-skip retraction fix, their five regression tests, and the non-decreasing-t guard are all absent at e21f74a19, and the two bugs they fix are silent HEAD data loss — merging a branch that went A→B→A drops the fact, a take-source merge where both sides chose B drops B, and range-reverting a no-op pair drops the value. Those are pre-existing on main (I confirmed all three there too, in-process and after reload), so this PR doesn't cause them, but it's the PR that promises to fix them and it restructures exactly the fold they live in. Just be sure to get those commits pushed (or, if they went somewhere else, point me at it and update the body) before this merges; the rest is ready.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Extends core's commit-walk family with a first-parent sibling sharing commits_stream, moves ownership of the stamp to the staging view rather than each caller, and (once pushed) the netting reuses NetChangeAccumulator from delta.rs.
  • Performance (speed first, memory second): ✔ First-parent walk is a single pointer chase with no visited set and no sort; restamp is one store in an existing pass; catch-up no longer full-reloads after merges. No performance-degradation risk.
  • Testing: ⚠️ Seven new integration tests are wired (grp_ledger), run in CI's --all-features nextest job, and go red under mutation; three core unit tests behind credential run the same way. The five regression tests the body lists are not on the branch.
  • Conventions: ⚠️ Multi-line, self-describing commit bodies; clippy -D warnings clean on six crates and fmt clean; but the PR body describes code that isn't pushed, and the cookbook now contradicts its own line 32 on fast-forward.

Verified locally at branch HEAD e21f74a19: grp_ledger 172 passed with the seven new names; restamp-off/walk-off mutations fail the expected subsets; core commit::tests 30 passed incl. the three new; ledger lib 37, transact lib 295; clippy clean on core/ledger/novelty/transact/indexer/api; fmt clean; CLI repros from #1783 pass at head and fail on main.

Happy to re-run the whole matrix the moment the missing commits land — with them this is an easy approve.


NOTE: I'd started to leave the above review (where you'll see some remarks about "missing commits"). I then saw a force-push of 3 commits which made me revisit the review. I think several of the above notes hold true, but I wanted to keep both top-level comments for clarity

@zonotope, a refresh rather than a new review: the branch hasn't changed where it matters since my last pass — 0ad6953f9 is 4b2dd3e38 plus a merge of main — so the one blocker stands, and I re-checked it on this exact head rather than trusting the earlier run.

The three commits you pushed are the branch the description promised, and they check out: the fold nets per fact through NetChangeAccumulator with the Replay/Undo direction implemented the way the comment says, the retraction builder skips winner-asserted values in both polarities, the five regression tests are wired through grp_ledger and go red exactly where they should when I turn each fix off, and every row of the CLI matrix that should have flipped did — both #1783 repros fixed, everything else byte-identical.

What I'm still requesting changes for is the netting rule itself: NetChangeAccumulator::finish keeps a fact only when its oldest and newest ops agree, i.e. it infers pre-range presence from the oldest op, and the commit stream can't support that inference because re-inserting a fact that already exists produces a real assert flake (only apply_commit dedups it). So a branch that re-inserts A and then deletes A nets to nothing and the merge leaves A on the target; re-insert then replace A→B leaves [A, B] at HEAD. I re-ran both regression tests on 0ad6953f9 today: the delete case reads ["Alice", "Bob"] where ["Bob"] is expected, and the replace case ["Alice", "B", "Bob"] where ["B", "Bob"] is expected. Both are correct on main and at e21f74a19, and it's the everyday shape of idempotent loads. The fix is newest-op-wins in finish() — one line, trialled: your five tests and the seven time-travel tests still pass, the two cases pass, take-source-after-restore stops losing its value as a bonus, and the only things that go red are the three accumulator unit tests and changes_netting_cancels_churn, which pin the old churn-hiding contract (that preview choice is yours; I'd show the net op). The two regression tests are on the it_merge.rs thread.

Still open from before: the t-guard sentence in the body has no code behind it (add the four lines or drop it), and the cookbook's line 32 still contradicts the new first-parent paragraph.

Two housekeeping notes: I saw the 09-10 force-push (the tip briefly sat at e658b17, main's own Turtle-logging fix, before you reset it to 4b2dd3e38 and merged main) — that also explains why the description was ahead of the branch on 09-09, no action needed; and the branch now conflicts with main in it_merge.rs since #1816 and the ref-race fix landed, both appending tests at EOF — a rebase keeps both blocks, and merge.rs auto-merges (the fold lives on the non-fast-forward path those four commits don't touch, but the rebased CI is the real check).

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Reuses the preview's NetChangeAccumulator and FactKey for the fold rather than inventing a second netting; first-parent walk family unchanged; winner-skip lives in the one shared retraction builder.
  • Performance (speed first, memory second): ✔ One FxHashMap pass over the source range per merge/revert and one FxHashSet over the winning flakes per conflict resolution; no query, novelty-read, or transaction-path change. No performance-degradation risk.
  • Testing: ⚠️ Five new integration tests wired, run in CI's --all-features nextest job, red under mutation; but none re-asserts an existing value, which is exactly the shape the rule gets wrong — two tests to add (supplied, and both fail on 0ad6953f9 today). The removed debug_assert! leaves the restamp guarded by three integration tests instead of every branch-op test.
  • Conventions: ⚠️ Clippy -D warnings clean on five crates, fmt clean; the three delta commits are subject-only, the first subject has a typo ("per factbefore"), and the body still describes a t guard that isn't in the code. ⚠️ needs a rebase onto main (it_merge.rs conflict).

Verified at 4b2dd3e38 (r2): grp_ledger 177 passed with the five new names; four mutations fail the expected subsets; core commit::tests 30, novelty lib 95, ledger lib 37, transact lib 295; fmt and clippy clean; CLI matrix at this head vs e21f74a19 vs main (24 cases); newest-op-wins trial green on everything but the four old-contract tests. Re-verified at 0ad6953f9 (r3, 2026-09-11): delta.rs:126-132 unchanged; the two supplied regression tests appended to it_merge.rs fail with ["Alice", "Bob"] / ["Alice", "B", "Bob"] (the other 177 grp_ledger tests filtered out, not re-run); merge-tree against main at 717d344dd conflicts only in it_merge.rs; force-push before/after read from the PR timeline.

Happy to re-run the matrix as soon as the finish() change, the two tests and the rebase land — with them this is an easy approve, and I'd expect it to be a same-day turnaround.

Comment thread fluree-db-core/src/commit.rs Outdated
split_mode = mode;
}
}
next = envelope.parent_ids().next().cloned();

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.

fluree-db-core/src/commit.rs:640 — optional. This is more of a question than a suggestion, tied to the body's "refuses a chain whose t fails to decrease": on a first-parent line t is contiguous by construction (each commit is parent.t + 1, a general merge lands at target.t + 1 with parents[0] = target head, and after a fast-forward the source's commits already sit on the target's numbering — verified with --at reads after an ff merge), so the guard would only ever fire on a corrupted chain and there's no bricking risk either way. If we want it as cheap insurance, something like if let Some((prev_t, _)) = result.last() { if envelope.t >= *prev_t { return Err(...) } } before the push at :641 is all it takes; if not, the body's sentence and its "non-decreasing-t guard" test bullet should go (nothing landed for it in the delta either — :615 is still just the doc comment). Minor, but I'd rather see it settled in this PR than have the description drift.

Comment thread docs/guides/cookbook-branching.md Outdated
fluree query --ledger mydb:experiment --at 3 'SELECT ?s ?p ?o WHERE { ?s ?p ?o }'
```

Each branch numbers its transactions on its own clock, starting from the point where it forked, so `--at 3` on `experiment` and `--at 3` on `main` are unrelated states. A merge lands on the target as a single commit at the target's next transaction number, carrying the whole resolved change from the source. Reads below that number return what the target held at the time: merging never rewrites a branch's earlier history, and a branch's state at any `--at` is the fold of its own line of commits, not of the branches merged into it.

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.

docs/guides/cookbook-branching.md:182 — optional. "A merge lands on the target as a single commit at the target's next transaction number" is the general-merge case; a fast-forward moves the ref and the source's commits become the target's line (their t values are already on the target's clock, so the contract still holds — it's just a different shape). Line 32 of the same file still says "Merge is fast-forward — The target branch must not have diverged. If it has, rebase first", which now contradicts this paragraph outright. Perhaps one clause here ("or, for a fast-forward, the source's commits simply become the target's line") and a fix to line 32 — not introduced by this PR, but this paragraph is where a reader will trip over it. If you agree it's right, I'd rather see it folded in now than lost in the backlog.

.map(|flake| Flake {
op: false,
t: 0, // overwritten by commit
t: 0, // restamped by StagedLedger::new

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.

fluree-db-api/src/rebase.rs:807 — optional, doc. Same seam as the blocking note, from the other side: resolve_overlay_ops (fluree-db-binary-index/src/read/types.rs:175) and resolve_current_flakes (fluree-db-core/src/range.rs:452) both say the same-t assert+retract tie "is currently unreachable" because the transaction accumulator dedups within a commit. Before this PR the fold and this retraction builder were the other producer; with per-fact netting and this filter they no longer are, so those comments become true again — and it'd be worth a clause in each naming the fold as the historical producer (and legacy merge commits written by the old code as the surviving one) so nobody removes the tie-break later. Very minor.

{
let stream =
trace_commits_by_id(Arc::clone(&cs), commit_head_id.clone(), local_t);
let stream = trace_first_parent_commits_by_id(

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.

fluree-db-api/src/ledger_manager.rs:2157 — decision for the reviewer, not the author. Existing ledgers: the body is right that commit blobs need nothing (the codec stores t once in the header, reader.rs:144) and novelty is correct on the next load, but index files built by old code after a merge keep source-clock stamps, and @t reads served from the index stay wrong until fluree reindex. There's no cheap detector (ROOT_V6_VERSION is a format version, not a writer stamp, and old merge commits look fine from the outside), so this is a call between bumping the root version in db, bumping solo's own EXPECTED_INDEX_FORMAT_VERSION when pinning this rev (solo's cold-start invalidate-and-reindex path, no db change), or a release note. Commenting here because there's no better anchor.

let mut flake_graph_ids: Vec<GraphId> = Vec::with_capacity(flakes.len());
for f in &flakes {
for f in &mut flakes {
f.t = staged_t;

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.

fluree-db-ledger/src/staged.rs:85 — praise. Stamping inside the pass from_flakes already makes for graph ids is the right place: every one of the ten StagedLedger::new callers is covered and the normal write path pays nothing. This is what makes --at honest below a branch operation regardless of who built the flakes.

{
let stream =
trace_commits_by_id(Arc::clone(&cs), commit_head_id.clone(), local_t);
let stream = trace_first_parent_commits_by_id(

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.

fluree-db-api/src/ledger_manager.rs:2157 — praise. Catch-up now applies the gap after a merge instead of tripping loaded != gap and full-reloading — a real win for long-lived server ledgers with merges.

assert_eq!(report.conflict_count, 1);

assert_eq!(query_all_names(&fluree, "mydb:main").await, vec!["C"]);
}

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.

fluree-db-api/tests/it_merge.rs:951 — optional (goes with the blocking note). The three fold tests here all pass under either survival rule, which is why they didn't catch the redundant-assert shape — the range never re-asserts a value that already exists. Two variants of merge_folds_source_history_per_fact pin it; both fail at this head and pass with newest-op-wins:

/// A redundant re-assert of a value that already exists still lands in the
/// commit (only novelty dedups it), so the fold must not read
/// "assert … retract" as created-then-destroyed: the deletion is real.
#[tokio::test]
async fn merge_carries_deletion_after_redundant_reassert() {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger = fluree.create_ledger("mydb").await.unwrap();
    let ctx = json!({"ex": "http://example.org/ns/"});
    let alice = json!({"@context": ctx, "@graph": [{"@id": "ex:alice", "ex:name": "Alice"}]});
    let main = fluree.insert(ledger, &alice).await.unwrap().ledger;
    fluree
        .create_branch("mydb", "dev", None, None)
        .await
        .unwrap();

    // dev: re-insert Alice (already present), then delete her.
    let dev = fluree.ledger("mydb:dev").await.unwrap();
    let dev = fluree.insert(dev, &alice).await.unwrap().ledger;
    fluree
        .update(
            dev,
            &json!({"@context": ctx, "delete": {"@id": "ex:alice", "ex:name": "Alice"}}),
        )
        .await
        .unwrap();
    assert!(query_all_names(&fluree, "mydb:dev").await.is_empty());

    fluree
        .insert(
            main,
            &json!({"@context": ctx, "@graph": [{"@id": "ex:bob", "ex:name": "Bob"}]}),
        )
        .await
        .unwrap();
    let report = fluree
        .merge_branch("mydb", "dev", None, ConflictStrategy::default())
        .await
        .unwrap();
    assert!(!report.fast_forward);
    assert_eq!(report.conflict_count, 0);

    assert_eq!(query_all_names(&fluree, "mydb:main").await, vec!["Bob"]);
}

/// Same shape with a replace instead of a delete: the target must end with
/// the new value only, not the old one alongside it.
#[tokio::test]
async fn merge_after_redundant_reassert_then_replace_has_no_phantom() {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger = fluree.create_ledger("mydb").await.unwrap();
    let ctx = json!({"ex": "http://example.org/ns/"});
    let alice = json!({"@context": ctx, "@graph": [{"@id": "ex:alice", "ex:name": "Alice"}]});
    let main = fluree.insert(ledger, &alice).await.unwrap().ledger;
    fluree
        .create_branch("mydb", "dev", None, None)
        .await
        .unwrap();

    let dev = fluree.ledger("mydb:dev").await.unwrap();
    let dev = fluree.insert(dev, &alice).await.unwrap().ledger;
    fluree
        .update(dev, &replace_name("ex:alice", "B"))
        .await
        .unwrap();
    assert_eq!(query_all_names(&fluree, "mydb:dev").await, vec!["B"]);

    fluree
        .insert(
            main,
            &json!({"@context": ctx, "@graph": [{"@id": "ex:bob", "ex:name": "Bob"}]}),
        )
        .await
        .unwrap();
    fluree
        .merge_branch("mydb", "dev", None, ConflictStrategy::default())
        .await
        .unwrap();

    assert_eq!(query_all_names(&fluree, "mydb:main").await, vec!["B", "Bob"]);
}

namespace_delta,
graph_delta,
} = collect_from_commits(commits, |f| f.invert_at(0));
} = collect_from_commits(commits, Fold::Undo);

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.

fluree-db-api/src/revert.rs:440 — optional. Not introduced by this PR, but newly reachable through it: when the netted Undo set is empty (a range that replaced and then restored a value), the pre-existing staged.is_empty() short-circuit at :464 returns commit: None, so the CLI prints "Reverted 2 commit(s) on 'main' (t=3 …)" while t doesn't move and no reverts txn-meta trail is written — whereas merge in the same situation deliberately lands the commit to record what happened (merge.rs:533-535). With newest-op-wins this particular shape emits no-op flakes and a commit lands again (I saw t=4 come back), but a genuinely empty net is still possible. I wonder if we want revert to mirror merge here and land an empty commit carrying the reverts entry, or at least report "nothing to revert" honestly. Minor — but if you agree it's right, I'd rather see it folded in now than lost in the backlog. Commenting here because :464 isn't in this diff.

let mut flake_graph_ids: Vec<GraphId> = Vec::with_capacity(flakes.len());
for f in &flakes {
for f in &mut flakes {
f.t = staged_t;

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.

fluree-db-ledger/src/staged.rs:85 — optional. This is so minor, but on the "dead staging assertion" from 4b2dd3e38: build_commit only ever gets flakes through view.into_parts() (fluree-db-transact/src/commit.rs:562), so I agree nothing can bypass this stamp today — which is also why the assertion was worth having: with the stamp turned off it fired in 23 merge/rebase/revert tests yesterday, and with it gone the same mutation is caught by three it_branch_time_travel tests instead (merge_does_not_create_phantom_duplicates_at_historical_t, merge_take_source_retractions_carry_merge_t, revert_inversions_carry_revert_t). That's still regression-proofing, so I'm fine either way; I'd just like the reasoning in the commit body, since all three delta commits are subject-only and the first one's subject has a typo ("per factbefore"). Commenting here because fluree-db-transact/src/commit.rs is no longer in the diff.

}
}
}
data.flakes = acc.finish();

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.

fluree-db-api/src/commit_data.rs:83 — blocking. The netting rule drops real deletions: a source range that re-asserts a fact and then retracts it nets to nothing, and the merge leaves the deleted value on the target. (Updating this thread in place: the fixes I asked for yesterday are here and hold up — the fold nets per fact, the retraction builder skips winner-asserted values, the five tests are wired and go red under mutation, and every row of yesterday's matrix that should have flipped did. This is a new finding in the netting itself.)

Mechanism: NetChangeAccumulator::finish (fluree-db-novelty/src/delta.rs:126-132) keeps a fact only when oldest_op == newest.op, which — as its doc at :101-103 says outright — infers pre-range presence from the oldest op. The commit stream can't support that inference: re-inserting a fact that already exists produces a real commit with an assert flake (receipt shows t=2 flakes=1); only Novelty::apply_commit (fluree-db-novelty/src/lib.rs:868-889) discards it at apply time, and this fold reads commit blobs. So "assert A (redundant) … retract A" is read as created-then-destroyed and dropped, and the retract never reaches the target.

Concrete cases, on a CLI built from this head and in-process through merge_branch: (1) main A; dev re-inserts A then deletes A; main adds an unrelated subject; merge → main HEAD still has A (dev has nothing). (2) Same but dev re-inserts A then replaces A→B → main HEAD is [A, B], the phantom-duplicate shape from #1783. Both read correctly on a CLI built from main and from e21f74a19 (the old concatenation happened to land the retract at the same t, and retract wins the tie), so this is introduced by f762a39b2. Idempotent loads and upserts emit redundant asserts all the time, so this is an everyday shape rather than a corner.

Fix: net by newest op wins — a fact's presence at the source head is decided by the last op the range applied to it, and the extra flakes that rule emits are no-ops when applied (a redundant assert is deduped by apply_commit; a retract of a fact the target no longer holds is harmless on read, reindex, and later writes — I checked that shape too). I trialled exactly this and it's one line:

    /// Facts the range touched, each represented by its newest in-range
    /// flake, so `op` is the fact's state at the range head. A redundant
    /// assert or a retract of an absent fact is a no-op when applied, so
    /// nothing is inferred about pre-range state. Unordered.
    pub fn finish(self) -> Vec<Flake> {
        self.map.into_values().map(|st| st.newest).collect()
    }

(and oldest_op goes away). With that in place: your five tests and all seven time-travel tests still pass, both cases above pass, R16-style take-source (source restored a value the target had changed — [] on every binary today) becomes [A], the net-no-op range revert lands a real commit again, and the replace case reads [B] before and after reindex (on main today it reads [B] from novelty and [A, B] after a rebuild — same-t pairs are where novelty and the index builder disagree, and a correct netting removes them). What goes red is only what pinned the old contract: delta::tests::{assert_then_retract_cancels, retract_then_assert_cancels, same_commit_pair_cancels_via_reverse_iteration} and it_merge_preview::changes_netting_cancels_churn. That last one is a real product choice — a preview that hides create-then-delete churn also hides the deletion in case (1) — and I'd lean toward the preview showing the net op since it's what the merge will apply, but if you'd rather keep the churn filter for display it needs to compare against the ancestor's actual state rather than infer it. Please also add the two cases above as regression tests next to merge_folds_source_history_per_fact (suggested text on it_merge.rs:951).

Commenting here because delta.rs:126-132 isn't in this diff (only its FactKey hunks are) and this line is where the rule enters the fold.

The DAG walk is bounded by its visited set. The first-parent walk had no bound
beyond the chain ending, so a parent that failed to decrease t was loaded as if
it were history and replayed into novelty, index rebuild and incremental
resolve. The collector and the stream now refuse such a chain as an invalid
commit, naming the commit and its child's t.

The stream was shaped like the DAG stream: walk envelopes to collect and order
the CIDs, then read a blob per commit. A lineage needs no ordering pass, so read
each blob once and follow its first parent from it. That halves the round trips
per commit. trace_commits_by_id returns to its own body and the helper that
briefly backed both streams is gone.

The guard also removes a fetch. Since t strictly decreases, a parent's t is at
most its child's minus one, so once that reaches the stop point the parent is
out of range and neither walk fetches it. Without this a single pass would have
read the boundary commit's whole blob where the previous code read only its
envelope, which would have cost incremental catch-up a full commit read per
notification.
Revert chose the commits it may revert by walking the whole commit graph, so it
accepted one that reached the branch through a merge. Conflict detection walks
the first-parent lineage, which never visits such a commit, so nothing it
touched was compared against the commits that followed: reverting it under Abort
applied silently even when a later commit changed the same key. Its t is on the
authoring branch's clock too, so the scan's lower bound was meaningless.

Resolve the plan against the first-parent lineage instead. A commit the branch
can reach but that is not on that lineage is refused, with a message saying it
arrived through a merge and to revert it on the branch that authored it. This
joins the existing refusals for genesis and merge commits. Ranges become a slice
of the lineage between their endpoints, so the second graph walk that confirmed
ancestry is gone.

The conflict walk is then sound by construction: every reverted commit is on the
lineage it walks and every t it compares is on this branch's clock. The common
path is now one first-parent walk where it used to be a full graph walk, plus
another for ranges; the graph walk runs only to tell a merged-in commit apart
from one this branch has never seen.
The revert section of the CLI branch reference now states that a commit must be
on the branch's own history, defines that as the line reached by following each
merge's first parent, and lists the three refusals together: the genesis commit,
a merge commit, and a commit that reached the branch through a merge. It also
says what to do with the third, which is to revert it on the branch that
authored it and merge again.

The comment about what the first-parent collector returns ran past the line
limit in both indexer call sites. It now wraps, and says the result is newest
first rather than restating the sort.

@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.

@zonotope per discussion in our Backlog Grooming call, I figured I'd share this re-review pass (merely as a comment since I'd previously already approved) just in case it's useful feedback but not as a requalification of the previous review's posture etc. Take it or leave it as it's helpful!


The netting regression is still on the branch at ab3d667d1. NetChangeAccumulator::finish (fluree-db-novelty/src/delta.rs:126-130) still keeps a fact only when its oldest and newest in-range ops agree, and none of the new commits touch delta.rs, commit_data.rs or merge.rs. I re-ran the two regression tests from the it_merge.rs thread against this exact head today, on a fresh build: re-insert-then-delete reads ["Alice", "Bob"] where ["Bob"] is expected, and re-insert-then-replace reads ["Alice", "B", "Bob"] where ["B", "Bob"] is expected — the same values as yesterday. The ask is unchanged and small: newest-op-wins in finish() plus those two tests. One new data point from #1822, which is stacked on this branch: with a sh:maxCount 1 shape on the property, the replace shape stops being silent and becomes a SHACL rejection of a merge that is genuinely conforming (dev ends at [B]; the fold stages only assert B, the target would end at [A, B], and the new validation refuses it), while the delete shape stays silent ([A, Bob] conforms). So once #1822 lands this bug also produces false rejections, which I'd rather we not ship.

The four new commits themselves are good, and I'd take them as-is:

  • 284193671 is the t guard the body promised — walk_first_parent at fluree-db-core/src/commit.rs:639-648 and the new single-pass trace_first_parent_commits_by_id at :793-838 both refuse a parent whose t fails to decrease — so my commit.rs:640 thread is resolved. I checked it both ways: turning the guard off in the collector fails test_first_parent_walk_rejects_non_decreasing_t on its first assert, turning it off in the stream fails it on the second. The single-pass stream is a real win (one blob read per commit instead of an envelope walk plus a blob read), and the t - 1 > stop_at_t bound is the right call for incremental catch-up, for the reason your commit body gives. One thing I traced rather than trusted: with this shape a corrupted chain yields the commits above the break before the error instead of erroring up front; all nine consumers drain into a Vec or set behind ? before applying anything, so nothing partially applies. Turning the bound off leaves every core test green, which is what a perf-only change should do.

  • 0c255c655 is correct and the reasoning in the body is exactly what the code does: compute_conflict_keys walks the lineage, so a commit that arrived through a merge was never compared against what followed, and its t was on the wrong clock for the stop bound. Resolving the plan on the lineage makes the conflict walk sound by construction; the (from_t, to_t] slice replaces the second DAG walk cleanly since both endpoints are on one chain; and the revert preview shares build_revert_context, so preview and revert refuse the same commits. Putting the plan back on the DAG locally fails revert_refuses_commit_that_arrived_through_a_merge and nothing else. One small ask: this is a user-visible behavior change (a revert that used to "succeed" now returns InvalidBranch) and the PR body doesn't mention it — the paragraph you added in ab3d667d1 at docs/cli/branch.md:363 is the right text, so maybe a line under "Fix" pointing at it.

  • 60e89e643 and ab3d667d1: tests-first and the docs, nothing to add beyond the body line above (and 60e89e643 is the one delta commit without a body, fwiw).

I also checked the merge of main (8ec2c19e3): it_merge.rs keeps both EOF blocks (33 test fns, the union of main's 28 and the branch's 23, nothing dropped), merge.rs auto-merged, and the 25 commits on main since the merge-base touch none of the branch-op files.

Still open and minor from before: the cookbook's line 32 ("Merge is fast-forward — the target must not have diverged; rebase first") still contradicts the general-merge paragraph at :204, and f762a39b2's subject typo is in history now, so leave it unless you're rebasing anyway.

Verified at ab3d667d1: grp_ledger 183 passed plus the two supplied tests failing with the values above; core commit::tests 31 passed including the new guard test; four mutations (revert plan on the DAG, collector guard off, stream guard off, boundary bound off) fail or pass the expected sets; cargo fmt --check clean; clippy -D warnings clean on core (credential), api (native) and indexer.

// it. Conflict detection walks that lineage, and `t` is only comparable
// along it, so only commits on it can be reverted. `lineage` is
// newest-first with strictly decreasing `t`.
let lineage = collect_first_parent_cids(store, head_id, 0).await?;

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.

fluree-db-api/src/revert.rs:693 — praise + one doc ask. This is the right fix and the body's reasoning is exactly what the code does: compute_conflict_keys (:785-822) walks the first-parent lineage, so a commit that reached the branch through a merge was never compared against the commits after it (its keys never landed in reverted_keys) and an Abort revert applied silently — and its t was on the other branch's clock, so the walk's stop bound was meaningless. Resolving the plan on the lineage makes that walk sound by construction, and the (from_t, to_t] slice is a clean replacement for the second DAG walk since both endpoints sit on one chain. I put the plan back on the DAG locally and only revert_refuses_commit_that_arrived_through_a_merge goes red, so the test has teeth; the revert preview goes through build_revert_context too, so it refuses the same commits. The one thing I'd add is a line in the PR body: this is a user-visible change (a revert that used to "succeed" now returns InvalidBranch), and the docs/cli/branch.md:363 paragraph is the right text to point at.

} else {
None
};
Some((Ok(commit), next))

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.

fluree-db-core/src/commit.rs:835 — optional, traced rather than trusted. With the single-pass shape a corrupted chain now yields the commits above the break and then the error, where the old collect-then-stream errored before yielding anything (the new unit test pins exactly this: two items, the second an Err). I went through all nine consumers to make sure nobody applies as they go — ledger/src/lib.rs:375 and historical.rs:235 collect commit_batches first, ledger_manager.rs:2157 collects then checks the count, rebase.rs:869/revert.rs:793/both delta.rs folds/bm25.rs:1142/vector.rs:514 fold into sets behind ? — so nothing partially applies. Just noting it here so the next reader doesn't have to. The t - 1 > stop_at_t bound is perf-only (all 31 core tests stay green with it removed), which is what your commit body claims.

The accumulator kept a fact only when its oldest and newest in-range ops agreed,
which infers whether the fact existed before the range. A commit stream cannot
support that inference: re-asserting a value the ledger already holds writes a
real assert flake, and only apply-time dedup discards it. So "assert then
retract" read as created-then-destroyed and the deletion never reached the
target. A branch that re-inserted a value and then deleted it merged with the
value still present, and the same shape with a replace left both values, which
is the phantom duplicate from #1783. Idempotent loads and upserts emit redundant
asserts all the time, so this is an everyday shape rather than a corner.

Keep each touched fact's newest op instead: it is the fact's state at the range
head, which is what replaying the range has to reproduce. What that emits is at
worst redundant, never wrong. A redundant assert is deduped on apply, and a
retract of a fact the target does not hold is a no-op for reads, reindexing and
later writes.

Merge preview follows the same rule and now shows the net op rather than hiding
churn, so a branch that created and then deleted a value previews as that
deletion. Hiding it would have hidden a deletion the merge does apply. The three
unit tests that pinned the old contract now assert newest-op-wins, and two
regression tests cover the re-assert shape in both its delete and replace forms.
@zonotope
zonotope merged commit 94fdf5e into main Sep 15, 2026
16 checks passed
@zonotope
zonotope deleted the fix/branch-workflow-t branch September 15, 2026 03:56
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.

Merge/rebase/revert transplant flakes with branch-local t — time-travel reads below a merge return rewritten history and phantom duplicates

2 participants