Skip to content

fix: route named graphs by ledger graph id, not transaction-local numbers - #1926

Merged
bplatz merged 2 commits into
mainfrom
fix/graph-routing-ledger-ids
Sep 25, 2026
Merged

bplatz merged 2 commits into
mainfrom
fix/graph-routing-ledger-ids

Conversation

@bplatz

@bplatz bplatz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A transaction numbered the named graphs it wrote with a local counter. JSON-LD started at 2, SPARQL, TriG and graph transfers at 3, and sync used a fixed 2. Those numbers left the transaction and were read as ledger graph ids:

  • Uniqueness missed duplicates. Enforcement queried the ledger graph that happened to share the local number. A duplicate written to any other named graph was accepted. For example, with named graphs A then B and alice's email in B, inserting bob with the same email into B committed.
  • SHACL skipped named-graph writes. The validator read staged subjects from the same wrong graph, didn't find the new rdf:type there, and never applied the shape. A nameless ex:Person in a named graph was accepted unless the two numbers happened to line up. For JSON-LD they never did, because local 2 is the ledger's #config graph.
  • Merge and revert combined graph lists by the wrong key. Commits persisted the local numbers, and merge and revert combined graph lists by those keys, so a later commit's graph was dropped from the list whenever two commits reused a number. The dropped graph's flakes still arrive, and staging rejects a flake in an unknown graph, so this surfaces as the failure below rather than as silent data loss.

Separately, merge, revert and rebase staging routed only graphs the target had already registered. Bringing in a named graph created on the source branch failed with unknown graph Sid.

Fix

  • Templates carry the graph IRI. TripleTemplate.graph is TemplateGraph::{Default, Iri, Var}, which replaces the local graph_id and the separate graph_var. Txn::write_graphs is the set of graph IRIs a transaction writes. All the local allocators are gone.
  • Staging reports ledger ids. stage_with_graph_delta returns graphs keyed by ledger graph id, with provisional ids for new graphs. Graph management returns every graph it touches. SHACL and uniqueness now read the graph a write actually lands in.
  • One graph map for uniqueness. Both uniqueness paths share a single Sid-to-graph map built from the staged namespace registry. Previously a graph IRI in a namespace the transaction introduced fell back to the default graph.
  • Commits assign graph ids. CommitOpts::with_graph_iris takes IRIs, and the commit records the ids its registry assigns. Merge and revert union the source commits' graphs by IRI.
  • Branch operations route source graphs. Merge, revert and rebase staging route graphs the target hasn't registered by the id the commit will assign. The merge preview carries the source's graphs too, via compute_delta_keys_and_changes.

Tests

Each test below fails without its fix:

  • uniqueness in the second of two named graphs, on SPARQL and JSON-LD
  • a SHACL violation in g/a, g/b and a new graph, on SPARQL and JSON-LD, plus a guard that a conforming write to g/b still passes
  • merging a branch whose two commits each create a named graph
  • rebasing a commit that creates a named graph

For SHACL, renumbering only staging's output is not a valid check, because staging and SHACL then agree on the wrong graph. The failing mutation renumbers only the graphs handed to the SHACL wrapper.

Existing data

The fix applies from now on. It does not re-check what is already stored. A ledger written before it may hold named-graph data that SHACL never validated, and duplicate values the uniqueness check never saw. For JSON-LD that covers every named-graph write, because local 2 was the #config graph. Operators who rely on SHACL or f:enforceUnique in named graphs should re-check that data.

Migration

None for data. Commits written before this change still carry local numbers in graph_delta. Every reader uses only the IRIs, and merge and revert now union by IRI, so those commits are handled. The TripleTemplate, Txn and CommitOpts changes are internal to the workspace.

@bplatz
bplatz added this pull request to stack #1922 September 25, 2026 03:37
@bplatz
bplatz requested a review from aaj3f September 25, 2026 03:37
@bplatz bplatz added the bug Something isn't working as expected label Sep 25, 2026
@bplatz
bplatz requested a review from zonotope September 25, 2026 03:37
@bplatz bplatz added the area:transact Staging, commit, import/bulk-import, novelty, retraction semantics label Sep 25, 2026
@bplatz
bplatz marked this pull request as ready for review September 25, 2026 03:38
@bplatz
bplatz force-pushed the fix/graph-routing-ledger-ids branch from f5b8410 to c72baaa Compare September 25, 2026 10:24

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

@bplatz really excellent find & fix. When looking at the problem I was nervous this PR may have backwards compat or breaking-change issues and I'm glad to see it doesn't. While doing the Claude-assisted review, I pushed it in a few places to do some extra consideration that the PR was edge-case correct and complete, and nothing significant turned up from those--which is great. Full review below:


This is a really satisfying PR— the part I like most is that it's mostly deletion. Four separate local allocators and a two-field template invariant collapse into TemplateGraph::{Default, Iri, Var} plus one BTreeSet of IRIs, with GraphRegistry left as the only thing in the system that ever hands out a number, and the result is that the whole class of bug becomes unrepresentable rather than patched. I spent most of my time on the question the title invites — is anything on disk keyed by the old numbers? — and the answer holds up: Flake.g is a Sid, every reader of the persisted Commit::graph_delta consumes only its IRI values (9 call sites, all traced), and apply_delta re-derives ids from the sorted unregistered set, so a pre-change commit replays to the same ids it always did. multi_op_graph_delta_mapping_survives_reload still passes and pins exactly that. No migration, no reindex, no misrouted read on existing data — the body's Migration section is correct.

Two things I'd add to the record rather than the code. First, I'd soften the "merge and revert could drop graphs" bullet: I couldn't construct a case where it loses data quietly, because the dropped graph's flakes still arrive and StagedOverlay::from_flakes hard-errors on an unknown graph Sid (fluree-db-ledger/src/staged.rs:90) — so in practice the fourth bullet (unknown graph Sid on any merge of a branch that created a named graph) is the symptom users actually hit, and it subsumes the third. Second, and more operationally: this fix is forward-only. Ledgers written before it may already hold named-graph rows that SHACL never validated and duplicate values uniqueness never saw — for JSON-LD every named-graph write, since local 2 is the #config graph — and nothing here re-validates them. That's the shape of the bug rather than a gap in the PR, but it's what I'd want to tell an operator who has been writing named graphs from JSON-LD, and it might be worth a line in the release notes.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Extends GraphRegistry's existing provisional_ids/apply_delta contract and deletes four parallel allocators rather than adding a fifth; the TemplateGraph enum makes the old two-field invariant unrepresentable.
  • Performance (speed first, memory second): ✔ Transaction staging only, no query-engine change. One per-flake u16-hash → IRI-hash on the named-graph write path (~10 ns, noise against the per-term string work already there); the uniqueness path now builds one Sid → GraphId map per transaction instead of two. No performance-degradation risk.
  • Testing: ✔ Seven new integration tests across both surfaces, all wired into grp_graphsource/grp_ledger and verified running by name locally; the uniqueness pair goes red under a targeted mutation of tx.rs::flake_graph_id. Full --all-features nextest and the W3C suite are green on c72baaa70 (run 36123813620, event=pull_request).
  • Conventions: ✔ Self-describing subject, thorough multi-line body, clippy/fmt green. Two stale graph_delta comments in test files noted above.

Verified locally at branch HEAD: cargo nextest run -p fluree-db-api --features native,shacl --test grp_graphsource --test grp_ledger over the seven new tests → 7 passed; mutation of tx.rs::flake_graph_id → both uniqueness tests fail as expected; worktree restored clean.

Approving so you can merge when ready — the filter_map at commit.rs:786 and the two stale comments are the only things I'd nudge on, and neither should hold this up.

Comment thread fluree-db-api/src/tx.rs
/// Sid: the graphs the transaction writes (`graph_delta`, keyed by ledger
/// graph id) and every registered graph. Sids come from the staged namespace
/// registry, which also knows namespaces the transaction introduced.
fn graph_ids_by_sid(

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.

Praise — graph_ids_by_sid quietly fixes a second bug that isn't in the PR title.

Building off staged_ns.lookup_sid_for_iri rather than snapshot.encode_iri means a graph IRI in a namespace this transaction introduced is now resolvable. Before, the snapshot's encoder didn't know that namespace, the lookup returned None, and the flake fell through to the default graph — so uniqueness checked graph 0.

Folding the two previously-separate Sid → GraphId maps into one built once per transaction is a nice bonus.


/// The graph a [`TripleTemplate`] writes to.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub enum TemplateGraph {

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.

Praise — TemplateGraph makes the mutual-exclusion invariant unrepresentable.

graph_id: Option<u16> + graph_var: Option<VarId> encoded "exactly one of these is set" in a doc comment and enforced it in two setters that each cleared the other. TemplateGraph::{Default, Iri, Var} makes the bad state impossible to construct.

That, plus deleting all four local allocators, is what makes me confident the class of bug is gone rather than patched.

/// will assign. The Sid is resolved against the state's namespaces plus
/// `namespace_delta`, the codes the incoming commits introduced, so it
/// matches the Sid their flakes carry.
fn unregistered_graphs(

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.

Praise — resolving the incoming graphs' Sids against the incoming namespace_delta is the subtle half of the merge fix.

Routing by the provisional id alone wouldn't have matched the Sid the arriving flakes actually carry, because those commits may have introduced the namespace themselves. Easy to get wrong, and the kind of thing that only shows up on a real cross-branch merge.

Good that compute_delta_keys_and_changes grew the fourth return too, so merge preview validates against the same graph set the merge will.

}
// Keyed by the ids the registry now holds, so a commit's graph_delta is
// the ledger's own id -> IRI mapping.
commit_record.graph_delta = graph_iris

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.

Optional — this is more of a question than a suggestion: a filter_map on the one hunk that writes the persisted mapping.

commit_record.graph_delta = graph_iris.into_iter().filter_map(|iri| Some((registry.graph_id_for_iri(&iri)?, iri))).collect() silently drops any IRI the registry can't resolve, and this is the line that decides what lands on disk.

I traced it and I don't think it can fire — the retain above keeps only unregistered-or-system IRIs, and apply_envelope_deltas runs unconditionally whenever graph_iris is non-empty — but a silent drop on the hunk that writes the persisted mapping is the kind of thing that stays quiet for a year and then loses a registration. Would we rather it be loud?

commit_record.graph_delta = graph_iris
    .into_iter()
    .map(|iri| {
        let g_id = base.snapshot.graph_registry.graph_id_for_iri(&iri).ok_or_else(|| {
            TransactError::FlakeGeneration(format!(
                "graph <{iri}> was written but is not in the registry after apply"
            ))
        })?;
        Ok((g_id, iri))
    })
    .collect::<Result<_>>()?;

Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now 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.

Agreed. It's loud now in 5abd390: a written IRI the registry can't resolve fails the commit with FlakeGeneration, using your shape.

pub graph_delta: FxHashMap<u16, String>,
/// Staging reports the full set keyed by ledger graph id, and the commit
/// registers any that are new.
pub write_graphs: BTreeSet<String>,

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.

Nit — fluree-db-api/tests/it_reserved_graph_writes.rs:74 and fluree-db-api/tests/it_sync_graph.rs:324 still describe the old field.

"Three spellings reach Txn::graph_delta: a GRAPH block, the WITH …" and "parse_sync_transaction's graph_delta guard rejects it with …". Both are write_graphs now.

Both comments are load-bearing explanations of why those tests exist, so they're worth keeping accurate — a reader who greps Txn::graph_delta after this lands finds nothing.

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

Commenting here because fluree-db-api/tests/it_reserved_graph_writes.rs is not in this diff.

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.

Fixed in 5abd390: both comments now say write_graphs. Two more in it_reserved_graph_writes.rs (:115, :158) had the same drift, and the TriG one also named the removed GraphIdAssigner, so those are updated too. So is a stale doc note in tx.rs that referred to it.

&self.written_graphs
}

fn graph_sid(&mut self, iri: &str) -> Sid {

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.

Optional — a perf note that is almost certainly a non-issue, flagged only because the body implies the fix is free.

graph_sid runs per flake and now hashes the graph IRI (HashMap<String, Sid>, so SipHash over ~30 bytes) where the old graph_sids.get(&g_id) hashed a u16.

That's on the order of 10 ns a flake, only on named-graph writes, against a loop that already does namespace splitting and sid_for_iri string hashing per term. I'd call it noise, and I'm not asking for anything here.

@bplatz
bplatz removed this pull request from stack #1922 September 25, 2026 18:27
Base automatically changed from fix/optional-null-semantics-1734 to main September 25, 2026 18:43
@bplatz
bplatz force-pushed the fix/graph-routing-ledger-ids branch from c72baaa to 6feaf9b Compare September 25, 2026 19:15
@bplatz
bplatz changed the base branch from main to feat/sparql-update-graph-var September 25, 2026 19:15
@bplatz
bplatz added this pull request to stack #1947 September 25, 2026 19:15
@bplatz
bplatz force-pushed the fix/graph-routing-ledger-ids branch from 6feaf9b to 249740b Compare September 25, 2026 20:16
Base automatically changed from feat/sparql-update-graph-var to main September 25, 2026 21:07
…bers

Transactions numbered the named graphs they wrote with a local counter
(JSON-LD from 2, SPARQL, TriG and transfers from 3, sync fixed at 2), and
those numbers escaped the transaction as if they were ledger graph ids:

- uniqueness enforcement looked for duplicates in the ledger graph that
  happened to share the local number, so a duplicate written to any other
  named graph was accepted
- SHACL validated staged subjects against that same wrong graph; it never
  saw the new rdf:type there and skipped the shape, so JSON-LD writes to
  named graphs (local 2 = #config) were effectively never validated
- commits persisted the local numbers, and merge and revert combined
  graph lists by those keys, dropping a later commit's graph when two
  commits reused a number

Templates now carry the graph IRI (TemplateGraph), transactions carry the
set of graphs they write (Txn::write_graphs), and the local counters are
gone. Staging returns its graphs keyed by ledger id, provisional for new
ones, so SHACL and uniqueness read the right graph. The uniqueness paths
share one Sid -> graph id map built from the staged namespace registry.
CommitOpts takes graph IRIs, and the commit records the ids its registry
assigns. Commit data from merge and revert is unioned by IRI.

Merge, revert and rebase staging routed only graphs the target had
registered, so bringing in a graph created on the source branch failed
with "unknown graph Sid". They now route those graphs by the id the
commit will assign, and the merge preview carries the source's graphs.
@bplatz
bplatz force-pushed the fix/graph-routing-ledger-ids branch from 249740b to 3b8136c Compare September 25, 2026 21:07
…mmit

The commit's graph_delta is the persisted id -> IRI mapping, and a
filter_map silently dropped any written IRI the registry could not
resolve. That can't happen today, but if it ever did the commit would
lose the graph's registration with no signal, so it is now an error.

Also updates comments that still described Txn::graph_delta and the
removed GraphIdAssigner; both are write_graphs now.
@bplatz

bplatz commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f thanks. Both nudges are in 5abd390: the commit's graph list now errors instead of silently dropping, and the stale graph_delta comments are fixed, plus a few more with the same drift.

I also took both notes for the record into the description:

  • The merge/revert bullet now says the dropped graph surfaces as the unknown graph Sid failure, not silent loss.
  • A new Existing data section says the fix doesn't re-check stored data, so a ledger written before it may hold named-graph rows that SHACL and uniqueness never saw (every JSON-LD named-graph write). The PR carries the bug label, so this lands under fixes in the release notes.

@bplatz
bplatz merged commit f7db742 into main Sep 25, 2026
16 checks passed
@bplatz
bplatz deleted the fix/graph-routing-ledger-ids branch September 25, 2026 21:31
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.

2 participants