Repository navigation
fix(neo4j): make OptimisticLockingSpec commit, observe and verify the background write - #16072
Conversation
There was a problem hiding this comment.
Pull request overview
This PR tightens the OptimisticLockingSpec Neo4j test to avoid silently continuing after a timed Thread.join(timeout) that may return before the background write completes, making slow CI runners fail deterministically instead of racing subsequent assertions.
Changes:
- Capture the background update thread in
Test optimistic locking disabled with 'version false'. - Replace
Thread.start { ... }.join(2000)with a stored thread,join(5000), and an explicit!isAlive()completion assertion. - Stop swallowing potential
InterruptedExceptionfrom the join path (now an interrupt will fail the test rather than masking it).
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## 8.1.x #16072 +/- ##
===================================================
+ Coverage 32.7869% 59.2593% +26.4724%
- Complexity 563 25149 +24586
===================================================
Files 84 2215 +2131
Lines 4941 108864 +103923
Branches 864 19797 +18933
===================================================
+ Hits 1620 64512 +62892
- Misses 3061 35423 +32362
- Partials 260 8929 +8669 🚀 New features to boost your workflow:
|
| // finishes; assert completion explicitly so a slow runner fails loudly instead of | ||
| // silently racing the assertions below. | ||
| backgroundUpdate.join(5000) | ||
| assert !backgroundUpdate.isAlive() |
There was a problem hiding this comment.
assert !backgroundUpdate.isAlive() verifies termination, not completion. A thread whose closure throws is equally not-alive (the default uncaught-exception handler just prints to stderr), so this assert passes when the background update crashed - the same silent outcome the comment says it prevents. And that crash path is live here (see the notes on lines 135 and 137). To actually assert completion, capture the closure's outcome and check it on the test thread, e.g.:
def failure = new AtomicReference<Throwable>()
def backgroundUpdate = Thread.start {
try {
OptLockNotVersioned.withNewSession {
def reloaded = OptLockNotVersioned.get(o.id)
assert reloaded
reloaded.name += ' in new session'
reloaded.save(flush: true)
}
} catch (Throwable t) {
failure.set(t)
}
}
backgroundUpdate.join(5000)
assert !backgroundUpdate.isAlive() && failure.get() == nullplus the assert reloaded guard the sibling test already has (line 93).
| // ignore | ||
| def backgroundUpdate = Thread.start { | ||
| OptLockNotVersioned.withNewSession { s -> | ||
| def reloaded = OptLockNotVersioned.get(o.id) |
There was a problem hiding this comment.
This get(o.id) returns null on the background thread, so the closure dies with an NPE on the next line before ever saving - silently, since nothing observes the thread's exception. The node created in the given: block exists only inside the main session's transaction: GormDatastoreSpec.setup() calls session.beginTransaction() and nothing in this feature commits it, while the background thread gets its own bolt session/transaction that cannot see the uncommitted CREATE. The sibling test works around exactly this by committing before spawning its thread (session.transaction.commit(); session.transaction.nativeTransaction.close(), lines 74-75). Without the same commit here, the concurrent update this test is named for never happens, and the new join(5000) + isAlive() check passes regardless.
| OptLockNotVersioned.withNewSession { s -> | ||
| def reloaded = OptLockNotVersioned.get(o.id) | ||
| reloaded.name += ' in new session' | ||
| reloaded.save(flush: true) |
There was a problem hiding this comment.
Even with the visibility problem fixed, this save(flush: true) is never committed. Bare withNewSession only binds/unbinds a session; the flush runs in a lazily started default transaction (Neo4jSession.assertTransaction() -> startDefaultTransaction()), and on unbind Neo4jSession.disconnect() calls Neo4jTransaction.close(), which closes the native bolt transaction without committing - the driver rolls it back. The only committing path is Neo4jTransaction.commit(), driven by withTransaction. The sibling test wraps its background save in OptLockVersioned.withTransaction { ... } (line 91) for this reason; this closure needs the same (and the unused s -> parameter can be dropped at the same time).
| } | ||
| // Unlike the unbounded join() above, join(timeout) can return before the thread | ||
| // finishes; assert completion explicitly so a slow runner fails loudly instead of | ||
| // silently racing the assertions below. |
There was a problem hiding this comment.
The assertions below cannot actually race the background update - they are unfalsifiable by it. o is loaded before the thread starts (line 131, name locked), line 148 appends in main session, the save is a blind SET n += $props with no version predicate (version false), and the re-read at line 159 goes through the main session's still-open transaction, which sees its own write (and holds the node's write lock, so a late background SET cannot land between lines 151 and 159). Both ex == null and o.name == 'locked in main session' hold even if lines 133-146 are deleted. Contrast the sibling's o.name == 'locked in new session' (line 121), which does verify its background write. Re-reading in a fresh session after the join and asserting the name is locked in new session before the main save would make the background update load-bearing and turn this into a real last-write-wins test.
| // Unlike the unbounded join() above, join(timeout) can return before the thread | ||
| // finishes; assert completion explicitly so a slow runner fails loudly instead of | ||
| // silently racing the assertions below. | ||
| backgroundUpdate.join(5000) |
There was a problem hiding this comment.
This converts a previously non-failing wait into a hard 5s cliff. Before, a background thread finishing in more than 2s was tolerated: join(2000) returns silently on timeout and the following sleep 5000 absorbed the overrun (~7s of effective grace). Now a single run over 5s fails at line 144, and the sleep 5000 headroom sits after the assert, so it no longer contributes anything to the completion check. With grails-data-neo4j/build.gradle setting retry { maxRetries = 2; failOnPassedAfterRetry = true }, one slow run reds the build even when the retry passes. Every equivalent test in the tree - the sibling above (line 98), the TCK copy in grails-datamapping-tck, and the hibernate5/7 variants - uses an unbounded .join(), which cannot return early and has no cliff; converging on that is both simpler and stronger. If the bounded form stays, consider a larger budget and an assert message that includes backgroundUpdate.state so a CI-only timeout is triageable.
| }.join(2000) | ||
| } catch (InterruptedException e) { | ||
| // ignore | ||
| def backgroundUpdate = Thread.start { |
There was a problem hiding this comment.
Merge hazard: feat/neo4j-gorm-registry-migration (branched from the same base commit) deletes this module and relocates this spec to grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/OptimisticLockingSpec.groovy - still containing the old join(2000) block, plus a stray session. -> manager.session. substitution inside the string literals (' in new manager.session'). A git merge-tree of the two heads reports a content conflict on this exact block, and the likely resolution (taking the migrated file wholesale) silently drops this fix. Worth coordinating with that branch, and/or applying the change to the TCK copy (grails-datamapping-tck/src/main/groovy/org/apache/grails/data/testing/tck/tests/OptimisticLockingSpec.groovy, which still has .join() + sleep(2000)), which survives the migration.
| backgroundUpdate.join(5000) | ||
| assert !backgroundUpdate.isAlive() | ||
| // Same headroom rationale as "Test optimistic locking" above. | ||
| sleep 5000 |
There was a problem hiding this comment.
Optional, pre-existing: this fixed sleep 5000 (and the sibling's at line 103) costs 5s on every green run. Once the background write actually lands (see the notes above), the deterministic replacement is a spock.util.concurrent.PollingConditions poll on the observable state - already the idiom in DirtyCheckingAfterListenerSpec and HibernateUpdateFromListenerSpec, and spock-core is on this module's test classpath. It returns as soon as the write is visible and fails with the actual observed value on timeout, instead of sleeping a fixed budget and hoping.
jdaugherty
left a comment
There was a problem hiding this comment.
I intend to fix all of these comments in a push here shortly.
| @@ -96,11 +99,18 @@ class OptimisticLockingSpec extends GormDatastoreSpec { | |||
| } | |||
| } | |||
| }.join() | |||
There was a problem hiding this comment.
The failure capture added below was only applied to the second test. This thread can still die silently (e.g. the assert reloaded on line 96), in which case the poll on line 107 times out after 10s reporting observedName == 'locked' and the actual exception is lost to stderr. Worth the same AtomicReference<Throwable> treatment for symmetry.
… background write Ports #16072 onto 8.0.x, where #15972 relocated this spec to grails-data-neo4j/core, and applies the remaining review feedback. The 'version false' test never exercised a concurrent write: the given: transaction was not committed, so the background session could not see the node, and its bare withNewSession save was closed without a commit. The final assertions passed regardless. Commit before spawning the thread, wrap the background save in withTransaction, and assert that an independent session observed the write before the main session's blind overwrite, so the background update is load-bearing. Both tests now capture the background thread's outcome in an AtomicReference and rethrow it, since a thread that died from an exception is indistinguishable from a finished one via join() or isAlive(). The fixed sleep 5000 in each test is replaced with a PollingConditions poll on the committed state; a healthy run finishes in ~0.2s instead of ~5s. The "write durability" rationale that justified the sleeps is dropped. The CI failure behind it was the TCK copy of this spec, which #15972 has since disabled for Neo4j; a Neo4j commit is visible to any new transaction as soon as it returns. Also drops the redundant nativeTransaction.close() after commit(), the unused closure parameters, and the 'manager.session' text that leaked into string literals during the module relocation. Co-authored-by: James Daugherty <[email protected]>
169193b to
43fca1c
Compare
|
I reviewed this since it was still set for RC2, but it looks like the upstream branch was changed. I'm going to remove this from RC2 and restore this PR as it was. |
43fca1c to
169193b
Compare
This comment has been minimized.
This comment has been minimized.
| // than sleep a fixed duration) until an independent session observes it, since the | ||
| // embedded Neo4j harness's own write-durability/visibility lag can outlast any fixed | ||
| // guess (heisenbug) - a noisy/loaded CI runner has been seen pushing past 2s, and this | ||
| // adapts instead of gambling on a bigger number. |
There was a problem hiding this comment.
This rationale does not match what actually failed. The CI failure that motivated #16070 (run 29704447551 on #15972, all three Neo4j legs) was ConditionNotSatisfiedError at OptimisticLockingSpec.groovy:102. At that commit, line 102 of this file is o.name += ' in main session', which is not a condition, while line 102 of the TCK copy (grails-datamapping-tck/src/main/groovy/org/apache/grails/data/testing/tck/tests/OptimisticLockingSpec.groovy, which grails-data-neo4j-core:test also runs via the extracted TCK classes) is ex instanceof OptimisticLockingException. That TCK test is the one that was failing; #15972 later diagnosed it as the uncommitted-node / read-committed problem and @IgnoreIf'd it for Neo4j. No run of this file has ever been observed outlasting a sleep, and a Neo4j commit is synchronous: once join() returns, the write is visible to any new transaction, so there is no durability or visibility lag to adapt to.
Keeping the poll as a cheap guard is fine, but the comment should not assert a mechanism that is not there. Something like "poll until an independent session sees the write rather than sleep a fixed budget" is enough, and the "seen pushing past 2s" claim should go (same for the "visibility-lag rationale" reference on line 165).
| // A thread that dies from an uncaught exception is also no longer alive, so join() | ||
| // alone can't distinguish a completed write from a crashed one; assert the captured | ||
| // outcome explicitly. | ||
| assert failure.get() == null |
There was a problem hiding this comment.
Nit: on failure the power assert renders only failure.get()'s toString(), so the background thread's stack trace is lost. if (failure.get()) throw failure.get() keeps the full trace in the report.
| // adapts instead of gambling on a bigger number. | ||
| new PollingConditions(timeout: 10, initialDelay: 0.1, delay: 0.2).eventually { | ||
| def observedName | ||
| OptLockVersioned.withNewSession { s -> |
There was a problem hiding this comment.
Nit, carried over from the previous round: the s -> parameters are still unused in all four withNewSession closures (lines 93, 109, 148, 168).
| given: | ||
| def o = new OptLockNotVersioned(name: 'locked').save(flush: true) | ||
| session.transaction.commit() | ||
| session.transaction.nativeTransaction.close() |
There was a problem hiding this comment.
Nit: Neo4jTransaction.commit() already closes the native transaction and its bolt session (commit() calls close()), so this nativeTransaction.close() is a no-op copied from line 78. Harmless, but it reads as if something were still open.
… background write Retargets #16072 onto 8.1.x, where #15972 relocated this spec to grails-data-neo4j/core, and applies the remaining review feedback. The 'version false' test never exercised a concurrent write: the given: transaction was not committed, so the background session could not see the node, and its bare withNewSession save was closed without a commit. The final assertions passed regardless. Commit before spawning the thread, wrap the background save in withTransaction, and assert that an independent session observed the write before the main session's blind overwrite, so the background update is load-bearing. Both tests now capture the background thread's outcome in an AtomicReference and rethrow it, since a thread that died from an exception is indistinguishable from a finished one via join() or isAlive(). The fixed sleep 5000 in each test is replaced with a PollingConditions poll on the committed state; a healthy run finishes in ~0.2s instead of ~5s. The "write durability" rationale that justified the sleeps is dropped. The CI failure behind it was the TCK copy of this spec, which #15972 has since disabled for Neo4j; a Neo4j commit is visible to any new transaction as soon as it returns. Also drops the redundant nativeTransaction.close() after commit(), the unused closure parameters, the 'manager.session' text that leaked into string literals during the module relocation, and the dead neo4jSession/sessionHolder locals with their unused imports. Co-authored-by: James Daugherty <[email protected]>
169193b to
f3f1d41
Compare
Summary
Retargeted to
8.1.x, where #15972 relocated this spec tograils-data-neo4j/core/src/test/groovy/grails/gorm/tests/OptimisticLockingSpec.groovy.'version false'test never exercised a concurrent write: thegiven:transaction was not committed, so the background session could not see the node, and its barewithNewSessionsave was closed without a commit. Its final assertions passed regardless. The test now commits before spawning the thread, wraps the background save inwithTransaction, and asserts that an independent session observed the write before the main session's blind overwrite, so the background update is load-bearing.AtomicReferenceand rethrow it, since a thread that died from an exception is indistinguishable from a finished one viajoin()orisAlive().sleep 5000in each test is replaced with aPollingConditionspoll on the committed state, so a healthy run finishes in ~0.2s instead of ~5s.nativeTransaction.close()aftercommit(), the unused closure parameters, themanager.sessiontext that leaked into string literals during the module relocation, and the deadneo4jSession/sessionHolderlocals with their unused imports.Test plan
./gradlew :grails-data-neo4j-core:test --tests "*OptimisticLockingSpec"on 8.1.x: both copies pass (module spec 3/3, TCK copy 2 pass + 1 skipped for Neo4j)./gradlew :grails-data-neo4j-core:codeStylecleanwithTransactionfails at the poll; removing the pre-spawncommit()fails at the backgroundassert reloaded