Skip to content

fix(#11155): async waitCompletion() returns under a steady producer: it goes around again only for cascades its own workers schedule - #11191

Merged
lvca merged 2 commits into
mainfrom
fix-11155-async-waitcompletion-steady-producer
Nov 3, 2026
Merged

lvca merged 2 commits into
mainfrom
fix-11155-async-waitcompletion-steady-producer

Conversation

@lvca

@lvca lvca commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Closes #11155.

Cause

Not a lock cycle. In the two thread dumps, main waits on a different CountDownLatch each time, and its CPU time grows between them. So it keeps finishing passes of waitCompletion() and starting new ones, while the 3 workers work through an endless stream of tasks. The tryLockFiles frame is just one sampled ordinary commit.

DatabaseAsyncExecutorImpl.waitCompletion looped while (isProcessing()). That is also true for tasks OTHER threads submit after the call began. The test's unrelated caller keeps all 3 queues full (one producer out-paces 3 workers on 4 CPUs), so every pass ends "still processing", for ever. GraphBatch.connectOutgoingEdgesParallel / connectIncomingEdgesParallel wait there for their own connect tasks, so the flush never ended. LocalDatabase.waitForAsyncCompletion(), the barrier of every index build (#6281), wrapped the same loop around it a second time.

Fix

  • waitCompletion goes around again only when a pass saw a cascade: a new LongAdder counts the tasks and commands scheduled by one of this executor's own workers (the Async cross-slot bidirectional edge: waitCompletion() can return before the in-edge is created, and a quiesce index build can miss it #6462 case). A cascade scheduled by a task queued before a marker lands in the counter before that marker fires, so an unchanged counter proves nothing was left behind the markers. Cost: one owner check per schedule, an increment only on worker-originated ones, no locks.
  • waitForAsyncCompletion() is a single waitCompletion(). Tasks submitted by other threads during a build race it either way; quiesceAsync() is what keeps them out of a scan.
  • The DatabaseAsyncExecutor.waitCompletion() javadoc says what it waits for. Behaviour change: tasks other threads submit while it waits are no longer waited for. The docs are updated in the async API reference.

Tests

New Issue11155WaitCompletionUnderSteadyProducerTest: one worker and a producer that always queues the next task before the running one finishes, so the executor is never idle. Three tests, each with @Timeout(60) as a hang detector: waitCompletion() returns, waitForAsyncCompletion() returns, a GraphBatch parallel flush ends. Each also asserts that the task submitted before the wait completed, and that the producer was still active afterwards.

  • Without the fix all three hang, with the CI dump's frames. With it they pass in ~0.06 s.
  • Related tests, run with the test JVM limited to 4 CPUs: Issue11155*, Issue5665*, Issue6462*, Issue6281*, Issue6303*, Issue10537*, Issue6526*, Issue6534*, GraphBatch*, DatabaseAsync*, *Async*Test, TransactionManager*, 225 tests, green.
  • Index build and quiesce tests (*IndexBuild*, *IndexBuilder*, CreateIndex*, *Quiesce*, LSMTreeIndexTest, TypeLSMTreeIndexTest, DropIndexTest): 172 tests, green.

Left as is

  • A steady external stream of tasks that themselves cascade (bidirectional async().newEdge) still moves the counter.
  • awaitCommands still waits for zero in-flight DDL commands.
  • GraphBatch could wait on its own connect tasks only, rather than the executor-wide barrier.

Summary by CodeRabbit

  • Bug Fixes
    • Async completion waits now finish after processing work submitted before the wait begins, including follow-up work scheduled by that work. They no longer wait indefinitely for unrelated work submitted concurrently by other threads.
    • Graph batch flushing can complete while other background work continues, with all edges submitted by the batch stored. These changes make completion behavior more predictable when the database is handling ongoing background activity.

…it goes around again only for cascades its own workers schedule
@lvca lvca added this to the 26.11.1 milestone Nov 3, 2026
@lvca lvca added bug concurrency Threading / concurrency / MVCC engine Core engine: document/schema API labels Nov 3, 2026
@lvca lvca self-assigned this Nov 3, 2026
@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Caution

Review failed

The pull request is closed.

Walkthrough

The async completion barrier now tracks worker-scheduled cascades and commands submitted before a wait begins. LocalDatabase.waitForAsyncCompletion() delegates to the barrier once. Regression tests cover both wait APIs and a parallel GraphBatch flush during continuous submissions.

Changes: Async completion barrier

Layer / File(s) Summary
Track commands covered by a wait
engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutorImpl.java
Commands receive sequence numbers. Each wait captures a submission sequence and waits only for commands at or below that sequence. Completion removes the command’s sequence and notifies waiters.
Bound waits to worker-scheduled cascades
engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutor.java, engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutorImpl.java, engine/src/main/java/com/arcadedb/database/LocalDatabase.java
The waitCompletion() documentation describes the work covered by the barrier. The implementation repeats marker passes when executor workers schedule additional tasks or commands. LocalDatabase.waitForAsyncCompletion() calls the barrier once.
Verify waits under continuous submissions
engine/src/test/java/com/arcadedb/database/async/Issue11155WaitCompletionUnderSteadyProducerTest.java
Regression tests check both wait APIs and command-pool waits during steady production. The parallel GraphBatch flush test verifies that all 40 edges exist.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

  • ArcadeData/arcadedb#8881: This PR changes the Python wait_completion timeout contract and calls Java waitCompletion(long), whose barrier contract changes here.

Suggested reviewers: robfrank

Merge Risk: Moderate · up to 6e9d8

Closing during async writes can silently lose an accepted write. The close path should prevent new admissions before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the fix for async waitCompletion() under a steady producer. It is specific and related to the primary change, although longer than ideal.
Description check Passed The description provides detailed cause, motivation, fix, related issue, tests, behavior changes, and additional notes. It omits the repository template headings and checklist, but the required conten…
Linked Issues check Passed The change addresses the coding requirement in #11155. DatabaseAsyncExecutorImpl.waitCompletion(long) now repeats marker passes only when executor workers schedule additional tasks or commands. It n…
Out of Scope Changes check Passed The changed files stay within #11155. The implementation changes the async wait behavior, the local database wrapper adopts that behavior, the public javadoc documents the behavior change, and the reg…
Full details: Description check

Explanation

The description provides detailed cause, motivation, fix, related issue, tests, behavior changes, and additional notes. It omits the repository template headings and checklist, but the required content is mostly present.

Full details: Linked Issues check

Explanation

The change addresses the coding requirement in #11155. DatabaseAsyncExecutorImpl.waitCompletion(long) now repeats marker passes only when executor workers schedule additional tasks or commands. It no longer repeats only because external producers keep the executor busy. LocalDatabase.waitForAsyncCompletion() now performs one waitCompletion() call. The new Issue11155WaitCompletionUnderSteadyProducerTest covers waitCompletion(), the database completion barrier, and parallel GraphBatch flushing under a continuously active external producer. Each test has a timeout and verifies that work submitted before the wait completes.

Full details: Out of Scope Changes check

Explanation

The changed files stay within #11155. The implementation changes the async wait behavior, the local database wrapper adopts that behavior, the public javadoc documents the behavior change, and the regression test covers the reported producer and GraphBatch scenario. No unrelated production feature or unrelated test change is present in the reviewed diff.

Full details: Docstring Coverage

Explanation

Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 6 functions across 4 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

ast-grep (0.51.1)

ast-grep could not parse rule config: /ast-grep-rules/ast-grep-essentials/rules/bash/security/hardcoded-password-assignment-bash.yml

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5c42adfe-2e98-4a81-935b-80a959fff3d9
Commits

Reviewing files that changed from the base of the PR and between dca7a0e and 2ce1666.

Files selected for processing: 4
  • engine/src/main/java/com/arcadedb/database/LocalDatabase.java
  • engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutor.java
  • engine/src/main/java/com/arcadedb/database/async/DatabaseAsyncExecutorImpl.java
  • engine/src/test/java/com/arcadedb/database/async/Issue11155WaitCompletionUnderSteadyProducerTest.java

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

@mergify

mergify Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@claude

claude Bot commented Nov 3, 2026

Copy link
Copy Markdown

Review: LGTM overall.

  • The fix targets the cause. waitCompletion now loops only when a worker-originated schedule happened during the pass, not whenever the executor is busy. The cost is one owner check per schedule and a LongAdder increment on worker-originated schedules only.
  • The regression test forces the interleaving deterministically and uses @Timeout only as a hang detector, which matches the CLAUDE.md guidance on wall-clock assertions.
  • Minor: the behaviour change (tasks other threads submit during the wait are no longer waited for) could affect callers that relied on waitCompletion() as a full-drain barrier. The javadoc and docs cover it. A grep of the other callers (server, import, tests) for that assumption would still be worthwhile.
  • Minor: the counter is read before each pass and after it. If a worker schedules a cascade between the post-pass read and the return, that is the same window a marker-based approach has. The PR argues it is covered, and I find the argument sound.

No security concerns.

@codacy-production

codacy-production Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

🟢 Coverage 91.67% diff coverage · -4.62% coverage variation

Metric Results
Coverage variation ✅ -4.62% coverage variation
Diff coverage ✅ 91.67% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (dca7a0e) 259676 227137 87.47%
Head commit (6e9d845) 292513 (+32837) 242351 (+15214) 82.85% (-4.62%)

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 (#11191) 24 22 91.67%

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.

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

  • Fix comments: Fix CodeRabbit comments on this PR

…ands submitted before it, not for none in flight
@lvca

lvca commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

On the first minor point, I checked every production caller of waitCompletion() / waitForAsyncCompletion(). All of them wait only for work they submitted themselves before calling: GraphBatch's connect tasks, the CSV and XML importers' own rows, and the three index builders plus REBUILD INDEX, where quiesceAsync() is what keeps concurrent writers out of the scan. LocalDatabase.close() is the one caller where other threads' tasks can be in flight. There it now returns as soon as the earlier work is done, instead of spinning until asyncCloseTimeout while another thread keeps submitting, and then shuts the workers down as before. No caller relied on the full-drain behaviour.

The command-pool half of the barrier had the same starvation (CodeRabbit's finding); it is fixed in 6e9d845.

@claude

claude Bot commented Nov 3, 2026

Copy link
Copy Markdown

Review of #11191: no blocking issues found.

  • Fix: the cascade counter (counterTasksScheduledByWorkers) is a sound replacement for while (isProcessing()). A cascade scheduled by a task queued before a marker lands in the counter before that marker fires, so an unchanged counter across a pass means nothing was left behind. The cost on the hot path is one owner check per schedule, plus a LongAdder increment only for worker-originated schedules.
  • Command barrier: awaitCommands now waits only for the sequences submitted up to its start, which fixes the same starvation one step earlier. The sequence is added to the set before the count, which is the right order. notifyAll now fires on every completion instead of only the last. That is correct, and cheap because only DDL commands go through it.
  • Tests: the deterministic producer forces the never-idle interleaving instead of hoping for it. It covers the plain, index-barrier, command and GraphBatch paths, and each test has a @Timeout as a hang detector. This follows the CLAUDE.md guidance on timing.

Minor, non-blocking

  1. The waitCompletion() behaviour change (tasks other threads submit during the wait are no longer awaited) could affect callers that relied on the old semantics, such as shutdown or close paths and tests that submit from several threads. The docs are updated, so a release-notes line is probably worth adding.
  2. ConcurrentSkipListSet<Long> boxes a Long per command. That is fine for DDL-only volume, but worth a comment if non-DDL commands ever go through it.
  3. In SteadyProducer.close(), async.waitCompletion() runs after the producer is stopped, so it could mask a hang with the full @Timeout. That is acceptable.

No security concerns.

@lvca
lvca merged commit 1188038 into main Nov 3, 2026
37 of 39 checks passed
@lvca
lvca deleted the fix-11155-async-waitcompletion-steady-producer branch November 3, 2026 06:41
@codecov

codecov Bot commented Nov 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.33333% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.37%. Comparing base (dca7a0e) to head (6e9d845).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...dedb/database/async/DatabaseAsyncExecutorImpl.java 82.60% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##               main   #11191   +/-   ##
=========================================
  Coverage     79.37%   79.37%           
- Complexity     4963     4965    +2     
=========================================
  Files          2325     2325           
  Lines        259676   259686   +10     
  Branches      56891    56892    +1     
=========================================
+ Hits         206119   206129   +10     
  Misses        32579    32579           
  Partials      20978    20978           

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

tae898 added a commit to ArcadeData/arcadedb-python that referenced this pull request Nov 3, 2026
…er wait_completion() (#210) (#211)

Engine 26.11.1-SNAPSHOT (ArcadeData/arcadedb#11191) ends waitCompletion() when the last
marker releases the waiter, not on an isProcessing() poll, so a worker can still flag
itself as executing for an instant after wait_completion() returns. Four tests asserted
"idle now" at that point and failed on the nightly image. They now wait, with a deadline,
for is_processing() to turn False. The wait_completion() docstring says what its return
does and does not promise.

Co-authored-by: Claude Opus 5.5 <[email protected]>
lvca added a commit that referenced this pull request Nov 3, 2026
…returns (#11217)

A worker counted the waitCompletion() marker's latch down before it dropped its
executing-task flag, so isProcessing() asked right after the return answered
true in up to half of the calls with nothing left to run (since #11191). The
worker now drops the flag before completed() releases any waiter, and a
dispatched command's in-flight count goes down before its sequence leaves the
set the barrier waits on.
robfrank pushed a commit that referenced this pull request Nov 5, 2026
…it goes around again only for cascades its own workers schedule (#11191)

* fix(#11155): async waitCompletion() returns under a steady producer: it goes around again only for cascades its own workers schedule

* fix(#11155): the command half of the async barrier waits for the commands submitted before it, not for none in flight

(cherry picked from commit 1188038)
robfrank pushed a commit that referenced this pull request Nov 5, 2026
…returns (#11217)

A worker counted the waitCompletion() marker's latch down before it dropped its
executing-task flag, so isProcessing() asked right after the return answered
true in up to half of the calls with nothing left to run (since #11191). The
worker now drops the flag before completed() releases any waiter, and a
dispatched command's in-flight count goes down before its sequence leaves the
set the barrier waits on.

(cherry picked from commit 614090f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug concurrency Threading / concurrency / MVCC engine Core engine: document/schema API

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Issue5665GraphBatchAsyncPoolChurnTest livelocks on 4 CPUs: async workers spin in tryLockFiles while GraphBatch waits for them

1 participant