Skip to content

Validate SHACL rules on merge operations - #1822

Merged
zonotope merged 16 commits into
mainfrom
fix/merge-shacl-validation
Sep 15, 2026
Merged

zonotope merged 16 commits into
mainfrom
fix/merge-shacl-validation

Conversation

@zonotope

@zonotope zonotope commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1782

Stacked on #1818 (fix/branch-workflow-t).

Problem

A transaction that would violate an attached SHACL shape is rejected at commit time. Merge, rebase, and revert build their commits on a parallel path that never consulted the shapes. So a take-both merge, whose resolution is "both values coexist", could leave two values on a sh:maxCount 1 property and report success. The violation sat in the ledger until someone ran fluree validate. Rebase replays and revert commits had the same gap.

Fix

Branch operations now stage and validate through one helper, stage_validated. Staging and validation can't be separated, so a future operation can't copy one without the other. It runs the same post-stage validation transactions run, under the ledger's configured posture.

  • Merge validates the resolved state before copying the source's commits or building the merge commit. A rejection writes nothing and leaves the target untouched. Fast-forward merges are skipped, because the adopted commits were validated when they were authored.
  • Rebase validates each replayed commit against the state it lands on. The first violation aborts the whole rebase, which has published nothing yet, and the error names the commit it stopped on.
  • Revert validates the inverted state. For example, undoing the commit that asserted a value a later sh:minCount requires is rejected.

A rejection returns the same ShaclViolation error and report a rejected transaction does. Warn-mode graphs log and proceed.

Cross-ledger shapes are enforced, not skipped. Commit replay skips a cross-ledger f:shapesSource, because the origin already validated it. A branch operation is authoring: the state it stages onto the target is a combination nobody has validated. So the model ledger is resolved at operation time, as it is for a transaction. This was the originating field case.

Merge preview

A preview that says mergeable while the merge would be rejected is worse than no preview. The preview now stages the resolved change set on a clone of the target state and runs the merge's own staging (stage_merge), so the two can't disagree.

  • New validation field. It carries conforms and, when rejected, the report the merge would fail with.
  • mergeable now means the merge will go through. The strategy applies without aborting and the result conforms. The docs previously warned it was not a guarantee.
  • Resolution matches the merge exactly. It uses the uncapped conflict set, whether or not conflicts are reported, and skips validation exactly where the merge would. The abort decision is shared through ConflictStrategy::aborts_on.
  • On by default through include_validation. CLI fluree branch diff --no-validate, server query parameter, and remote client. The local and remote text printers show the validation outcome and a mergeable line.

Behavior changes to note

  • Preview cost. A non-fast-forward preview now loads the target state and runs a validation pass by default. Use include_validation=false for count-only previews.
  • Namespace-code collisions. Sibling branches allocate namespace codes independently. When two siblings give the same code to different prefixes, the merge was already refused at commit build. It now fails earlier as a BranchConflict (409), and the preview reports it that way instead of returning an internal error.

Tests

it_branch_shacl.rs adds 12 tests:

  • Plain-transaction controls showing each state is one a transaction would refuse.
  • Rejected merges, including one through a cross-ledger shape.
  • A rejected rebase replay and a rejected revert.
  • A conforming merge and warn mode, both passing.
  • Preview cases: violation, conforming, opt-out, conflict resolution with reporting off, and a sibling namespace collision.

The branch op tests were observed failing before the fix. Removing validation from the shared helper fails six of them.

Docs

Updated: docs/api/endpoints.md, docs/cli/server-integration.md (new rule 12 in the merge preview contract), docs/cli/branch.md, docs/getting-started/rust-api.md, and the SHACL and branching cookbooks. Also docs/security/cross-ledger-policy.md, which lists branch operations among the enforced surfaces and explains why they don't take the replay carve-out.

Out of scope

  • The rebase report's failures field is still never populated. A rejected replay aborts the rebase instead.
  • Follow-up: Sibling merges can pick a common ancestor on the wrong clock. The namespace-collision behavior above is one symptom of the same topology.

@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 this makes a great deal of sense given the problem description. I think the design seems sound and makes sense. I've included the full review below, but some headline notes I'd give additional signal to:

  • prepare_rebase calls coupy_source_index which publishes the source's index ref onto the branch before the replay loop actually runs, which as a result then, I think, can make the branch read as main afterwards even if the rebase is rejected. Maybe I'm reading that logic wrong--you know more about this than I do (for sure, lol)
  • It seems revert_preview doesn't have the staging or validation that merge preview does (revert_preview still builds only with build_revert_context) so the preview can appear clean even when the code will actually reject it.
  • The PR body claims "When two siblings give the same code to different prefixes, the merge was already refused at commit build. It now fails earlier as a BranchConflict (409), and the preview reports it that way" but I don't know that this is in fact accurate. There's the note about "Follow-up: #." but that sibling follow-up isn't named--so I wasn't sure if either the first claim deserves amending or if the follow-up intends to reconcile this?

There are some other notes of significance below, but wanted to give the two above items some human-foregounding first. I'm approving because your work tends to be faster than my review cycles, so I don't want to hold you up and risk this branch getting stuck in a merge-conflict-resolution spiral against all the other PRs that are getting merged


This is the fix #1782 wanted and it's built the way I'd have hoped: one helper (stage_validated) that the merge, rebase, revert and the merge preview all go through, running the transaction path's own post-stage validator under the ledger's configured posture, with cross-ledger shapes resolved at operation time exactly as a transaction resolves them, and the merge preview reusing the merge's staging so mergeable can't drift.

I verified the parts that matter rather than reading them: the 12 tests are wired through grp_ledger under shacl (CI's --all-features runs them), all 195 pass at head, short-circuiting the validator fails exactly the six you said, and warn-as-reject fails only the warn-mode test. Fast-forward skipping is sound for a stronger reason than the body gives (a ff means the target head is the ancestor, so the post-ff state is the source head state that the source validated commit-by-commit, config changes included).

I'm requesting changes for one thing, and it's small: prepare_rebase still publishes the source's index ref onto the branch (copy_source_index at rebase.rs:447 → publish_index at :850) before the replay loop, and a rejection now returns through rebase_branch's ? at :246 with no reset_head. With an indexed source that leaves the branch record at commit_t=2, index_t=2, index_head=<main's>, and since the loader only replays novelty when commit_t > snapshot.t, the branch reads as main afterwards — in my repro dev's own B disappears from every read and a follow-on insert builds on main's state. Pre-existing ordering, but this PR makes it the routine outcome of a rejected rebase and the docs/test say "left as it was" (the test only passes because memory-mode main is unindexed). Moving the index copy to after the replay loop, plus running that test against an indexed source, is the whole ask.

Two smaller notes inline: the body's "the merge now fails earlier as a BranchConflict" holds for the preview only — the merge on the same sibling fixture dies in find_common_ancestor with a storage NotFound before it reaches staging — and a ff preview's absent validation is unpinned (dropping the gate turns nothing red; test supplied). One merge-order point that isn't yours: #1818's finish() netting is still underneath this branch, and with a maxCount shape it now produces a false SHACL rejection of a conforming merge (re-insert then replace) alongside the silent deletion loss (re-insert then delete) — so that fix should land first and this rebase on it.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Extends apply_shacl_policy_to_staged_view through one shared stage_validated/stage_merge seam and one shared ConflictStrategy::aborts_on; no parallel validator, no second SHACL entry point; cross-ledger resolution reuses the tx path's ResolveCtx.
  • Performance (speed first, memory second): ✔ No query-engine, novelty-read, or transaction-path change. Branch ops pay a transaction-equivalent validation by design; the merge-preview GET now loads the target and recompiles shapes per call by default (opt-out at every surface), plus one Vec<Flake> clone when changes are also requested. No performance-degradation risk on hot paths.
  • Testing: ⚠️ 12 wired integration tests that run in CI and go red under mutation (validator off → 6, warn-as-reject → 1); but the rebase test cannot see the index-ref regression (unindexed source), the ff-preview contract is unpinned (gate off → 0 red), and the merge side of the sibling-collision claim is untested and false at head.
  • Conventions: ⚠️ fmt clean; clippy -D warnings clean on api (--all-targets, native,shacl), novelty, cli, server-lib; api compiles without shacl; docs updated across seven files and accurate except the two over-claims noted. All ten commits are subject-only (repo convention is a body) and 449e1d236's subject has "it's" for "its"; the body's #<sibling> placeholder is unfilled.

Verified locally at branch HEAD 2b134afff: grp_ledger 195 passed with all 12 new names; three mutations (validator short-circuit, ff gate, warn-as-reject) red exactly where expected; six probes (two #1818 shapes, Abort-without-conflicts, sibling merge, ff preview, indexed-source rebase) with the values quoted above; cargo fmt --check clean; clippy clean on the four crates; novelty lib 95 passed.

Happy to re-run the indexed-source rebase and the two #1818 shapes as soon as the index-copy move lands and #1818's finish() fix is underneath

// the state it lands on; the first violation aborts the whole rebase,
// which has published nothing yet, naming the commit it stopped on.
let (view, outcome) = self
.stage_validated(state, flakes, &original_commit.namespace_delta, "rebase")

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:669 — blocking. A rejected rebase leaves the branch's nameservice record pointing at the source's index, and the branch then reads as the source. Real location is rebase.rs:447 → :850 and :246; commenting here because those lines aren't in this diff.

Mechanism: prepare_rebase calls copy_source_index at :447, before the replay loop, and that helper doesn't just copy artifacts — it publish_index(branch_id, source_record.index_t, index_cid)es onto the branch's record (:850). When build_replay_commit now returns ShaclViolation from stage_validated here, the error goes out through rebase_branch's let staged = self.prepare_rebase(…).await? at :246, which is above the apply_rebase rollback arm, so reset_head(rollback_snapshot) never runs. The commits really are unpublished, as the comment says; the index ref is not.

Concrete case at this head, in-process: main alice A (t=1); fork dev; dev alice B (t=2); main installs the maxCount 1 shape (t=2) and is indexed (support::rebuild_and_publish_index(&fluree, "mydb:main")); rebase_branch("mydb", "dev", …) → ShaclViolation, as designed. Afterwards dev's record is commit_t=2, index_t=2, index_head=<main's index cid>. LedgerState::load_with_store (fluree-db-ledger/src/lib.rs:281) replays novelty only when commit_t > snapshot.t, so dev now loads main's index and nothing else: names(dev) reads ["A"] — B is gone and main's shape is visible on dev — and a follow-on insert on dev lands at t=3 on that state (["A", "Carol"]). B is still on dev's commit chain and unreachable from every read. Your code didn't introduce the ordering (a mid-replay 422 or storage error hit the same path before), but this PR turns it from a rare operational failure into the documented, expected outcome of a class of rebases — and docs/cli/branch.md:209 ("the branch is left as it was") and the // dev is untouched. assertions at it_branch_shacl.rs:386-388 both claim the opposite. The test passes only because memory-mode main has no index, so copy_source_index is a no-op there.

Fix, small: move the copy_source_index call from :447 to after the replay loop succeeds (end of the general path, just before Ok(StagedRebase { … }), so the raft caller of prepare_rebase keeps it) — replay reads self.ledger(&source_id) and never the copied index, so nothing in the build phase needs it early. Minimally, wrap the prepare failure the way apply is wrapped: reset_head(&branch_id, rollback_snapshot) on Err, since the snapshot at :361 carries both index fields and reset_head restores them (memory.rs:218-221, storage_ns.rs:752). And please run rebase_rejected_when_replay_violates_shape against an indexed source (add support::rebuild_and_publish_index(&fluree, "mydb:main").await after the shape install and assert the record's index_head_id is unchanged) so "left as it was" is actually pinned.

// Commits stream newest-first, so a plain insert leaves the oldest
// commit's prefix in place for a colliding code.
for (code, prefix) in commit.namespace_delta {
namespace_delta.insert(code, prefix);

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-novelty/src/delta.rs:161 — merge-order. #1818's netting regression is still on the base tip this branch validates through (NetChangeAccumulator::finish, :127-130, keeps a fact only when oldest_op == newest.op), and with a shape on the property it stops being silent. Commenting here because :127-130 isn't in this diff.

Two probes at this head, both with alice A + sh:maxCount 1 seeded on main. (a) dev re-inserts A (redundant, but a real assert flake in the commit) then replaces A→B; main adds bob; default merge → the fold drops A's retract and stages only assert B onto a target holding A → ShaclViolation on a merge whose true result [B] conforms. (b) dev re-inserts A then deletes A; same merge → the fold stages nothing, the merge "succeeds", main reads ["A", "Bob"], and validation can't notice because [A] conforms. Newest-op-wins in finish() fixes both (the one-liner in the #1818 thread), and I'd rather this PR not ship a false-rejection path on top of a silent-loss path — so land #1818's fix first and let this rebase on it.

// needs the netted source delta too. A fast-forward adopts commits
// already validated when they were authored, so it is skipped.
let need_validation = opts.include_validation
&& !fast_forward

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_preview.rs:517 — optional, test gap. Claude caught this by mutation: with && !fast_forward removed here, nothing in it_branch_shacl or it_merge_preview goes red — the ff preview just validates the ff state and everything still passes, so the "fast-forward previews carry no validation" contract in the docs is unpinned. One test closes it; it passes today:

#[tokio::test]
async fn preview_fast_forward_carries_no_validation() {
    let fluree = FlureeBuilder::memory().build_memory();
    let _main = seed_alice_with_shape(&fluree).await;
    let dev = fluree.ledger("mydb:dev").await.unwrap();
    fluree.update(dev, &replace_name("ex:alice", "B")).await.unwrap();
    let preview = fluree
        .merge_preview_with("mydb", "dev", None, MergePreviewOpts::default())
        .await
        .expect("preview");
    assert!(preview.fast_forward);
    assert!(preview.validation.is_none(), "a fast-forward adopts already-validated commits");
    assert!(preview.mergeable);
}

Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

/// can mean different prefixes on each. Such a merge cannot be built; the
/// preview reports that as a branch conflict rather than an internal error.
#[tokio::test]
async fn preview_reports_conflict_when_sibling_namespaces_collide() {

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_branch_shacl.rs:626 — optional, PR-body correction. The body says the sibling namespace collision "was already refused at commit build. It now fails earlier as a BranchConflict (409), and the preview reports it that way." This test proves the preview half. I ran the merge half on the same fixture (merge_branch("mydb", "b", Some("a"), default)) and it never reaches stage_merge: it dies in prepare_merge at find_common_ancestor (merge.rs:281, which walks the target head through the source's branched store) with Core(Storage("Failed to read commit envelope … Not found: fluree:memory://mydb/main/commit/…")) — a 500-class error. The preview survives because it walks a union store (merge_preview.rs:443-447). So the 409 is preview-only, and the merge/preview pair still disagree on sibling topology — which I think is exactly the "#" follow-up the body names, whose number is still a placeholder. I'm not asking for the topology fix here (the wrong-clock ancestor means a union store in prepare_merge alone probably isn't it, so that's genuinely the follow-up's scope); just that the body sentence say what's true and the placeholder get its number.

Comment thread docs/cli/server-integration.md Outdated
would abort (currently `strategy=abort` with one or more conflicts) or, when
`validation` is present, when the merged state fails the target's SHACL
shapes (rule 12). With validation on, `mergeable=true` means a subsequent
`POST /merge` with the same strategy will succeed unless either branch

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/cli/server-integration.md:1047 — optional, docs. "With validation on, mergeable=true means a subsequent POST /merge with the same strategy will succeed unless either branch changes in between" (also docs/cli/branch.md:275, rust-api.md:1299, cookbook-branching.md:193) is a touch stronger than the code can promise: the merge commit still goes through build_commit's novelty backpressure (CommitOpts::default() at merge.rs:637, no skip_backpressure), so a NoveltyAtMax 503 can follow a mergeable: yes, and the sibling-topology error above is another way. I'd phrase it as "neither the strategy nor the target's shapes will reject it" and leave the residual reasons implicit, or list them. Very minor.

Comment thread fluree-db-api/src/merge_preview.rs Outdated
// The change summary below still needs the net set when it was
// requested; otherwise hand it over without a copy.
let net = if need_changes {
net_flakes.clone()

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_preview.rs:663 — optional, perf whisper. When include_changes and validation are both on, net_flakes.clone() copies the whole netted change set once so build_change_summary can take it by value afterwards. I don't think this matters (preview-only, not hot-path), but if build_change_summary could borrow a slice the clone goes away. Not a big deal.

Comment thread fluree-db-api/src/revert.rs Outdated
// Undoing a commit can remove a value a later shape requires. The
// inverted state is validated like any transaction producing it.
let (view, outcome) = self
.stage_validated(target_state, staged, &namespace_delta, "revert")

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:493 — question, not a suggestion. Merge got a preview that runs the merge's own staging so mergeable can't lie; the revert preview (revert_preview.rs) still stops at build_revert_context, so it can say fine for a revert this line will now reject (the minCount case in revert_rejected_when_inverse_violates_shape). I wonder if we want the same stage_validated pass there with a validation field, or whether revert previews are meant to stay cheap. Your call — happy to talk it through.

/// which the snapshot will not carry until the commit lands; they make
/// the operation's own terms encodable for `sh:sparql` lowering and
/// resolvable in messages. `op` names the operation in error messages.
pub(crate) async fn stage_validated(

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/branch_validation.rs:80 — praise. This is the right seam and the right shape: the staging and the validation are one function, so the next branch op can't get one without the other; stage_merge on top of it is why the preview and the merge can't disagree under warn mode or on the strategy. I checked the "no request surface" claim rather than trusting it — no requested mode, no identity, no inline shapes, origin_validated_replay: false — and the ResolveCtx and head-t resolution for a cross-ledger M are the same the transaction path uses (tx.rs:2536 etc., resolver.rs:153-155), so "resolved at operation time, as it is for a transaction" is literally true.

outcome.into_result()?;

// Create merge commit with the source head as an additional parent,
// propagating namespace and graph deltas from the source branch.

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:650 — praise. copy_commit_chain now sits after outcome.into_result()?, so a rejected merge really does write nothing into the target namespace — the one branch op where the ordering is right by construction.

The preview skips validation on a fast-forward, because the commits it adopts
were validated when they were authored. Nothing held that condition in place:
removing it left every test passing, since the fast-forward state validates
cleanly anyway.

Assert the field is absent on a fast-forward preview. With the condition removed
the test fails, so the contract the docs state is now pinned by something.
@zonotope zonotope added bug Something isn't working as expected area:transact Staging, commit, import/bulk-import, novelty, retraction semantics labels Sep 15, 2026
@zonotope zonotope changed the title Fix/merge shacl validation Validate SHACL rules on merge operations Sep 15, 2026
@zonotope
zonotope merged commit 3561ebc into main Sep 15, 2026
16 checks passed
@zonotope
zonotope deleted the fix/merge-shacl-validation branch September 15, 2026 13:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:transact Staging, commit, import/bulk-import, novelty, retraction semantics bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Branch merge/rebase/revert commit without SHACL validation — a merge silently writes state the ledger's own shapes reject

2 participants