Repository navigation
fix: bound the help-waiting loop on a wedged peer (follow-up to #5062) - #5072
Conversation
Round-6 review of #5062 (merged before this landed) found a real liveness hole plus two minor items: - Empty-own-queue helping spin (the real one): offerHelping had no backstop when the helping worker's own queue was empty - offer fails on a wedged-alive peer, the deferral budget never grows (nothing to poll), poll() returns null, continue: forever. Both workers were silently lost in normal operation, and the javadoc's liveness argument silently assumed a non-empty own queue. Fix (option a): the helping loop now applies the same progress-gated STALLED_NO_PROGRESS_WINDOWS backstop as the producer path, measured in wall-clock windows of checkForStalledQueuesMaxDelay, and fails the hand-off loudly after 12 flat windows (60s default). The throw unwinds through scheduleTask into executeTask's catch: onError + batch rollback + completed(), and the worker survives and keeps serving its queue. Only the long, conservative bound is used (not the 3-window cross-slot one) because aborting mid-task costs the batch; a peer parked on a slow chain is outlived as long as its individual tasks stay under the bound - the same documented operator cliff as the producer backstop. Red-first: AsyncHelpingEmptyQueueBackstopTest (spun forever with no error on the previous code; now surfaces the stall in ~1.2s at a 50ms window and the worker stays serviceable). - Prompt shutdown bail: after consuming FORCE_EXIT the helping loop kept looping to hand off the follow-up, so close() paid the whole grace period before the r4 interrupt escalation. The loop now bails at the top once forceShutdown is set, dropping the follow-up loudly (workers are dying - same semantics as the target-dead branch). Red-first: AsyncShutdownPromptHelpingBailTest (close() paid the full 8s grace on the previous code; now returns in ~1.3s). The r4 escalation stays as the backstop for parks that never poll the marker (budget-exhausted offerWaiting). - waitCompletion partial-enqueue note (round-6 point 3, an earlier round failed to land it): the early return-false in the enqueue loop is not a leak - markers already enqueued on earlier workers execute and count down a latch nobody awaits anymore. Comment added. The offerHelping javadoc liveness claim is corrected to match: no cheap-trigger detector, but two bounded escapes (progress backstop, shutdown bail). Release notes updated. Verified: mvn -pl engine compile; com.arcadedb.database.async battery (22 tests, includes the two new red-first regressions) plus AsyncTest (11) - all green, including the r4 escalation test unchanged.
|
Tick the box to add this pull request to the merge queue (same as
|
There was a problem hiding this comment.
Code Review
This pull request hardens the asynchronous executor's helping loop to prevent infinite spinning when a worker hands off a cross-slot task to a wedged-alive peer while its own queue is empty. It introduces a progress-gated backstop for stalled queue detection, ensures prompt bailing upon consuming a shutdown marker, and adds corresponding regression tests. The review feedback highlights potential issues with using System.currentTimeMillis() for monotonic interval measurements due to clock skew sensitivity, and warns of a vulnerability where a zero or negative delay configuration could trigger false-positive stall exceptions, suggesting the use of System.nanoTime() and adding a guard condition.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| final long now = System.currentTimeMillis(); | ||
| if (now - windowStart >= checkForStalledQueuesMaxDelay) { | ||
| final long nowCompleted = target.completedTaskCount; | ||
| if (nowCompleted == observedCompleted) { | ||
| if (++windowsWithoutProgress >= STALLED_NO_PROGRESS_WINDOWS) | ||
| throw new DatabaseOperationException( | ||
| "Asynchronous queue of " + target.getName() + " is stalled: no task completed in the last " + ( | ||
| STALLED_NO_PROGRESS_WINDOWS * checkForStalledQueuesMaxDelay) | ||
| + " ms while handing off a cross-slot task. The worker may be blocked inside a user task or callback"); | ||
| } else { | ||
| windowsWithoutProgress = 0; | ||
| observedCompleted = nowCompleted; | ||
| } | ||
| windowStart = now; | ||
| } |
There was a problem hiding this comment.
There are two issues with the current stall detection interval check:
- Clock Skew Sensitivity: Using
System.currentTimeMillis()can cause false-positive stalls if the system clock is adjusted forward, or block stall detection if adjusted backward. UsingSystem.nanoTime()is immune to clock adjustments. - Zero/Negative Delay Vulnerability: If
checkForStalledQueuesMaxDelayis configured to be0or negative,now - windowStart >= checkForStalledQueuesMaxDelaywill evaluate totrueimmediately on every iteration. Since the loop runs extremely fast,windowsWithoutProgresswill quickly exceedSTALLED_NO_PROGRESS_WINDOWS(12) and throw a false-positiveDatabaseOperationExceptionalmost instantly, completely breaking the async executor.
Guarding the check with delayNs > 0 prevents this vulnerability.
| final long now = System.currentTimeMillis(); | |
| if (now - windowStart >= checkForStalledQueuesMaxDelay) { | |
| final long nowCompleted = target.completedTaskCount; | |
| if (nowCompleted == observedCompleted) { | |
| if (++windowsWithoutProgress >= STALLED_NO_PROGRESS_WINDOWS) | |
| throw new DatabaseOperationException( | |
| "Asynchronous queue of " + target.getName() + " is stalled: no task completed in the last " + ( | |
| STALLED_NO_PROGRESS_WINDOWS * checkForStalledQueuesMaxDelay) | |
| + " ms while handing off a cross-slot task. The worker may be blocked inside a user task or callback"); | |
| } else { | |
| windowsWithoutProgress = 0; | |
| observedCompleted = nowCompleted; | |
| } | |
| windowStart = now; | |
| } | |
| final long now = System.nanoTime(); | |
| final long delayNs = TimeUnit.MILLISECONDS.toNanos(checkForStalledQueuesMaxDelay); | |
| if (delayNs > 0 && now - windowStart >= delayNs) { | |
| final long nowCompleted = target.completedTaskCount; | |
| if (nowCompleted == observedCompleted) { | |
| if (++windowsWithoutProgress >= STALLED_NO_PROGRESS_WINDOWS) | |
| throw new DatabaseOperationException( | |
| "Asynchronous queue of " + target.getName() + " is stalled: no task completed in the last " + ( | |
| STALLED_NO_PROGRESS_WINDOWS * checkForStalledQueuesMaxDelay) | |
| + " ms while handing off a cross-slot task. The worker may be blocked inside a user task or callback"); | |
| } else { | |
| windowsWithoutProgress = 0; | |
| observedCompleted = nowCompleted; | |
| } | |
| windowStart = now; | |
| } |
| self.waitingCrossSlotOffer = true; | ||
| try { | ||
| long observedCompleted = target.completedTaskCount; | ||
| long windowStart = System.currentTimeMillis(); |
There was a problem hiding this comment.
Using System.currentTimeMillis() to measure elapsed time is sensitive to system clock adjustments (such as NTP synchronization or manual clock changes). It is highly recommended to use System.nanoTime() for monotonic interval measurements to prevent potential timing anomalies or false-positive stall detections.
| long windowStart = System.currentTimeMillis(); | |
| long windowStart = System.nanoTime(); |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 11 |
🟢 Coverage 100.00% diff coverage · +0.02% coverage variation
Metric Results Coverage variation ✅ +0.02% coverage variation Diff coverage ✅ 100.00% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (bca87b8) 167049 112498 67.34% Head commit (04469ce) 167176 (+127) 112624 (+126) 67.37% (+0.02%) Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch:
<coverage of head commit> - <coverage of common ancestor commit>Diff coverage details
Coverable lines Covered lines Diff coverage Pull request (#5072) 20 20 100.00% Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified:
<covered lines added or modified>/<coverable lines added or modified> * 100%
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.
Code Review — PR #5072 (follow-up to #5062)Reviewed the diff and traced the surrounding Correctness — the two behavioral changes hold up
Minor suggestions (non-blocking)
Performance / safety
Nice, careful work. The javadoc correction accurately reflects the new two-escape design. LGTM once the (optional) positive-case test is considered. Note: I was unable to execute the Maven test run in this review environment; the above is based on static analysis. The PR reports the full |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #5072 +/- ##
============================================
+ Coverage 65.59% 65.61% +0.02%
- Complexity 841 843 +2
============================================
Files 1687 1687
Lines 135246 135373 +127
Branches 28941 28969 +28
============================================
+ Hits 88710 88830 +120
- Misses 34428 34429 +1
- Partials 12108 12114 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…obustness Response to review round 1 (LGTM with minors): - Point 2 (positive/false-negative test): taken - it covers the one branch the red-first pair cannot reach. A peer that keeps completing tasks while its queue stays full must never trip the helping backstop, which is exactly the else-reset branch; a progress-blind regression there would falsely abort hand-offs on every saturated pipeline after the bound. AsyncHelpingSlowPeerProgressTest simulates the peer's progress white-box by ticking its (now package-private) completedTaskCount, because a genuinely progressing peer frees queue slots and ends the park before enough windows elapse - the tick is the deterministic signature of a saturated pipeline refilled by faster producers. Two-phase assertion: ~40 windows of ticked progress with no stall, then progress stops and the backstop must fire, which proves the counter was resetting rather than never advancing. Mutation-verified: with the else-reset removed the test fails during the tick phase. - Point 3 (test helper duplication): taken - shared AsyncTestTasks factory (awaitTask/countingTask/noOpTask) now backs the three tests of this PR; the tests merged with #5062 are left untouched to keep this PR's footprint small. - Point 4 (thread-recreation via setTransactionUseWAL side effect): taken - dedicated package-private recreateThreadsForTests() hook (same precedent as the #4955 getBestSlot test hook); the three tests of this PR use it instead of the WAL setter side effect. - Point 1 (extract shared stall-window helper): declined for now, as the review allows - the two sites sample differently (offerWaiting once per failed 5s offer with dual thresholds, offerHelping on wall clock across 1-100ms iterations with a single threshold), so a stateful helper would obscure more than it protects. Verified: mvn -pl engine compile; com.arcadedb.database.async battery (23 tests, includes the new mutation-verified positive case) plus AsyncTest (11) - all green.
|
Round 1 addressed in ac615d9, per point: 2. Positive-case test - taken. It covers the one branch the red-first pair cannot reach: the 3. Helper duplication - taken. Shared 4. Thread-recreation side effect - taken. Dedicated package-private 1. Stall-window helper extraction - deferred, as the review allows. The two sites sample differently: Verification: |
Review: PR #5072 - bound the help-waiting loop on a wedged peerReviewed the source change ( What's strong here
Minor observations (non-blocking)
Style / conventionsConsistent with the surrounding code and CLAUDE.md: Nice work - the fix is tightly scoped, the reasoning in the commit messages and comments is traceable, and the test coverage is thorough. |
Round 2 was 'looks good to merge' with one precision nit taken: at tiny configured delays each helping-loop iteration is floored by the offer window (100ms with an empty own queue), so the nominal windows-x-delay product in the stall message understated the real elapsed time. The message now reports the measured span since the first no-progress window. The other two observations were the reviewer's own verifications of intended behavior (shutdown-bail drops the in-flight hand-off by design - FORCE_EXIT only, workers dying; the positive-case test's single-writer volatile tick is documented white-box). Stall/backstop battery green: empty-queue backstop, slow-peer progress (mutation-guard), wedged-worker, slow-peer-no-false-stall, prompt bail.
|
Review: PR #5072 - bound the help-waiting loop on a wedged peer Reviewed the diff statically against the surrounding What is solid
Minor observations (non-blocking)
Test coverage Good: red-first proof for both fixes (empty-queue spin and shutdown bail), a positive guard that a progressing-but-saturated peer never trips, plus a shared Verification note: I reviewed statically and did not re-run the suite. The PR states mvn -pl engine compile and the full com.arcadedb.database.async battery (22) plus AsyncTest (11) pass. |
…al-edge failure mode in the note Round 3 endorsed the fix end to end (unwinding, shutdown bail, test hook safety all independently verified). Two cosmetics taken: the stall message now measures from the LAST observed progress instead of the first no-progress window, so the reported span covers the full 12-window trip (the previous measurement under-reported by ~1 window vs the producer path); and the release note states the concrete failure mode when the backstop trips on a bidirectional-edge follow-up - a PARTIAL edge (the outgoing direction persisted, the incoming link dropped) until the operation is repeated, surfaced via onError. Acknowledged without change: the positive-case test's ~6x timing margin (the one test sensitive to a host stall; documented), tagging left consistent with the untagged async package, and the documented white-box tick. Backstop battery green.
Code Review: PR #5072 - bound the help-waiting loop on a wedged peerThorough, well-reasoned follow-up to #5062. The root-cause analysis of the liveness hole is accurate: with an empty own queue the deferral budget in What's done well
Minor points / questions (non-blocking)
Test coverageStrong. Three focused regressions (empty-queue backstop, progressing-peer-never-trips, prompt shutdown bail) each with explicit red-first evidence in the PR description, plus the existing async battery re-run. Nothing obvious missing. Nice work - the concurrency reasoning and the comment cross-references to specific review rounds make this easy to follow. |
…obustness Response to review round 1 (LGTM with minors): - Point 2 (positive/false-negative test): taken - it covers the one branch the red-first pair cannot reach. A peer that keeps completing tasks while its queue stays full must never trip the helping backstop, which is exactly the else-reset branch; a progress-blind regression there would falsely abort hand-offs on every saturated pipeline after the bound. AsyncHelpingSlowPeerProgressTest simulates the peer's progress white-box by ticking its (now package-private) completedTaskCount, because a genuinely progressing peer frees queue slots and ends the park before enough windows elapse - the tick is the deterministic signature of a saturated pipeline refilled by faster producers. Two-phase assertion: ~40 windows of ticked progress with no stall, then progress stops and the backstop must fire, which proves the counter was resetting rather than never advancing. Mutation-verified: with the else-reset removed the test fails during the tick phase. - Point 3 (test helper duplication): taken - shared AsyncTestTasks factory (awaitTask/countingTask/noOpTask) now backs the three tests of this PR; the tests merged with #5062 are left untouched to keep this PR's footprint small. - Point 4 (thread-recreation via setTransactionUseWAL side effect): taken - dedicated package-private recreateThreadsForTests() hook (same precedent as the #4955 getBestSlot test hook); the three tests of this PR use it instead of the WAL setter side effect. - Point 1 (extract shared stall-window helper): declined for now, as the review allows - the two sites sample differently (offerWaiting once per failed 5s offer with dual thresholds, offerHelping on wall clock across 1-100ms iterations with a single threshold), so a stateful helper would obscure more than it protects. Verified: mvn -pl engine compile; com.arcadedb.database.async battery (23 tests, includes the new mutation-verified positive case) plus AsyncTest (11) - all green. (cherry picked from commit ac615d9)
Round 2 was 'looks good to merge' with one precision nit taken: at tiny configured delays each helping-loop iteration is floored by the offer window (100ms with an empty own queue), so the nominal windows-x-delay product in the stall message understated the real elapsed time. The message now reports the measured span since the first no-progress window. The other two observations were the reviewer's own verifications of intended behavior (shutdown-bail drops the in-flight hand-off by design - FORCE_EXIT only, workers dying; the positive-case test's single-writer volatile tick is documented white-box). Stall/backstop battery green: empty-queue backstop, slow-peer progress (mutation-guard), wedged-worker, slow-peer-no-false-stall, prompt bail. (cherry picked from commit 2fb1528)
…al-edge failure mode in the note Round 3 endorsed the fix end to end (unwinding, shutdown bail, test hook safety all independently verified). Two cosmetics taken: the stall message now measures from the LAST observed progress instead of the first no-progress window, so the reported span covers the full 12-window trip (the previous measurement under-reported by ~1 window vs the producer path); and the release note states the concrete failure mode when the backstop trips on a bidirectional-edge follow-up - a PARTIAL edge (the outgoing direction persisted, the incoming link dropped) until the operation is repeated, surfaced via onError. Acknowledged without change: the positive-case test's ~6x timing margin (the one test sensitive to a host stall; documented), tagging left consistent with the untagged async package, and the documented white-box tick. Backstop battery green. (cherry picked from commit 04469ce)
Follow-up to #5062, addressing the round-6 review findings that landed after the merge.
The liveness hole (round-6 point 1)
offerHelpinghad NO backstop when the helping worker's OWN queue is empty. A worker handing off a cross-slot follow-up (the bidirectional-edge incoming-link task) to a wedged-alive peer spun forever:offerfails (peer's queue full, peer completes nothing butisAlive()is true);helpDeferredTasksstays empty - there is nothing to poll);self.queue.poll()returnsnull,continue- forever.Both workers were silently lost during normal operation (not just shutdown), with no error surfaced - and the javadoc's liveness argument silently assumed a non-empty own queue. The producer path already failed loudly at the 12-window backstop; the cross-scheduling worker did not.
Fix: the helping loop now applies the same progress-gated
STALLED_NO_PROGRESS_WINDOWS(12) backstop as the producer path, measured in wall-clock windows ofcheckForStalledQueuesMaxDelay(60s with defaults). On trip, the hand-off fails loudly: the exception unwinds throughscheduleTaskintoexecuteTask's catch -onError+ batch rollback +completed()- and the worker itself survives and keeps serving its queue. Only the long, conservative bound is used (not the 3-window cross-slot one) because aborting mid-task costs the current batch; a peer parked on a legitimately slow chain is outlived as long as its individual tasks stay under the bound - the same operator cliff already documented for the producer backstop.Red-first evidence:
AsyncHelpingEmptyQueueBackstopTest- on the previous code it spun forever with no error (10s latch timeout); fixed code surfaces the stall in ~1.2s at a 50ms test window, and a follow-up task scheduled on the same worker still executes (the worker survives the aborted hand-off).Prompt shutdown bail (round-6 point 2)
After consuming
FORCE_EXITthe helping loop setforceShutdownbut kept looping to hand off the follow-up, so on a wedged peerclose()paid the whole grace period before the #5062 interrupt escalation fired. The loop now bails out at the top of each iteration once the flag is set, dropping the follow-up loudly via the shutdown exception - workers are dying, same semantics as the target-dead branch. The interrupt escalation stays in place as the backstop for parks that never poll the marker (a budget-exhausted worker waiting inofferWaiting).Red-first evidence:
AsyncShutdownPromptHelpingBailTest- on the previous codeclose()paid the full 8s grace period (9.5s elapsed); fixed code returns in ~1.3s.waitCompletion note (round-6 point 3)
One-line comment at the enqueue-phase early return: completion markers already enqueued on earlier workers are not a leak - they execute and count down a latch nobody awaits anymore.
The
offerHelpingjavadoc liveness claim is corrected to match the implementation, and the release notes are updated.Verification
mvn -pl engine compile; fullcom.arcadedb.database.asyncbattery (22 tests, including the two new red-first regressions) plusAsyncTest(11) - all green, including the #5062 shutdown-escalation regression unchanged.