Skip to content

fix: bound the help-waiting loop on a wedged peer (follow-up to #5062) - #5072

Merged
lvca merged 4 commits into
mainfrom
fix/5062-followup-helping-liveness
Jul 7, 2026
Merged

lvca merged 4 commits into
mainfrom
fix/5062-followup-helping-liveness

Conversation

@lvca

@lvca lvca commented Jul 7, 2026

Copy link
Copy Markdown
Member

Follow-up to #5062, addressing the round-6 review findings that landed after the merge.

The liveness hole (round-6 point 1)

offerHelping had 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:

  • offer fails (peer's queue full, peer completes nothing but isAlive() is true);
  • the deferral budget never grows (helpDeferredTasks stays empty - there is nothing to poll);
  • self.queue.poll() returns null, 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 of checkForStalledQueuesMaxDelay (60s with defaults). On trip, the hand-off fails loudly: the exception unwinds through scheduleTask into executeTask'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_EXIT the helping loop set forceShutdown but kept looping to hand off the follow-up, so on a wedged peer close() 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 in offerWaiting).

Red-first evidence: AsyncShutdownPromptHelpingBailTest - on the previous code close() 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 offerHelping javadoc liveness claim is corrected to match the implementation, and the release notes are updated.

Verification

mvn -pl engine compile; full com.arcadedb.database.async battery (22 tests, including the two new red-first regressions) plus AsyncTest (11) - all green, including the #5062 shutdown-escalation regression unchanged.

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

mergify Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@gemini-code-assist gemini-code-assist Bot 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.

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.

Comment on lines +1197 to +1211
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;
}

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.

high

There are two issues with the current stall detection interval check:

  1. 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. Using System.nanoTime() is immune to clock adjustments.
  2. Zero/Negative Delay Vulnerability: If checkForStalledQueuesMaxDelay is configured to be 0 or negative, now - windowStart >= checkForStalledQueuesMaxDelay will evaluate to true immediately on every iteration. Since the loop runs extremely fast, windowsWithoutProgress will quickly exceed STALLED_NO_PROGRESS_WINDOWS (12) and throw a false-positive DatabaseOperationException almost instantly, completely breaking the async executor.

Guarding the check with delayNs > 0 prevents this vulnerability.

Suggested change
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();

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.

medium

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.

Suggested change
long windowStart = System.currentTimeMillis();
long windowStart = System.nanoTime();

@codacy-production

codacy-production Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 11 complexity

Metric Results
Complexity 11

View in Codacy

🟢 Coverage 100.00% diff coverage · +0.02% coverage variation

Metric Results
Coverage variation ✅ +0.02% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

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.

@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Code Review — PR #5072 (follow-up to #5062)

Reviewed the diff and traced the surrounding DatabaseAsyncExecutorImpl machinery (offerHelping, offerWaiting, the run loop, executeTask, createThreads). Overall this is a well-reasoned, well-documented, and well-tested fix. The three round-6 items are addressed cleanly and the reasoning in both the commit message and the code comments is excellent. Notes below.

Correctness — the two behavioral changes hold up

  • Empty-own-queue backstop (point 1): The mirror of the producer-side progress-gated bound is correct. With an empty own queue, helpDeferredTasks never grows, so poll() returns null and the loop can only exit via the new wall-clock backstop. Reading target.completedTaskCount (volatile) for progress and resetting windowStart/windowsWithoutProgress matches the offerWaiting semantics. The trip minimum is STALLED_NO_PROGRESS_WINDOWS * checkForStalledQueuesMaxDelay (~60s default), consistent with the documented producer cliff.
  • Worker survival: Confirmed the throw unwinds correctly. offerHelping is only reachable with self != null (i.e. mid-execute() inside executeTask), so the DatabaseOperationException propagates out of the user task into executeTask's catch → onError + rollback + completed() + completedTaskCount++, and the run loop keeps serving. Good.
  • Prompt shutdown bail (point 2): Consuming FORCE_EXIT sets self.forceShutdown; the next iteration's top-of-loop check throws before another offer attempt. forceShutdown is only ever set during close()/kill() (lines 803, 1226), so there's no risk of dropping a task during normal operation. The r4 interrupt escalation is correctly retained as the backstop for the offerWaiting park path.

Minor suggestions (non-blocking)

  1. Duplicated stall-detection logic. The progress-window accounting now exists in both offerWaiting (1091-1123) and offerHelping (1197-1211) with subtly different loop shapes. Extracting a small helper (e.g. boolean advanceStallWindow(...) returning whether to trip) would reduce the risk of the two drifting apart in a future round. Acceptable to defer given the differing control flow, but worth a thought.

  2. Missing positive/false-negative test. Both new tests prove the backstop trips on a wedged peer. Consider adding one that proves it does not trip when the target is slow-but-progressing (completes a task every window while its queue stays full) — that directly exercises the else { windowsWithoutProgress = 0; observedCompleted = nowCompleted; } reset and guards the "operator cliff" from regressing into false aborts on legitimately slow peers.

  3. Test helper duplication. awaitTask()/noOpTask() (and countingTask()) are copy-pasted across the two new files. A small shared base/util in the async test package would DRY these up.

  4. Thread-recreation via side-effect. Both tests rely on setTransactionUseWAL(true) to force createThreads() so the ASYNC_OPERATIONS_QUEUE_SIZE=2 is picked up (since setParallelLevel(2) is a no-op when the level already equals 2). It's documented with a comment and works, but it's an obscure coupling — if setTransactionUseWAL ever stops calling createThreads(), the tests silently lose their intended queue capacity. A dedicated test hook to rebuild the pool would be more robust.

Performance / safety

  • No busy-spin: with an empty own queue the offer blocks up to 100ms per iteration, so the wait is ~10 iterations/sec, not a hot loop. Memory stays bounded by the existing queueCapacity deferral budget. No new allocations on the hot path.
  • No new security surface.

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 com.arcadedb.database.async battery (22) + AsyncTest (11) green.

@codecov

codecov Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 65.61%. Comparing base (bca87b8) to head (04469ce).
⚠️ Report is 35 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 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.

@lvca lvca self-assigned this Jul 7, 2026
@lvca lvca added this to the 26.7.2 milestone Jul 7, 2026
…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.
@lvca

lvca commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

Round 1 addressed in ac615d9, per point:

2. Positive-case test - taken. It covers the one branch the red-first pair cannot reach: the else { windowsWithoutProgress = 0; ... } reset. AsyncHelpingSlowPeerProgressTest pins the exact backstop scenario (empty own queue, full peer queue) but injects steady progress by ticking the peer's completedTaskCount (made package-private for this, same precedent as the other test hooks) - white-box because a genuinely progressing peer frees queue slots and ends the park long before enough windows elapse, while the tick reproduces the signature of a saturated pipeline refilled by faster producers. Two-phase assertion: ~40 elapsed windows of ticked progress with no stall, then progress stops and the backstop must fire, proving the counter was resetting rather than merely never advancing. Mutation-verified: with the reset branch deleted the test fails during the tick phase.

3. Helper duplication - taken. Shared AsyncTestTasks factory (awaitTask/countingTask/noOpTask) now backs the three tests of this PR. The tests that merged with #5062 are left untouched to keep this PR's footprint small; they can migrate opportunistically.

4. Thread-recreation side effect - taken. Dedicated package-private recreateThreadsForTests() hook (same precedent as the #4955 getBestSlot hook); the three tests of this PR use it instead of setTransactionUseWAL(true), so they no longer depend on that setter calling createThreads().

1. Stall-window helper extraction - deferred, 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. A stateful shared helper would need to parameterize both the sampling cadence and the trip policy, which obscures more than it protects at two call sites; the new positive-case test now guards the semantics both loops must share.

Verification: mvn -pl engine compile; com.arcadedb.database.async battery (23 tests, including the new mutation-verified positive case) plus AsyncTest (11) - all green.

@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review: PR #5072 - bound the help-waiting loop on a wedged peer

Reviewed the source change (DatabaseAsyncExecutorImpl.java), the three new regression tests, the shared task factory, and the release-note update. This is a careful, well-reasoned fix. Summary: looks good to merge, with a few minor observations below (none blocking).

What's strong here

  • The liveness fix is correct and minimal. The empty-own-queue spin was a genuine hole: offer fails on a wedged-alive peer, helpDeferredTasks never grows (nothing to poll), poll() returns null, continue forever. Reusing the existing progress-gated STALLED_NO_PROGRESS_WINDOWS bound keeps the new escape semantically consistent with the producer-side backstop in offerWaiting rather than inventing a second policy.
  • Correct adaptation of the window mechanic. The producer path lets the blocking queue.offer(task, checkForStalledQueuesMaxDelay, ...) time each window; the helping path can't (its offer window is 1ms/100ms), so it measures windows on the wall clock (now - windowStart >= checkForStalledQueuesMaxDelay) and resets observedCompleted/counter on progress. The reset-on-progress branch matches the producer path exactly.
  • No task loss on the backstop trip. The throw unwinds through scheduleTask -> executeTask's catch (onError + rollback + completed()), the worker survives, and the helpDeferredTasks it drained from its own queue are still picked up by the run loop (helpDeferredTasks.isEmpty() ? queue.poll(...) : helpDeferredTasks.pollFirst()).
  • Test quality is excellent. Red-first regressions for both the liveness hole and the prompt-shutdown bail, plus a mutation-verified positive case (AsyncHelpingSlowPeerProgressTest) guarding the else-reset branch that the red-first pair can't reach. Using a dedicated recreateThreadsForTests() hook instead of the setTransactionUseWAL() side effect, and extracting AsyncTestTasks, are both the right call.
  • recreateThreadsForTests() -> createThreads() calls shutdownThreadsLocked() first under lifecycleLock, so the hook doesn't leak the prior pool.

Minor observations (non-blocking)

  1. Nominal vs. actual backstop time when the delay is very small. With an empty own queue the offer window is 100ms. If checkForStalledQueuesMaxDelay is set below that (the tests use 50ms), each iteration is bounded below by the 100ms offer, so the effective backstop is ~12 x 100ms rather than the nominal 12 x 50ms reported in the error message. Harmless in production (default 5000ms >> 100ms) and it only makes the bound more conservative, but the reported "last N ms" can understate the real elapsed time at tiny delays. Worth a one-line note if you want the message to stay precise.

  2. Shutdown-bail drops the in-flight follow-up. The new top-of-loop forceShutdown throw discards the task being handed off. This is only reachable via FORCE_EXIT (forced/prompt close()), never the graceful waitCompletion() drain, and it matches the existing "workers are dying" target-dead semantics - so it's fine, just calling it out explicitly as verified behavior for future readers.

  3. peer.completedTaskCount++ from the test thread in the positive-case test is a non-atomic write to a volatile, but it's sound here since the peer worker is parked in awaitTask (completing nothing) and the test thread is the sole writer during the tick phase. The comment already documents this white-box assumption.

Style / conventions

Consistent with the surrounding code and CLAUDE.md: final on new locals/params, class-imported types, package-private test hook precedent, no new dependencies, comprehensive javadoc updated to match the implementation. The javadoc correction (removing the "no liveness detector" claim in favor of the two bounded escapes) is accurate.

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

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review: PR #5072 - bound the help-waiting loop on a wedged peer

Reviewed the diff statically against the surrounding DatabaseAsyncExecutorImpl code and the existing #5062 backstop machinery. Overall this is a well-targeted, well-documented fix. The two liveness holes are real, the fixes are minimal and localized, and both are backed by red-first regression tests plus a positive-case guard against false trips. Nice work.

What is solid

  • Correct root-cause fix. The empty-own-queue case genuinely had no backstop: offer fails, helpDeferredTasks never grows (nothing to poll), self.queue.poll() returns null then continue forever. Reusing the same progress-gated STALLED_NO_PROGRESS_WINDOWS bound as the producer path keeps the two escapes semantically consistent.
  • Exception unwinding verified. The thrown DatabaseOperationException propagates through executeTask message.execute() into catch(Throwable) then onError + rollback + completed() in finally, so the worker survives and the outer task latch still counts down. The worker-survives claim holds.
  • Prompt shutdown bail is correct. Consuming FORCE_EXIT sets forceShutdown; the top-of-loop check throws on the next iteration and the run loop while(!forceShutdown) exits. No 100ms offer delay is paid because the check precedes the offer.
  • Test hook is justified and safe. setParallelLevel(2) is a no-op when the default already equals 2, so threads keep the pre-test queue size; recreateThreadsForTests() forces a rebuild, and createThreads() calls shutdownThreadsLocked() first, so no thread leak. queueCapacity is read at construction (ASYNC_OPERATIONS_QUEUE_SIZE / parallelLevel, floored at 1), confirming the "capacity 1 per worker" comment.

Minor observations (non-blocking)

  1. Diagnostic message under-reports by ~1 window. noProgressSince is set on the first detected no-progress window, which is already one checkForStalledQueuesMaxDelay after windowStart. So the reported now - noProgressSince covers ~11 windows, while the producer path reports the nominal STALLED_NO_PROGRESS_WINDOWS * checkForStalledQueuesMaxDelay (12). The inline comment explains the measured-vs-nominal intent, so this is cosmetic, but the two stall messages read slightly differently for the same 12-window trip.

  2. Dropped follow-up = possible half-edge. On a legitimate 60s+ peer stall, aborting the hand-off rolls back the batch and drops the follow-up, which in the bidirectional-edge case is the incoming-link task. That can leave a persisted outgoing direction without its incoming counterpart until the peer eventually drains. This is the documented operator cliff (same tradeoff as the producer backstop) and onError surfaces it, so it is acceptable, but it may be worth making explicit in the release note that the failure mode is a partial edge, not just a dropped task.

  3. AsyncHelpingSlowPeerProgressTest timing margin. Progress is ticked every 100ms against a 12 x 50ms = 600ms bound, so the safety margin against a false trip is ~6x. Comfortable on a normal box, but a CI pause longer than 600ms on the ticking thread would falsely trip the backstop. Low risk given the margin; flagging only because it is the one test whose green depends on the host not stalling.

  4. Test tagging. The three new tests run ~1-3s each. CLAUDE.md suggests @tag("slow") for multi-second functional regressions, but no existing test in com.arcadedb.database.async is tagged, so leaving them untagged is consistent with the package. Optional.

  5. White-box peer.completedTaskCount++. Non-atomic on a volatile, but the test is the sole writer while the peer is parked (documented in the Javadoc). Fine as-is.

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 AsyncTestTasks factory. Assertions use the AssertJ assertThat(...) style per project convention. The worker-survives-the-abort assertion is a nice touch.

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.
@lvca
lvca merged commit f3fab92 into main Jul 7, 2026
11 of 13 checks passed
@lvca
lvca deleted the fix/5062-followup-helping-liveness branch July 7, 2026 05:07
@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Code Review: PR #5072 - bound the help-waiting loop on a wedged peer

Thorough, 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 offerHelping can never grow (self.queue.poll() returns null -> continue forever), so a wedged-but-alive peer silently lost both workers with no error. The fix reuses the existing STALLED_NO_PROGRESS_WINDOWS bound consistently, and both fixes ship with red-first regression tests. Overall this looks correct and mergeable (and I see it already merged).

What's done well

  • Correct adaptation of the cadence difference between the two backstops. The producer path (offerWaiting) blocks exactly checkForStalledQueuesMaxDelay per offer(), so it can count one no-progress window per iteration. offerHelping intentionally uses a short offer window (1ms/100ms) to keep freeing slots, so counting per-iteration would be wrong; switching to a wall-clock now - windowStart >= checkForStalledQueuesMaxDelay gate makes both converge on "12 windows = 60s of zero completions". This subtlety was handled correctly.
  • Coverage of the mixed case. windowStart advances on wall-clock regardless of whether own-queue items were deferred, so the backstop still trips even if a few items drain before the queue empties. The empty-queue and budget-exhausted (return false -> bounded wait) paths compose cleanly.
  • Prompt shutdown bail is consistent with the existing escalation. Bailing at the top of the loop once forceShutdown is set drops the follow-up loudly (same semantics as the target-dead branch), and the shutdownThreadsLocked interrupt escalation (line ~944) remains as the backstop for parks that never poll the marker. The dropped in-flight task is still notified via completed() in executeTask's finally, and queued/deferred tasks via drainQueueNotifyingWaiters, so waitCompletion() callers aren't left hanging.
  • Good use of a shared AsyncTestTasks factory to cut duplication across the three new tests, and the AsyncHelpingSlowPeerProgressTest positive-case guard (progress must reset the counter) is exactly the test that prevents a false-abort regression on a saturated-but-progressing pipeline.

Minor points / questions (non-blocking)

  1. Operator visibility on trip. When the empty-queue backstop fires on a bidirectional-edge follow-up, the outgoing direction is already persisted and the incoming link is dropped -> a PARTIAL edge (documented in the release note). The stall is surfaced only through the onError callback. The producer-side backstop behaves the same way (throws without logging), so this is consistent, but given the data-integrity consequence it may be worth a throttled LogManager WARNING at the trip site so operators without an onError handler still see it. Consider for a future pass.

  2. completedTaskCount visibility relaxed to package-private for a white-box test. Documented clearly, and the alternative (a real progressing peer frees slots and ends the park) genuinely can't reproduce the "full queue + steady progress" signature. Acceptable, though it's a small encapsulation leak; a test-only hook would keep the field private if you want to tighten it later. The test's direct peer.completedTaskCount++ from the test thread is safe only because the peer is parked in user code (single writer) - that invariant is load-bearing and correctly documented.

  3. Redundant thread churn in test setup. setParallelLevel(2) already calls createThreads(2) when the current level differs, and then recreateThreadsForTests() rebuilds again. Harmless (test-only) and the explicit hook is genuinely needed for the case where the default level is already 2, but the double rebuild is slightly wasteful.

  4. Timing assertions. AsyncShutdownPromptHelpingBailTest (elapsed < 5000 vs 8s grace) and the backstop tests (await(10s) vs ~1.2s trip) all have generous margins, so low flake risk. AsyncShutdownPromptHelpingBailTest relies on a Thread.sleep(300) to get worker 0 into the helping loop before close(); that's the only ordering assumption and the margin absorbs it.

Test coverage

Strong. 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.

robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant