Skip to content

fix(#11811): guarded UPDATE and MATCH ... SET no longer write a record that stopped matching their WHERE - #11823

Closed
shaunpatterson wants to merge 5 commits into
ArcadeData:mainfrom
shaunpatterson:fix/11808-guarded-update-atomic
Closed

shaunpatterson wants to merge 5 commits into
ArcadeData:mainfrom
shaunpatterson:fix/11808-guarded-update-atomic

Conversation

@shaunpatterson

@shaunpatterson shaunpatterson commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Part of #11811: the guarded UPDATE / MATCH ... SET half, reported as #11808 and closed as a duplicate of #11811. The guarded DELETE half of #11811 (#11810) is not covered here.

Summary

A guarded UPDATE ... WHERE (SQL) or MATCH ... WHERE ... SET (openCypher) could write a record that no longer satisfied its WHERE. Under READ_COMMITTED, if a concurrent commit changed the record between the statement's read and modify(), the executors cleared the stale-read flag (#8610) because the assigned values are re-evaluated on the reloaded content. The predicate was not re-evaluated, so two callers could both win a compare-and-set such as UPDATE T SET claimed = true WHERE claimed IS NULL.

Changes

  • SQL: ConvertToUpdatableResultStep receives the UPDATE's WhereClause. When modify() reloaded different content, the WHERE is evaluated again on the reloaded record and the record is skipped if it no longer matches. Only a reloaded record pays for the second evaluation.
  • openCypher: RowGuards records on the statement context whether the rows are selected by a predicate (a WHERE, or a property map in a pattern). SetClauseApplier refuses a reloaded record with the retryable ConcurrentModificationException in that case, so the statement runs again and its predicate sees the committed state. A statement with no predicate (MATCH (v:V) SET v.n = v.n + 1) is unchanged and still builds on the reloaded content.
  • openCypher, the other records of the row: the predicate may have read a record the SET does not write (MATCH (a:A), (b:B) WHERE a.claimed IS NULL SET b.flag = true). Before a guarded SET writes a row, RowGuards.refuseIfRowChanged compares every record the row binds with its committed content (ImmutableDocument.latestIfChangedSinceRead(), which reads the newest content without touching the record the row holds; a page whose version did not move costs no read) and refuses the row with the retryable conflict if one changed.
  • openCypher MERGE: its pattern is the predicate. MergeStep checks each record it matched against its committed content; one a concurrent commit changed so that it no longer matches the pattern (or deleted) refuses the statement with the retryable conflict, so the retry matches, or creates, what the pattern selects now. A record that still matches stays matched, so the hot upsert MERGE (c:C {id: $id}) ON MATCH SET c.n = c.n + 1 keeps building on a concurrent increment instead of retrying. The ON MATCH SET (and a SET the MERGE absorbed) checks the pattern again on a write target modify() reloaded.
  • Tests in ConcurrentRecordWriteTest.StaleReadModify using the existing in-statement interleaving helper: SQL and Cypher (WHERE and pattern property) guarded updates write nothing, a SQL WHERE that still matches keeps building on the concurrent write, MERGE ... ON MATCH SET on a record that stopped matching writes nothing, a WHERE on one alias stops a SET on another, a MERGE pattern on one alias stops an ON MATCH SET on another, and a MERGE whose record still matches commits.

How to test

./mvnw -pl engine test -Dtest='ConcurrentRecordWriteTest*,CypherConcurrentWriteTest*,UpdateStatementExecutionTest'

The three guarded tests of the first commit fail on main ("Expecting value to be false but was true") and pass here.

End to end, the repro from the issue (cas_race.py, 8 threads, HTTP session transactions and autocommit, SQL and Cypher) went from 1 to 14 rounds with two winners per 150 to 0 in 1,200 rounds with this change. The hot-counter case (UPDATE C SET n = n + 1 WHERE id = 'a' from 8 threads) shows the same conflict rate as before (255 and 246 failed statements out of 1,200).

Review round (5ecdaf1)

Both review findings held:

  • MERGE: RowGuards.hasRowPredicate never looked at the MERGE clause, so MERGE (v:V {n: 0}) ON MATCH SET v.claimed = true wrote a record a concurrent commit had moved to n = 5. Flagging MERGE as guarded would have turned every contended upsert into a retry (CypherConcurrentWriteTest.onMatchSetSeesTheIncrementCommittedAfterTheMatch asserts it commits), so the pattern is checked again on the committed content instead.
  • Cross alias: the check covered the SET target only, so MATCH (v:V), (w:W) WHERE v.n = 0 SET w.claimed = true wrote w after v stopped matching.

New tests, each failing on the previous head of this branch (22d2633) and passing here: cypherMergeOnMatchSetWhosePatternStoppedMatchingInsideTheStatementWritesNothing, cypherSetOnAnotherAliasWhoseWhereStoppedMatchingInsideTheStatementWritesNothing, cypherMergeOnMatchSetOnAnotherAliasWhosePatternStoppedMatchingInsideTheStatementWritesNothing; cypherMergeOnMatchSetOnAnotherAliasWhosePatternStillMatchesCommits is the counterpart and passes on both.

Scope: the checks run where a write clause applies a row: SET, ON MATCH SET, and a SET a MERGE absorbed. Without read-set validation at commit, a commit landing after that check and before this transaction commits still changes a record the row was selected by (the target itself is checked at commit, as it is written). An anonymous node or relationship of a MERGE path pattern is not bound in the row and is not checked; a single anonymous MERGE node is.

Tests run: the whole engine module without the slow and benchmark groups, 27,746 tests: 27,715 passed, 22 skipped, 9 failed. After merging main (48a1109), the 9 failing tests' classes and the guard tests were run again: CypherCountChainStartsAtSelectiveEndIssue11594Test (fixed on main by #11828), ColumnarEquivalenceTest, FacetOracleSelfTest, FacetExecutorTermsTest, ConcurrentRecordWriteTest (34) and CypherConcurrentWriteTest (33) all passed. The remaining 2 were ReplicatedApplyPublicationTest timing failures, which also fail on main's CI.

Bug prevention

Overlap with #11826

#11826 (#11818) fixes the same race: the SQL UPDATE part (ConvertToUpdatableResultStep evaluates the WHERE again on reloaded content) is the same approach in both, and both change SetClauseApplier and ImmutableDocument. #11826 also covers openCypher REMOVE and DELETE and SQL DELETE, and re-evaluates the openCypher predicates instead of refusing every reloaded guarded row. This PR covers what #11826 lists as not covered: MERGE ... ON MATCH SET and a predicate on a record the clause does not write. Whichever lands first, the other needs a rework, not just a merge.

…te a record that stopped matching their WHERE

- SQL: the UPDATE's WHERE is evaluated again on a record modify() reloaded after a concurrent commit; a record that no longer matches is skipped.
- openCypher: a SET whose rows were selected by a WHERE or a pattern property map refuses a reloaded record with the retryable conflict.
- Regression tests in ConcurrentRecordWriteTest.StaleReadModify.

Fixes ArcadeData#11808
@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 45 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9c875de0-e703-4de9-bb21-5be2ca482228
Commits

Reviewing files that changed from the base of the PR and between 571f803 and ae4b022.

Files selected for processing: 8

  • engine/src/main/java/com/arcadedb/database/ImmutableDocument.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/CypherExecutionPlan.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/RowGuards.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/steps/MergeStep.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/steps/SetClauseApplier.java
  • engine/src/main/java/com/arcadedb/query/sql/executor/ConvertToUpdatableResultStep.java
  • engine/src/main/java/com/arcadedb/query/sql/executor/UpdateExecutionPlanner.java
  • engine/src/test/java/com/arcadedb/database/ConcurrentRecordWriteTest.java
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@mergify

mergify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is closed, so it cannot be queued. Reopen it to get the box back.

@codacy-production

codacy-production Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 84 complexity

Metric Results
Complexity 84

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@github-actions github-actions Bot added concurrency Threading / concurrency / MVCC engine Core engine: document/schema API has-issue The PR links an issue it resolves opencypher severity:major A feature is broken or returns wrong results, with no practical workaround sql triage:lgtm PR triage: nothing blocking, ready for a maintainer labels Nov 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Triage: triage:lgtm · severity:major · areas: engine, sql, opencypher, concurrency · has-issue

Review of #11823

The change fixes #11808 (severity:major). A guarded UPDATE ... WHERE or MATCH ... WHERE ... SET could write a record that no longer matched its predicate, so two callers could both win a compare-and-set. I only read the diff and did not run the tests.

What the PR does

  • SQL: ConvertToUpdatableResultStep now gets the UPDATE's WhereClause. It re-evaluates the clause only when modify() reloaded different content (isBasedOnStaleRead()), and skips the record if it no longer matches. The normal path pays nothing extra.
  • openCypher: the new RowGuards records on the statement context whether the rows come from a predicate. SetClauseApplier then throws the retryable ConcurrentModificationException for a reloaded record instead of clearing the stale-read flag. Statements with no predicate keep the Vertex modify() silently reloads a stale read under READ_COMMITTED, losing read-modify-write updates (Java API) #8610 behaviour.
  • Four regression tests in ConcurrentRecordWriteTest.StaleReadModify cover the SQL skip, the SQL "still matches" case, and the Cypher WHERE and pattern-property cases. The PR says the guarded ones fail on main.
  • There are no new dependencies and no security concerns.

Non-blocking suggestions

  1. RowGuards.hasRowPredicate only looks at the top-level MATCH, WITH and statement WHERE clauses. Check that predicates in other clause shapes are covered, or that they fail safe. These are OPTIONAL MATCH, MERGE patterns, WHERE after UNWIND or CALL, and subqueries, such as MATCH ... WITH ... MATCH ... WHERE ... SET. An extra test for one of them would help.
  2. GUARDED_ROWS is stored as a plain context variable named guardedRows. Consider a name that cannot collide with user parameters or variables, or confirm that the variable lookup namespaces them.
  3. The SQL tests assert the outcome only. The Cypher tests do not assert that the retryable ConcurrentModificationException is thrown, and an explicit assertion would pin that contract. A small test for UPDATE ... UPSERT ... WHERE would also be useful, since the same whereClause feeds that path.
  4. The SQL path silently skips the record while the Cypher path throws. The behaviour is documented in the Javadoc, but state the difference explicitly in the PR description or release notes.

…ern or other records stopped matching

- MERGE: a matched record a concurrent commit changed so that it no longer matches the pattern is refused with the retryable conflict, at the match and again when ON MATCH SET (or an absorbed SET) reloads it; one that still matches keeps building on the commit.
- MATCH/WITH predicates: before a SET writes a row, every record of the row is checked against its committed content, not only the write target, so a WHERE on one alias no longer lets a write to another alias through.
- ImmutableDocument.latestIfChangedSinceRead() reads the newest committed content without touching the record the row holds.
- Tests in ConcurrentRecordWriteTest.StaleReadModify.
@robfrank robfrank added this to the 26.12.1 milestone Nov 18, 2026
@robfrank robfrank self-assigned this Nov 18, 2026
@github-actions github-actions Bot added triage:lgtm PR triage: nothing blocking, ready for a maintainer and removed triage:lgtm PR triage: nothing blocking, ready for a maintainer labels Nov 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Triage: triage:lgtm · severity:major · areas: engine, opencypher, sql, concurrency · has-issue

Review of #11823 (fixes #11808)

Summary: The fix closes a real compare-and-set hole. Under READ_COMMITTED, a guarded SQL UPDATE ... WHERE or Cypher MATCH ... WHERE ... SET could write a record that no longer matched its predicate. The diff touches only engine query and record code plus tests. I found no security hazard, no new dependency and no unrelated change.

What I checked

  • SQL: ConvertToUpdatableResultStep re-evaluates the WHERE only when modify() reloaded the record (isBasedOnStaleRead()). The common path pays nothing, and a record that stopped matching is skipped. That is a clean, minimal change.
  • Cypher: RowGuards.register records on the context whether the statement has a row predicate. SetClauseApplier refuses a reloaded target with the retryable ConcurrentModificationException. refuseIfRowChanged covers the case where the predicate read a record other than the one the SET writes. The ImmutableDocument.latestIfChangedSinceRead() fast path compares page versions first, so unchanged pages are not re-read.
  • MERGE: The pattern is re-checked against the committed content instead of treating MERGE as guarded. This keeps the hot upsert ON MATCH SET c.n = c.n + 1 from turning into retries.
  • Tests: ConcurrentRecordWriteTest covers the SQL and Cypher guarded updates, the still-matching counterparts, the cross-alias cases and the MERGE cases. It uses the existing interleaving helper and the assertThat(...) style.

Suggestions (non-blocking)

  1. ImmutableDocument.latestIfChangedSinceRead() is new public API with several branches: known-stale, deleted record, page version unchanged but content differs, record already modified in the transaction. It is only exercised indirectly through the Cypher tests. A small direct test in the engine database package would protect those branches.
  2. RowGuards.hasRowPredicate is only covered through end-to-end Cypher statements. A short unit test for the predicate shapes would help: WHERE in MATCH, WITH ... WHERE, a node property map, a parameter map, a relationship property map, and a statement with no predicate.
  3. The Cypher regression tests only exercise SET. A test for a guarded MATCH ... WHERE ... SET through the executeWithSeedRow path, which also calls RowGuards.register, would pin that entry point.
  4. SQL variants worth one test each: UPDATE ... UPSERT, and an UPDATE with a LIMIT or a subquery source, to confirm the re-check behaves as expected.
  5. Cost note: refuseIfRowChanged walks every property of every row for each guarded SET row. It is cheap when the page version has not moved, but wide rows on large guarded updates could add up. Consider restricting it to the record-typed bindings gathered once per row shape.
  6. The PR description says guarded DELETE is a sibling (Guarded DELETE can remove a record a concurrent transaction just updated so the WHERE no longer holds #11810). That is fine to leave out of this PR, but please make sure that issue stays open.

Overall this looks correct and well scoped.

# Conflicts:
#	engine/src/main/java/com/arcadedb/query/opencypher/executor/CypherExecutionPlan.java
@github-actions github-actions Bot added triage:lgtm PR triage: nothing blocking, ready for a maintainer and removed triage:lgtm PR triage: nothing blocking, ready for a maintainer labels Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Triage: triage:lgtm · severity:major · areas: engine, opencypher, sql, concurrency · has-issue

Triage of #11823 (fixes #11808). No security hazard found, and the diff contains nothing aimed at the reviewer.

What it does

  • SQL: ConvertToUpdatableResultStep now gets the UPDATE's WhereClause. It re-evaluates the WHERE only when modify() reloaded stale content, and skips the record if it no longer matches. The cost is paid only on the reload path.
  • openCypher: the new RowGuards marks statements whose rows are selected by a WHERE or a pattern property map. SetClauseApplier refuses a reloaded record with the retryable ConcurrentModificationException in that case. RowGuards.refuseIfRowChanged does the same for the other records bound in the row.
  • MERGE: it re-checks the pattern against the latest committed content, so a contended upsert that still matches does not retry.

The fix targets the right class of bug. The severity (severity:major: wrong results on a compare-and-set with no practical workaround) matches the issue label.

Tests

  • The tests in ConcurrentRecordWriteTest.StaleReadModify cover the main shapes: SQL and Cypher, with WHERE and with pattern properties. They also cover cross-alias and MERGE cases, each with a counterpart that must still commit. They use the existing interleaving helper and the assertThat(...) style from CLAUDE.md.
  • Please consider tests for:
    • a SQL UPDATE with UPSERT or LIMIT and a stale read, to show the skip does not change the row count or RETURN semantics;
    • a relationship-property MERGE pattern;
    • ImmutableDocument.latestIfChangedSinceRead() directly: the deleted-record case (null buffer) and the knownStale branch.

Minor notes, none blocking

  1. RowGuards.refuseIfRowChanged iterates every property of the row on every SET application of a guarded statement. latestIfChangedSinceRead is cheap when the page version did not move, but wide rows over many records add overhead. Consider caching a per-row check, or restricting it to the aliases the predicate references.
  2. RowGuards.GUARDED_ROWS is stored as a context variable. Please confirm that sub-contexts, such as subqueries, CALL {} and UNION branches, inherit it. Only the two CypherExecutionPlan entry points call register.
  3. The description says the guarded DELETE (Guarded DELETE can remove a record a concurrent transaction just updated so the WHERE no longer holds #11810) has the same bug. That is acceptable as a separate issue, but add a TODO or a linked issue reference near RowGuards.
  4. MergeStep does not check anonymous nodes or relationships of a path pattern. That is documented in the PR, but a Javadoc note on RowGuards or MergeStep would help future readers.

# Conflicts:
#	engine/src/main/java/com/arcadedb/query/opencypher/executor/steps/SetClauseApplier.java
@github-actions github-actions Bot added triage:lgtm PR triage: nothing blocking, ready for a maintainer and removed triage:lgtm PR triage: nothing blocking, ready for a maintainer labels Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Triage: triage:lgtm · severity:major · areas: engine, opencypher, sql, concurrency · has-issue

Review of #11823

This fixes the guarded UPDATE / MATCH ... SET compare-and-set race from #11808. That issue is labelled severity:major, and the diff supports it: wrong results (two callers both win a CAS) with no practical workaround.

What I checked

  • SQL: ConvertToUpdatableResultStep re-evaluates the WHERE only when modify() reloaded stale content (isBasedOnStaleRead()). The common path pays nothing, and the planner change is minimal.
  • openCypher: RowGuards marks a statement as guarded when it has a WHERE or a pattern property map. A reloaded target then gets the retryable ConcurrentModificationException. Unguarded statements such as SET v.n = v.n + 1 keep building on the reloaded content.
  • Cross-alias check: refuseIfRowChanged covers records that the predicate read but the SET does not write.
  • MERGE: MergeStep re-checks the pattern instead of flagging the statement as guarded. A contended ON MATCH SET c.n = c.n + 1 therefore still commits rather than retrying.
  • Tests: ConcurrentRecordWriteTest has failing-before and passing-after cases for SQL and Cypher, including the "still matches" counterparts. They use the existing interleaving helper and the assertThat(...) style from CLAUDE.md.
  • Conventions: No new dependencies, no security concerns, and no unrelated changes. The new file has the license header, and final is used consistently.

Non-blocking suggestions

  1. RowGuards.refuseIfRowChanged runs for every row of a guarded statement and iterates all row properties. For each ImmutableDocument it can read a page via latestIfChangedSinceRead(). That is probably fine given the page-version short-circuit, but a large guarded MATCH ... SET is worth a quick benchmark or at least a note.
  2. RowGuards.hasRowPredicate is deliberately conservative. A pattern property map or a WITH ... WHERE flags the whole statement, so some statements will now retry that previously committed. A unit test for hasRowPredicate (WITH WHERE, relationship properties, parameter maps) would pin that behaviour.
  3. The PR description notes the remaining gaps: the commit-time read-set is not validated, and anonymous MERGE path elements are not checked. Please keep those tracked in follow-up issues, along with the guarded DELETE (Guarded DELETE can remove a record a concurrent transaction just updated so the WHERE no longer holds #11810).
  4. SQL: consider one test for UPDATE ... UPSERT or a subquery WHERE. These go through matchesFilters with the context and should behave the same.

Overall this is solid and well tested.

@shaunpatterson shaunpatterson changed the title fix(#11808): guarded UPDATE and MATCH ... SET no longer write a record that stopped matching their WHERE fix(#11811): guarded UPDATE and MATCH ... SET no longer write a record that stopped matching their WHERE Nov 19, 2026
@shaunpatterson

Copy link
Copy Markdown
Contributor Author

This branch now conflicts with main and is not auto-rebased: main already contains an equivalent fix (#11818, SelectionPredicates) and #11808 is closed. The branch carries a competing design (RowGuards, a BiPredicate stillSelected) in SetClauseApplier, ConvertToUpdatableResultStep and UpdateExecutionPlanner. What it adds beyond main is the MERGE pattern check in MergeStep (main passes SelectionPredicates.NONE there). Suggest porting only that part onto SelectionPredicates and closing this PR.

@robfrank

Copy link
Copy Markdown
Collaborator

Thanks for this. Main moved under it: #11826 (fixes #11818) landed the re-check of the selecting predicates for SQL UPDATE ... WHERE and openCypher MATCH ... WHERE ... SET / REMOVE through the new SelectionPredicates, and #12472 refuses a guarded DELETE of a record changed since it was read. Together they fix the two shapes of #11811, which I'm closing.

This PR now conflicts in SetClauseApplier, ConvertToUpdatableResultStep and ImmutableDocument, and as your description says it needs a rework rather than a merge. The parts that are still uncovered on main are exactly what it adds:

  • MERGE ON MATCH SET (SetClauseApplier.forMergeAction is built with SelectionPredicates.NONE)
  • a predicate on an alias the SET does not write (MATCH (a), (b) WHERE a.claimed IS NULL SET b.flag = true)

Both are tracked in #12593 now. Could you rebase onto main, rebuild those two on top of SelectionPredicates, and point the PR at #12593 (Closes #12593 only if it covers every shape listed there, otherwise Part of #12593)?

@shaunpatterson

shaunpatterson commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Superseded by #11826 (merged), which fixes the guarded UPDATE / MATCH ... SET half of #11811, as noted in the closing comment on #11811. Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

concurrency Threading / concurrency / MVCC engine Core engine: document/schema API has-issue The PR links an issue it resolves opencypher severity:major A feature is broken or returns wrong results, with no practical workaround sql triage:lgtm PR triage: nothing blocking, ready for a maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants