Skip to content

fix(#4953,#4954,#4961): async executor stall detector, shutdown draining, concurrency cleanups - #5062

Merged
lvca merged 8 commits into
mainfrom
fix/4953-4954-4961-async-executor
Jul 7, 2026
Merged

lvca merged 8 commits into
mainfrom
fix/4953-4954-4961-async-executor

Conversation

@lvca

@lvca lvca commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

Part of the 2026-07 engine audit remediation (#4962), group async-executor.

Per-issue verdicts

#4953 - stall detector false-positives and rolls back the in-flight batch: fixed

Re-verified against current main: scheduleTask still peeked the queue head across two checkForStalledQueuesMaxDelay windows and threw on identical identity, and newEdge's cross-slot incoming-edge follow-up still blocked one worker on another worker's full queue (a real wait cycle the detector broke by throwing inside the worker, rolling back up to commitEvery - 1 already-executed ops and dropping the follow-up).

Fix (both parts, coherently in scheduleTask):

  • Help-while-waiting (park-then-run): a worker of this executor that must wait on a full queue drains its OWN queue in the meantime, but does NOT execute the polled tasks re-entrantly - a nested execution could commit or roll back the suspended task's partial writes, breaking per-task atomicity (this replaced an earlier re-entrant design during review). Polled tasks are parked in a thread-confined helpDeferredTasks deque and executed by the run loop, in poll order, once the current task fully unwinds; draining alone frees the slot the parked peer is waiting on, so cross-slot cycles resolve with every task executed, no exception, no rollback. The parked backlog is bounded by the worker's queue capacity; past that budget the worker falls back to the detecting bounded wait below.
  • Progress-based detection for external producers: per-worker monotonic completedTaskCount + a waitingCrossSlotOffer flag, with two thresholds. A target parked handing a task cross-slot with a flat completed count (a likely scheduling cycle, only reachable after budget exhaustion) surfaces after 3 consecutive no-progress windows (15s by default), so a peer merely busy on one slow task does not trip it; a target wedged inside user code (infinite loop / blocking call, flag never set) surfaces after 12 windows (60s by default) instead of hanging the producer forever. Both tunable via setCheckForStalledQueuesMaxDelay(). A worker merely busy on a slow task no longer trips anything.

#4954 - shutdown/interrupt drops queued tasks, hanging completion waiters: fixed

Re-verified: the interrupt handler still did queue.clear() (dropping tasks whose completed() never ran, hanging scanType()/waitCompletion()), and shutdownThreadsLocked still blocked on an untimed queue.put(FORCE_EXIT) under lifecycleLock (a busy worker with a full queue wedged database.close()).

Fix: every run-loop exit path now drains the queue (and the parked help-deferral list) notifying completed() on each leftover task; DatabaseAsyncScanBucket / DatabaseAsyncBrowseIterator count their latches down from completed() (invoked on execution AND drop) instead of inside execute(); shutdown offers FORCE_EXIT with a 1s timeout and interrupts the worker on failure (with a WARNING if it will not die within 10s); waitCompletion(timeout) treats the timeout as a single budget spanning the enqueue and await phases, with a worker-liveness check instead of an untimed put; scheduleTask undoes an offer that lands after the target worker's final drain (best-effort: documented residual races for the opt-in fast queue, which cannot remove, and for an offer landing before isAlive() flips; the former logs a WARNING).

#4961 - low-severity concurrency cleanups: fixed (all three checkboxes)

  • Async executor settings (parallelLevel, commitEvery, backPressurePercentage, transactionUseWAL, transactionSync, checkForStalledQueuesMaxDelay, onOk/onError callbacks) are now volatile; setCommitEvery rejects values < 1 (0 made every task fail on count % 0) and the constructor clamps the configured batch size.
  • QueryEngineManager and SparseVectorScoringPool rejection handlers now cancel a RunnableFuture rejected after pool shutdown instead of leaving its waiter blocked in an untimed Future.get() forever (no test: both pools are JVM-wide singletons that are never shut down inside a test JVM without breaking sibling tests; the change is the minimal safe branch).
  • QueryEngineManager.register() is synchronized and publishes a copy-on-write map, so the public post-construction registration path cannot corrupt the lock-free getEngine/getAvailableLanguages readers.

Test evidence (red-first)

All nine new regression tests fail on unfixed code exactly on the audited defect, and pass after the fix:

  • AsyncStallDetectorFalsePositiveTest: unfixed threw DatabaseOperationException: Asynchronous queue 0 is stalled for a healthy worker busy 1.2s.
  • AsyncCrossSlotSchedulingDeadlockTest: deterministic 2-worker cross-offer cycle (queue capacity 1); unfixed dropped both follow-up markers (latch timeout) and fired the stall exception.
  • AsyncHelpingAtomicityTest: deterministic ordering probe; with re-entrant helping the polled task runs (and with commitEvery=1 commits the suspended task's partial write) before the suspended task unwinds.
  • AsyncWedgedWorkerStallTest: unfixed let a producer hang for the full wedge duration on a worker blocked in user code; fixed throws at the 12-window backstop.
  • AsyncSlowPeerNoFalseStallTest: unfixed threw the stall exception after a single flat window at a producer targeting a budget-exhausted worker whose cross-slot peer was merely slow; fixed waits 3 windows and completes normally.
  • AsyncShutdownDrainTest.killNotifiesCompletionOfDroppedQueuedTasks: unfixed never called completed() on the queued probes (latch timeout).
  • AsyncShutdownDrainTest.closeDoesNotBlockOnFullQueueOfBusyWorker: unfixed close() blocked ~15s in put(FORCE_EXIT) (await(8s) failed).
  • AsyncWaitCompletionTimeoutTest: unfixed waitCompletion(700) blocked far past its timeout while the enqueue phase retried on a full queue.
  • AsyncConfigValidationTest: unfixed accepted setCommitEvery(0).

Focused suites run green: com.arcadedb.database.async.* (19 tests), AsyncTest, SelectExecutionTest, QueryEngineManagerLanguagesTest, QueryEngineManagerPoolTest, GraphBatchTest, GraphBatchUniqueIndexTest, GraphBatchCommitRetryTest, ACIDTransactionTest, MVCCTest.

Conflict risks with sibling audit branches

All other changes are confined to com.arcadedb.database.async.

…ing, config visibility

#4953 (MEDIUM): the queue stall detector compared the IDENTITY of the queue
head across two offer windows of checkForStalledQueuesMaxDelay (5s). Any
head task running longer than 2x the delay (a heavy DatabaseAsyncCommand)
left the head untouched, so a healthy producer blocked on the full queue
was thrown a spurious "Asynchronous queue is stalled". Worse, under
bidirectional edge load the cross-slot incoming-edge follow-up made worker
A block offering into worker B's full queue while B blocked offering into
A's - a real wait cycle the detector could only break by throwing INSIDE
the worker, which rolled back the whole in-flight commit batch (up to
commitEvery-1 already-executed ops silently discarded unless onError was
wired) and dropped the follow-up (ghost half-edges).

Fix, two coherent parts in scheduleTask:
- A worker of this executor that must wait on a full queue now HELPS: it
  drains and executes tasks from its OWN queue while waiting (re-entrant
  executeTask extracted from the run loop; recursion capped at depth 32),
  so workers never sleep on each other's queues and cross-slot cycles
  resolve on their own with every task executed and nothing rolled back.
  Completion markers polled while helping are deferred until the hand-off
  succeeds, preserving the waitCompletion() contract.
- External producers use progress-based detection: per-worker monotonic
  completedTaskCount plus a waitingCrossSlotOffer flag. The stall error is
  thrown only when the target worker completed no task over a whole window
  while itself parked handing a task to another queue (a genuine scheduling
  cycle beyond the helping budget) or after the worker died; a slow task no
  longer trips it.

#4954 (MEDIUM): kill()'s interrupt made the worker queue.clear() its queue,
discarding tasks whose completed() never ran, so threads blocked in
scanType()/waitCompletion() hung forever; tasks enqueued after FORCE_EXIT
were silently dropped the same way; and shutdownThreadsLocked blocked on an
untimed queue.put(FORCE_EXIT) under lifecycleLock, so a busy worker with a
full queue wedged database.close() (and any later createThreads/kill) for
as long as its current task ran.

Fix: on any run-loop exit (FORCE_EXIT, shutdown flag, interrupt) the worker
now drains its queue notifying completed() on every leftover task;
DatabaseAsyncScanBucket/DatabaseAsyncBrowseIterator count their latches
down from completed() (invoked on both execution and drop) instead of
execute(); shutdown offers FORCE_EXIT with a 1s timeout and interrupts the
worker on failure; waitCompletion() replaces its untimed put with a bounded
offer plus a worker-liveness check; scheduleTask undoes an offer that
landed after the target worker's final drain.

#4961 (LOW, grouped cleanups): parallelLevel, commitEvery,
backPressurePercentage, transactionUseWAL, transactionSync,
checkForStalledQueuesMaxDelay, onOk/onError callbacks are now volatile
(written by user threads, read by workers); setCommitEvery rejects values
< 1 (0 made every task fail on count % 0) and the constructor clamps the
configured batch size; the QueryEngineManager and SparseVectorScoringPool
rejection handlers cancel a RunnableFuture rejected after pool shutdown
instead of leaving its waiter blocked in an untimed Future.get() forever;
QueryEngineManager.register() publishes a copy-on-write map so the public
post-construction registration path cannot corrupt lock-free readers.

Red-first evidence (all five tests fail on unfixed code, pass after):
- AsyncStallDetectorFalsePositiveTest: DatabaseOperationException
  "Asynchronous queue 0 is stalled" thrown at scheduleTask while the worker
  was healthy but busy 1.2s with a 100ms delay.
- AsyncCrossSlotSchedulingDeadlockTest: deterministic 2-worker cross-offer
  cycle (queue capacity 1); on unfixed code both follow-up markers are
  dropped (latch timeout) and the stall exception fires.
- AsyncShutdownDrainTest.killNotifiesCompletionOfDroppedQueuedTasks: probes
  queued behind an interrupted blocker never got completed() (latch
  timeout).
- AsyncShutdownDrainTest.closeDoesNotBlockOnFullQueueOfBusyWorker: close()
  blocked ~15s on put(FORCE_EXIT) behind a 15s task (await(8s) failed).
- AsyncConfigValidationTest: setCommitEvery(0) was accepted.

Tests: com.arcadedb.database.async.* (15 tests), AsyncTest,
SelectExecutionTest, QueryEngineManagerLanguagesTest,
QueryEngineManagerPoolTest, GraphBatchTest, GraphBatchUniqueIndexTest,
GraphBatchCommitRetryTest, ACIDTransactionTest, MVCCTest - all green; the
three timing-sensitive new tests re-run 3x with no flakes.
@mergify

mergify Bot commented Jul 6, 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

@codacy-production

codacy-production Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 37 complexity

Metric Results
Complexity 37

View in Codacy

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

@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 to prevent deadlocks, queue stalls, and hangs during shutdown. Key improvements include progress-based stall detection, a help-while-waiting mechanism for worker threads, and proper completion notifications for dropped tasks. Feedback on these changes highlights critical issues: coupling the worker liveness check with task removal success can cause hangs on unsupported queues; the waitCompletion method fails to respect the specified timeout during the queue offer phase; and unhandled exceptions during deferred task execution in offerHelping could prevent subsequent tasks from completing.

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 +942 to +947
if (!target.isAlive() && removeQuietly(queue, task))
// The worker exited (shutdown) after its final queue drain but before this offer landed:
// the task would sit unexecuted forever. Undo the offer and fail like any post-shutdown
// scheduling attempt.
throw new DatabaseOperationException(
"Async executor has been shut down; cannot schedule asynchronous task " + task);

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.

critical

The check !target.isAlive() && removeQuietly(queue, task) incorrectly couples the liveness check with the success of removing the task from the queue. For queue implementations that do not support task removal (such as PushPullBlockingQueue, which is the default 'fast' queue), removeQuietly will always return false. Consequently, if the target worker thread is dead, the task will remain in the queue forever without throwing a DatabaseOperationException, causing any thread waiting on its completion to hang indefinitely.

We should always throw DatabaseOperationException if the target worker is dead, regardless of whether the task could be successfully removed from the queue.

        if (!target.isAlive()) {
          removeQuietly(queue, task);
          // The worker exited (shutdown) after its final queue drain but before this offer landed:
          // the task would sit unexecuted forever. Undo the offer and fail like any post-shutdown
          // scheduling attempt.
          throw new DatabaseOperationException(
              "Async executor has been shut down; cannot schedule asynchronous task " + task);
        }

Comment on lines 380 to +390
for (int i = 0; i < threads.length; ++i)
try {
semaphores[i] = new DatabaseAsyncCompletion();
threads[i].queue.put(semaphores[i]);
// #4954: bounded offer with a liveness check instead of an untimed put(): a worker that
// exited (shutdown) will never drain a full queue, so the old code hung here forever.
while (!threads[i].queue.offer(semaphores[i], 500, TimeUnit.MILLISECONDS))
if (!threads[i].isAlive()) {
// NOTHING WILL EVER RUN ON THIS QUEUE ANYMORE: TREAT IT AS FLUSHED
semaphores[i].completed();
break;
}

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

The waitCompletion(long timeout) method does not respect the specified timeout during the queue offer phase. If the target worker's queue is full and the worker is busy executing a long-running task, the while (!threads[i].queue.offer(...)) loop will block repeatedly for 500ms intervals, potentially exceeding the requested timeout before even reaching the semaphore wait phase.

We should calculate the remaining timeout and use it as the limit for the offer operation, returning false immediately if the timeout has already elapsed.

    final long beginTime = System.currentTimeMillis();
    for (int i = 0; i < threads.length; ++i)
      try {
        semaphores[i] = new DatabaseAsyncCompletion();
        while (true) {
          final long elapsed = System.currentTimeMillis() - beginTime;
          if (timeout > 0 && elapsed >= timeout)
            return false;

          final long remaining = timeout > 0 ? timeout - elapsed : 500;
          final long offerTimeout = Math.min(500, remaining);

          if (threads[i].queue.offer(semaphores[i], offerTimeout, TimeUnit.MILLISECONDS))
            break;

          if (!threads[i].isAlive()) {
            // NOTHING WILL EVER RUN ON THIS QUEUE ANYMORE: TREAT IT AS FLUSHED
            semaphores[i].completed();
            break;
          }
        }
      }

Comment on lines +1068 to +1070
if (deferred != null)
for (final DatabaseAsyncTask t : deferred)
self.executeTask(t);

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

In the finally block of offerHelping, if self.executeTask(t) throws an exception (for example, if t.completed() throws an exception, or if transaction commit/rollback fails), the loop will terminate abruptly. This will prevent any remaining deferred completion tasks in the list from being executed, which can cause other threads waiting on those completion markers to hang indefinitely.

We should wrap each executeTask(t) call in a try-catch block to ensure that a failure in one deferred task does not block the completion of others.

      if (deferred != null)
        for (final DatabaseAsyncTask t : deferred)
          try {
            self.executeTask(t);
          } catch (final Throwable e) {
            LogManager.instance()
                .log(self, Level.SEVERE, "Error on executing deferred completion task %s", e, t);
          }

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: async executor stall detector, shutdown draining, concurrency cleanups (#4953/#4954/#4961)

Solid, carefully-reasoned PR. The red-first regression tests, the copy-on-write register(), the volatile settings, the RunnableFuture.cancel() on post-shutdown rejection, and the bounded-offer + liveness-check rework of waitCompletion()/shutdown are all well done and address the audited defects cleanly. A few things worth a second look before merge.

1. Liveness regression: a genuinely wedged worker no longer surfaces an error to producers (medium)

offerWaiting() now only throws "is stalled" when target.waitingCrossSlotOffer is true (plus the dead-worker branch):

final long nowCompleted = target.completedTaskCount;
if (nowCompleted == observedCompleted && target.waitingCrossSlotOffer)
    throw new DatabaseOperationException("Asynchronous queue " + slot + " is stalled...");

The old head-identity detector fired for any worker whose head task stopped making progress. The new detector fires only for a cross-slot offer cycle. A worker stuck for a non-cross-slot reason - an infinite loop in a user callback, a deadlock on an external lock, a blocking I/O that never returns - leaves completedTaskCount flat but waitingCrossSlotOffer == false, so a producer calling scheduleTask(..., waitIfQueueIsFull=true, ...) now blocks forever instead of eventually throwing.

This matters concretely for scanType(): it schedules bucket tasks with waitIfQueueIsFull=true from an external thread and then does an untimed semaphore.await(). Before, a wedged worker produced a stall exception that surfaced; now scanType() hangs indefinitely. Trading the false positives for a total loss of hang detection feels too far. Consider keeping a much larger absolute backstop timeout (e.g. a multiple of checkForStalledQueuesMaxDelay, or a dedicated config) that throws regardless of waitingCrossSlotOffer, so a truly stuck worker still fails loudly rather than silently wedging callers.

2. Re-entrant executeTask shares the worker's single transaction with the outer task (medium, help path)

When a worker parks in offerHelping() mid-execution of an outer task and drains its own queue, the nested executeTask(own) runs inside the same thread-bound transaction and shares count:

  • On a nested commitEvery boundary it calls database.commit(); database.begin(); - committing the outer task's already-applied (but not yet logically complete) mutations early, and shifting the outer task's own commit cadence because count is shared.
  • More concerning: on a nested failure it does if (database.isTransactionActive()) database.rollback();, which discards the outer task's in-flight work too. Control then returns to the outer message.execute() continuation (now with no active tx), the outer task finishes, and its finally still calls message.completed() - reporting success for work that was silently rolled back. For the bidirectional-edge case this is exactly the "ghost half-edge" class of bug the PR is trying to eliminate, just relocated to the help path.

At minimum this transactional entanglement deserves an explicit design note; ideally the nested-execution rollback/commit semantics should be reasoned about (or the help path should avoid committing/rolling back the outer transaction). The current tests use requiresActiveTx()==false tasks, so this path is not exercised.

3. offerHelping swallows FORCE_EXIT but keeps blocking on the target (low)

When helping pulls FORCE_EXIT off its own queue it sets self.forceShutdown = true and continues looping to hand task to target. If target is alive but its queue never drains, the helper keeps looping and won't observe its own shutdown until the hand-off succeeds - so shutdownThreadsLocked()'s join(10_000) can burn the full 10s and log the WARNING. Rare, but worth a comment or a bail-out when self.forceShutdown is set.

4. "fast" queue (PushPullBlockingQueue) can't undo the post-drain offer (low)

removeQuietly() returns false for the fast queue (no remove(Object)), so the shutdown-race guard in scheduleTask (offer landing after the worker's final drainQueueNotifyingWaiters) cannot undo the enqueue, and that task's completed() never runs - the exact hang #4954 targets, still open for ASYNC_OPERATIONS_QUEUE_IMPL=fast. Probably acceptable as a known limitation, but worth a note in the code so it isn't assumed covered.

5. Test tagging (CLAUDE.md)

CLAUDE.md asks that multi-second functional regression tests be annotated @Tag("slow"). AsyncStallDetectorFalsePositiveTest (1.2s head-task sleep) and especially AsyncShutdownDrainTest.closeDoesNotBlockOnFullQueueOfBusyWorker (15s blocker, 8s+5s joins) run for several seconds and are timing-sensitive; consider tagging them @Tag("slow") at the method or class level so regular CI can skip them.

Minor / positive notes

  • Math.max(1, ...) in the constructor plus the setCommitEvery(<1) rejection nicely closes the count % 0 hole from both directions - good.
  • DatabaseAsyncCompletion/scan/browse latches are CountDownLatch, so the "completed() on execute AND on drop" contract is idempotent per task - correct, no double-count risk.
  • scanType()/waitCompletion() still use untimed awaits; combined with finding build support #1 that's where an indefinite hang would actually manifest.

Overall the direction is right and the shutdown/config/register fixes look ready. Findings #1 and #2 are the ones I'd want addressed (or explicitly accepted with rationale) before merge.

Automated review; please verify findings independently.

@codecov

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.76023% with 50 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.59%. Comparing base (50efba6) to head (bca87b8).
⚠️ Report is 26 commits behind head on main.

Files with missing lines Patch % Lines
...dedb/database/async/DatabaseAsyncExecutorImpl.java 72.97% 23 Missing and 17 partials ⚠️
...db/database/async/DatabaseAsyncBrowseIterator.java 42.85% 2 Missing and 2 partials ⚠️
...cadedb/database/async/DatabaseAsyncScanBucket.java 75.00% 1 Missing and 1 partial ⚠️
...db/index/sparsevector/SparseVectorScoringPool.java 0.00% 2 Missing ⚠️
...in/java/com/arcadedb/query/QueryEngineManager.java 66.66% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5062      +/-   ##
============================================
- Coverage     65.59%   65.59%   -0.01%     
+ Complexity      842      841       -1     
============================================
  Files          1687     1687              
  Lines        135151   135246      +95     
  Branches      28912    28941      +29     
============================================
+ Hits          88648    88710      +62     
- Misses        34409    34428      +19     
- Partials      12094    12108      +14     

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

@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review: async executor stall detector, shutdown draining, concurrency cleanups (#4953, #4954, #4961)

Thorough, well-documented work. The commit message and per-issue verdicts make the intent easy to follow, each defect has a red-first regression test, and the concurrency-audit rationale lines up with the CLAUDE.md guidance. The refactor of the run loop into a re-entrant executeTask plus drainQueueNotifyingWaiters is clean, and moving semaphore.countDown() from execute()'s finally into completed() in DatabaseAsyncScanBucket/DatabaseAsyncBrowseIterator correctly closes the "dropped task never releases the latch" hole.

Below are the concerns I found, ranked. None are blockers on the fixes' correctness for the tested scenarios, but a few deserve a second look.

1. Transaction-boundary interleaving introduced by help-while-waiting (design concern, worth verifying)

executeTask (lines ~198-228) runs the shared count++ / commit-every-N batching contract, and it is now called re-entrantly from offerHelping while an outer task is suspended mid-execute() inside scheduleTask. If a helped task lands on count % commitEvery == 0, database.commit() fires in the middle of the outer task's execution, committing the outer task's partial writes together with the helped tasks. When the outer task later continues and finishes in a new transaction, a crash in that window leaves the outer task's early writes committed and its follow-up not yet run.

That is precisely the "ghost half-edge" failure mode #4953 sets out to eliminate (out-edge committed, in-edge follow-up not yet scheduled), reintroduced in a narrower window. For the bidirectional-edge path this is the exact scenario that exercises helping. Worth confirming that partial-task atomicity is preserved - e.g. by not letting a commit() boundary fall inside a re-entrant help, or by documenting that async edge creation is not atomic across the out/in pair (it may already not be). At minimum this deserves a comment at the count % commitEvery site noting it can run nested.

2. offerHelping has no stall/liveness backstop beyond target death (potential indefinite hang)

offerWaiting keeps progress-based stall detection, but offerHelping (lines ~1040-1080) only breaks out on !target.isAlive(). If the target worker is alive but permanently wedged in user code (infinite loop, or blocked on a lock the producing worker holds) with a full queue, the helping worker drains its own queue and then loops forever on the 100ms offer with no detection. The old head-identity detector, flawed as it was, would eventually throw here. This is a real reduction of the safety net for genuine user-code deadlocks (which no longer trip any detector, since waitingCrossSlotOffer is false when a worker is stuck in user code). Probably acceptable, but please confirm it is an intentional trade-off and consider a bounded overall budget before giving up.

3. waitCompletion(timeout) enqueue phase ignores the timeout (minor)

In waitCompletion (lines 385-390) the new bounded-offer loop retries offer(500ms) while isAlive(), with no reference to the timeout argument - the timeout is only honored later in the await phase (line 404). A caller passing waitCompletion(1000) can still block far longer than 1s if a worker stays alive with a persistently full queue. Not a regression (the old put() was also unbounded), but since the method now takes a timeout it would be nice to respect it during enqueue too.

4. Post-offer liveness recovery is a no-op on the "fast" queue (minor, edge race)

scheduleTask guards a late offer with if (!target.isAlive() && removeQuietly(queue, task)) (lines ~389-394). removeQuietly returns false for PushPullBlockingQueue (remove(Object) unsupported), so when the "fast" queue impl is selected a task that lands right after the worker's final drain sits unexecuted forever and its completed() never fires (caller hangs). The default is standard/ArrayBlockingQueue, where remove works, so real-world exposure is low - but a one-line comment noting the fast-queue gap (or draining once more) would help.

5. FORCE_EXIT consumed during helping is silently swallowed (confirm intent)

In offerHelping, polling FORCE_EXIT from the own queue sets self.forceShutdown = true and does not re-enqueue it. Exit is then driven by the forceShutdown flag, and shutdownThreadsLocked's join(10s) still completes, so this looks correct - just flagging that the shutdown marker is now consumed in a second place; a brief comment that the flag (not the marker) drives the exit would aid future readers.

Test coverage

Strong on the three fixed defects (false-positive, cross-slot deadlock, shutdown drain, config validation), all red-first. As the description notes, the QueryEngineManager.register() copy-on-write and the two RunnableFuture.cancel rejection-handler branches are untested; the rationale (JVM-wide singletons) is reasonable. If feasible, the register() copy-on-write publish is unit-testable in isolation without touching the shared pool.

Nits

  • AtomicLong counterScheduledTasks correctly became final (good catch alongside the volatile pass).
  • The three timing-sensitive tests are inherently CI-flake-prone (1.2s/10s/15s sleeps). Per CLAUDE.md they are candidates for @Tag("slow") so they don't lengthen the default build; closeDoesNotBlockOnFullQueueOfBusyWorker in particular runs ~8-15s.

Overall this is a solid hardening pass with excellent documentation. My main ask is to nail down the transaction-atomicity question in (1) before merge.

Response to review round 1:

- Point 1 (nested commit mid-task): taken, and broader than reported.
  Beyond the count % commitEvery boundary, a helped
  DatabaseAsyncTransaction / DatabaseAsyncCompletion /
  DatabaseAsyncIndexCompaction commits any active tx at entry, and helped
  CRUD tasks roll back the shared tx on their own error path - all able
  to commit or destroy the suspended outer task's partial writes. Fixed
  by never executing polled tasks re-entrantly: offerHelping parks them
  (helpDeferredTasks, budget = queue capacity, failover to the detecting
  bounded wait past the budget) and the run loop executes them once the
  current task unwinds. executeTask keeps !nested guards on the batch
  commit and rollback as defense-in-depth. helpingDepth /
  MAX_HELPING_DEPTH removed (provably dead: nothing nests anymore).
  Red-first regression test: AsyncHelpingAtomicityTest.
- Point 2 (no liveness backstop in offerHelping): intentional trade-off,
  kept and now documented in the javadoc. A target wedged forever in
  user code is indistinguishable from one busy on a legitimately slow
  task, and throwing out of a worker mid-task is exactly the #4953
  defect (batch rollback + silently dropped follow-up). The deferral
  budget adds a bounded failover for cycles beyond it.
- Point 3 (waitCompletion(timeout) unbounded enqueue): taken. The
  timeout is now a single budget spanning the enqueue and await phases.
  Red-first regression test: AsyncWaitCompletionTimeoutTest.
- Point 4 (removeQuietly no-op on the fast queue): accepted as a
  documented gap (comment); the impl is opt-in and the window is an
  offer racing the worker's exit.
- Point 5 (FORCE_EXIT consumed while helping): by design; the comment
  now spells out that the forceShutdown flag, not the marker, drives the
  run-loop exit, so shutdown's bounded join still completes.
- Coverage note (QueryEngineManager.register copy-on-write):
  acknowledged; the constructor is private and the instance owns a live
  ThreadPoolExecutor, so an isolated unit test needs reflection or
  pollutes the JVM-wide singleton's language list for sibling tests.
- Nit (@tag("slow")): measured instead of tagged - the fixes themselves
  keep these fast because the long sleeps are interrupted by the code
  under test: AsyncShutdownDrainTest (both methods) 1.03s,
  stall-detector test 1.47s, cross-slot test <0.1s. None crosses the
  multi-second bar.

Release notes amended to describe the park-then-run helping semantics.

Verified: mvn -pl engine compile; full com.arcadedb.database.async
battery (17 tests) plus AsyncTest, ACIDTransactionTest, MVCCTest green.
@lvca

lvca commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

Thanks for the thorough review - point 1 was a genuine catch and turned out to be broader than stated. Addressed in c5d7986, per point:

1. Transaction-boundary interleaving in help-while-waiting - taken (and it was worse than reported). Verified: besides the count % commitEvery boundary, a helped DatabaseAsyncTransaction, DatabaseAsyncCompletion or DatabaseAsyncIndexCompaction commits any active transaction at entry, and helped CRUD tasks roll back the shared transaction on their internal error path - each of those could commit or destroy the suspended outer task's partial writes. Rather than patching the one commit site, offerHelping no longer executes polled tasks re-entrantly at all: they are parked in a thread-confined helpDeferredTasks deque and the run loop executes them, in poll order, once the current task fully unwinds. Draining alone frees the slot the peer is parked on, so the #4953 cycle-resolution property is unchanged (the cross-slot regression test still passes). The parked backlog is capped at the queue capacity; past the budget the worker falls back to the bounded wait with stall detection, restoring producer backpressure. executeTask additionally guards the batch commit and the rollback with !nested as defense-in-depth, with the comment you asked for. Red-first regression test: AsyncHelpingAtomicityTest (fails on the previous code with the partial write committed mid-task). A side effect: helpingDepth/MAX_HELPING_DEPTH became provably dead (nothing nests anymore) and were removed.

2. No liveness backstop in offerHelping - intentional, now documented. A detector here would re-introduce the #4953 false positive in a new spot: consider A offering into B's full queue while B is parked cross-slot on a slow-but-healthy C - B shows a flat completed count and waitingCrossSlotOffer == true, so a progress-based detector would make A throw, roll back its in-flight batch and silently drop the follow-up, which is the exact defect this PR fixes. A worker wedged forever in user code is indistinguishable from one busy on a legitimately slow task, so any bound is a guess that fires on healthy load first. The trade-off is now spelled out in the offerHelping javadoc, and the new deferral budget from point 1 gives the loop a bounded failover into the detecting wait for cycles beyond it.

3. waitCompletion(timeout) enqueue phase - taken. The timeout is now a single budget spanning the enqueue and await phases. Red-first regression test: AsyncWaitCompletionTimeoutTest.

4. removeQuietly no-op on the fast queue - accepted as a documented gap. Comment added. Draining a live worker's queue from a foreign thread would race the worker itself, so the honest options are the comment or dropping PushPullBlockingQueue support; went with the comment since the impl is opt-in and the window is an offer racing the worker's exit.

5. FORCE_EXIT consumed while helping - by design, comment extended to state that the forceShutdown flag (not the marker) drives the run-loop exit, so shutdownThreadsLocked's bounded join still completes.

Coverage note on QueryEngineManager.register(): acknowledged, left untested. The constructor is private and each instance owns a live ThreadPoolExecutor, so an isolated unit test needs reflection or permanently pollutes the JVM-wide singleton's language list for sibling tests in the same fork.

Nit (@tag("slow")): measured rather than tagged - the long sleeps are interrupted by the very code under test, so the suites stay fast: AsyncShutdownDrainTest (both methods, including closeDoesNotBlockOnFullQueueOfBusyWorker) 1.03s total, AsyncStallDetectorFalsePositiveTest 1.47s, AsyncCrossSlotSchedulingDeadlockTest <0.1s. None crosses the multi-second bar CLAUDE.md sets for the tag.

Verification: mvn -pl engine compile, the full com.arcadedb.database.async battery (17 tests, includes the two new red-first regressions) plus AsyncTest, ACIDTransactionTest and MVCCTest - all green.

@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review: async executor stall detector, shutdown draining, concurrency cleanups

I reviewed the full diff plus the surrounding source (DatabaseAsyncExecutorImpl, DatabaseAsyncTask/DatabaseAsyncCompletion/DatabaseAsyncAbstractCallbackTask, and the scan/browse tasks). This is a high-quality, carefully reasoned change: the three defects are real, the fixes are coherent, the inline rationale is excellent, and the five regression tests are genuinely red-first. Points worth discussing before merge, ordered by impact.

1. Semantic regression: the stall exception is no longer a safety valve for a genuinely wedged worker (medium)

In offerWaiting, for the common non-worker producer path the stall exception now fires only when nowCompleted == observedCompleted && target.waitingCrossSlotOffer, i.e. it requires the target worker to itself be parked handing a task to another queue. If a worker is genuinely stuck (an infinite loop or a blocking call inside a user execute()/callback), waitingCrossSlotOffer is false, so this branch never triggers and the producer blocks indefinitely in the while (!queue.offer(...)) loop with no exit.

Previously the head-identity detector would throw after ~2 windows, which - however false-positive-prone - also acted as a backstop that converted a hung worker into a thrown exception on the producer rather than an indefinitely hung application thread. That backstop is now gone for the most common scheduling path. The offerHelping javadoc explains the deliberate choice ("a target wedged forever in user code is indistinguishable from one busy on a legitimately slow task"), and I agree throwing inside the worker was wrong. But throwing on the producer side after a long, clearly-abnormal wait (e.g. N windows with zero target progress, regardless of waitingCrossSlotOffer) is a different thing and was arguably the useful half of the old behavior. Consider a producer-side circuit-breaker with a much larger, configurable bound so a stuck user task surfaces as an error instead of a silent hang. At minimum, please note in the release notes that producers scheduling onto a wedged worker now wait forever by design.

2. Residual gap with PushPullBlockingQueue (removeQuietly) - confirm acceptable (low/medium)

removeQuietly swallows UnsupportedOperationException for the "fast" queue impl, so a task landing right after the target worker final drain cannot be undone and its completed() never fires - re-introducing exactly the 4954 hang class (a scanType()/waitCompletion() waiter blocked forever) for users who opted into ASYNC_OPERATIONS_QUEUE_IMPL=fast. The window is narrow and documented, but it is a real correctness hole rather than a perf trade-off. Could the post-drain landing be closed by having drainQueueNotifyingWaiters loop until an offer can no longer succeed, or by re-draining after the shutdown flag is observed? If it truly stays a known gap, a WARNING log in the catch (so an operator sees why a waiter hung) would help field diagnosis.

3. Test tagging per CLAUDE.md (low)

CLAUDE.md asks for @Tag("slow") on functional regression tests with noticeably long elapsed time. Several new tests block for multiple seconds worst-case (AsyncStallDetectorFalsePositiveTest ~1.2s head task; AsyncHelpingAtomicityTest an 800ms quiescence sleep; AsyncShutdownDrainTest a 15s / 10s blocker released via interrupt) and assert on wall-clock timing - the classic CI flake source. Consider @Tag("slow") at least on the two shutdown tests and shortening blocker sleeps where the latch releases early anyway.

4. AsyncHelpingAtomicityTest absence-assertion is timing-based (low)

Thread.sleep(800) then asserting countType == 0 proves the partial write was not yet committed, but a slow CI box could reorder this nondeterministically. A deterministic hook (a latch the helped task blocks on, released only after the count assertion) would be more robust than a fixed sleep. The property under test is valuable and the test does catch the bug on unfixed code.

Things verified as correct

  • Moving semaphore.countDown() from execute() finally into completed() in DatabaseAsyncScanBucket/DatabaseAsyncBrowseIterator: both implement DatabaseAsyncTask directly (default no-op completed()), so no double-countdown, and executeTask finally still calls completed() on the exception path - timing preserved for the normal case and now also fires on drop.
  • waitCompletion single-budget rewrite: enqueue loop honors the shared beginTime budget, the dead-worker branch pre-completes the marker so await returns immediately, and timeout <= 0 still maps to effectively-infinite. Already-enqueued markers on a later timed-out worker execute harmlessly - not a leak.
  • The nested/executingTask.getAndSet guard in executeTask is dead today (helping defers rather than nests) but is correct defense-in-depth and well documented.
  • volatile on the mutable settings, setCommitEvery(0) rejection + constructor clamp, the RunnableFuture.cancel(false) rejection branches, and the copy-on-write register() are all correct.

Nits

  • offerHelping busy-window of 1 ms when the own queue is non-empty is a tight spin; fine given it is bounded by the drain budget, but a one-line comment that it is intentionally aggressive would help.
  • The worker.getOwner() == this identity check correctly scopes the help path to workers of this executor - good for multi-database setups sharing thread-name prefixes.

Overall: strong work, clearly the product of a careful audit. My only real ask before merge is a decision on point 1 (the lost producer-side backstop for a wedged worker) and confirmation that point 2 fast-queue gap is acceptable, both ideally reflected in the release notes.

… code

Response to review round 2:

- Point 1 (lost producer-side safety valve): taken, the claim is correct.
  The round-1 detector required target.waitingCrossSlotOffer, so a worker
  wedged inside a user execute()/callback (flag stays false) let producers
  hang forever in the offer loop. offerWaiting now also throws after
  STALLED_NO_PROGRESS_WINDOWS (12) consecutive stall windows with zero
  completed tasks - 60s with the default 5s window, tunable via
  setCheckForStalledQueuesMaxDelay(). Progress-gated and 30x longer than
  the old 2-window head-identity bound, so the #4953 single-slow-task
  false positive stays fixed while a hung worker surfaces as an error.
  Red-first regression test: AsyncWedgedWorkerStallTest (hung for the
  full wedge duration with no exception on the previous code).
  AsyncStallDetectorFalsePositiveTest widened to a 300ms window so its
  1.2s busy task keeps a 3x margin below the new backstop instead of
  sitting exactly on it.
- Point 2 (fast-queue removeQuietly residual): confirmed acceptable, gap
  kept but no longer silent - a WARNING now names the stranded task and
  points at the standard queue impl, and the release notes document the
  residual window. Closing it worker-side is not possible with the
  BlockingQueue API (a drain loop cannot atomically prevent late offers)
  and producer-side draining is unsafe on an SPSC-oriented queue.
- Point 3 (test tagging): declined with measurements - elapsed times are
  ~1s worst (shutdown pair 1.03s, stall test ~1.5s, others <1s) because
  the code under test interrupts the long sleeps; the sleeps are failure
  ceilings, not elapsed time, so @tag("slow") per CLAUDE.md's
  multi-second bar does not apply.
- Point 4 (timing-based absence assertion): taken. The 800ms sleep is
  replaced by a deterministic ordering probe: the helped task records
  whether it ran before the suspended task's completed() fired, and the
  test pins the interleaving by waiting for the aggregate queue size to
  drop when the helping loop polls the probe. Verified to catch the bug:
  with inline execution temporarily reinjected the probe fails in 0.18s;
  the fixed code passes. Test now runs in ~40ms (was ~840ms).
- Nit (1ms helping window): comment added marking the tight spin as
  intentional and bounded by the deferral budget.

Release notes updated with the wedged-worker backstop semantics and the
fast-queue residual gap, as requested.

Verified: mvn -pl engine compile; com.arcadedb.database.async battery
(18 tests, includes the new red-first wedged-worker regression) plus
AsyncTest (11) - all green.
@lvca

lvca commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

Round 2 addressed in b075b42, per point:

1. Lost producer-side backstop for a wedged worker - taken, the claim is correct. The round-1 detector required target.waitingCrossSlotOffer, so a worker wedged inside a user execute()/callback never tripped it and the producer hung forever in the offer loop. offerWaiting now keeps the one-window cross-slot-park fast path and adds a progress-gated circuit-breaker: after STALLED_NO_PROGRESS_WINDOWS (12) consecutive stall windows in which the target completed zero tasks while its queue stayed full, the producer throws with a message naming the likely cause (60s with the default 5s window, tunable via setCheckForStalledQueuesMaxDelay()). That is 30x the old 2-window head-identity bound and gated on actual progress, so the #4953 single-slow-task false positive stays fixed. Red-first regression test: AsyncWedgedWorkerStallTest (on the previous code it hung for the full wedge duration with no exception). One knock-on: AsyncStallDetectorFalsePositiveTest moved from a 100ms to a 300ms window - its 1.2s busy task would otherwise have sat exactly on the 12x100ms backstop boundary; at 300ms it keeps a 3x margin below the backstop while remaining 4x over the old false-positive bound. Release notes document the new behavior.

2. Fast-queue removeQuietly residual - confirmed acceptable, no longer silent. Worker-side closing is not achievable with the BlockingQueue API (no drain loop can atomically prevent a late offer from landing after the final poll), and producer-side draining of the dead worker's queue is unsafe on the SPSC-oriented PushPullBlockingQueue. Took your fallback suggestion: the catch now logs a WARNING naming the stranded task and pointing at the standard queue impl, and the release notes document the residual window (opt-in impl, offer-vs-exit race).

3. Test tagging - declined with measurements. The long sleeps are failure ceilings, not elapsed time: the code under test interrupts them, so the suites measure AsyncShutdownDrainTest 1.03s for both methods (including closeDoesNotBlockOnFullQueueOfBusyWorker), the stall-detector test ~1.5s, everything else under 1s. None reaches the multi-second bar CLAUDE.md sets for @Tag("slow"), and tagging them out of default CI would exempt exactly the regression guards for these hang classes.

4. Timing-based absence assertion - taken. The 800ms sleep in AsyncHelpingAtomicityTest is gone. The test now pins the interleaving deterministically: it waits for the aggregate queue size to drop (the observable moment the helping loop polls the probe out of the worker's own queue), and the probe itself records whether it ran before the suspended task's completed() fired - a pure ordering fact on the worker thread, no wall clock involved. Validated both ways: with inline execution temporarily reinjected the probe fails in 0.18s; the fixed code passes. The test dropped from ~840ms to ~40ms.

Nit (1ms helping window): comment added marking the tight spin as intentional (every iteration frees a slot the parked peer may be waiting on) and bounded by the deferral budget.

Verification: mvn -pl engine compile; com.arcadedb.database.async battery (18 tests, including the new red-first wedged-worker regression) plus AsyncTest (11) - all green.

@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review: PR #5062 - async executor stall detector, shutdown draining, concurrency cleanups

Thorough, high-quality concurrency work. The diagnosis of each defect is precise, the fixes are internally coherent, and the "help-while-waiting + defer, don't nest" design is the right call for preserving per-task atomicity. The red-first regression tests are excellent: deterministic interleavings via latches/queue-size probes rather than timed sleeps wherever possible. Findings are ranked by importance; none are outright blockers, but the first is worth a discussion.

1. Possible new false-positive stall for producers waiting on a help-waiting worker (medium)

In offerWaiting, the external-producer path throws immediately after a single window of no progress when the target is itself cross-slot waiting:

if (nowCompleted == observedCompleted) {
  if (target.waitingCrossSlotOffer)
    throw ... "is stalled" ...   // fires after just ONE window

Walk the case where worker A is cross-scheduling into worker B and A's help-deferral budget is exhausted (A parked queueCapacity tasks and fell through offerHelping into the bounded offerWaiting). A is now parked with a full queue and waitingCrossSlotOffer=true, completing nothing. A producer P offering onto A's full queue throws on the first window where A made no progress, even if B is merely slow (busy > 1 window) rather than deadlocked, and would have accepted A's task a moment later. That is a narrower recurrence of the exact #4953 false-positive this PR sets out to remove.

It is gated behind budget exhaustion (needs queueCapacity parked tasks, unlikely with the default 1024/parallelLevel sizing), which is why I'm flagging rather than blocking. Consider requiring N>1 consecutive no-progress windows on the waitingCrossSlotOffer branch too, symmetric with the wedged-worker backstop, so a slow-but-live peer does not trip it.

2. Residual orphan race in scheduleTask post-offer recheck (low, inherent)

if (!target.isAlive() && removeQuietly(queue, task)) throw ...

There is still a window where the offer lands after the worker's final drainQueueNotifyingWaiters() poll returns null but before isAlive() flips to false; the recheck sees isAlive()==true, skips removal, and the task's completed() never fires. The window is a few instructions wide and is arguably unavoidable without a lock on the shutdown path, but it means the "worker exited after final drain" guarantee is best-effort, not total. Worth a one-line comment acknowledging it (you already document the analogous fast-queue gap in removeQuietly).

3. helpDeferredTasks memory footprint (low)

The deferral budget is queueCapacity, which with the default ASYNC_OPERATIONS_QUEUE_SIZE=1024 (divided by parallelLevel) can park hundreds/thousands of task objects in a single worker's ArrayDeque before falling back. Bounded and thread-confined, so correct; just noting it as a transient heap spike under sustained cross-slot pressure. Fine to leave as-is.

4. PR description drift vs. final implementation (docs only)

The description still says the fix uses "re-entrant executeTask extracted from the run loop, recursion capped at 32." The shipped code deliberately does the opposite: it defers polled tasks to the run loop and never nests (the whole point of AsyncHelpingAtomicityTest). Please update the description so reviewers do not chase a design that isn't there; there is no "cap at 32" in the code.

Things that are right and worth calling out

  • Moving semaphore.countDown() from execute()'s finally into completed() in DatabaseAsyncScanBucket/DatabaseAsyncBrowseIterator is the correct fix for the drop-on-shutdown hang, and it stays single-count since these implement the interface directly (no DatabaseAsyncAbstractCallbackTask double-countdown).
  • waitCompletion now treats the timeout as a single budget spanning enqueue + await with a liveness check: closes the untimed-put hang cleanly.
  • commitEvery clamped in the constructor and rejected in the setter closes the count % 0 ArithmeticException from both directions.
  • volatile on the mutable settings + synchronized copy-on-write register() are minimal and correct; the RunnableFuture cancel-on-reject in both JVM-wide pools is the right small safe branch.
  • The nested defense-in-depth guard in executeTask is dead today (helping never nests) but harmless and well-commented.

Test coverage

Strong. Red-first evidence per issue, deterministic ordering probes (helpedRanBeforeOuterFinished, queue-size spin) instead of sleeps, @Timeout on the timeout test. Two optional gaps: (a) a test for the point-1 scenario (budget-exhausted producer vs. a slow-but-live cross-slot peer, asserting it does not throw), and (b) the fast-queue orphan-window WARNING path, though both are hard to make deterministic.

Nice work overall. My only substantive ask is a second look at finding #1 (or a comment explaining why the single-window throw is acceptable there) and fixing the PR description in #4.

Reviewed against CLAUDE.md conventions (final params, no FQNs, performance-first, TDD).

Response to review round 3:

- Point 1 (single-window false positive on a budget-exhausted worker):
  taken, claim verified. The waitingCrossSlotOffer branch threw after ONE
  flat window; a worker that exhausted its help-deferral budget and fell
  into the bounded wait shows exactly that signature while its peer is
  merely busy on one slow task. The branch is now gated on
  STALLED_CROSS_SLOT_NO_PROGRESS_WINDOWS = 3 consecutive no-progress
  windows (15s by default). Why 3 and not 12: the cross-slot-park state
  is only reachable after budget exhaustion and carries genuine
  deadlock-cycle risk the wedged state does not, so real capped cycles
  must still fail loudly in bounded time; but the bound must exceed 2,
  the old head-identity threshold a peer busy on a single slow task can
  flatten, or the #4953 false positive recurs. Red-first regression
  test: AsyncSlowPeerNoFalseStallTest (on the previous code the producer
  was thrown "Asynchronous queue 0 is stalled" after one window with the
  peer 200ms from release; injectable deterministically because the
  deferral budget equals the queue capacity, 1 in the test config).
- Point 2 (post-offer orphan race): confirmed inherent, documented at
  the recheck site - an offer landing after the final drain poll but
  before isAlive() flips passes the guard; closing it would need a lock
  on the scheduling hot path.
- Point 3 (helpDeferredTasks footprint): documented on the field - at
  most queueCapacity task references per worker (one extra queue's
  worth), a transient spike that drains at the next unwind. Behavior
  unchanged per reviewer.
- Point 4 (PR description drift): PR body rewritten to the shipped
  park-then-run + dual-threshold design; the "re-entrant executeTask,
  recursion capped at 32" paragraph is gone and the test-evidence list
  now covers all nine red-first regressions.

Release notes updated with the 3-window cross-slot bound.

Verified: mvn -pl engine compile; com.arcadedb.database.async battery
(19 tests, includes the new red-first slow-peer regression) plus
AsyncTest (11) - all green.
@lvca

lvca commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

Round 3 addressed in df58057, per point:

1. Single-window false positive on a budget-exhausted worker - taken, claim verified. The waitingCrossSlotOffer branch indeed threw after one flat window, and the interleaving is real: a worker that exhausted its help-deferral budget sits in the bounded wait with the flag set and a flat completed count while its peer may be merely slow. It is also deterministically injectable, since the deferral budget equals the queue capacity (1 in the test config): red-first regression test AsyncSlowPeerNoFalseStallTest, where the previous code threw "Asynchronous queue 0 is stalled" at a producer whose peer was 200ms from release. The branch is now gated on STALLED_CROSS_SLOT_NO_PROGRESS_WINDOWS = 3 consecutive no-progress windows (15s by default). Deliberately 3 rather than mirroring the wedged bound of 12: the cross-slot-park state is only reachable after budget exhaustion and carries a genuine deadlock-cycle risk the wedged state does not, so real capped cycles should still fail loudly in bounded time - but the bound must exceed 2, the old head-identity threshold that a peer busy on one slow task can flatten, or the #4953 false positive recurs. Release notes updated with the dual thresholds.

2. Post-offer orphan race - confirmed inherent, documented. An offer landing after the final drainQueueNotifyingWaiters() poll but before isAlive() flips passes the recheck; closing it would require a lock on the scheduling hot path. One-line comment added at the recheck, parallel to the fast-queue note in removeQuietly.

3. helpDeferredTasks footprint - documented, behavior unchanged. Field comment now states the bound: at most queueCapacity task references per worker (ASYNC_OPERATIONS_QUEUE_SIZE / parallelLevel, so one extra queue's worth in the worst case), a transient spike under sustained cross-slot pressure that drains at the next unwind.

4. PR description drift - fixed. The body no longer describes the abandoned re-entrant design ("recursion capped at 32" is gone); it now documents the shipped park-then-run helping, the deferral budget, the dual-threshold detector, and lists all nine red-first regression tests.

On the "things that are right" section: all accurate, no corrections - including the note that the nested guard in executeTask is dead today and kept as documented defense-in-depth. On the optional coverage gaps: (a) is now covered by AsyncSlowPeerNoFalseStallTest; (b) the fast-queue WARNING path stays untested - agreed it is hard to make deterministic, as it requires losing a race against thread termination on an impl whose queue cannot be inspected safely from a second consumer.

Verification: mvn -pl engine compile; com.arcadedb.database.async battery (19 tests, including the new red-first slow-peer regression) plus AsyncTest (11) - all green.

@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review: async executor stall detector, shutdown draining, concurrency cleanups (#4953/#4954/#4961)

Thorough, well-documented work. The problem analysis in the PR body and the inline #issue/#5062 review comments make the reasoning traceable, and the nine red-first regression tests are tuned with small checkForStalledQueuesMaxDelay windows (50-500ms) so they stay fast without needing @Tag("slow"). The core design decisions are sound:

  • Park-then-run instead of re-entrant helping is the right call. Deferring polled tasks to helpDeferredTasks and running them only after the current task unwinds preserves per-task atomicity, and the nested guard in executeTask is good defense-in-depth.
  • Progress-based detection (completedTaskCount) genuinely fixes the head-identity false positive, and moving completed() out of execute()'s finally into a first-class completed() method (scan/browse) so drainQueueNotifyingWaiters can release latches on dropped tasks is a clean fix for [engine] Async executor shutdown/interrupt drops queued tasks, permanently hanging completion waiters #4954. completed() is invoked exactly once per task (executed XOR drained), so no double count-down.

A few things worth a second look:

1. Shutdown can leave a worker alive with only a WARNING (no escalation). In shutdownThreadsLocked, interrupt() is sent only when offer(FORCE_EXIT, 1s) fails. But FORCE_EXIT can be consumed inside offerHelping (which sets forceShutdown = true and keeps looping to hand off the follow-up). If that peer queue stays full, the worker will not re-check forceShutdown until offerHelping/offerWaiting returns, which for a wedged peer only happens at the stall backstop (~60s with defaults). Meanwhile the offer succeeded, so no interrupt is sent; join(10s) times out and you only log a WARNING. Consider escalating: if (toClose[i].isAlive()) { toClose[i].interrupt(); toClose[i].join(...); } before/at the warning, so close() does not return with a live worker that only self-heals up to ~60s later.

2. Cross-slot fast-throw (3 windows / 15s) can false-positive on a legitimate chain. For W0 -> W1 -> W2 where W2 is busy on a genuinely slow task, W1 is parked cross-slot (waitingCrossSlotOffer=true) with a flat completedTaskCount, so W0 throws after STALLED_CROSS_SLOT_NO_PROGRESS_WINDOWS even though the chain would resolve once W2 finishes. 15s is a heuristic that only barely outlives a ~10s slow task. Not a blocker (documented tradeoff), but worth calling out that deep chains with slow tasks remain a residual false-positive surface. A note in the tunable's docs would help operators.

3. waitCompletion(timeout) semantics changed. The timeout is now a single budget spanning enqueue + await (previously enqueue was an untimed put, timeout applied only to await). This is more correct, but a caller passing a short timeout can now get false back having flushed only some workers' completion markers. Please double-check existing callers of waitCompletion(smallTimeout) do not rely on the marker always being enqueued.

4. removeQuietly throw path skips completed() (standard queue too). In the fast path, if offer succeeds but the worker died, the task is removed and scheduleTask throws without calling completed(). For a latch-based caller (scan/browse) the exception propagates so the caller will not await, which is fine, but the asymmetry (drain path notifies, this path does not) is subtle. Fine as-is; just flagging for the record.

Minor / nits:

  • STALLED_NO_PROGRESS_WINDOWS/STALLED_CROSS_SLOT_NO_PROGRESS_WINDOWS are static final constants but interact with the volatile checkForStalledQueuesMaxDelay; a one-line note that only the window duration is tunable (not the window count) would preempt confusion.
  • The #4961 rejection-handler branches in QueryEngineManager and SparseVectorScoringPool are correct (cancel the RunnableFuture instead of stranding Future.get()); the "no test because JVM-wide singleton" justification is reasonable.
  • register() copy-on-write + synchronized is the right pattern for the rare-write/hot-read map.

Overall this is a solid, careful hardening of a tricky concurrency area with strong test evidence. Items 1 and 3 are the ones I would most want addressed (or explicitly acknowledged) before merge.

…onsumed FORCE_EXIT while helping

Response to review round 4:

- Point 1 (close() returns with a live worker): taken, claim verified.
  interrupt() was sent only when the FORCE_EXIT offer FAILED; a worker
  parked in offerHelping consumes the marker (sets forceShutdown, keeps
  looping to hand off the follow-up), so on a wedged peer's full queue
  the flag went unchecked, join timed out and close() returned with the
  worker alive (self-healing only at the stall backstop, up to ~60s).
  shutdownThreadsLocked now escalates: still alive after the grace
  period -> interrupt() + re-join before the WARNING. The interrupt is
  handled loudly and safely at every park (offer -> InterruptedException
  -> scheduleTask converts to DatabaseOperationException -> onError ->
  run loop exits on the flag -> drain notifies completed()), and it only
  fires after the full grace, so healthy shutdowns never see it (whole
  shutdown suite unchanged). The 10s grace is now the package-private
  shutdownJoinTimeoutMs so the regression test does not wait production
  timeouts. Red-first test: AsyncShutdownEscalationTest - the wedged
  peer deliberately SWALLOWS interrupts (real user code), because a peer
  that honors them dies via the existing offer-failed path, frees its
  queue and masks the defect (first test draft proved exactly that).
- Point 2 (deep-chain false positive on the 3-window cross-slot bound):
  acknowledged as documented trade-off. Note added to the
  setCheckForStalledQueuesMaxDelay javadoc and the release notes: chains
  deeper than two workers with tasks slower than 3 windows (15s default)
  need a larger window duration.
- Point 3 (waitCompletion budget semantics vs existing callers):
  verified safe, full sweep reported. Every production caller (engine
  LocalDatabase, GraphBatch x2, ManualIndexBuilder, TypeIndexBuilder,
  integration CSV/XML importers) uses the no-arg infinite-budget form,
  identical to the old behavior. Every timeout caller is a test using a
  generous bound (3s-30s) that relies only on "true means flushed",
  which is unchanged; the tests that can receive false handle it
  explicitly. No caller relies on the marker always being enqueued.
- Point 4 (throw path skips completed()): fine as-is per reviewer;
  one-line comment added - the scheduling caller is still on the stack
  and the exception informs it directly, no waiter can be parked yet.
- Nit: constants comment now states only the window duration is tunable
  (setCheckForStalledQueuesMaxDelay); the window counts are fixed.

Verified: mvn -pl engine compile; com.arcadedb.database.async battery
(20 tests, includes the new red-first escalation regression) plus
AsyncTest (11) - all green.
@lvca

lvca commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

Round 4 addressed in 213dca8, per point:

1. close() returning with a live worker - taken, claim verified. interrupt() was indeed only sent when the offer(FORCE_EXIT, 1s) failed, and a worker parked in offerHelping consumes the marker (sets forceShutdown, keeps looping to hand off the follow-up), so on a wedged peer's full queue the flag went unchecked until the stall backstop (~60s) while join timed out with just a WARNING. shutdownThreadsLocked now escalates exactly as suggested: still alive after the grace period -> interrupt() + re-join before the WARNING. Interrupt handling at the parks was re-verified: the offer park throws InterruptedException, scheduleTask converts it to a loud DatabaseOperationException (onError), the run loop exits on the flag and the drain notifies completed() on leftovers - and since the escalation fires only after the full grace period, healthy shutdowns never see it (the existing shutdown suite is byte-identical in behavior). The 10s grace became the package-private shutdownJoinTimeoutMs so the regression test does not sit through production timeouts. Red-first test: AsyncShutdownEscalationTest. One instructive detail: the wedged peer in the test deliberately SWALLOWS interrupts, because a peer that honors them is interrupted via the existing offer-failed path, drains its queue on exit and thereby frees the helping worker - the first test draft passed on unfixed code for exactly that reason. The interrupt-swallowing peer is also the realistic shape of the wedge (user code catching InterruptedException and continuing).

2. Deep-chain false positive on the 3-window cross-slot bound - acknowledged, documented for operators. Note added to the setCheckForStalledQueuesMaxDelay javadoc and the release notes: chains deeper than two workers whose tail runs individual tasks longer than 3 windows (15s by default) can still trip the cross-slot detector; raise the window duration for such workloads.

3. waitCompletion(timeout) semantics vs existing callers - verified safe. Full sweep across engine, server, console, integration and tests: every production caller (LocalDatabase, GraphBatch x2, ManualIndexBuilder, TypeIndexBuilder, CSV/XML importers) uses the no-arg form, which maps to an infinite budget and behaves exactly as before. Every caller passing a timeout is a test using a generous bound (3s-30s) that relies only on "true means fully flushed" - unchanged - and the few that can receive false handle it explicitly. No caller relies on the completion marker always being enqueued.

4. Throw-path completed() asymmetry - kept as-is, now commented at the site: unlike the shutdown drain (where the scheduling caller is long gone), here the caller is still on the stack and the exception informs it directly, so no waiter can be parked on the removed task yet.

Nit: the constants block now states explicitly that only the window duration is tunable (setCheckForStalledQueuesMaxDelay()); the window counts are compile-time fixed.

Verification: mvn -pl engine compile; com.arcadedb.database.async battery (20 tests, including the new red-first escalation regression) plus AsyncTest (11) - all green.

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

Metric Results
Complexity 44

View in Codacy

🟢 Coverage 82.46% diff coverage · -7.22% coverage variation

Metric Results
Coverage variation ✅ -7.22% coverage variation
Diff coverage ✅ 82.46% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (50efba6) 135151 100779 74.57%
Head commit (bca87b8) 167049 (+31898) 112498 (+11719) 67.34% (-7.22%)

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 (#5062) 171 141 82.46%

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 5062 (async executor: stall detector, shutdown draining, concurrency cleanups)

Reviewed the full diff against main. This is high-quality, carefully-reasoned concurrency work: the inline comments explain the why of every non-obvious decision, the tests are red-first and (impressively) deterministic ordering probes rather than timed sleeps, and the design correctly walked back the earlier re-entrant-helping approach to a park-then-run model that preserves per-task atomicity. Nice.

Below are the things worth calling out - mostly documented residual tradeoffs, no blockers.

Correctness / design - looks right

  • Non-reentrant help-while-waiting (offerHelping): draining the own queue into a thread-confined helpDeferredTasks deque and letting the run loop execute them after the current task unwinds is the correct fix. Executing polled tasks re-entrantly would have committed/rolled back the suspended task's partial writes under commitEvery. AsyncHelpingAtomicityTest (commitEvery=1 + ordering probe) nails exactly this.
  • executeTask nested guard: defense-in-depth even though the deferral design means nested is always false today - good, and clearly commented as such.
  • Shutdown draining (drainQueueNotifyingWaiters) + moving semaphore.countDown() from execute()'s finally into completed() on DatabaseAsyncScanBucket/DatabaseAsyncBrowseIterator: correctly releases scanType()/waitCompletion() waiters on dropped tasks. completed() is invoked exactly once per task (executed once via executeTask finally, or dropped once via drain), so no double-countdown.
  • waitCompletion single-budget spanning enqueue+await with a liveness check replacing the untimed put() is a clear improvement over the previous unbounded hang.
  • Issue 4961 cleanups are all sound: volatile on user-written/worker-read settings, commitEvery >= 1 validation + constructor clamp, copy-on-write register() map, and future.cancel(false) for tasks rejected post-shutdown (avoids the untimed Future.get() hang).

Residual concerns (documented, but worth surfacing)

  1. Single legitimately-long task can still trip a false stall. The wedged-worker backstop (STALLED_NO_PROGRESS_WINDOWS = 12, 60s default) fires whenever the target worker completes zero tasks for 12 windows while its queue stays full - and a legitimately slow single task (a large scanBucket, a heavy user callback) is indistinguishable from a wedged one. This is the same false-positive class as the original issue 4953, just moved from ~10s to a tunable ~60s. The comments acknowledge it and point at setCheckForStalledQueuesMaxDelay(), which is the right call, but it's a behavioral cliff operators should know about. Consider a one-line note in release-26.7.2.md that a task legitimately exceeding STALLED_NO_PROGRESS_WINDOWS * checkForStalledQueuesMaxDelay needs the delay raised.
  2. fast queue (PushPullBlockingQueue) orphan window on the shutdown/offer race: removeQuietly can't undo the offer, so a task landing right after a dead worker's final drain never gets completed(). Documented, logs a WARNING, opt-in impl only - acceptable, and closing it would cost a lock on the hot path.
  3. waitCompletion partial enqueue: if the timeout budget is exhausted after some markers were already enqueued, the method returns false while those markers still run and count down latches nobody awaits. Benign, but a sentence noting it would help a future reader.

Minor

  • In offerWaiting, target.waitingCrossSlotOffer is re-read every iteration, so a worker flipping between parked/not-parked biases which threshold (3 vs 12 windows) applies without resetting windowsWithoutProgress. Acceptable for a heuristic; just noting it's not strictly one-or-the-other.
  • shutdownJoinTimeoutMs being package-private volatile purely for test tunability is a reasonable, minimal seam.

Tests

Excellent coverage - 9 new regression tests, each shown to fail red on unfixed code on the exact defect. Deterministic latch-based ordering (AsyncHelpingAtomicityTest, AsyncCrossSlotSchedulingDeadlockTest) rather than sleeps is exactly the right approach for concurrency regressions and keeps them low-flake.

Verdict: LGTM. No blocking issues; the residual items are documented tradeoffs. The one thing I'd most want in the release notes is the operator-facing note on point 1 (long legit task vs. stall threshold).

Note: I could not run mvn compile in this review sandbox (Maven not permitted); relying on CI for build/test confirmation.

… stall cliff

The round's verdict was LGTM with documented-tradeoff residuals. The one
ask taken: the release note now states the backstop cliff explicitly - a
single legitimately long task exceeding 12 x checkForStalledQueuesMaxDelay
(60s default) with producers waiting on its full queue is
indistinguishable from a wedged worker and trips the stall exception;
raise the delay for legitimately long tasks. Also added the reviewer's two
clarifying one-liners: waitCompletion's benign partial-enqueue on a false
return, and the threshold selection being re-read per window without
resetting the count.

Focused stall/escalation suites green.
@claude

claude Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review: async executor stall detector, shutdown draining, concurrency cleanups (#4953, #4954, #4961)

Overall this is high-quality work: the diagnoses are accurate, the fixes are coherent, and the test suite is genuinely red-first with deterministic ordering probes rather than sleeps where it matters. The park-then-run redesign (avoiding re-entrant executeTask) is the right call for per-task atomicity, and the volatile/config-validation/copy-on-write cleanups are all correct. A few observations below, one of which I think is worth a second look.

1. Liveness gap: a worker help-waiting with an empty own queue on a wedged peer hangs forever (no backstop)

offerHelping (DatabaseAsyncExecutorImpl.java ~1162) has no stall backstop equivalent to the producer path's STALLED_NO_PROGRESS_WINDOWS. Consider a worker A executing a task that schedules the cross-slot incoming-edge follow-up into peer B, where:

  • B is wedged inside user code (infinite loop / blocking call): alive, isAlive()==true, queue full, completes nothing;
  • A's own queue happens to be empty at that moment.

The loop then spins: window=100, offer fails, B alive, helpDeferredTasks.size() (0) < queueCapacity so no budget failover, self.queue.poll() returns null, continue - forever. Unlike the producer path, A never surfaces a stall. The only escapes are B dying or a shutdown-interrupt (r4 escalation).

The javadoc claims: "As long as the target is alive it either progresses (offer eventually lands) or is itself parked cross-slot, in which case draining resolves the cycle or the budget above fails over to the detecting wait." That reasoning silently assumes the own queue is non-empty so the budget eventually fills. When A's own queue is empty the budget never grows, so there is no failover and no detection - two workers can be permanently lost during normal operation (not just shutdown). Given #4953's whole premise was eliminating forever-hangs, this asymmetry (producers get a backstop, cross-scheduling workers do not) is worth an explicit decision plus doc correction, or a bounded no-progress backstop on the worker path too. I understand the atomicity constraint means you cannot throw mid-task cheaply; but the current doc overstates the guarantee.

2. offerHelping ignores forceShutdown once it has consumed FORCE_EXIT

When the loop polls FORCE_EXIT, it sets self.forceShutdown = true but keeps looping to hand off to the target. If the target is wedged (per #1), the worker ignores its own shutdown request and only recovers via the r4 interrupt escalation after the full grace period. A cheap if (self.forceShutdown) return false; (or throw) at the top of the loop would let it bail promptly and make close() fast in that path without waiting on escalation. Minor, since escalation is a correct backstop, but it would tighten shutdown latency.

3. waitCompletion mid-enqueue early return (minor / intentional)

When the enqueue budget expires partway through the worker loop, return false leaves completion markers already enqueued on earlier workers. That is harmless (they just count down a discarded latch), but worth a one-line note so a future reader does not mistake it for a leak.

Things I checked and am satisfied with

  • Park-then-run correctly preserves the waitCompletion ordering contract: the hand-off offer returns before offerHelping returns, and deferred tasks (including completion markers) run only after the suspended task fully unwinds.
  • drainQueueNotifyingWaiters covers both helpDeferredTasks and the queue, so completed()/latches are released on every exit path - the scanType()/waitCompletion() hang is genuinely closed.
  • The !nested guard in executeTask is provably dead today but a reasonable defense-in-depth; completedTaskCount incrementing unconditionally is fine since nesting is gone.
  • queueCapacity deferral budget bounds helpDeferredTasks at one queue's worth per worker - the memory note is accurate.
  • volatile settings, setCommitEvery(<1) rejection + constructor clamp, QueryEngineManager.register() copy-on-write, and the two RunnableFuture.cancel(false) rejection handlers are all correct.
  • removeQuietly fast-queue gap and the 3-window vs 12-window thresholds are reasonable, documented trade-offs.

Test coverage

Excellent. Nine red-first regressions, each pinned to a specific defect, with the deterministic queue-size interleaving probe in AsyncHelpingAtomicityTest being a nice improvement over the earlier timed sleep. One suggestion: none of the tests exercise scenario #1 (worker help-waiting with an empty own queue on a wedged peer) - if you decide that path should have a backstop, add a red-first test for it; if you decide it is acceptable, a test asserting the documented behavior would lock in the intent.

Nice, careful work overall. My main ask is a decision plus doc fix on point #1.

@lvca
lvca merged commit 813cf4b into main Jul 7, 2026
22 of 26 checks passed
@lvca
lvca deleted the fix/4953-4954-4961-async-executor branch July 7, 2026 03:47
lvca added a commit that referenced this pull request 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 added a commit that referenced this pull request Jul 7, 2026
…veness

fix: bound the help-waiting loop on a wedged peer (follow-up to #5062)
hoogenbj pushed a commit to Locstat/arcadedb that referenced this pull request Jul 7, 2026
…eData#5062)

Round-6 review of ArcadeData#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.
oc007us pushed a commit to oc007us/arcadedb-grpc that referenced this pull request Jul 8, 2026
…the 100% CPU spin

SelectParallelIterator's DatabaseAsyncBrowseIterator callback handed records
to the consumer with 'while (true) { if (queue.offer(record)) break; }': an
unbounded busy-spin with no backoff and no shutdown check. When the consumer
stopped draining (exception in user code, early return, satisfied limit, or
plain abandonment), one async worker per bucket spun at 100% CPU forever.
Worse than the issue describes: the next Database.close()/drop() then hung
indefinitely, because closeInternal() calls the async executor's unbounded
waitCompletion() behind the wedged workers.

Red-first evidence (test run against unmodified main): 4 AsyncExecutor
workers RUNNABLE at SelectParallelIterator.java:86 with ~706,000 ms CPU each
on a 712 s old JVM (pinned at 100% since the first test), and the JUnit main
thread parked forever in LocalDatabase.closeInternal -> waitCompletion during
TestHelper teardown; the run had to be killed.

The offer is now bounded and cooperative. A producer facing a full queue
parks 0.1 ms between attempts (no CPU burn even while legitimately waiting)
and gives up when:
- the iterator was closed (SelectIterator is now AutoCloseable; the parallel
  implementation's close() signals the producers, the serial one is a no-op);
- the worker was interrupted (async executor shutdown escalation, ArcadeData#4954);
- enough records were produced to satisfy the limit; or
- the consumer made no progress for the whole stall bound: the select
  timeout when set, otherwise 60 s, matching the async executor's
  zero-progress backstop from ArcadeData#5062.

A producer that gives up returns false from the browse callback, ending its
task through the regular completion path (completed() notification, batch
commit, semaphore countdown), so the async executor contracts hardened in
ArcadeData#5062 are preserved: no exception is thrown through the worker and no
in-flight commit batch is rolled back. A consumer still alive after the
producers stalled out gets a TimeoutException instead of a silently
truncated result set, unless it opted into truncation with a non-throwing
timeout; a consumer-side timeout (thrown or not) now also stops the
producers before surfacing.

The rework fixes three latent defects in the same code path:
- limit was accounted producer-side (the callback bumped the inherited
  'returned' field, racily, from multiple workers), so hasNext() could stop
  the consumer before it received 'limit' records - down to zero when the
  producers outran it. 'returned' now counts records handed to the consumer
  (matching the serial semantics) and a dedicated AtomicLong counts
  production for the early-stop;
- skip > 0 crashed with a NullPointerException: the base constructor
  consumes the skipped records via the overridden fetchNext() before the
  subclass initialized the queue. The override now falls back to serial
  consumption until the parallel machinery exists;
- a record published between the consumer's last poll and the final
  producer's countDown() could be lost at end of stream (the loop condition
  read queue emptiness and the latch in two non-atomic steps); the consumer
  now re-polls once after observing the latch at zero, which is race-free
  because every offer happens-before its producer's countdown.

New regression tests (SelectParallelIteratorTest, 10,000 records across 8
buckets so the 4,096-slot queue is guaranteed to fill): full-scan sanity,
limit returns exactly N and releases the workers, early close releases the
workers, an abandoned consumer releases the workers within the stall bound,
and skip works on the parallel path. All were red on main (the first one to
run wedged the JVM permanently); all green in 1.5 s with the fix. Also ran
the full com.arcadedb.query.select.* and com.arcadedb.database.async.* +
AsyncTest suites: 97 tests, 0 failures.
robfrank pushed a commit that referenced this pull request Aug 14, 2026
Response to review round 1:

- Point 1 (nested commit mid-task): taken, and broader than reported.
  Beyond the count % commitEvery boundary, a helped
  DatabaseAsyncTransaction / DatabaseAsyncCompletion /
  DatabaseAsyncIndexCompaction commits any active tx at entry, and helped
  CRUD tasks roll back the shared tx on their own error path - all able
  to commit or destroy the suspended outer task's partial writes. Fixed
  by never executing polled tasks re-entrantly: offerHelping parks them
  (helpDeferredTasks, budget = queue capacity, failover to the detecting
  bounded wait past the budget) and the run loop executes them once the
  current task unwinds. executeTask keeps !nested guards on the batch
  commit and rollback as defense-in-depth. helpingDepth /
  MAX_HELPING_DEPTH removed (provably dead: nothing nests anymore).
  Red-first regression test: AsyncHelpingAtomicityTest.
- Point 2 (no liveness backstop in offerHelping): intentional trade-off,
  kept and now documented in the javadoc. A target wedged forever in
  user code is indistinguishable from one busy on a legitimately slow
  task, and throwing out of a worker mid-task is exactly the #4953
  defect (batch rollback + silently dropped follow-up). The deferral
  budget adds a bounded failover for cycles beyond it.
- Point 3 (waitCompletion(timeout) unbounded enqueue): taken. The
  timeout is now a single budget spanning the enqueue and await phases.
  Red-first regression test: AsyncWaitCompletionTimeoutTest.
- Point 4 (removeQuietly no-op on the fast queue): accepted as a
  documented gap (comment); the impl is opt-in and the window is an
  offer racing the worker's exit.
- Point 5 (FORCE_EXIT consumed while helping): by design; the comment
  now spells out that the forceShutdown flag, not the marker, drives the
  run-loop exit, so shutdown's bounded join still completes.
- Coverage note (QueryEngineManager.register copy-on-write):
  acknowledged; the constructor is private and the instance owns a live
  ThreadPoolExecutor, so an isolated unit test needs reflection or
  pollutes the JVM-wide singleton's language list for sibling tests.
- Nit (@tag("slow")): measured instead of tagged - the fixes themselves
  keep these fast because the long sleeps are interrupted by the code
  under test: AsyncShutdownDrainTest (both methods) 1.03s,
  stall-detector test 1.47s, cross-slot test <0.1s. None crosses the
  multi-second bar.

Release notes amended to describe the park-then-run helping semantics.

Verified: mvn -pl engine compile; full com.arcadedb.database.async
battery (17 tests) plus AsyncTest, ACIDTransactionTest, MVCCTest green.

(cherry picked from commit c5d7986)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
… code

Response to review round 2:

- Point 1 (lost producer-side safety valve): taken, the claim is correct.
  The round-1 detector required target.waitingCrossSlotOffer, so a worker
  wedged inside a user execute()/callback (flag stays false) let producers
  hang forever in the offer loop. offerWaiting now also throws after
  STALLED_NO_PROGRESS_WINDOWS (12) consecutive stall windows with zero
  completed tasks - 60s with the default 5s window, tunable via
  setCheckForStalledQueuesMaxDelay(). Progress-gated and 30x longer than
  the old 2-window head-identity bound, so the #4953 single-slow-task
  false positive stays fixed while a hung worker surfaces as an error.
  Red-first regression test: AsyncWedgedWorkerStallTest (hung for the
  full wedge duration with no exception on the previous code).
  AsyncStallDetectorFalsePositiveTest widened to a 300ms window so its
  1.2s busy task keeps a 3x margin below the new backstop instead of
  sitting exactly on it.
- Point 2 (fast-queue removeQuietly residual): confirmed acceptable, gap
  kept but no longer silent - a WARNING now names the stranded task and
  points at the standard queue impl, and the release notes document the
  residual window. Closing it worker-side is not possible with the
  BlockingQueue API (a drain loop cannot atomically prevent late offers)
  and producer-side draining is unsafe on an SPSC-oriented queue.
- Point 3 (test tagging): declined with measurements - elapsed times are
  ~1s worst (shutdown pair 1.03s, stall test ~1.5s, others <1s) because
  the code under test interrupts the long sleeps; the sleeps are failure
  ceilings, not elapsed time, so @tag("slow") per CLAUDE.md's
  multi-second bar does not apply.
- Point 4 (timing-based absence assertion): taken. The 800ms sleep is
  replaced by a deterministic ordering probe: the helped task records
  whether it ran before the suspended task's completed() fired, and the
  test pins the interleaving by waiting for the aggregate queue size to
  drop when the helping loop polls the probe. Verified to catch the bug:
  with inline execution temporarily reinjected the probe fails in 0.18s;
  the fixed code passes. Test now runs in ~40ms (was ~840ms).
- Nit (1ms helping window): comment added marking the tight spin as
  intentional and bounded by the deferral budget.

Release notes updated with the wedged-worker backstop semantics and the
fast-queue residual gap, as requested.

Verified: mvn -pl engine compile; com.arcadedb.database.async battery
(18 tests, includes the new red-first wedged-worker regression) plus
AsyncTest (11) - all green.

(cherry picked from commit b075b42)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
Response to review round 3:

- Point 1 (single-window false positive on a budget-exhausted worker):
  taken, claim verified. The waitingCrossSlotOffer branch threw after ONE
  flat window; a worker that exhausted its help-deferral budget and fell
  into the bounded wait shows exactly that signature while its peer is
  merely busy on one slow task. The branch is now gated on
  STALLED_CROSS_SLOT_NO_PROGRESS_WINDOWS = 3 consecutive no-progress
  windows (15s by default). Why 3 and not 12: the cross-slot-park state
  is only reachable after budget exhaustion and carries genuine
  deadlock-cycle risk the wedged state does not, so real capped cycles
  must still fail loudly in bounded time; but the bound must exceed 2,
  the old head-identity threshold a peer busy on a single slow task can
  flatten, or the #4953 false positive recurs. Red-first regression
  test: AsyncSlowPeerNoFalseStallTest (on the previous code the producer
  was thrown "Asynchronous queue 0 is stalled" after one window with the
  peer 200ms from release; injectable deterministically because the
  deferral budget equals the queue capacity, 1 in the test config).
- Point 2 (post-offer orphan race): confirmed inherent, documented at
  the recheck site - an offer landing after the final drain poll but
  before isAlive() flips passes the guard; closing it would need a lock
  on the scheduling hot path.
- Point 3 (helpDeferredTasks footprint): documented on the field - at
  most queueCapacity task references per worker (one extra queue's
  worth), a transient spike that drains at the next unwind. Behavior
  unchanged per reviewer.
- Point 4 (PR description drift): PR body rewritten to the shipped
  park-then-run + dual-threshold design; the "re-entrant executeTask,
  recursion capped at 32" paragraph is gone and the test-evidence list
  now covers all nine red-first regressions.

Release notes updated with the 3-window cross-slot bound.

Verified: mvn -pl engine compile; com.arcadedb.database.async battery
(19 tests, includes the new red-first slow-peer regression) plus
AsyncTest (11) - all green.

(cherry picked from commit df58057)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…onsumed FORCE_EXIT while helping

Response to review round 4:

- Point 1 (close() returns with a live worker): taken, claim verified.
  interrupt() was sent only when the FORCE_EXIT offer FAILED; a worker
  parked in offerHelping consumes the marker (sets forceShutdown, keeps
  looping to hand off the follow-up), so on a wedged peer's full queue
  the flag went unchecked, join timed out and close() returned with the
  worker alive (self-healing only at the stall backstop, up to ~60s).
  shutdownThreadsLocked now escalates: still alive after the grace
  period -> interrupt() + re-join before the WARNING. The interrupt is
  handled loudly and safely at every park (offer -> InterruptedException
  -> scheduleTask converts to DatabaseOperationException -> onError ->
  run loop exits on the flag -> drain notifies completed()), and it only
  fires after the full grace, so healthy shutdowns never see it (whole
  shutdown suite unchanged). The 10s grace is now the package-private
  shutdownJoinTimeoutMs so the regression test does not wait production
  timeouts. Red-first test: AsyncShutdownEscalationTest - the wedged
  peer deliberately SWALLOWS interrupts (real user code), because a peer
  that honors them dies via the existing offer-failed path, frees its
  queue and masks the defect (first test draft proved exactly that).
- Point 2 (deep-chain false positive on the 3-window cross-slot bound):
  acknowledged as documented trade-off. Note added to the
  setCheckForStalledQueuesMaxDelay javadoc and the release notes: chains
  deeper than two workers with tasks slower than 3 windows (15s default)
  need a larger window duration.
- Point 3 (waitCompletion budget semantics vs existing callers):
  verified safe, full sweep reported. Every production caller (engine
  LocalDatabase, GraphBatch x2, ManualIndexBuilder, TypeIndexBuilder,
  integration CSV/XML importers) uses the no-arg infinite-budget form,
  identical to the old behavior. Every timeout caller is a test using a
  generous bound (3s-30s) that relies only on "true means flushed",
  which is unchanged; the tests that can receive false handle it
  explicitly. No caller relies on the marker always being enqueued.
- Point 4 (throw path skips completed()): fine as-is per reviewer;
  one-line comment added - the scheduling caller is still on the stack
  and the exception informs it directly, no waiter can be parked yet.
- Nit: constants comment now states only the window duration is tunable
  (setCheckForStalledQueuesMaxDelay); the window counts are fixed.

Verified: mvn -pl engine compile; com.arcadedb.database.async battery
(20 tests, includes the new red-first escalation regression) plus
AsyncTest (11) - all green.

(cherry picked from commit 213dca8)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
… stall cliff

The round's verdict was LGTM with documented-tradeoff residuals. The one
ask taken: the release note now states the backstop cliff explicitly - a
single legitimately long task exceeding 12 x checkForStalledQueuesMaxDelay
(60s default) with producers waiting on its full queue is
indistinguishable from a wedged worker and trips the stall exception;
raise the delay for legitimately long tasks. Also added the reviewer's two
clarifying one-liners: waitCompletion's benign partial-enqueue on a false
return, and the threshold selection being re-read per window without
resetting the count.

Focused stall/escalation suites green.

(cherry picked from commit bca87b8)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
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.

(cherry picked from commit 5021921)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…PU spin

SelectParallelIterator's DatabaseAsyncBrowseIterator callback handed records
to the consumer with 'while (true) { if (queue.offer(record)) break; }': an
unbounded busy-spin with no backoff and no shutdown check. When the consumer
stopped draining (exception in user code, early return, satisfied limit, or
plain abandonment), one async worker per bucket spun at 100% CPU forever.
Worse than the issue describes: the next Database.close()/drop() then hung
indefinitely, because closeInternal() calls the async executor's unbounded
waitCompletion() behind the wedged workers.

Red-first evidence (test run against unmodified main): 4 AsyncExecutor
workers RUNNABLE at SelectParallelIterator.java:86 with ~706,000 ms CPU each
on a 712 s old JVM (pinned at 100% since the first test), and the JUnit main
thread parked forever in LocalDatabase.closeInternal -> waitCompletion during
TestHelper teardown; the run had to be killed.

The offer is now bounded and cooperative. A producer facing a full queue
parks 0.1 ms between attempts (no CPU burn even while legitimately waiting)
and gives up when:
- the iterator was closed (SelectIterator is now AutoCloseable; the parallel
  implementation's close() signals the producers, the serial one is a no-op);
- the worker was interrupted (async executor shutdown escalation, #4954);
- enough records were produced to satisfy the limit; or
- the consumer made no progress for the whole stall bound: the select
  timeout when set, otherwise 60 s, matching the async executor's
  zero-progress backstop from #5062.

A producer that gives up returns false from the browse callback, ending its
task through the regular completion path (completed() notification, batch
commit, semaphore countdown), so the async executor contracts hardened in
in-flight commit batch is rolled back. A consumer still alive after the
producers stalled out gets a TimeoutException instead of a silently
truncated result set, unless it opted into truncation with a non-throwing
timeout; a consumer-side timeout (thrown or not) now also stops the
producers before surfacing.

The rework fixes three latent defects in the same code path:
- limit was accounted producer-side (the callback bumped the inherited
  'returned' field, racily, from multiple workers), so hasNext() could stop
  the consumer before it received 'limit' records - down to zero when the
  producers outran it. 'returned' now counts records handed to the consumer
  (matching the serial semantics) and a dedicated AtomicLong counts
  production for the early-stop;
- skip > 0 crashed with a NullPointerException: the base constructor
  consumes the skipped records via the overridden fetchNext() before the
  subclass initialized the queue. The override now falls back to serial
  consumption until the parallel machinery exists;
- a record published between the consumer's last poll and the final
  producer's countDown() could be lost at end of stream (the loop condition
  read queue emptiness and the latch in two non-atomic steps); the consumer
  now re-polls once after observing the latch at zero, which is race-free
  because every offer happens-before its producer's countdown.

New regression tests (SelectParallelIteratorTest, 10,000 records across 8
buckets so the 4,096-slot queue is guaranteed to fill): full-scan sanity,
limit returns exactly N and releases the workers, early close releases the
workers, an abandoned consumer releases the workers within the stall bound,
and skip works on the parallel path. All were red on main (the first one to
run wedged the JVM permanently); all green in 1.5 s with the fix. Also ran
the full com.arcadedb.query.select.* and com.arcadedb.database.async.* +
AsyncTest suites: 97 tests, 0 failures.

(cherry picked from commit 64e024d)
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)
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