Skip to content

fix(merge): fast-forward merges land on queue-backed nameservices and keep the target's index root - #1816

Merged
bplatz merged 7 commits into
mainfrom
fix/ff-merge-publishes-ref
Sep 10, 2026
Merged

bplatz merged 7 commits into
mainfrom
fix/ff-merge-publishes-ref

Conversation

@bplatz

@bplatz bplatz commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Direct Fluree::merge_branch fast-forwards could fail on a queue-backed nameservice with per-branch queue is empty — nothing staged for this branch. From an indexed source, the same path could also adopt the source's branch-qualified graph registry, causing the target to stop resolving its own governance configuration while ordinary data queries continued to work.

This PR advances the commit ref against the prepared target head, preserves the target's index, and makes a full reindex repair visible to subsequent cached reads. The branch includes current origin/main; #1801 has merged.

Commit publication and ordering

  • Fast-forwards use one RefPublisher::compare_and_set_ref with the target head captured during preparation. A concurrent target commit causes BranchConflict (409); callers re-run the merge to recompute against the new head. There is no retry based only on transaction-time ordering.
  • An already-reached head is idempotent success only when both transaction time and commit ID match. Repeating a completed fast-forward copies zero commits.
  • A failed merge rolls back only if the target still has this merge's published head. Losing the CAS preserves the concurrent writer's head instead of resetting it; on Raft, avoiding that reset also avoids clearing the branch queue.
  • Direct API fast-forwards go through Raft consensus but bypass the per-branch work queue, so they can overtake previously queued transactions. The server's QueuedTransactor::merge → commit_worker::process_merge path queues and prepares merges alongside transactions; it was not affected by the empty-queue failure and retains queue ordering.

The queue failure affected direct API callers on queue-backed deployments, including embedded Raft use. It did not prevent every proposal or merge on every replicated deployment. The queue publication contract remains unchanged; fast-forwards neither weaken it nor invent a no-op commit.

Target index and repair

An index root carries branch-qualified graph_iris. Publishing the source root as the target's relabelled the target's reserved txn-meta/config slots. The target now retains its own index ref and reads the merged range from commits until indexing catches up. Fast-forwards also skip copying the source's unreferenced index artifacts, avoiding unnecessary storage reads and writes. Rewriting/adopting source roots is deferred.

For an already-affected target, run a full reindex (fluree reindex mydb:main, or the serving instance's Fluree::reindex). After successful publication, reindex evicts the calling instance's cached ledger, including when the new root has the same index transaction time. Subsequent loads see the repaired registry and governance configuration. Existing caller-held handles must be reacquired; other serving instances must reload their cached ledger. Rewriting config alone does not repair the registry.

The indexing escalation is now reproduced: the first incremental cycle stamps the target's ledger ID but preserves the adopted branch labels. The next cycle fails the graph_iris[0] must be txn-meta IRI validation. The normal indexer then falls back to a full rebuild and restores the target labels; it does not permanently stop indexing. The branching cookbook documents the repair, fallback, index catch-up cost, and queue-ordering distinction.

Validation

  • cargo test -p fluree-db-api --test grp_ledger: 170 passed, including deterministic public-API races with a real concurrent target commit at smaller and equal transaction times, idempotent repetition, absence of the copied source root, same-time reindex cache repair, and both indexing cycles on an affected root.
  • cargo test -p fluree-db-api --test grp_index reindex: 23 passed (67 unrelated tests filtered out).
  • cargo test -p fluree-db-consensus --features raft,testing --test it_embedded_node: 6 passed, including the real queue-backed fast-forward regression.
  • cargo clippy -p fluree-db-api --all-targets --no-deps -- -D warnings and the consensus equivalent with --features raft,testing: passed.
  • cargo fmt --all -- --check and git diff --check: passed.
  • Six mutation checks failed as expected: remove idempotent success, retry CAS against a newer target, ignore commit identity, restore unconditional rollback, restore the unused source-index copy, and remove reindex cache eviction. All mutations were restored before the passing checks above.

…ng a commit

Merging a branch that is strictly ahead of an untouched target failed on
any queue-backed nameservice:

  Failed to merge branch: Nameservice error: Storage error:
  publish_commit on <ledger>:main: per-branch queue is empty —
  nothing staged for this branch

`publish_commit`'s contract on the raft data plane is "apply the staged
queue front". A fast-forward stages nothing on the target — that is what
makes it a fast-forward — so the call had no queue entry to apply. The
general path stages a merge commit and therefore worked, which inverts
the expected difficulty: a divergent merge succeeded while a clean,
conflict-free, fast-forwardable one could not. Reproduced on a throwaway
ledger — branch two commits ahead of an untouched main fails; add one
commit to main so the merge must copy, and it succeeds.

The fix is the one bulk import already made for the same reason. Its
`publish_import_commit_head` documents it: a ref-level fast-forward
"carries the exact strictly-newer semantics the file/S3 nameservices give
`publish_commit`, and every nameservice implements it via `RefPublisher`,
so the bulk importer works under all data planes without touching the
transactor's queue contract". The fast-forward arm of `apply_merge` now
does the same, with the same CAS-conflict handling: an already-there head
is idempotent success, retry exhaustion is reported as contention, and a
genuinely diverged head says to re-run the merge.

Memory and file nameservices are unaffected — their `publish_commit` was
already a ref write, which is why every existing fast-forward merge test
passed while the raft data plane could not merge at all.

Decision: fast-forward at the ref rather than teaching publish_commit to tolerate an empty queue — the queue contract is what makes the transactor's ordering guarantees checkable, and loosening it to serve a caller that stages nothing would weaken it for every caller that does
Decided-by: session
Alternative: stage a no-op commit on the target so publish_commit has a queue front — rejected: it invents a commit nobody made, which is the history pollution a governed graph's audit trail exists to rule out
The bug this covers was invisible to every existing merge test because
they all build `FlureeBuilder::memory()`, whose `publish_commit` is
already a plain ref write. All fifteen passed while the replicated data
plane could not merge a fast-forwardable branch at all.

So the test belongs beside the embedded Raft node, where the nameservice
is queue-backed for real: one commit on main, a branch, two commits on
the branch, none on main, then merge. Reverting the fix makes it fail
with the exact production message — "publish_commit on ffdb:main:
per-branch queue is empty — nothing staged for this branch" — which is
what makes it a regression test rather than a restatement.

It also asserts the replicated head actually moved: a merge that reported
success without advancing the ref would leave the proposal unlanded,
which is the same silent failure from the other direction.
@bplatz
bplatz requested review from aaj3f and zonotope September 8, 2026 21:28
An index root carries `graph_iris`, the slot to IRI table the graph
registry is re-seeded from, and those IRIs are branch-qualified: slot 1
is `urn:fluree:{ledger}:{branch}#txn-meta`, slot 2 is `...#config`. The
fast-forward arm published the SOURCE's root as the target's index, so
main adopted the branch's labels. The config graph is resolved by slot,
so main then read the branch's empty config and reported itself
ungoverned while its real config sat in a user slot, and re-running the
config write routed there too. Data queries resolve by slot and kept
working, which is what made the corruption invisible.

The target now keeps its own index ref and rebuilds from the copied
commits, the same cost as any un-indexed write. Rewriting the source
root's `graph_iris` before publishing would be the optimisation, not
the fix.

The regression test lives with the other merge tests rather than beside
the embedded raft node: that harness wires no indexer, so the source
never has a root to publish and any registry assertion there passes
vacuously. Here the branch gets a real root through a branch-aware
rebuild, and the test fails on the old code with main's slot 1
relabelled to the branch's txn-meta IRI.
…y a published head

`fast_forward_commit` retries on `t`-ordering, but a fast-forward is an
ancestry claim: `prepare_merge` decided the target head is the common
ancestor. A commit landing on the target between prepare and apply has
a smaller `t` than the source head, so the retry loop re-read it and
overwrote it, and that commit was orphaned. The general path is guarded
by its write lock and `expected_head_ref`; the fast-forward arm now does
a single `compare_and_set_ref` expecting the head it was prepared
against, and a mismatch is a 409 branch conflict telling the caller to
re-run the merge.

`merge_branch`'s failure path force-reset the target to the pre-merge
snapshot on every error. On a lost CAS that reverted the concurrent
writer's head. Roll back only when the target's head is the one this
merge published; a failure before the publish leaves the nameservice
alone.
@bplatz bplatz changed the title fix(merge): a fast-forward merge advances the ref instead of publishing a commit fix(merge): fast-forward merges land on queue-backed nameservices and keep the target's index root Sep 9, 2026
Base automatically changed from fix/unicode-dictionary-error to main September 10, 2026 11:57

@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 carefully built, @bplatz, and makes very good sense against the (real-verified) bugs described — the diagnosis of both bugs holds up at the mechanism, the fix reuses the importer's ref-level fast-forward instead of loosening the queue contract or inventing a commit, and the two rejected alternatives in the trailers are the ones I'd have rejected for the same reasons. I reverted each fix and watched its test fail with the exact assertion (slot 1 relabelled to urn:fluree:mydb:feature#txn-meta at it_merge.rs:884) and the verbatim production message (per-branch queue is empty at it_embedded_node.rs:489), and compare_and_set_ref is present and atomic on every backend (memory under the write lock, file via rename-based compare_and_swap, S3 via put_if_match, DynamoDB via a conditional UpdateItem on id and t, raft through the state machine). Two calibration notes on the body rather than the code: the "no proposal could ever be landed on a replicated deployment" claim is true of direct Fluree::merge_branch callers on a raft nameservice (solo's --data-raft standalone, this test), but fluree-db-server's own raft mode goes through QueuedTransactor::merge → commit_worker::process_merge, which re-stages via prepare_merge and publishes through the queue and was never broken; and I don't see an existing test that pins the idempotent re-run — it works (I tried it), it's just not covered. The notes inline are all small fold-ins: the fast-forward arm still copies the source's index artifacts with no remaining consumer, the source_index_for_publish doc is now inverted, nothing pins the "CAS against the prepared head" half of the hardening, and the repair path for already-affected ledgers wants one disconnect in reindex plus a cookbook line (Claude traced that an affected ledger stops indexing incrementally on its second cycle, which makes the doc line worth having).

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends RefPublisher::compare_and_set_ref exactly as publish_import_commit_head does; no parallel construct; queue contract untouched.
  • Performance (speed first, memory second): ✔ no hot path touched; merge-time cost intentionally higher (target re-indexes the merged range instead of adopting the root) and I agree with the trade; one avoidable O(source-index) copy on the fast-forward arm flagged as an optional fold-in.
  • Testing: ✔ both new tests are wired (grp_ledger.rs:14 includes it_merge; the consensus test is a plain tests/ target under --features raft,testing), run, and go red under mutation; ⚠️ the CAS-expectation and idempotent-re-run behaviours are exercised by nothing.
  • Conventions: ✔ multi-line bodies with decision trailers, self-describing subjects, fmt/clippy clean under CI's pin; ⚠️ no docs change for a user-visible behaviour change (fast-forward no longer carries the source index) and no repair note.

Verified locally at branch HEAD (d86c5a3, toolchain 1.97.0): grp_ledger 166 passed, it_embedded_node 6 passed, both mutations red, cargo fmt --all -- --check clean, cargo clippy -p fluree-db-api --all-targets -- -D warnings and cargo clippy -p fluree-db-consensus --features raft,testing --all-targets -- -D warnings clean. git merge-tree against #1818 (fix/branch-workflow-t) merges clean — its merge.rs hunks are the use fluree_db_core line and collect_commit_data, which only the general arm calls, so no composition hazard in either order.

Approving so you can merge when ready, but maybe worth folding a few of these in first — and since this is stacked on #1801 it has had no CI run at all (the green checks are the Release workflow's plan job), so just be sure to retarget to main once #1801 lands so ci.yml actually exercises it before it goes in.

// registry the target created for itself. Adopting the root would
// need its `graph_iris` rewritten to the target's before publish;
// that is the optimisation, not the fix.
if let Some((index_cid, _index_t)) = source_index_for_publish {

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/merge.rs:455 — optional (performance, merge-time). I don't think this is hot-path, but with the root publish gone the fast-forward arm still runs copy_index_to_branch for the source's whole index (root, every leaf, branch manifests, arenas — 32-wide reads and writes, ledger/loading.rs:377-380) into the target namespace, and as far as I can trace nothing in the target references any of it now: the target's index ref is untouched and IncrementalRootBuilder starts from the target's own root, so the copies sit unreferenced until an index sweep collects them. On S3 that's O(source index) PUTs per fast-forward for nothing. Minimally we could set source_index_for_publish: None in build_merge_ff (merge.rs:508-512) so the copy stays general-merge-only; or, more fully, do the graph_iris rewrite the commit body names as the optimisation and get the adoption back. Minor and non-blocking — but if you agree it's right, I'd rather see it in this PR than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 62fa6c1

// registry the target created for itself. Adopting the root would
// need its `graph_iris` rewritten to the target's before publish;
// that is the optimisation, not the fix.
if let Some((index_cid, _index_t)) = source_index_for_publish {

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/merge.rs:455 — optional (stale doc; commenting here because merge.rs:84-86 is not in this diff). StagedMerge::source_index_for_publish's doc still says "Best-effort copy after the ref advance so the target reuses the source's index. Only set for fast-forward" — after this PR the target doesn't reuse it, and the general arm has set it too since merge.rs:685-688. Worth a one-line correction (or it simplifies away if the copy becomes general-only per the note above).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 62fa6c1

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

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:905 — optional (test). The PR body says the existing merge tests cover the idempotent re-run; I may be reading them wrong, but I don't see one — merge_source_continues_after_merge (:544-592) re-merges with a new commit, so the second merge copies 1 and never hits the Conflict { actual == new } arm. I tried a same-head re-merge on the memory nameservice and it does come back Ok (fast-forward, 0 copied, same head), so the arm is reachable and right; it just isn't pinned, and it's ~15 lines to pin it:

let r1 = fluree.merge_branch("mydb", "dev", None, ConflictStrategy::default()).await.unwrap();
let r2 = fluree.merge_branch("mydb", "dev", None, ConflictStrategy::default()).await
  .expect("re-running a landed fast-forward is idempotent");
assert!(r2.fast_forward);
assert_eq!(r2.commits_copied, 0);
assert_eq!(r2.new_head_id, r1.new_head_id);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 62fa6c1

};
match self
.publisher()?
.compare_and_set_ref(&target_id, RefKind::CommitHead, Some(&expected), &new_ref)

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/merge.rs:407 — optional (test), more of a question than a suggestion. Claude caught this while mutating: reverting the CAS back to publish_commit leaves all 52 memory-plane merge tests green; only the consensus test catches it, and only through the queue error — so nothing pins "the CAS expects the head prepare_merge computed against", which is the hardening half of this arm. apply_merge being private is a fair reason there's no direct test, but the transact crate already has the shape for this: a LosePublishRaceNameService-style wrapper (fluree-db-transact/src/commit.rs:1356) around the memory nameservice that advances the target head once inside compare_and_set_ref before delegating would drive the race through the public merge_branch and assert the 409. Happy to talk it through if you think the shim isn't worth its weight here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 62fa6c1

// txn-meta still read correctly); it is the label table that is
// wrong, which is worse for being invisible to a data query.
//
// Leaving the target's own index ref alone costs a rebuild from

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/merge.rs:450 — optional (repair path; commenting here because admin.rs and docs/ are not in this diff). Two things about "a full reindex repairs an already-affected ledger; the cached handle keeps serving the stale registry until evicted". First, the lever is missing: reindex publishes the new root (admin.rs:2078) and returns without disconnecting the cached handle, unlike the drop/purge paths (admin.rs:701, :811, :1201), and LedgerManager::disconnect is public (ledger_manager.rs:1500) but no route exposes it — so today the repair is "reindex, then restart the process". A one-liner after the publish, mirroring admin.rs:701, would make reindex the whole repair. Second, and I traced this rather than ran it, so I may be wrong: the damage on an affected ledger escalates. Its first incremental index cycle passes the resolver's label check because that check keys off the root's ledger_id (resolver.rs:1217-1218), then from_old_root re-stamps ledger_id to the target (incremental_root.rs:41-43) while set_graph_iris carries the branch labels forward (build/incremental.rs:1278) — so the second cycle trips graph_iris[0] must be txn-meta IRI and the ledger stops indexing incrementally until the full rebuild. If that holds, it's worth saying in the PR body and in docs/guides/cookbook-branching.md, which already carries the analogous "no index → replays from genesis; transact a no-op to force a rebuild" note for --at branches (:194) — a fast-forward target now has that shape for the merged range too. Non-blocking, but the doc line is cheap.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 62fa6c1

Reindex now evicts the calling instance's cached ledger, and the regression verifies corrected graph labels and governance reads without a manual disconnect. The cookbook includes repair and cache-reload instructions.

I also reproduced both indexing cycles: the first retains the adopted labels; the second fails the txn-meta label validation, but the normal indexer then falls back to a full rebuild and repairs the labels. The test and docs capture that fallback rather than claiming indexing permanently stops.

The existing cached-handle ownership test also needed to reacquire its handle after reindex eviction; that CI follow-up is in 5c782ce. Its index-presence and dictionary-ownership assertions remain intact.

.await?
{
CasResult::Updated => {}
// Idempotent re-run: the head is already exactly where

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/merge.rs:411 — praise. The idempotent arm compares the full head (t and id), not just t, and the expected is the prepared head rather than a fresh read (:397-400 ← :503-527) — that's what makes it an ancestry check instead of fast_forward_commit's t-ordering. Worth preserving as-is if the arm gets touched again.

// concurrent writer included — leaves the target's head
// to that writer; forcing the snapshot back over it
// would orphan their commit.
let head_is_ours = self

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/merge.rs:148 — praise. Gating reset_head on "the head is the one this merge published" also closes a raft-side hazard the body doesn't mention: reset_head on that plane clears the branch queue (reset_head_clears_queue_and_stamps_marker), so the old unconditional rollback on a pre-publish failure could drop a concurrent writer's staged entries as well as their head.

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

The changes look good to me, but I think there's a semantic we need to clarify now. The fast-forward merges now bypass the work queue on raft. A fast-forward merge will front-run a commit submitted well before it on a busy ledger. This is probably fine in practice, but it does prioritize merges over commits, so it might be worth a doc update making that explicit.

Skip unused source index copies on fast-forward merges. Evict the local
ledger cache after a successful reindex so same-time root replacements
repair graph registry and configuration reads immediately on reload.

Exercise the public merge API with deterministic concurrent commits,
including equal-t/different-CID heads, and pin idempotent re-merges.
Reproduce index adoption and the second-cycle full-rebuild fallback.
Document direct Raft queue bypass, index catch-up, and cache repair.

Validation: 170 ledger tests, 23 reindex tests, 6 embedded Raft tests;
API and consensus clippy; workspace fmt; six expected mutation failures.
The dictionary ownership regression kept using a handle from before
reindex. Reindex now evicts that cache entry so same-time root repairs
are visible on subsequent loads; refresh by ledger ID cannot update
the caller's detached handle.

Drop the old handle and reacquire the cached ledger after reindex.
Keep the index-presence, probe-count, and unique-ownership assertions
for the post-index, steady-state, and SPARQL write paths.

Validation: reproduced the CI assertion locally before the fix;
172 tests passed (grp_ledger and both dictionary ownership binaries),
targeted clippy and workspace formatting passed.
@bplatz

bplatz commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

@zonotope — Addressed in 62fa6c1

The Rust API docs and branching cookbook now state that direct Fluree::merge_branch fast-forwards go through Raft consensus but can overtake work in the per-branch queue. The server's QueuedTransactor::merge path remains queue-ordered.

@aaj3f — The PR description now limits the empty-queue failure to direct API callers on queue-backed deployments and removes the broad claim about all replicated proposal workflows. It also describes the new race/idempotency coverage, index catch-up cost, and verified second-cycle full-rebuild fallback. Replies on the five actionable inline threads point to the implementation commit. The prepared-head CAS, full (t, commit ID) comparison, and rollback guard are preserved and covered by mutation checks.

The CI failure was the existing dictionary-ownership test using a handle retained across reindex eviction. Fixed in 5c782ce by reacquiring the cached handle after reindex; the index-presence and ownership assertions are unchanged. I reproduced the original failure locally, then passed both ownership test binaries and all 170 ledger tests (172 total), targeted clippy, and workspace formatting. The fix is pushed for a fresh CI run.

@bplatz
bplatz merged commit b61a9a6 into main Sep 10, 2026
16 checks passed
@bplatz
bplatz deleted the fix/ff-merge-publishes-ref branch September 10, 2026 17:47
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.

3 participants