Repository navigation
fix: route named graphs by ledger graph id, not transaction-local numbers - #1926
Conversation
f5b8410 to
c72baaa
Compare
aaj3f
left a comment
There was a problem hiding this comment.
@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 existingprovisional_ids/apply_deltacontract and deletes four parallel allocators rather than adding a fifth; theTemplateGraphenum 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 oneSid → GraphIdmap per transaction instead of two. No performance-degradation risk. - Testing: ✔ Seven new integration tests across both surfaces, all wired into
grp_graphsource/grp_ledgerand verified running by name locally; the uniqueness pair goes red under a targeted mutation oftx.rs::flake_graph_id. Full--all-featuresnextest and the W3C suite are green onc72baaa70(run36123813620,event=pull_request). - Conventions: ✔ Self-describing subject, thorough multi-line body, clippy/fmt green. Two stale
graph_deltacomments 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.
| /// 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( |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
c72baaa to
6feaf9b
Compare
6feaf9b to
249740b
Compare
…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.
249740b to
3b8136c
Compare
…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.
|
@aaj3f thanks. Both nudges are in 5abd390: the commit's graph list now errors instead of silently dropping, and the stale I also took both notes for the record into the description:
|
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:
AthenBand alice's email inB, inserting bob with the same email intoBcommitted.rdf:typethere, and never applied the shape. A namelessex:Personin 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#configgraph.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
TripleTemplate.graphisTemplateGraph::{Default, Iri, Var}, which replaces the localgraph_idand the separategraph_var.Txn::write_graphsis the set of graph IRIs a transaction writes. All the local allocators are gone.stage_with_graph_deltareturns 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.CommitOpts::with_graph_iristakes IRIs, and the commit records the ids its registry assigns. Merge and revert union the source commits' graphs by IRI.compute_delta_keys_and_changes.Tests
Each test below fails without its fix:
g/a,g/band a new graph, on SPARQL and JSON-LD, plus a guard that a conforming write tog/bstill passesFor 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
#configgraph. Operators who rely on SHACL orf:enforceUniquein 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. TheTripleTemplate,TxnandCommitOptschanges are internal to the workspace.