Skip to content

fix(neo4j): make OptimisticLockingSpec commit, observe and verify the background write - #16072

Merged
jdaugherty merged 1 commit into
8.1.xfrom
fix/optimistic-locking-spec-join-assert
Sep 30, 2026
Merged

jdaugherty merged 1 commit into
8.1.xfrom
fix/optimistic-locking-spec-join-assert

Conversation

@borinquenkid

@borinquenkid borinquenkid commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Retargeted to 8.1.x, where #15972 relocated this spec to grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/OptimisticLockingSpec.groovy.

  • 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. Its final assertions passed regardless. The test now commits before spawning the thread, wraps the background save in withTransaction, and asserts that an independent session observed the write before the main session's blind overwrite, so the background update is load-bearing.
  • Both tests 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, so a healthy run finishes in ~0.2s instead of ~5s.
  • Drops the "write durability" rationale for the sleeps: the CI failure behind test(neo4j): give OptimisticLockingSpec's cross-thread heisenbug more headroom #16070 was the TCK copy of this spec, which Neo4j GormRegistry migration (consolidated: replaces #15816, #15951, #15817, #15832, #15833) #15972 has since disabled for Neo4j, and a Neo4j commit is visible to any new transaction as soon as it returns.
  • Also removes 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.

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:codeStyle clean
  • Mutation checks: removing the background withTransaction fails at the poll; removing the pre-spawn commit() fails at the background assert reloaded

Copilot AI review requested due to automatic review settings July 30, 2026 22:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 InterruptedException from 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

codecov Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.2593%. Comparing base (95021df) to head (f3f1d41).
⚠️ Report is 93 commits behind head on 8.1.x.

Additional details and impacted files

Impacted file tree graph

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

see 2131 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@borinquenkid borinquenkid moved this to Todo in Apache Grails Jul 31, 2026
@borinquenkid borinquenkid added this to the grails:8.0.0-RC2 milestone Jul 31, 2026
@borinquenkid
borinquenkid requested review from jdaugherty and a lite review from Copilot August 9, 2026 17:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.

@borinquenkid borinquenkid moved this from Todo to In Progress in Apache Grails Aug 16, 2026
// finishes; assert completion explicitly so a slow runner fails loudly instead of
// silently racing the assertions below.
backgroundUpdate.join(5000)
assert !backgroundUpdate.isAlive()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() == null

plus 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, 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

Copy link
Copy Markdown
Contributor

@borinquenkid

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I intend to fix all of these comments in a push here shortly.

@@ -96,11 +99,18 @@ class OptimisticLockingSpec extends GormDatastoreSpec {
}
}
}.join()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

jdaugherty added a commit that referenced this pull request Sep 24, 2026
… 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]>
@jdaugherty
jdaugherty force-pushed the fix/optimistic-locking-spec-join-assert branch from 169193b to 43fca1c Compare September 24, 2026 14:14
@jdaugherty
jdaugherty changed the base branch from feat/gorm-registry-core-impl to 8.0.x September 24, 2026 14:14
@jdaugherty

Copy link
Copy Markdown
Contributor

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.

@jdaugherty
jdaugherty force-pushed the fix/optimistic-locking-spec-join-assert branch from 43fca1c to 169193b Compare September 24, 2026 14:16
@jdaugherty
jdaugherty changed the base branch from 8.0.x to feat/gorm-registry-core-impl September 24, 2026 14:16
@testlens-app

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: 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 ->

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: 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]>
@jdaugherty
jdaugherty force-pushed the fix/optimistic-locking-spec-join-assert branch from 169193b to f3f1d41 Compare September 30, 2026 15:16
@jdaugherty
jdaugherty changed the base branch from feat/gorm-registry-core-impl to 8.1.x September 30, 2026 15:16
@jdaugherty jdaugherty changed the title fix(neo4j): assert background thread completion in OptimisticLockingSpec fix(neo4j): make OptimisticLockingSpec commit, observe and verify the background write Sep 30, 2026
@jdaugherty
jdaugherty merged commit b8ba0e6 into 8.1.x Sep 30, 2026
85 of 161 checks passed
@jdaugherty
jdaugherty deleted the fix/optimistic-locking-spec-join-assert branch September 30, 2026 15:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants