Repository navigation
fix(cypher): a statement's clauses see one another's writes, and the last holds - #2184
Conversation
…last holds A write statement whose clauses touch the same facts ran as one Txn: every clause read the state before the statement and staged as one operation. So `SET n.name = "y" SET n.name = "w"` asserted both values, `REMOVE n.name SET n.name = "x"` removed the name, `SET n.name = "y", n.name = "w"` kept both, and a CREATE after a SET of a multi-valued property, or after a DETACH DELETE, created one node per stored value the SET or the DELETE looked up. Such statements now run through the sequential driver, which stages each clause against the state the clauses before it leave, and the stager folds each fact to its last write, the fold SPARQL's `;`-separated updates use. `interacting_writes` decides: two clauses writing one property key or label (on any variables, since two can bind one node), a DETACH DELETE with any other write, a CREATE with a clause that looks up stored values, or a SET writing one key twice, split at the repeat. Statements whose clauses can't meet keep the single Txn. The driver now stages a node's DETACH DELETE, and seeds a SET, REMOVE or DETACH DELETE only with the rows that bind its target, so it takes an OPTIONAL MATCH before them: a row the OPTIONAL MATCH leaves unbound writes nothing. Without that, the clause's own lookup of the stored value bound the free target to any node. Each new test runs a statement and the SPARQL UPDATE that means the same on ledgers seeded alike, and requires the same state and the same commit.
`interacting_writes` cloned and split every statement's clauses and ran the driver's member checks before knowing whether any two clauses meet. A statement with one clause that isn't a SET writing a key twice now returns at once; otherwise the clauses are compared as they are, and the checks and the split run only for a statement that routes. Also pins a SET on a node the statement creates: the single Txn refused it, and the driver stages it after the CREATE.
…view Each operation of a sequential write (a `;`-separated SPARQL update, a multi-clause Cypher statement, a Transaction) stages against a virtual state, and each virtual state's new overlay content missed the planner stats cache, so every operation and every probe assembled the stats again over the whole novelty window. On a 1,000-node ledger with all of it in novelty, that was about 70% of a routed two-SET Cypher statement on one node. The stager now pins the stats of the state the write began on onto each virtual state it advances to (`Novelty::pin_planner_stats`, cleared by any change to the overlay's content), and `cached_stats_view_for_db` returns the pin before assembling anything. The pinned view is estimates only (`StatsView::estimates_only`): the ref-only flags and the observed datatype sets read "unknown", so a licence the base's stats grant can't be read for a state an operation has changed. The counts are off by the write's own flakes, which planning tolerates. The cache key also folds the semantic-elision vouch in only where it changes the view (class counts trustworthy: novelty empty, current state), so a read and an update WHERE on the same state share one build. The new test reads a transaction after an operation gives an all-ref predicate its first literals: `FILTER(?x = ?y)` keeps value equality.
…e gains a literal The first version of the pinned-stats test used a literal pair the join unifies only in the index's encoding, so it passed with the licences left on the pinned view. A NaN, which the join unifies with itself and `=` holds unequal, fails it: with the licences left on, the read returns the NaN's subject paired with itself.
Assembling the planner stats walks every novelty flake, and for each one hashed its object, datatype and subject into std `HashMap`s (SipHash) as cloned keys, to count distinct values and subjects per predicate. On a ledger with its data in novelty that was most of the pass, and the pass runs for every query and update WHERE whose overlay changed since the last one. The distinct-value and distinct-subject maps now key by references into novelty, which outlives the pass, and the per-pass maps keyed by the ledger's own terms (those two, the per-predicate deltas, the graph index) use FxHash. These keys aren't adversarial, so SipHash's DoS resistance buys nothing here. The output doesn't depend on map order: `finalize_properties` sorts its entries, and the counts are sums.
Two CREATEs never meet, and CREATE chains are the common multi-clause write. The A/B showed the comparison's ten small allocations on a three-CREATE statement; it now returns before building anything.
…less a RETURN reads it The sequential driver applied every clause's facts to a virtual state so the next clause could read them, the last clause included. Only a trailing RETURN reads the state after the last clause; the commit reads the merged result. The last write clause of a statement without a RETURN (and that isn't a MERGE, which probes its own writes) now stages without building it, as SPARQL's last `;` operation already does. The final state is reachable only with the answered RETURN (`AnsweredReturn::final_state`), so no caller can read a state that wasn't built. `cypher_unread_final_state` stamps whether the stager holds a state after the last clause.
The fold that keeps each fact's last write keys a map by fact identity, and the first-retraction map by fold index. Both were std SipHash maps; they use FxHash now, like the planner stats pass. Nothing iterates the fold index, and the first retractions are applied one index at a time, so map order can't change the merged result.
|
Heads up before you dig in: I found a few more shapes in this same class, all around relationship |
…rder, and refuses a parallel relationship
A statement with a relationship's DELETE and another write clause ran as one
Txn, against the state before the statement:
- `SET r.v = 5 DELETE r` deleted the edge but left `v` on the deleted
relationship: the DELETE cleared only the properties stored before.
- `DELETE r CREATE (a)-[:K]->(b)`: the edge's retraction and re-assertion
cancelled, so the old relationship and its properties stayed beside the
new one.
- Beside another clause, `DELETE r` never reached the parallel-edge check, so
deleting one of two relationships on an edge deleted both.
Such statements now go to the sequential driver. A relationship's DELETE
meets every other clause; its seeded Txn re-matches the edge `r` was matched
on, in the state the clauses before it leave, so the cleanup sees their
writes and the fold handles the rest.
The parallel-edge check itself counted only the relationships the MATCH kept,
so `MATCH (a)-[r:K {w: 1}]->(b) DELETE r` (or a WHERE on r) hid the sibling
and deleted it too, even as a statement of its own. The probe now lists every
relationship on the edge, without r's filters, and refuses when one isn't r.
The single-clause path and the driver use the same probe; the driver runs it
against the virtual state, so a sibling an earlier clause created counts.
…ds the edge The parallel-relationship check ran as a Cypher query: the statement's MATCH, then a fresh `MATCH (a)-[sib:T]->(b)` listing every relationship on the edge. An unfiltered relationship pattern with bound endpoints plans as a scan of every reifier of the type, so the check alone cost about 18M instructions warm on a 1,000-edge ledger, and a filtered `DELETE r` of its own came out 1.53x what it cost before. The check now runs at staging, where the `f:reifies*` cascade already looks up the relationships on each retracted edge: a Cypher `DELETE r` marks its Txn (`TxnOpts::relationship_deletes`), and staging refuses an edge that carries more than one relationship, naming the variables. The cascade's lookup is factored out (`edge_reifiers`) and is the only one. The check reads the state the Txn stages on, the driver's virtual state included, and never sees the MATCH's filters, so no query runs for it at all.
|
The relationship |
bplatz
left a comment
There was a problem hiding this comment.
Approving. The routing, the reuse of the sequential stager and the stats pinning look right to me, and the twin tests are a good shape. A few inline comments to review before merging. The first two are correctness gaps: a mixed DETACH DELETE a, r is now refused, and a multi-target clause after an OPTIONAL MATCH drops writes. I traced both from the code rather than running them, so a twin test for each would confirm them.
Checked and sound:
estimates_onlyclears every licence-bearing field I could find a reader for (the ref-only equality fold, the exact-datatype scan narrowing, class-count elision), and the stats-backed count paths only run with empty novelty, which a virtual state never has.- The stats-cache key condition matches the
class_coverage_trustworthyexpression exactly. edge_reifierskeeps the cascade's lookup, graph stamping and re-point exclusion.- The unbuilt final state can't be reached outside
AnsweredReturn.
Optional: the "Not in this PR" items could each get a Follow-up: #N issue.
| // Staging refuses an edge that carries another relationship, | ||
| // which the base-edge retraction would take too. | ||
| self.opts | ||
| .relationship_deletes |
There was a problem hiding this comment.
This marks the whole Txn, and the check in cascade_attachment_retracts then applies to every edge the Txn retracts, not only r's. A single clause that mixes a DETACH node target with a relationship stays on the single Txn (detect_conditional returns None for mixed targets), so
MATCH (a:P)-[r:K]->(b:P) DETACH DELETE a, ris now refused, naming r, whenever any of a's edges carries two relationships. On main it commits, which is what DETACH DELETE a asks for: every relationship on a goes. Nothing covers the mixed shape today.
Setting the marker only when the clause has no DETACH node target puts that shape back where main has it. Scoping the check to edges matching r's (s, T, o) would be the precise version.
There was a problem hiding this comment.
You're right, and the test agrees: at 8ce44d4fe, MATCH (a:P {id: "a"})-[r:K]->(c:P {id: "c"}) DETACH DELETE a, r is refused naming r whenever a's other edge (a)-[:K]->(b) carries two relationships, and it commits on main.
Fixed in 45f251e78. The marker now names the delete template that retracts r's edge (TxnOpts::relationship_deletes holds RelationshipDelete { var, template }), staging notes the edges those templates retract as it instantiates them (RelationshipEdges in stage.rs), and the cascade only checks those. So it's the precise version you described, with one extra step I think is right: an edge that another delete template also retracts is left out of the check. That's exactly a DETACH DELETE of one of the edge's endpoints, which takes every relationship on the node anyway, so MATCH (a)-[r:K {w: 1}]->(b) DETACH DELETE a, r with r's own edge parallel commits too (as on main), as does DETACH DELETE b, r. Scoping to r's (s, T, o) alone would still have refused those two.
The precision cuts the other way too: … , (c:P {id: "c"}) DETACH DELETE c, r (a DETACH that doesn't reach r's edge) and DETACH DELETE r on a parallel edge are still refused, and a_parallel_relationship_the_detach_delete_does_not_reach_still_refuses pins both. Restoring the transaction-wide check fails a_detach_delete_beside_a_relationship_takes_every_relationship_on_the_node on your exact shape, and dropping just the DETACH exemption fails it on r's own edge. Without the marker staging notes nothing, so other transactions don't pay for it.
While I was in here I found the driver had the same class from its side: validate_members refused any DELETE clause mixing a node and a relationship, and DETACH DELETE r, with the "bare node DELETE" message, so SET a.seen = true DETACH DELETE a, r and SET r.v = 5 DETACH DELETE r were refused where main committed them (with the SET's write left behind). 2cb225bbb accepts both; a_detach_delete_of_a_relationship_beside_a_set_leaves_nothing covers the second.
| // clause's own lookup of stored values to bind, so such | ||
| // rows are not seeded. | ||
| let targets = clause_targets(clause); | ||
| let bound = table.bound_on(&targets); |
There was a problem hiding this comment.
bound_on takes every target of the clause, so a row that leaves any one of them unbound is dropped whole, writes to the targets it does bind included. Cypher skips only the write to the null target.
With no K neighbour for n:
MATCH (n:P {id: "a"}) OPTIONAL MATCH (n)-[:K]->(m:P) SET n.age = 1, m.seen = true REMOVE n.seenroutes here (both clauses write seen), and n.age is never set; main sets it. And
MATCH (n:P {id: "a"}) OPTIONAL MATCH (n)-[:K]->(m:P) SET n.x = 1 DETACH DELETE n, mleaves n in place with x = 1. Both reach the driver only because validate_members now admits an OPTIONAL MATCH without a CREATE or MERGE.
Seeding per target would fix it: split the clause by target variable when some row leaves one unbound (items on different targets are independent once repeated keys are split). Keeping the OPTIONAL MATCH refusal when a write clause has more than one target would also do. Worth a twin test either way.
There was a problem hiding this comment.
Confirmed both. At 8ce44d4fe, MATCH (n:P) OPTIONAL MATCH (n)-[:knows]->(m:P) SET n.age = 1, m.seen = true REMOVE n.seen never sets age on the node with no knows neighbour, and MATCH (n:P {id: "a"}) OPTIONAL MATCH (n)-[:knows]->(m:P) SET n.x = 1 DETACH DELETE n, m leaves n in place with x = 1.
Fixed in b58b6b60f with the per-target seeding you suggested. When some row leaves one of a clause's targets unbound, the clause stages once per target, each part seeded with the rows that bind it (parts_by_bound_target / clause_on); when every row binds every target it stages whole, so the common case doesn't pay an extra stage. Items on different targets are independent once a SET's repeated key is split (and the rest write distinct keys or labels), so the parts write what the clause would. One ordering detail: a DELETE's relationship targets stage after its node targets, so a node's DETACH DELETE takes the edge before the relationship's DELETE re-matches it, which keeps the split consistent with the single-Txn exemption in the other thread.
Twin tests (Cypher vs the equivalent SPARQL ; update, same state and same commit counts): an_optional_match_that_leaves_one_target_unbound_writes_the_others and an_optional_match_that_leaves_one_delete_target_unbound_deletes_the_other. The first also has a row where m binds the node another row's n binds, so the REMOVE has to see the SET's write through a different variable.
I went with the fix over keeping the refusal, since main sets n.age there and refusing would have been a regression of its own.
| // A relationship's DELETE beside another write clause has no single-`Txn` | ||
| // form that sees the other clauses' writes or checks the edge for a | ||
| // parallel relationship, so it goes to the driver even when the driver | ||
| // will refuse it (unnamed endpoints, say), as a DELETE r of its own does. |
There was a problem hiding this comment.
Since 29cb059 the single Txn does check the edge for a parallel relationship: the lowering marks every DELETE r with relationship_deletes, whichever path stages it. So the second half of this reason no longer holds.
The effect of the bypass is that a relationship's DELETE beside a member the driver defers (FOREACH, say, or an OPTIONAL MATCH before a CREATE) now routes here and is refused, where main committed it. The PR body says a statement with a deferred member keeps the single Txn.
Either is defensible, since the single Txn still doesn't let the clauses see each other's writes, but the comment and the body should agree. If refusing is the intent, it belongs under Behavior changes.
There was a problem hiding this comment.
Agreed the comment and the body disagreed, and that the second half of the comment's reason went stale with 29cb059cf. I've made the code match the body in 2cb225bbb: the bypass is gone (and deletes_a_relationship with it), so a statement with a member the driver defers keeps the single Txn whether or not it also deletes a relationship, and the single Txn checks the relationship's edge at staging.
I may be wrong about this, but I don't think main committed any of those shapes. A FOREACH over a literal list unrolls into plain clauses during parameter substitution, before routing sees it (expand_foreach in fluree-db-cypher/src/params.rs), and one over a runtime list is refused there; and the single-Txn lowering refuses each of the other deferred members itself (CALL { … } before a write, an OPTIONAL MATCH before a CREATE, and a node's bare DELETE in a multi-clause statement, all in lower_cypher_update.rs). So the visible effect of the bypass was which refusal message you got. a_relationship_delete_beside_a_deferred_clause_keeps_one_txn pins the routing (detect_sequential returns None) and the single Txn's message for two of them.
The other half of the bypass's reason, unnamed endpoints, is gone too: 2cb225bbb doesn't need named endpoints (next thread).
| /// variable was matched on, in the state the clauses before it leave, and | ||
| /// staging refuses an edge that carries another relationship (one an earlier | ||
| /// clause created included), as for a `DELETE r` of its own. | ||
| fn rel_delete_edges( |
There was a problem hiding this comment.
The re-match is built from the endpoint names of the raw MATCH (rel_edge), but the driver accepts a WITH in the read prefix. If I'm reading the row table right, a WITH that rebinds an endpoint name, e.g.
MATCH (a:P)-[r:K]->(b:P) WITH b AS a, a AS b, r SET r.v = 5 DELETE rseeds the re-match with the swapped values, it matches nothing, and the DELETE writes nothing while the SET commits. detect_conditional refuses WITH + DELETE for this reason.
Contrived, so low priority. Since r is seeded and pins the edge, re-matching with fresh endpoint variables might sidestep it entirely (and drop the named-endpoint requirement here). Refusing a WITH before a relationship's DELETE in validate_members would also do.
There was a problem hiding this comment.
You're right about the mechanism. One wrinkle on the example itself: WITH b AS a, a AS b, r returns zero rows from the read prefix, so on 8ce44d4fe that exact statement writes nothing at all, neither the SET nor the DELETE. That's the read side's alias-onto-a-bound-name bug, the WITH flavour of #1857 / #1870, not this PR's code, so I've left it there.
The class does reproduce with a rebind the read side handles: at 8ce44d4fe, MATCH (a:P {id: "a"})-[r:K]->(b:P {id: "b"}) WITH r MATCH (a:P {id: "c"}) SET r.v = 5 DELETE r commits the SET and the DELETE writes nothing, since the re-match (a)-[r:K]->(b) is seeded with the new a. A pattern read in either direction (MATCH (x {id: "b"})-[r:K]-(y {id: "a"}) SET x.seen = true DELETE r) missed the same way, since the re-match assumed left-to-right.
Fixed in 2cb225bbb. I tried the fresh-endpoint re-match first and it was correct, but over 1,000 rows (MATCH (a:R)-[r:K]->(b:S) SET r.v = 5 DELETE r) it went from 833M to 4,719M instructions: with only r bound, (s)-[r:K]->(o) plans as a scan of every K relationship per row rather than a lookup of r's bundle (startNode(r) / endNode(r) have the same problem, 1,024M vs 101M for the plain read). So instead the driver follows the read clauses' scope: it works out which variables are relationships and which hold each one's endpoints (subject first, from the pattern's direction), following WITH projections and aliases. The read prefix names an unnamed endpoint, and a WITH that keeps a relationship but drops or rebinds an endpoint also projects that endpoint under a name of the driver's own (#__cy_seq_rel_…); neither changes what the statement matches, since an endpoint is a function of its relationship. The re-match is then seeded with r and both endpoints, so it stays a point lookup: 837M for the 1,000-row case, 882M with a WITH r that drops the endpoints. Only a pattern read in either direction still re-matches with endpoints of its own (pinned by r, correct but on the slow shape); I filed #2237 for the planner side of that.
Same commit, same class: WITH a, b, r AS q SET q.v = 5 DELETE q now deletes the relationship (it was refused), a name a WITH takes from a relationship stops being treated as one, and the named-endpoint requirement is gone, both beside other clauses and for a DELETE r of its own (that check only existed for the old probe). The parallel check still applies with unnamed endpoints. Tests: a_relationship_delete_after_a_with_deletes_that_relationship (including WITH DISTINCT r and an aggregating WITH), a_relationship_delete_needs_no_endpoint_names_or_direction (db120719f adds a right-to-left pattern, which fails if the endpoint order is swapped), and transact_cypher_delete_relationship_requires_named_endpoints in it_query_cypher.rs became …_with_an_anonymous_endpoint.
Accepting unnamed endpoints is a small behavior change (a shape that used to be refused now commits), so I've called it out in the PR body.
| @@ -128,9 +164,10 @@ statements. | |||
| fluree-db-transact is not modified. | |||
There was a problem hiding this comment.
Stale now: stage()'s cascade gained the relationship_deletes check, and SPARQL's ; updates plan their later operations from the pinned stats.
There was a problem hiding this comment.
Yep, stale on both counts. Rewritten in 6d5071014: the non-impact note now says what reaches shared code (the cascade's check on a Cypher DELETE r's edges, which no other transaction marks, and the stager pinning one stats view so SPARQL's later ; operations plan from it). I also dropped the routing note's "comes here even when the driver will refuse it" and described the re-match, the per-target seeding and the scoped check.
| `REMOVE`), with each clause observing the writes of the clauses before it | ||
| and rows piping downstream — the standard Cypher loading idioms: | ||
| `REMOVE` / `DETACH DELETE` / a relationship's `DELETE`), with each clause | ||
| observing the writes of the |
There was a problem hiding this comment.
Nit: the reflow left a short line here.
There was a problem hiding this comment.
Reflowed in 6d5071014, thanks.
…ip DELETE's own edges
A Cypher `DELETE r` marked its whole `Txn`, and staging then refused any
edge the `Txn` retracted that carried two relationships. A clause that
mixes a node's DETACH DELETE with a relationship (`DETACH DELETE a, r`)
stays on the single `Txn`, so it was refused whenever any of `a`'s edges
carried two relationships, where it should take every relationship on `a`.
The marker now names the delete template that retracts `r`'s edge
(`TxnOpts::relationship_deletes` holds `RelationshipDelete { var, template }`).
Staging notes the edges those templates retract as it instantiates them,
and the cascade refuses a parallel relationship only on those. An edge
another delete template retracts too is left out: that is a DETACH DELETE
of one of its endpoints, which takes every relationship on the node.
Without the marker, staging notes nothing.
…ough the relationship
The driver re-matched a relationship's edge as `(a)-[r:T]->(b)`, using the
endpoint names of the statement's raw MATCH. A WITH can rebind those names
(`WITH r MATCH (a:P {id: "c"})`), so the re-match found nothing and the
DELETE wrote nothing while the clauses beside it committed. A pattern read
in either direction missed the same way, and the re-match needed named
endpoints.
The driver now follows the read clauses' scope. Which variables are
relationships, and which variables hold each one's endpoints, come from a
walk that follows WITH projections and aliases (`WITH r AS q … DELETE q`
deletes the relationship). The read prefix names an unnamed endpoint, and a
WITH that keeps a relationship but drops or rebinds an endpoint also
projects that endpoint under a name of the driver's own; neither changes
what the statement matches. The re-match is seeded with `r` and both
endpoints, so it stays a point lookup of the edge. For a pattern read in
either direction it takes endpoint variables of its own, pinned to `r`'s
edge by `r` itself.
With that, a relationship's DELETE needs no named endpoints, on its own or
beside other clauses. A DELETE clause in the driver may hold a node's
DETACH DELETE, a relationship's DELETE, or both, and `DETACH DELETE r`
stages as `DELETE r` does.
A statement with a member the driver doesn't stage (a node's bare DELETE,
`CALL { … }` before the writes, an OPTIONAL MATCH before a CREATE) keeps
the single `Txn` again when it also deletes a relationship. The single
`Txn` checks the relationship's edge since the parallel check moved into
staging, and its lowering refuses each of those members in turn.
…get's writes The driver seeded a SET, REMOVE or DELETE clause only with the rows that bind every one of its targets. A row an OPTIONAL MATCH left unbound on one target was dropped whole, so its writes to the targets it did bind were lost: `OPTIONAL MATCH (n)-[:K]->(m) SET n.age = 1, m.seen = true REMOVE n.seen` never set `n.age` when `n` had no `K` neighbour, and `SET n.x = 1 DETACH DELETE n, m` left `n` in place. When some row leaves a target unbound, the clause now stages once per target, each part seeded with the rows that bind it. Items on different targets are independent once a SET's repeated key is split, so the parts write what the clause would. A DELETE's relationship targets stage after its node targets, so a node's DETACH DELETE takes the edge before the relationship's DELETE re-matches it. When every row binds every target, the clause stages whole, as before.
…nd the scoped parallel check The design doc's non-impact note said `stage()` was unchanged and SPARQL paths untouched; the cascade now checks a Cypher `DELETE r`'s edges, and the sequential stager pins one stats view for a write's operations. Its routing note still said a relationship's DELETE reaches the driver when the driver would refuse it. The query docs drop the named-endpoint requirement, describe `DETACH DELETE a, r`, a row an OPTIONAL MATCH leaves partly unbound, and a DELETE after a WITH in a multi-clause statement, and reflow a short line.
…left The re-match takes the edge's subject from the pattern's direction; an incoming pattern pins that it reads the endpoints in edge order.
|
Thanks, this was a really useful pass. All four of the inline correctness items held up when I turned them into tests (with one wrinkle on the
The review-round changes leave every row of the perf tables within 0.6% of what you reviewed (instruction counts, release); the body has the numbers. On the optional "Not in this PR" items: I filed an issue with a concrete plan for each rather than folding them in, since each is its own scope. Per-occurrence |
# Conflicts: # fluree-db-transact/src/stage.rs
# Conflicts: # fluree-db-query/src/stats_cache.rs
|
Merged |
Brings #2247, #2232, #2246, #2248, #2245, #2230, #2205, #2231, #2255, #2219, #2209, #2207, #2190, #2216, #2186, #2215, #2213, #2184, #2210, #2206, #2198, #2187, #2183, #2200, #2193, #2199, #2196 and #2145 into next. Resolutions: - Novelty: main's fact-state trim (a cutoff plus a bounded sweep) and the dictionary's coverage watermark sit on next's graph slots and per-graph OrdMaps. A commit's reification links count toward coverage. Planner stats from segment sums decline under annotations, whose link deltas only the walk counts, and otherwise carry the indexed link counts. - Stats-view identity: the index root's id reaches the snapshot through next's root decoder (`decode` takes the id, as `take_snapshot_metadata` does). `LedgerState::load_record` has a decoding-root form beside `load_decoding_root`. - Transact: #2184's parallel-relationship check runs in next's link cascade, counting the `rdf:reifies` links on the retracted edge that the transaction does not retract itself. Main's bundle `edge_reifiers` is dropped, and `subjects_with_prior_rows` and `enforce_single_target_reifiers` stay deleted. The upsert pre-check takes main's dictionary probe and bounded seek. - Query: geo search resolves the graph's POST tree once at open (pooled graphs keep their filter), an empty manifest when there is none. `branch_or_none` reads the dedicated branch, and the batched joins keep next's pooled lanes. The stats-view key hashes the root id. - Indexer: `apply_dict_novelty` and `compact_forward_streams` take the cycle's compaction budget, so the term dictionary keeps its reserved share. `Prefetched` holds `ContentBytes`. `relocalize_sorted_commit` rewrites next's 20-byte types records. - Disk cache: main's in-flight write registration, with an empty entry still read as crash debris that a write replaces. The process-wide eviction walk stays removed. - Graph import (#2232): fenced CAS and publishes, the seed carries the record's namespace and fence, 32-bit graph ids and next's loaders. An import into a graph of an existing ledger refuses triple terms and edge annotations: the splice merges no triple-term dictionary yet. - Iceberg: `create_iceberg_graph_source` goes with main (a source needs a mapping); the R2RML path keeps next's `model_instance`. - CLI: main's shared import flags without the leaflet flags; `graph import` routes through next's process-wide server routing, and `upload_source_import` serves next's `Destination`. Doc sources read a ledger through the command's open instance. - Tests: sibling ledger ids become distinct names, `genesis_ledger` is awaited, Cypher state dumps include each relationship's `rdf:reifies` link, and the graph-import arena test checks the refusal instead.
Cypher: a statement's clauses see one another's writes, and the last holds
A Cypher write statement whose clauses touch the same facts ran as one
Txn. Every clause read the state before the statement, and all of them staged as one operation, so a later clause neither saw an earlier one's write nor replaced it. SPARQL's;-separated updates and JSON-LD already go through the sequential stager, which folds each fact to its last write (#2109). So does Cypher's own sequential driver, but only statements with aMERGEreached it.On
main, against(n:P {id: "a", name: "x", tags: ["t1", "t2"]}):mainMATCH (n:P {id: "a"}) SET n.name = "y" SET n.name = "x"+"y":{"x", "y"}"x", nothing committedMATCH (n:P {id: "a"}) SET n.name = "y" SET n.name = "w"{"y", "w"}"w"MATCH (n:P {id: "a"}) SET n.name = "y", n.name = "w"(one clause){"y", "w"}"w"MATCH (n:P {id: "a"}) SET n:P REMOVE n:PMATCH (m:P {id: "a"}), (n:P {id: "a"}) SET m.name = "y" SET n.name = "w"{"y", "w"}"w"MATCH (n:P {id: "a"}) SET n.name = "y" DETACH DELETE nname "y"survives the deleteMATCH (n:P {id: "a"}) DETACH DELETE n CREATE (:P {id: "a"})MATCH (n:P {id: "a"}) SET n.tags = "t3" CREATE (:Q)Qper stored tagQThe last two are the same seam from the other side. A SET, a REMOVE or a DETACH DELETE finds what it replaces with an
OPTIONALlookup in the statement'sWHERE. ACREATEin the sameTxnfires once per solution, so it fired once per stored value the lookup found.A relationship's
DELETEhad the same seam, against(a:P)-[:K {w: 1}]->(b:P). For the "parallel" rows, a second relationship(a)-[:K {w: 2}]->(b)sits on the same edge:mainMATCH (a)-[r:K]->(b) SET r.v = 5 DELETE rv 5is left on the deleted relationshipMATCH (a)-[r:K]->(b) DELETE r CREATE (a)-[:K {w: 7}]->(b)w 1, and the new onew 7MATCH (a)-[r:K {w: 1}]->(b) SET a.seen = true DELETE rMATCH (a)-[r:K]->(b) DELETE ris refusedMATCH (a)-[r:K {w: 1}]->(b) DELETE r, or… WHERE r.w = 1 DELETE rIn the first two, the DELETE cleared only what was stored before the statement, and in the second the edge's retraction and re-assertion cancelled (#2144), so the old relationship's cleanup never ran. In the third, a relationship's
DELETEbeside another clause never reached the check aDELETE rof its own gets, which refuses when the edge carries another relationship. In the fourth, that check counted only the relationships theMATCHkept, so{w: 1}hid the sibling from it.REMOVE n.name SET n.name = "x"belonged in this table until #2144: it committed-name "x", and the name was gone. #2144 nets an update's facts as sets, so the-xand+xin that oneTxnnow cancel andmaingets it right. It routes to the driver here and stays right, and its test stays in as a twin.The fix
These statements now go to the sequential driver (
fluree-db-api/src/cypher_seq.rs). It stages each clause against the state the clauses before it leave, seeded with the MATCH rows, and the stager folds each fact to its last write. That's the same fold SPARQL;updates use; there's no Cypher copy of it.interacting_writesdecides which statements route there, and every Cypher write path calls it throughdetect_sequential(autocommit, Bolt transactions, consensus). Two clauses meet when:DETACH DELETEor a relationship'sDELETE;CREATEand the other looks up stored values.A SET whose items write one key twice meets itself and is split at the repeat. Statements whose clauses can't meet keep the single
Txn:CREATEchains, SETs of different keys, and every single-clause write except that SET.The driver now also:
DETACH DELETE, as a seededTxnlike a SET;DELETE(orDETACH DELETE r) as a seededTxnthat re-matches the edgeris on, in the state the clauses before it leave. The re-match is seeded withrand the variables that hold its endpoints at the end of the read clauses, so it's a point lookup of the edge. Which variables are relationships, and which hold their endpoints, comes from the read clauses' scope,WITHaliases included: the read prefix names an unnamed endpoint, and aWITHthat keeps a relationship but drops an endpoint also projects the endpoint under a name of the driver's own, neither of which changes what the statement matches. A pattern read in either direction (-[r:K]-) re-matches with endpoints of its own, pinned to the edge byr. One DELETE clause can hold a node'sDETACH DELETEand a relationship'sDELETE;OPTIONAL MATCHbefore them. A row theOPTIONAL MATCHleaves unbound on one of a clause's targets skips the writes to that target and keeps the rest: the clause then stages once per target, each part seeded with the rows that bind it. Seeding the unbound row would have left the target free for the clause's own value lookup to bind to any node.The parallel-relationship check moved from a query run before the write into staging, at the point where the
f:reifies*cascade looks up the relationships on each edge it retracts. A CypherDELETE rmarks itsTxnwith the delete template that retractsr's edge (TxnOpts::relationship_deletes). Staging notes the edges those templates retract and refuses one of them that carries more than one relationship. An edge another delete template also retracts is left out: that's aDETACH DELETEof one of its endpoints, which takes every relationship on the node, soMATCH (a)-[r:K]->(b) DETACH DELETE a, rtakes them all, as onmain. That lookup (edge_reifiersinstage.rs) is the only one, shared with the cascade.r's property map orWHERE. So a filter can't hide a sibling.DELETE rof its own gets the same check, and no query runs for it any more.DELETEretracts. A transaction without the marker notes nothing.Behavior changes
CREATEfollowed by a SET of the created node (CREATE (n:P) SET n.name = "y") used to be refused ("SET requires a preceding MATCH"). It now stages.RETURNon a statement that now routes: it has the driver's full read surface. Under Raft consensus over HTTP, such aRETURNis refused before submission, as for any multi-clause statement.DELETE ralready does: "DELETE of relationshiprfailed: parallel relationships share its underlying edge, …". That covers aDELETE rfiltered down to one of the relationships on an edge (by a property map or aWHERE), and a relationship'sDELETEbeside other clauses. It also coversCREATE (a)-[:K {…}]->(b) DELETE r, where theCREATEputs a second relationship onr's edge first; onmainthat one keptrand committed the new relationship beside it. ADETACH DELETEof one of the edge's endpoints in the same clause (DETACH DELETE a, r) still takes every relationship on the node, as onmain.err:db/InvalidTransaction) where the loneDELETE rrefusal used to be a Cypher error (also 400). The message is the same.DELETEno longer needs named endpoints (MATCH (:P)-[r:K]->(:P) DELETE r), on its own or beside other clauses. It used to be refused; the requirement existed for the parallel-relationship probe, which staging has replaced. The parallel check still applies.DELETEafter aWITH, honoring theWITH's scope.mainrefuses aWITHbefore aDELETE.DELETE,FOREACHover a runtime list,CALL { … }, and anOPTIONAL MATCHbefore aCREATEorMERGE. A statement with one of these keeps the singleTxn, whose lowering refuses it, whether or not it also deletes a relationship.Tests
The 14 new twin tests in
it_cypher_seq_writes.rseach run a Cypher statement and the SPARQL UPDATE that means the same (one operation per clause) on ledgers seeded alike. Each requires both sides to end in the same expected state, with the same assertion and retraction counts.On
main: 10 of the 14 fail, every one of them on the Cypher side, and the SPARQL side passes wherever it's checked.a_set_on_a_node_the_statement_creates_writes_that_node_onceis one of the 10:mainrefuses the statement, and the test pins the newly accepted shape.The four that pass on
main:a_set_to_the_stored_value_writes_nothingandan_optional_match_that_finds_nothing_writes_nothingare controls.remove_then_set_of_the_same_value_keeps_ithas passed there since fix(transact): net an update's facts as sets, not by row count #2144.an_optional_match_that_finds_nothing_before_two_sets_writes_nothingguards the driver's seeding.Each routing rule (key, label, DETACH, CREATE-with-lookup, the SET split, the bound-row seeding) was turned off on its own, and each time a test failed.
The state after the last clause (below) has three tests of its own:
a_trailing_return_reads_the_last_clauses_writecovers autocommit, the transaction builder the consensus committers use, aTransactionand a Bolt transaction.the_next_statement_in_a_transaction_reads_a_write_with_no_returncovers a Bolt transaction and aTransaction.a_write_commits_the_same_facts_with_or_without_a_returnruns four statements each way and requires the same state and the same commit.cypher_unread_final_statestamp too. Reverting the change fails the last two, and dropping its RETURN guard fails the first and the last.A relationship's
DELETEhas six tests, each reading the relationships back through Cypher and the full set of triples:a_set_on_a_relationship_then_its_delete_leaves_nothinga_relationship_deleted_then_created_again_is_the_new_onea_multi_clause_delete_of_a_parallel_relationship_refuses(both clause orders, and a SET onr)a_filtered_delete_of_a_parallel_relationship_refuses(a property map, and aWHERE)a_sibling_an_earlier_clause_created_refuses_the_delete, which checks that the parallel check reads the state the earlier clauses leavea_relationship_delete_with_no_sibling_commits, the control: the same statements commit when the edge carries one relationship.The first five fail on
mainand the control passes there. The refusals also check that nothing was written. Turning the routing off, the staging check off, its marker off, or its count off by one each fails at least three of them, the existing parallelDELETE rtest included for the last three.Review round (all in
it_cypher_seq_writes.rsunless noted). Each fails with its fix reverted:a_detach_delete_beside_a_relationship_takes_every_relationship_on_the_nodeanda_parallel_relationship_the_detach_delete_does_not_reach_still_refusespin the check's scope from both sides:DETACH DELETE a, rcommits whether the parallel edge isr's or another ofa's, and aDETACH DELETEthat doesn't reachr's parallel edge, orDETACH DELETE r, still refuses. Restoring the transaction-wide check fails the first, dropping theDETACHexemption fails it onr's own edge, and dropping the check fails the second and five others.a_relationship_delete_after_a_with_deletes_that_relationship: aWITHthat drops the endpoints and a laterMATCHthat rebinds one,WITH DISTINCT r, an aggregatingWITH,WITH r AS q. Before this round the first committed the SET and deleted nothing.a_relationship_delete_needs_no_endpoint_names_or_direction: unnamed endpoints, a pattern read in either direction (before, the SET committed and the relationship stayed), and one read right to left, plus the parallel refusal with unnamed endpoints. Swapping the endpoint order for a right-to-left pattern fails it.a_detach_delete_of_a_relationship_beside_a_set_leaves_nothing.an_optional_match_that_leaves_one_target_unbound_writes_the_othersandan_optional_match_that_leaves_one_delete_target_unbound_deletes_the_other.a_relationship_delete_beside_a_deferred_clause_keeps_one_txnpins the routing for a deferred member beside a relationship'sDELETE.it_query_cypher.rs,transact_cypher_delete_relationship_requires_named_endpointsbecametransact_cypher_delete_relationship_with_an_anonymous_endpoint.The driver's cost
Routing these statements through the driver first cost about 2.4× on a one-node statement. A profile put 69% of it in the planner stats. They're assembled over the whole novelty window, and that ran once per clause, because each clause's state is new to the stats cache. Two changes take that back out, and they help every sequential write, not only Cypher:
Novelty::pin_planner_statsholds them, and any change to the novelty's content clears them.cached_stats_view_for_dbreturns the pin before assembling anything.StatsView::estimates_only): the ref-only flags and observed datatype sets read "unknown", so a licence the base's stats grant (filter_fold's node-only soundness guard reads an estimate that a spurious retraction can drive to zero #1721) can't be read for a state a write has changed.a_transaction_read_after_a_predicate_gains_literals_keeps_value_equalitypins that, and it fails with the licences left on.That left a statement over many rows at 1.15× the single
Txn(1,000 rows, two SETs). Split by phase, the clauses' WHEREs together cost what the one merged WHERE did, and the commit was cheaper, since it writes 2,000 facts where the singleTxnwrote 3,000. The difference was the driver's own work: the fold, the state it builds after each clause, and the final merge. Two smaller changes came out of that:RETURNreads the state after the last clause; the commit reads the merged result. So the last write clause of a statement with noRETURNnow stages without building that state, as SPARQL's last;operation already does. A MERGE still builds it, since it probes its own writes.RETURN(AnsweredReturn::final_state), so a caller can't read one that wasn't built. The callers that read it before did so only to format theRETURN.Transactionreads its transaction's state, which the merged result advances, not the driver's.HashMap.Perf
Release build, against
mainateaa4c8e4b, measuring retired instructions per statement on a fresh 1,000-node ledger with its data in novelty, 7 runs in each of 2 interleaved rounds:mainSET n.name = "y" SET n.name = "w"DETACH DELETE n CREATE (…)REMOVEthen SET of the stored value;operationsCREATEsCOUNT(*)over a two-pattern join, first runCOUNT(*), stats already cachedThe last two changes move the two 1,000-node routed rows. Two SETs went from 386.4M (1.15×) to 361.8M with the state after the last clause left unbuilt, then to 357.4M with the fold's FxHash.
REMOVEthen SET went from 212.9M to 201.6M. Every other row moved by about 1% or less.For a relationship's
DELETE, the comparison is against this PR before it. That's the same code asmainfor these statements, which ran as oneTxn. The seed is 1,000(:R)-[:K {w}]->(:S)relationships created by Cypher:MATCH (a:R {id: 7})-[r:K]->(b:S) SET r.v = 5 DELETE r… SET a.seen = true DELETE rMATCH (a:R)-[r:K]->(b:S) SET r.v = 5 DELETE rDELETE rof its own, one node{w: 7}DELETE rof its own, 1,000 rowsA
DELETE rof its own got cheaper because the parallel check no longer runs a query. The routed one-node statement costs more mostly in its clause's re-match of(a)-[r:K]->(b): a named relationship pattern with no property filter plans as a scan of every relationship of its type, onmaintoo. Fixing that is a planner change for every relationship read, and it isn't in this PR. Measured the same way, every statement in the table above moved by 1% or less with this change.The review round's changes (the scoped check, the endpoint-seeded re-match, per-target seeding) leave every row of both tables within 0.6% of the code reviewed, except
DELETE rof its own over 1,000 rows, which runs in two modes (about 4,390M and 4,470M) on both. Release, 7 runs in each of 2 interleaved rounds against the reviewed code. Three shapes this round newly handles, over the same 1,000 relationships: unnamed endpoints (MATCH (:R)-[r:K]->(:S) SET r.v = 5 DELETE r) 837M, the same as named; aWITH rthat drops the endpoints 882M (51.0M for one node). Re-matching with onlyrseeded, as a pattern read in either direction still does, costs about 5.6× that (4,658M), because a bound relationship variable doesn't drive its edge lookup (Follow-up: #2237).The first-run queries are cheaper because they build the planner stats, and the stats pass is cheaper. Once the stats are cached, a query costs what it did, with the same allocation count. The JSON-LD writes don't touch the sequential stager, and they're flat too.
I also ran criterion, at the commit before those last two changes (neither touches a path these benches run), on the CI compare set (
query_overlay_matrix,query_hot_bsbm,query_hot_negation_count,query_hot_limit_startup) plustransact_commitandtransact_upsert_replace, at quick/tiny, in three passes:main, this branch against it, andmainagain against itself. The machine was shared and loaded, andmainagainst itself moved by as much as −62% and +76%, so wall-clock here can't resolve a few percent. The one place this branch read slower than bothmainpasses was its pass overquery_overlay_matrix(star_overlay399 µs against 112 / 107 µs, withgroupby_overlay,count_cachedandstar_cachedup the same way). So I ran that bench four more times, alternatingmainand this branch. This branch's first of those ran during a load spike and read high again (star_base92 µs). In its second, every scenario came in at or under the slower of the twomainruns, exceptstar_overlay, which was 0.2% over it (102.4 and 105.7 µs onmain, 105.9 µs here). The instruction counts above cover the same query conditions without the noise.Embedders that plan Cypher writes themselves
A caller that plans with
cypher_write_plan_with_skolemand refusesWritePlan::Sequentialwill now refuse the statements this PR routes. Those statements committed the wrong facts on that path before. To take them, stage the plan through the driver, as the consensus committer does:fluree.stage(handle).cypher_sequential(CypherSeqInput { plan, governance, skolem_txn_id })…execute(). The result'scypher_returncarries a trailingRETURN. The same change also takes MERGE chains.Gates
cargo check --workspace --all-targets --all-features: clean, after mergingmain.cargo clippy -p fluree-db-transact -p fluree-db-api --all-targets --all-features --no-deps -- -D warnings: clean.cargo fmt --all --check: clean.fluree-db-api, all features: 5,386 passed, 28 skipped.fluree-db-transact,fluree-db-queryandfluree-db-cypher, all features: 2,379 passed, 1 skipped.testsuite-sparqlisn't touched here, and I didn't run it.Not in this PR
DELETEretracts an edge). Follow-up: Cypher:DELETEof one relationship among several on the same edge #2234FOREACHover a runtime list andCALL { … }in a write statement. Follow-up: Cypher:FOREACHover a runtime list, andCALL { … }, before or among multi-clause writes #2235Txn, 1.07× at 1,000 rows, mostly each operation's staged view, which the sequential stager builds and then takes apart. SPARQL's;updates pay that onmaintoo. Follow-up: Sequential writes: a routed statement over many rows still costs more than oneTxn#2236startNode(r)/endNode(r)reads). Follow-up: Query: a bound relationship variable doesn't drive its edge lookup #2237WITH b AS awhereais already bound returns no rows; that's Cypher: a RETURN alias matching a pattern variable silently replaces the projection, and can drop every row #1857 / CypherWITH/RETURNcannot re-project a bound name — ORDER BY resolves aliases by surface expression, not by variable #1870, on the read side.