Repository navigation
fix(#4953,#4954,#4961): async executor stall detector, shutdown draining, concurrency cleanups - #5062
Conversation
…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.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 37 |
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.
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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);
}| 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; | ||
| } |
There was a problem hiding this comment.
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;
}
}
}| if (deferred != null) | ||
| for (final DatabaseAsyncTask t : deferred) | ||
| self.executeTask(t); |
There was a problem hiding this comment.
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);
}
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 1. Liveness regression: a genuinely wedged worker no longer surfaces an error to producers (medium)
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 This matters concretely for 2. Re-entrant
|
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
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 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)
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 2.
|
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.
|
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 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 3. waitCompletion(timeout) enqueue phase - taken. The timeout is now a single budget spanning the enqueue and await phases. Red-first regression test: 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 5. FORCE_EXIT consumed while helping - by design, comment extended to state that the Coverage note on Nit (@tag("slow")): measured rather than tagged - the long sleeps are interrupted by the very code under test, so the suites stay fast: Verification: |
|
Review: async executor stall detector, shutdown draining, concurrency cleanups I reviewed the full diff plus the surrounding source ( 1. Semantic regression: the stall exception is no longer a safety valve for a genuinely wedged worker (medium) In 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 2. Residual gap with PushPullBlockingQueue (removeQuietly) - confirm acceptable (low/medium)
3. Test tagging per CLAUDE.md (low) CLAUDE.md asks for 4. AsyncHelpingAtomicityTest absence-assertion is timing-based (low)
Things verified as correct
Nits
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.
|
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 2. Fast-queue removeQuietly residual - confirmed acceptable, no longer silent. Worker-side closing is not achievable with the 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 4. Timing-based absence assertion - taken. The 800ms sleep in 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: |
Review: PR #5062 - async executor stall detector, shutdown draining, concurrency cleanupsThorough, 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 if (nowCompleted == observedCompleted) {
if (target.waitingCrossSlotOffer)
throw ... "is stalled" ... // fires after just ONE windowWalk the case where worker A is cross-scheduling into worker B and A's help-deferral budget is exhausted (A parked It is gated behind budget exhaustion (needs 2. Residual orphan race in
|
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.
|
Round 3 addressed in df58057, per point: 1. Single-window false positive on a budget-exhausted worker - taken, claim verified. The 2. Post-offer orphan race - confirmed inherent, documented. An offer landing after the final 3. 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 Verification: |
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
A few things worth a second look: 1. Shutdown can leave a worker alive with only a WARNING (no escalation). In 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 ( 3. 4. Minor / nits:
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.
|
Round 4 addressed in 213dca8, per point: 1. close() returning with a live worker - taken, claim verified. 2. Deep-chain false positive on the 3-window cross-slot bound - acknowledged, documented for operators. Note added to the 3. waitCompletion(timeout) semantics vs existing callers - verified safe. Full sweep across engine, server, console, integration and tests: every production caller ( 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 ( Verification: |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 44 |
🟢 Coverage 82.46% diff coverage · -7.22% coverage variation
Metric Results Coverage variation ✅ -7.22% coverage variation Diff coverage ✅ 82.46% diff coverage 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.
Code review - PR 5062 (async executor: stall detector, shutdown draining, concurrency cleanups)Reviewed the full diff against Below are the things worth calling out - mostly documented residual tradeoffs, no blockers. Correctness / design - looks right
Residual concerns (documented, but worth surfacing)
Minor
Tests Excellent coverage - 9 new regression tests, each shown to fail red on unfixed code on the exact defect. Deterministic latch-based ordering ( 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 |
… 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.
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 1. Liveness gap: a worker help-waiting with an empty own queue on a wedged peer hangs forever (no backstop)
The loop then spins: 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 2.
|
…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.
…veness fix: bound the help-waiting loop on a wedged peer (follow-up to #5062)
…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.
…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.
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)
… 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)
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)
…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)
… 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)
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)
…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)
…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)
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:
scheduleTaskstill peeked the queue head across twocheckForStalledQueuesMaxDelaywindows and threw on identical identity, andnewEdge'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 tocommitEvery - 1already-executed ops and dropping the follow-up).Fix (both parts, coherently in
scheduleTask):helpDeferredTasksdeque 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.completedTaskCount+ awaitingCrossSlotOfferflag, 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 viasetCheckForStalledQueuesMaxDelay(). 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 whosecompleted()never ran, hangingscanType()/waitCompletion()), andshutdownThreadsLockedstill blocked on an untimedqueue.put(FORCE_EXIT)underlifecycleLock(a busy worker with a full queue wedgeddatabase.close()).Fix: every run-loop exit path now drains the queue (and the parked help-deferral list) notifying
completed()on each leftover task;DatabaseAsyncScanBucket/DatabaseAsyncBrowseIteratorcount their latches down fromcompleted()(invoked on execution AND drop) instead of insideexecute(); shutdown offersFORCE_EXITwith 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 untimedput;scheduleTaskundoes an offer that lands after the target worker's final drain (best-effort: documented residual races for the opt-infastqueue, which cannot remove, and for an offer landing beforeisAlive()flips; the former logs a WARNING).#4961 - low-severity concurrency cleanups: fixed (all three checkboxes)
parallelLevel,commitEvery,backPressurePercentage,transactionUseWAL,transactionSync,checkForStalledQueuesMaxDelay, onOk/onError callbacks) are nowvolatile;setCommitEveryrejects values < 1 (0 made every task fail oncount % 0) and the constructor clamps the configured batch size.QueryEngineManagerandSparseVectorScoringPoolrejection handlers now cancel aRunnableFuturerejected after pool shutdown instead of leaving its waiter blocked in an untimedFuture.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()issynchronizedand publishes a copy-on-write map, so the public post-construction registration path cannot corrupt the lock-freegetEngine/getAvailableLanguagesreaders.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 threwDatabaseOperationException: Asynchronous queue 0 is stalledfor 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 withcommitEvery=1commits 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 calledcompleted()on the queued probes (latch timeout).AsyncShutdownDrainTest.closeDoesNotBlockOnFullQueueOfBusyWorker: unfixedclose()blocked ~15s input(FORCE_EXIT)(await(8s) failed).AsyncWaitCompletionTimeoutTest: unfixedwaitCompletion(700)blocked far past its timeout while the enqueue phase retried on a full queue.AsyncConfigValidationTest: unfixed acceptedsetCommitEvery(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
docs/release-26.7.2.md(expected: every audit group appends here)engine/src/main/java/com/arcadedb/query/QueryEngineManager.java(concurrency/pool layer; touched for the [engine] Low-severity concurrency cleanups (async field visibility, rejection-handler task drop) #4961 rejection-handler and register() items)engine/src/main/java/com/arcadedb/index/sparsevector/SparseVectorScoringPool.java(same reason)All other changes are confined to
com.arcadedb.database.async.