Skip to content

fix(#6199, #6200): the flush drains wake on the page, and one suspended database's backlog is its own - #6223

Merged
lvca merged 12 commits into
mainfrom
issue-6199-6200
Aug 16, 2026
Merged

lvca merged 12 commits into
mainfrom
issue-6199-6200

Conversation

@lvca

@lvca lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member

Fixes #6199, fixes #6200. Both are follow-ups of #6133.

#6199 - the drains stop polling

Both waits on the flush pipeline discovered that it had emptied by sleeping and asking again, so the latency they paid was set by the poll interval rather than by when the pages actually landed:

  • waitAllPagesOfDatabaseAreFlushed polls every 10 ms, and every close(), rename(), index compaction, backup suspension and the snapshot barrier's first drain goes through it;
  • waitPendingPagesOfDatabaseUntil polls every 1 ms, and its caller (PageManager.openSnapshot, step 2 of the t0 barrier) runs it with both the database's apply write lock and the JVM-wide page-manager lock held. Every one of those Thread.sleep(1) calls was a millisecond in which no committer of any database in the process could publish a page - paid even when the pages had landed 999 us earlier.

Since #6133, FlushPageIndex.release() is the only path on which a database's pending count goes down, so a "this database just drained" signal has exactly one hook. The per-database counter now doubles as the monitor: release() notifies on the transition to zero (and removeAllOfDatabase notifies on a purge), and both waits call FlushPageIndex.awaitDrain instead of sleeping.

The guard is re-read inside the monitor, so a release landing between the caller's check and the park cannot be slept through. The bounded wait is kept, not as the mechanism but as the bound on a hypothetical lost notification and to keep the callers' timeout machinery re-evaluated - which is why the residual drain's fallback stays at the 1 ms it used to sleep: worst case unchanged, common case immediate.

Rejected, as the issue suggests: shortening the poll interval. It burns a core under a JVM-wide lock to improve the average without touching the worst case.

#6200 - the cap stops charging one database's backlog to everyone

The cap of #4728 bounds heap, which is JVM-wide, so a global ceiling is the right thing to measure. What did not follow is that the response should be global too, and it was: once one suspended database's backlog crossed the cap, flushPagesFromQueueToDisk returned without polling at all. The bounded queue then filled and scheduleFlushOfPages throttled the committing threads - of every open database, not just of the suspended one - and, because publishPages holds the JVM-wide page-manager lock across the enqueue, it throttled them inside that lock. A leader shipping a multi-GB snapshot of database A stalled the committers of unrelated databases B and C, whose pages could have gone straight to disk, which strictly relieves the heap the cap protects.

What this PR does instead of the issue's proposal

The issue proposed keeping the gate on the drain side and making the back-off selective (poll as usual, flush non-suspended batches, put the over-cap suspended batch back). That would have to re-queue the held batch, and a batch put back at the tail is reordered against the other batches of its own database: two commits can leave two MutablePage copies of the same PageId pending at once (the #4544 case), and deferring the newer one first means the older one is written over it at resume. It also cannot bound the heap on its own - the pages weigh exactly the same in the queue as in the deferred map, so moving them around does not stop the growth; only holding the producers does.

So the throttle moved to the producer side, where it belongs, and the drain-side gate is gone entirely:

  • PageManagerFlushThread.awaitDeferredBacklogUnderCap(database) holds a committer while the backlog is at or over the cap and its own database is suspended. A database that is not suspended never enters it - its pages cannot grow the backlog.
  • It is called before the page-manager lock is taken: as a separate step of publishPages, and directly in writePages for the asynchronous compaction writes that do not go through publishPages. This is the whole point - held one line lower, the wait would be served inside a JVM-wide lock and we would be back to stalling everybody.
  • The flush thread always drains, so B's and C's batches are polled and written while A sits over the cap.
  • deferredRAMBytes is split into a per-database counter plus the derived total (getDeferredRAMBytesOf), which is what item 2 of Backup phase-1 follow-ups: copy() drops settings on Export/Import, deferred-RAM metric unwired, no per-database compression override #6087 needs for a gauge tagged by database - not expressible before, because the number did not exist per database.
  • A committer held for more than 10 s says so once, at WARNING, naming the database whose backlog is holding it.

The heap bound is unchanged in the worst case (cap plus whatever was already admitted), and tighter in practice: while a database is suspended, deferring a batch is a map insert with no I/O, so the queue does not build up and the total tracks the cap closely.

Tests

  • Issue6199DrainWakeupTest (new) - stretches the fallback interval to a minute so a wait that ends inside the assertion timeout can only have been ended by the signal; races the release against the park 300 times to pin the guarded-wait shape; covers the purge wake-up and the barrier's hard deadline (including the wait(0) trap an expired deadline would otherwise be). Verified to fail on the pre-fix behaviour: 3 of 5 tests red with the notify removed.
  • Issue6200PerDatabaseDeferredBacklogTest (new) - a second database's batch is flushed while the first sits at twice the cap; the suspended database's own committers are held and then released by the resume; a non-suspended database is never held; the accounting splits per database and sums to the total. Verified to fail on the pre-fix behaviour: 3 of 4 tests red with the drain-side gate restored.
  • PageManagerFlushSuspendBackpressureTest - Replica stuck in STALLED #4728's own bound, re-asserted where the enforcement moved: past the cap, no further page of the suspended database can be published.
  • Full engine module suite green (11998 tests), including Issue6133PendingPagesPerDatabaseTest, Issue6125SnapshotBarrierAndCapTest, PageManagerFlushSuspendDeferRaceTest, PageManagerFlushSuspendRefCountTest, Issue5326ApplyChangesPendingFlushTest, FlushRobustnessTest and PageSnapshotTest.

…ed database's backlog is its own

#6199 - both drains of the flush pipeline discovered that it had emptied by SLEEPING and asking again, so
their latency was the poll interval rather than when the pages actually landed: 10 ms for the bulk drain
every close, rename, index compaction and backup suspension goes through, and 1 ms for the snapshot t0
barrier's residual drain - which polls with the database's apply write lock AND the JVM-wide page-manager
lock held, so each of those sleeps was a millisecond in which no committer of any database could publish a
page. Since #6133 there is exactly one place a database's pending count goes down, so the drains now park on
a signal raised there. The bounded wait stays as the bound on a lost notification (and to keep the callers'
timeout machinery re-evaluated), which is why the residual one stays at the 1 ms it used to sleep: the worst
case is unchanged, the common case is immediate.

#6200 - the deferred-flush cap of #4728 bounds heap, which is JVM-wide, so a global ceiling is right; its
RESPONSE was global too, and that was not. Once one suspended database's backlog crossed the cap the flush
thread stopped polling the shared queue altogether, so the queue filled and the committers of EVERY open
database were throttled - and, because publishPages holds the page-manager lock across the enqueue, throttled
inside a JVM-wide lock. A leader shipping a multi-GB snapshot of database A stalled the committers of
unrelated databases B and C, whose pages could have gone straight to disk and RELIEVED the heap the cap
protects.

The cap is now served on the committer side, in awaitDeferredBacklogUnderCap, and only for the databases that
are actually suspended - they are the only ones whose batches are ever deferred. It is called BEFORE the
page-manager lock is taken (a separate step of publishPages, and directly in writePages for the asynchronous
compaction writes that do not go through it), so throttling A's writers no longer stalls B's. The flush thread
always drains. deferredRAMBytes is split into a per-database counter plus the derived total, which is what
item 2 of #6087 needs to tag its gauge by database, and a committer held for more than 10 s now says so, at
WARNING, naming the database whose backlog is holding it.

Regression tests: Issue6199DrainWakeupTest stretches the fallback interval to a minute so a wait released
inside the assertion timeout can only have been released by the signal, and races the release against the
park 300 times to pin the guarded-wait shape; Issue6200PerDatabaseDeferredBacklogTest proves the drain keeps
serving other databases past the cap, that the suspended database's own committers are still held and then
released, and that the accounting splits and sums. PageManagerFlushSuspendBackpressureTest moved its #4728
bound to where the enforcement moved.
@lvca lvca self-assigned this Aug 16, 2026
@mergify

mergify Bot commented Aug 16, 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 Aug 16, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 36 complexity

Metric Results
Complexity 36

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.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review of #6223 (fixes #6199, #6200)

Solid piece of work. Both fixes replace poll-based waits with proper guarded wait/notify, and the per-database backlog accounting is a clean way to scope the #4728 cap's response without weakening its bound. The javadoc is unusually thorough about the exact race windows being closed, and the regression tests (Issue6199DrainWakeupTest, Issue6200PerDatabaseDeferredBacklogTest, plus the rewritten PageManagerFlushSuspendBackpressureTest) exercise the actual race conditions rather than just the happy path (e.g. aReleaseRacingTheParkIsNeverMissed running 300 iterations with no handshake).

Correctness

  • FlushPageIndex.awaitDrain/release guarded-wait pattern is correct: the guard is re-read under the counter's own monitor, so a release() landing between the caller's hasPendingOf() check and the park cannot be missed - confirmed by walking through both interleavings.

  • PageManagerFlushThread.awaitDeferredBacklogUnderCap's loop also does the check-then-wait atomically under deferredRAMLock, so no lost-wakeup there either.

  • One narrow race worth a look: resetDeferredRAMIfDrained() (PageManagerFlushThread.java ~line 741) does

    if (deferredByDatabase.isEmpty()) {
      deferredRAMBytes.set(0);
      deferredRAMByDatabase.clear();
      signalDeferredRAM();
    }

    deferredByDatabase.isEmpty() is read on the caller's thread (resumeFlushing/removeAllPagesOfDatabase), while the flush thread can concurrently offer() a new deferred batch for a different database and call addDeferredRAM(otherDb, +delta) in flushPagesFromQueueToDisk. If that interleaves between the isEmpty() check and the set(0)/clear(), the just-added backlog gets wiped from both the per-database map and the total, transiently defeating the cap for that other database until its next mutation. This pattern already existed pre-PR for the bare deferredRAMBytes.set(0), so it's not new, but the PR widens the blast radius slightly by adding deferredRAMByDatabase.clear() to the same unguarded window. Given it's called out as a "safety net... absorb any drift", this is probably an accepted tradeoff, but might be worth a one-line comment acknowledging the (very narrow) race, or gating the whole block under deferredRAMLock to close it for free.

  • PageManager.awaitDeferredBacklogUnderCap(List<MutablePage> pages) assumes the whole list belongs to one database (pages.getFirst().getPageId().getDatabase()). That holds for every current caller (publishPages is per-transaction/per-database, and the writePages call sites all pass single-database lists), but it's an implicit invariant with no assertion - a future caller that passes a mixed-database batch would silently throttle (or fail to throttle) the wrong database rather than fail loudly. Worth a short comment noting the assumption, since it's easy to violate accidentally later.

Design

Test coverage

Coverage looks thorough for both issues: wake-on-drain vs. wake-on-timeout distinction (stretching the fallback interval to a minute to disambiguate), the race-the-park stress test, purge-releases-waiters, hard-deadline preservation for the residual drain, and for #6200 - other databases not stalled, the suspended database's own committers still throttled, non-suspended databases never blocked by someone else's backlog, and per-database sums matching the total. The rewritten PageManagerFlushSuspendBackpressureTest correctly moved its assertions to match the new throttling point instead of just deleting coverage.

One gap: I didn't see a test exercising the resetDeferredRAMIfDrained race above, or closeAndJoin's signalDeferredRAM() releasing a committer parked on a database that's still suspended at shutdown - the doc comment calls this out explicitly but I didn't spot a corresponding regression test. Might be worth one, since it's exactly the kind of thing that's easy to silently regress (a future refactor removing that signalDeferredRAM() call would hang closeAndJoin() under exactly the conditions the comment describes).

Nits

  • GlobalConfiguration.java doc-only change reads well and matches the new behavior.
  • No concerns on the wire-protocol/dependency rules in CLAUDE.md - this PR doesn't touch any of that surface.

Overall: no blocking issues found. The one race in resetDeferredRAMIfDrained is narrow enough (requires a specific interleaving between an unrelated database's first deferral and another database's drain-to-empty) that I'd call it a follow-up rather than a blocker, but flagging it since it directly touches the correctness of the mechanism this PR is fixing.

…ed wholesale

Review of #6223. The safety net inherited from #4728 read `deferredByDatabase.isEmpty()` on the resuming
thread and, if it looked empty, zeroed the JVM-wide total and (as of this branch) the whole per-database
split. The flush thread can be deferring the FIRST batch of an unrelated database in exactly that window, and
its fresh charge was then wiped - the cap defeated for it until its next mutation.

Fixed at the source rather than around it. The drift the net existed for came from resumeFlushing's Phase 1
skipping a batch, or the tail of one, whose database closed mid-unsuspend: those pages left the backlog with
their bytes still charged to it, and every later suspension was throttled by that much. They are now released
like any other page - the page is simply not written, since there is nothing left to write it to.

The reset becomes releaseResidualDeferredRAM(database): strictly one database, called only where that
database's backlog has provably ended - after Phase 3b, where the argument Phase 2 already rests on
(suspension cleared under suspendLock, new suspenders gated out by resumingDatabases) guarantees nothing can
defer another of its batches, and on the close/drop purge. Nothing it does can touch a sibling. On the purge
path it also fixes a leak of this branch's own making: dropping the per-database entry without subtracting
its residual left the total inflated forever.

Also from the review: documented on PageManager.awaitDeferredBacklogUnderCap that a batch carries the pages
of ONE database - the invariant PagesToFlush, the per-database pending count and the suspension check all
already rest on, and which a mixed batch would break long before it reached the cap.

New tests: oneDatabaseResumingDoesNotWipeAnotherDatabaseBacklog (the race above, deterministically) and
shutdownReleasesACommitterParkedOnAStillSuspendedDatabase (closeAndJoin's signal, whose absence would hang a
committer against a condition that can never become true).

Unrelated flake found while running the two together: Issue5326ApplyChangesPendingFlushTest waited for
`deferredRAMBytes > 0`, which with two commits only proves the FIRST batch was deferred. A second copy still
in the QUEUE is detached without touching the deferred accounting, so the "both copies left the backlog"
assertion saw one page's worth and blamed the detach for a race in its own wait. It now waits for the
pipeline to drain into the backlog.

Full engine suite green (12000 tests).
@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

I read through the full diff (GlobalConfiguration, FlushPageIndex, PageManager, PageManagerFlushThread, and the new/updated tests) and traced the concurrency arguments by hand. This is a very carefully engineered change with unusually thorough in-code rationale; nice work.

Correctness / concurrency

  • The FlushPageIndex.awaitDrain / release guarded-wait is textbook-correct: the guard is re-read inside synchronized(counter), so a release() racing the park can't be missed (the notifier can't enter its synchronized block until the waiter has released the monitor via wait()). I traced the "stale counter after removeAllOfDatabase" edge case (a waiter holding a reference to an orphaned counter whose int value was never zeroed) and confirmed it only degrades to a bounded timeout, never a hang - pendingOf() still answers 0 afterward and the caller's own loop re-checks it. Good, matches the documented "safety net" behavior.
  • addDeferredRAM / addDeferredRAMTotal's "signal only on downward cap crossing" is safe under concurrent updates because AtomicLong.getAndAdd linearizes the total, so the one call whose (previous, previous+delta) actually straddles the cap is guaranteed to exist and fire the signal - no lost-wakeup window there either.
  • awaitDeferredBacklogUnderCap's guarded wait on deferredRAMLock is likewise sound: setSuspended(false) clears the suspended flag and finishes resumeFlushing (which flushes/releases the deferred batches) before calling signalDeferredRAM() in its finally, so a committer woken by that signal will always observe both !isSuspended(db) and the drained backlog consistently.
  • The move of awaitDeferredBacklogUnderCap to before PageManager.lock() in publishPages, and directly into writePages for the async-compaction callers that bypass publishPages, is the crux of the The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200 fix and looks correctly placed - I checked both writePages(..., true) call sites (LSMTreeIndexCompacted) and confirmed neither holds the page-manager lock when calling in.
  • Nice catch in the PR's own second commit: fixing the blanket deferredByDatabase.isEmpty() reset that could wipe a sibling database's fresh charge. The replacement (releaseResidualDeferredRAM, scoped to one database, called only where Phase 2's suspendLock/resumingDatabases argument already guarantees exclusivity) is correctly reasoned.

One thing worth double-checking (not confirmed as a bug)

removeAllPagesOfDatabase (close/drop path) calls releaseResidualDeferredRAM(database) without holding suspendLock(database), unlike resumeFlushing's Phase 1-4 which is carefully serialized against a concurrent defer in flushPagesFromQueueToDisk. If it's possible for a database to be closed/dropped while still suspended and while the flush thread is mid-poll of one of its batches, there's a theoretical window where flushPagesFromQueueToDisk re-creates a deferredByDatabase/deferredRAMByDatabase entry for the database after removeAllPagesOfDatabase already cleaned it up - and since nothing will ever call resumeFlushing for a database that's gone, that batch (and its RAM charge) would leak for the life of the process. This pattern predates this PR (the old blanket reset had the same exposure), so it may already be ruled out elsewhere (e.g. close() waiting out any outstanding suspension before reaching this point) - worth a sentence in the PR description or a quick sanity check if it isn't already guaranteed elsewhere.

Performance

  • release() keeps the hot per-page path to a volatile decrement + comparison, only touching the monitor on the exact page that drains the counter to zero - matches the "performance and GC" mandate well.
  • addDeferredRAMTotal's "signal only on downward crossing" avoids taking the monitor once per page during a large resume.
  • Reusing the AtomicInteger counter object itself as the monitor (rather than a parallel lock map) avoids an extra allocation/map and closes a publish-race window at the same time - good call, and explicitly justified in the Javadoc.

Test coverage

Excellent. Issue6199DrainWakeupTest distinguishes "woken by signal" from "woken by poll" by stretching the fallback interval to a minute (a wait ending well inside that must have been the signal), covers the guarded-wait race 300 times, purge wake-up, and the residual drain's hard-deadline edge cases (including the wait(0)-means-forever trap). Issue6200PerDatabaseDeferredBacklogTest covers the core regression (other databases keep draining past one database's cap), the cap still holding the suspended database's own committers, per-database accounting summing to the total, the sibling-not-wiped-on-resume race, and shutdown releasing a still-parked committer. The PR description states these were verified red against the pre-fix code, which is exactly the right way to validate a concurrency regression test.

Security

None of this touches trust boundaries or external input - no concerns.

Minor nits

  • The extensive prose Javadoc/inline comments are borderline for the project's usual comment density, but here they're all explaining non-obvious why (races avoided, rejected alternatives, worst-case reasoning) rather than restating what, so they read as justified rather than noise.
  • DEFERRED_BACKLOG_WAIT_POLL_MILLIS = 100 and DEFERRED_BACKLOG_WARN_MILLIS = 10_000 are reasonable defaults; no issue, just flagging they're not configurable if an operator ever wants a different WARNING cadence - probably not worth the complexity for a first cut.

Overall: solid, well-tested fix for both issues, with a good paper trail of rejected alternatives (shorter poll interval, selective re-queue back-off) and why they were rejected. I'd merge after a maintainer confirms the close/drop-while-suspended question above is already a non-issue.

…rred batches under the same monitor

Answers the question round 2 of the review left for a maintainer, and the answer was not "already ruled out
elsewhere": the window is real.

removeAllPagesOfDatabase cleared `suspended` and detached `deferredByDatabase` holding nothing, while
flushPagesFromQueueToDisk decides to defer under the database's suspend monitor - it checks isSuspended and
offers the batch inside it. So the flush thread could read "suspended" just before the purge ran and offer
its batch just after, re-creating a deferred queue for a database the purge had already forgotten. Nothing
ever resumes a database that is gone, so everything in that window is permanent: the batch, the map entry
pinning the closed LocalDatabase instance with its pages in RAM, and a charge on the JVM-wide total that
would throttle the committers of every LATER suspension in the process.

The flag and the detach now happen under suspendLock(database), flag first - the same construction Phase 2 of
the resume already relies on, and for the same reason: once the flag is clear no further batch can be
deferred. suspendLocks.remove moved after the block, or a defer racing it would resolve a FRESH monitor and
be excluded by nothing. The batchRAM accounting stays outside it: batchRAM takes each batch's own monitor,
and suspendLock BEFORE batch.pages is the one nesting this class allows.

Tests: purgingASuspendedDatabaseTakesItsWholeBacklogWithIt pins the accounting deterministically (no queue,
no charge, no flag, and the sibling that is still suspended keeps its own), and
aBatchPolledWhileTheDatabaseIsPurgedIsNeverLeftDeferredForIt races a poll against a purge 200 times.
The race test reproduces the leak against the unguarded version - about one run in three, around iteration
100 - so it is a real guard rather than a vacuous one. New package-private hasDeferredBatches accessor for it,
the same shape as FlushPageIndex.isTracked.

Full engine suite green (12002 tests).
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Answering the close/drop-while-suspended question from the last review round rather than confirming it as a non-issue: the window is real, and it is now closed in e47f11e.

removeAllPagesOfDatabase cleared suspended and detached deferredByDatabase while holding nothing, but flushPagesFromQueueToDisk decides to defer inside synchronized (suspendLock(db)) - it checks isSuspended and offers the batch in the same critical section. So the flush thread could read "suspended" just before the purge ran and offer its batch just after it, re-creating a deferred queue for a database the purge had already forgotten. Since nothing ever resumes a database that is gone, everything in that window is permanent: the batch, the map entry pinning the closed LocalDatabase instance with its pages in RAM, and a charge on the JVM-wide total that would throttle the committers of every later suspension in the process.

Nothing else rules it out - the database write lock a close takes only excludes suspenders that hold the matching read lock for their whole window, which is not a property this class can rest on.

Fix: the flag drop and the detach now happen under suspendLock(database), flag first, which is exactly the construction Phase 2 of the resume already relies on (once the flag is clear, no further batch can be deferred). suspendLocks.remove moved after that block, or a defer racing it would resolve a fresh monitor and be excluded by nothing; the batchRAM accounting stays outside it, since batchRAM takes each batch's own monitor and suspendLock → batch.pages is the one nesting this class allows.

Two tests: purgingASuspendedDatabaseTakesItsWholeBacklogWithIt pins the accounting deterministically (no queue, no charge, no flag, and a sibling that is still suspended keeps its own backlog), and aBatchPolledWhileTheDatabaseIsPurgedIsNeverLeftDeferredForIt races a poll against a purge 200 times. The race test reproduces the leak against the unguarded version - about one run in three, around iteration 100 - so it is a real guard.

On the other nit: leaving DEFERRED_BACKLOG_WAIT_POLL_MILLIS and DEFERRED_BACKLOG_WARN_MILLIS non-configurable for now, as suggested.

Full engine suite green: 12002 tests, 0 failures.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

This is a well-reasoned fix for two real bugs in the flush pipeline (#6199's poll-latency and #6200's global-stall-on-one-suspended-database), and the follow-up commits show the author self-reviewing hard: the residual-reset-wipes-a-sibling bug and the purge/defer race were both caught and fixed in later commits of this same branch. I traced the guarded-wait logic in FlushPageIndex.awaitDrain/release and the deferredRAMLock wait in awaitDeferredBacklogUnderCap by hand (classic "recheck the condition inside the monitor" pattern) and didn't find a lost-wakeup hole — the one scenario that looks like one (removeAllOfDatabase abandoning a counter without zeroing it while a waiter is mid-awaitDrain) degrades to the bounded fallback wait exactly as documented, not a hang, and that fallback bound is unchanged from the pre-#6199 behavior.

Nits

  • engine/src/main/java/com/arcadedb/engine/PageManagerFlushThread.java:147 — the javadoc on deferredRAMByDatabase links to {@link #resetDeferredRAMIfDrained}, but no method by that name exists in this class; the method that actually drops a database's entry is releaseResidualDeferredRAM. Looks like a leftover from an earlier name during the review iterations. Worth fixing so the link isn't dead (and doesn't trip -Xdoclint if that's enforced anywhere).

  • awaitDeferredBacklogUnderCap's WARNING log (PageManagerFlushThread.java:860-863) reports the JVM-wide deferredRAMBytes.get() rather than getDeferredRAMBytesOf(db). Given the cap itself is JVM-wide that's defensible, but an operator reading "commits on database X throttled... backlog is Y, at or above the cap" may reasonably read Y as X's own backlog rather than the total across every suspended database. Might be worth logging both numbers, or naming the field in the message as "JVM-wide deferred backlog", since The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200's whole point is that one database's backlog can throttle another.

  • awaitDeferredBacklogUnderCap parks every held committer of every suspended database on one shared deferredRAMLock, so a signal (crossing the cap downward, a resume, shutdown, a purge) wakes all of them via notifyAll regardless of which database they belong to. Given signals are rare (only on the downward cap crossing, not per byte) this is a non-issue in practice, just flagging it as a minor thundering-herd note in case backlog churn near the cap boundary turns out to be less rare than assumed in production.

Things I specifically checked and found sound

  • The producer-side backpressure (awaitDeferredBacklogUnderCap) is called before PageManager.lock() in both publishPages and writePages, which is the crux of the The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200 fix — confirmed the flush thread itself never calls back into this method, so there's no self-deadlock path.
  • The resumeFlushing phase ordering (flag-clear under suspendLock → gated re-suspension via resumingDatabases → residual release last) correctly prevents a new deferral from landing between the flag clear and the residual release, so releaseResidualDeferredRAM finding non-zero should only happen on a genuine accounting bug, not a race.
  • removeAllPagesOfDatabase's new suspendLock-guarded flag-clear-and-detach (commit 3) closes the purge-vs-defer race the second review round called out; the described repro rate ("about one run in three, around iteration 100") in aBatchPolledWhileTheDatabaseIsPurgedIsNeverLeftDeferredForIt gives good confidence this wasn't a vacuous guard.
  • Test coverage is thorough for this kind of change — the "stretch the fallback to a minute so only the signal could have ended the wait" technique in Issue6199DrainWakeupTest is a good way to distinguish "woken by notify" from "woken by poll" without instrumenting the production code, and PageManagerFlushSuspendBackpressureTest was correctly moved to assert on the new committer-side enforcement point rather than the removed drain-side one.
  • No new dependency, no new thread pool (reuses the existing dedicated flush thread + waiter parking, consistent with the engine's no-common-ForkJoinPool rule), and the changes stay inside engine/.

Nothing here blocks merging as far as I can tell from static review; the nits above are cosmetic/doc issues, not functional ones.

…vadoc link is repaired

Review round 3, both cosmetic.

The javadoc of deferredRAMByDatabase still linked #resetDeferredRAMIfDrained, a method removed two commits ago
when the blanket reset became the per-database releaseResidualDeferredRAM - a dead link, and one -Xdoclint
would reject.

The throttle WARNING reported only the JVM-wide total, which reads as "database X's own backlog" next to
"commits on database X have been throttled". It is very often NOT its own: the cap is on the total across every
suspended database, which is the entire subject of #6200. It now names the JVM-wide figure as such and gives
this database's share beside it.

Also documented, in answer to the same round's thundering-herd note, why one shared monitor is the right shape:
every parked committer is waiting on the same number - the JVM-wide total, which any database's release can
move under the cap - so a per-database monitor would have to be notified for all of them anyway. The herd is
bounded by the signal firing only on the DOWNWARD crossing of the cap, on a resume, on a purge and on shutdown,
never per released page.
@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

This is an unusually well-engineered PR: the javadoc explains why each lock/ordering choice is safe, the four commits show real iterative self-review (each fixing a race the previous one introduced), and the two new test classes (Issue6199DrainWakeupTest, Issue6200PerDatabaseDeferredBacklogTest) target the actual races rather than just the happy path. The core ideas - a guarded-wait signal instead of polling for the drain, and moving the 4728 backpressure from the drain side (JVM-wide stall) to the producer side (per-database, pre-lock) - are both correct and clearly better than what they replace.

One correctness concern survived my read, plus a couple of smaller notes.

Possible double-release of deferredRAMBytes when a database is purged while its own resume is in flight

PageManagerFlushThread.addDeferredRAM (engine/src/main/java/com/arcadedb/engine/PageManagerFlushThread.java:754-770):

private void addDeferredRAM(final BasicDatabase database, final long delta) {
    if (delta == 0) return;
    if (delta > 0)
      deferredRAMByDatabase.computeIfAbsent(database, k -> new AtomicLong()).addAndGet(delta);
    else {
      final AtomicLong bytes = deferredRAMByDatabase.get(database);
      if (bytes != null)
        bytes.addAndGet(delta);
    }
    addDeferredRAMTotal(delta);   // unconditional
}

For a negative delta, the per-database update is skipped when bytes == null (entry already removed), but addDeferredRAMTotal(delta) still runs unconditionally and decrements the JVM-wide total anyway.

That matters because resumeFlushing's Phase 1 (line 606-661) and removeAllPagesOfDatabase (line 900-949) are NOT mutually exclusive for the same database. Phase 1 only holds replayDrainLock(database) while it walks the deferred batches and calls addDeferredRAM(database, -page.getPhysicalSize()) per page (line 653); removeAllPagesOfDatabase never touches replayDrainLock at all - it only takes suspendLock(database) for the flag/detach step, then calls releaseResidualDeferredRAM(database) (line 944) outside any lock shared with Phase 1.

So the interleaving:

  1. Database D is suspended, a backup finishes, and the backup thread calls setSuspended(D, false) which starts resumeFlushing(D) Phase 1, synchronously writing a large deferred backlog to disk one page at a time.
  2. Concurrently, D gets closed/dropped (LocalDatabase.close() sets open = false BEFORE calling removeModifiedPagesOfDatabase, which calls removeAllPagesOfDatabase(D), per LocalDatabase.java:2502-2514 - exactly the 'closed mid-unsuspend' case Phase 1's batch.database.isOpen() check already anticipates).
  3. removeAllPagesOfDatabase finds deferredByDatabase.get(D) already empty (Phase 1 took it), so droppedDeferred == null, but it still calls releaseResidualDeferredRAM(D), which zeroes/removes the deferredRAMByDatabase entry for D and subtracts whatever was left in it from the JVM-wide total.
  4. Phase 1, still mid-loop on the other thread, keeps calling addDeferredRAM(D, -page.getPhysicalSize()) for the remaining not-yet-processed pages. deferredRAMByDatabase.get(D) is now null (step 3 removed it), so the per-database part is skipped, but addDeferredRAMTotal still subtracts those bytes from the JVM-wide total again, even though they were already folded into step 3's bulk residual release.

The JVM-wide deferredRAMBytes total ends up double-decremented and can go negative. getDeferredRAMBytes() (PageManager.java) returns it unclamped, and the cap check deferredRAMBytes.get() >= maxDeferredRAM in awaitDeferredBacklogUnderCap would then read false for every suspended database in the process until enough new deferrals push the (negative) total back over the cap - i.e. the 4728 OOM protection this whole PR is about could be silently defeated for other, unrelated suspended databases until the counter recovers. getDeferredRAMBytesOf already clamps to 0, but the total that the cap actually reads does not have the same guard.

This requires a fairly specific interleaving (close/drop of a database racing the tail of its own resume), so it may be rare in practice, but the PR already treats an analogous race (aBatchPolledWhileTheDatabaseIsPurgedIsNeverLeftDeferredForIt, racing flushPagesFromQueueToDisk against removeAllPagesOfDatabase) as worth a dedicated 200-iteration stress test - this is the same shape one level up (resumeFlushing's Phase 1 vs. the purge), and I don't see a test that races those two specifically.

Possible fix: only call addDeferredRAMTotal(delta) in the negative-delta branch when bytes != null (mirroring 'a release never touches accounting it doesn't own' for the total the same way it's already done for the per-database entry). That would make releaseResidualDeferredRAM's bulk release and the loser's straggling per-page releases mutually exclusive without adding a new lock.

Smaller notes

  • getDeferredRAMBytesOf clamps negative readings to 0 (Math.max(0L, bytes.get())), which is good defensive practice for the gauge, but it also means a drift like the one above would be invisible in the per-database metric while still corrupting the total the cap actually enforces - worth the same clamp (or at least an assertion/WARNING) on deferredRAMBytes itself, since that's the number the backpressure decision is made from.
  • Nit: awaitDeferredBacklogUnderCap's early-exit uses !(database instanceof final Database db) and silently skips backpressure for any BasicDatabase that isn't a Database. Presumably unreachable for real flush-pipeline callers (pages only ever come from local databases), but a one-line comment saying so explicitly would save a future reader the same trip through BasicDatabase/Database I just took.
  • The 300-iteration (aReleaseRacingTheParkIsNeverMissed) and 200-iteration (aBatchPolledWhileTheDatabaseIsPurgedIsNeverLeftDeferredForIt) race tests spin up and join real threads per iteration; not egregiously slow, but if they push the engine module's regular run time up noticeably it might be worth the slow tag per the repo's own convention rather than leaving that judgment to CI wall-clock.

What I did not flag

The signal/guarded-wait shape in FlushPageIndex (counter object doubling as its own monitor, guard re-read inside synchronized), the placement of awaitDeferredBacklogUnderCap strictly before the page-manager lock in both publishPages and writePages, the downward-crossing-only signal in addDeferredRAMTotal (bounds the thundering herd), and the suspendLock-then-detach ordering in both resumeFlushing Phase 2 and removeAllPagesOfDatabase all check out against the invariants the comments claim for them.

I read the diff and the surrounding source statically (this sandbox couldn't run mvn to execute the new tests), so treat the race above as traced through the actual lock structure and believed reachable rather than reproduced.

…counter actually still holds

Review round 4 found a real double-release, and its diagnosis was right: addDeferredRAM moved the JVM-wide
total unconditionally, even when the per-database entry was already gone. releaseResidualDeferredRAM takes a
database's whole remaining charge in ONE getAndSet(0) plus subtraction, and it is not mutually exclusive with
the per-page releases of that same database's resume - Phase 1 walks the deferred batches holding only
replayDrainLock, while the purge takes neither that nor anything else Phase 1 holds. A close or drop landing
mid-resume therefore took bytes Phase 1 had not released yet, and Phase 1 released them again.

That drives the total NEGATIVE, and the total is what the cap is read from: `total >= cap` answers false for
every suspended database in the process until enough new deferrals climb back over it, so the #4728 OOM
protection is silently off for databases that have nothing to do with the one being purged.

The suggested fix - skip the total when the entry is null - is NOT sufficient, and the new test says so: it
still failed at iteration 25, because the AtomicLong reference can be read BEFORE the purge removes the entry
and used after. The guard has to be on the VALUE. The per-database counter is now the authority on what may be
released: the take is atomic and clamped at zero (getAndAccumulate), and only what it actually held moves off
the total. Every interleaving of the bulk take and the per-page ones now sums to the same thing.

Also from the same round: deferredRAMBytes gets a negative-value repair with a one-shot WARNING, since unlike
the per-database gauge (cosmetic, already clamped) it is the number the backpressure decision is made from.
That repair would HIDE this whole class of bug from the tests - a double release lands on zero after the clamp,
indistinguishable from a correct run - so the repair count is exposed and asserted to stay zero.

New test aPurgeRacingItsOwnResumeReleasesTheSameBytesOnlyOnce: it fails at iteration 0 on every run against
the unfixed code, and at iteration 25 against the insufficient fix. 500 iterations green after this one.

Nits from the same round: repaired the stale link left by the rename to releaseResidualDeferredRAM, and said
explicitly why awaitDeferredBacklogUnderCap's `instanceof Database` is a cast rather than a filter. NOT taking
the @tag("slow") suggestion: the two race classes run in 1.2 s and 0.9 s, far under the bar CLAUDE.md sets.

Full engine suite green (12003 tests).
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Round 4's double-release finding was real and reproducible - thanks, that one was well traced. Fixed in 21da075, but the suggested fix turned out not to be enough:

  • Skipping addDeferredRAMTotal when bytes == null still failed the new test at iteration 25. The AtomicLong reference can be read before releaseResidualDeferredRAM removes the entry and used after it, so the guard has to be on the value, not the entry.
  • The per-database counter is now the authority on what may be released: the take is atomic and clamped at zero (getAndAccumulate), and only what the counter actually still held moves off the JVM-wide total. Every interleaving of the bulk take and the straggling per-page ones now sums to the same thing.

New regression test aPurgeRacingItsOwnResumeReleasesTheSameBytesOnlyOnce (100 iterations of resume-racing-purge on a 400-page batch): fails at iteration 0 on every run against the unfixed code, at iteration 25 against the insufficient fix, and is green for 500 iterations across 5 runs with the value-based take.

On the smaller notes:

  • deferredRAMBytes now gets the negative-value guard you asked for: a repair to zero plus a one-shot WARNING, since unlike the per-database gauge it is the number the backpressure decision is made from. One consequence worth flagging: that repair would otherwise hide exactly this class of bug from the tests, because a double release lands on zero after the clamp and looks like a correct run - so the repair count is exposed package-private and the race tests assert it stays zero.
  • Stale {@link #resetDeferredRAMIfDrained} repaired (leftover from the rename in commit 2), and awaitDeferredBacklogUnderCap's instanceof Database now says explicitly that it is a cast rather than a filter.
  • Not taking the @Tag("slow") suggestion: measured, Issue6200PerDatabaseDeferredBacklogTest runs in 1.2 s and Issue6199DrainWakeupTest in 0.9 s, well under the "noticeably long" bar CLAUDE.md sets for that tag.

Full engine suite green: 12003 tests, 0 failures.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review of #6223

I read through the full diff (GlobalConfiguration, FlushPageIndex, PageManager, PageManagerFlushThread, and the four test files) with the working tree already at the tip of this branch, so I could check call sites and surrounding context rather than just the patch hunks.

Overall assessment

This is a well-reasoned pair of fixes. The core ideas check out:

  • Parking on FlushPageIndex's per-database counter as its own monitor (guarded wait, re-read under the lock) is a textbook-correct pattern, and release() only taking the lock on the transition to drained keeps the hot path essentially unchanged (a volatile decrement + comparison).
  • Moving the Replica stuck in STALLED #4728 cap enforcement to the committer side (awaitDeferredBacklogUnderCap, called before PageManager.lock()) genuinely fixes the described bug: I verified publishPages calls it outside lock()/unlock(), and traced all 8 call sites of PageManager.writePages - only the two LSMTreeIndexCompacted callers pass asyncFlush=true (the only path that can ever land in deferredByDatabase); every other caller passes false and goes straight to a synchronous flushPage() that never touches the deferred backlog, so the new gate covers exactly the paths that need it and nothing else.
  • The addDeferredRAM/addDeferredRAMTotal/releaseResidualDeferredRAM accounting is subtle (a per-database clamped take-what's-still-there release, feeding a derived JVM-wide total) but internally consistent, and the "downward crossing" signal logic is correct under concurrent getAndAdd because AtomicLong operations are linearizable - exactly one release call will observe previous >= cap && previous+delta < cap for any given crossing, so the signal can't be silently missed by two updates splitting the crossing.
  • resumeFlushing's Phase 1 change (always run the finally release even when the database closed mid-unsuspend, instead of continue/break-ing past it) is a real fix for the drift the old blanket reset was compensating for, and the lock ordering (suspendLock before batch.pages, documented and consistent) looks correctly threaded through flushPagesFromQueueToDisk, resumeFlushing, and removeAllPagesOfDatabase.

Minor finding (low severity, correctness of a latency guarantee, not of results)

FlushPageIndex.removeAllOfDatabase drops the per-database entry from pending and notifies on the counter, but it does not zero the counter's own int value first:

```java
void removeAllOfDatabase(final BasicDatabase database) {
pages.keySet().removeIf(pageId -> database.equals(pageId.getDatabase()));
final AtomicInteger counter = pending.remove(database);
if (counter != null)
synchronized (counter) {
counter.notifyAll();
}
}
```

There's a narrow window in awaitDrain where a racing removeAllOfDatabase can fire its (one-shot) notifyAll() before the waiter enters synchronized (counter):

```java
void awaitDrain(final BasicDatabase database, final long maxWaitMillis) throws InterruptedException {
...
final AtomicInteger counter = pending.get(database); // (1) resolves the counter, non-null
if (counter == null) return;
// <- a concurrent removeAllOfDatabase's pending.remove() + notifyAll() can land here
synchronized (counter) {
if (counter.get() <= 0) // (2) counter's int was never touched by removeAllOfDatabase, so this is still the stale positive value
return;
counter.wait(maxWaitMillis); // parks anyway; nothing will ever notify it again
}
}
```

Since the bulk purge never decrements the counter (it just drops the map entry), the guard re-read at (2) doesn't observe "drained" and the waiter parks despite the signal having already fired. This is bounded, not a hang - maxWaitMillis still applies, and the next call to awaitDrain for that database gets a fresh pending.get that correctly returns null - so it degrades to exactly the old poll-and-sleep behavior for one cycle, which the class javadoc already calls out as the accepted fallback for "a hypothetical lost notification." Practically this only matters if some thread is awaiting a database's drain concurrently with another thread purging that same database (via close()/drop()), which may not be reachable in the current call graph, and even if it is, the cost is one bounded wait (10ms/1ms in production; the tests only stretch this interval, so they wouldn't be affected by this specific race in an observable way).

Trivial fix if you want to close it: counter.set(0) right before (or as part of) the synchronized (counter) { counter.notifyAll(); } block in removeAllOfDatabase, so a racing guard re-read sees the drained state regardless of ordering.

Test coverage

Very thorough for concurrency-sensitive code: the new Issue6199DrainWakeupTest distinguishes a real notify from the fallback poll by stretching the interval to a minute (a good technique), and Issue6200PerDatabaseDeferredBacklogTest exercises the purge/resume races that the commit history says were found in earlier review rounds (aBatchPolledWhileTheDatabaseIsPurgedIsNeverLeftDeferredForIt, aPurgeRacingItsOwnResumeReleasesTheSameBytesOnlyOnce), including asserting the drift-repair counter stays at zero rather than just checking the clamped total (which would hide a double-release). Issue5326ApplyChangesPendingFlushTest's wait condition fix (drained-pipeline check instead of deferredRAMBytes > 0) is a legitimate flake fix, not just a rename.

I didn't find anything to flag on the security front (no external input, no serialization changes), and didn't spot a case where the new code allocates on the hot per-page path beyond what already existed (the synchronized in release()/addDeferredRAMTotal only fires on state transitions, not per page).

I was unable to run a full mvn verify in this sandbox (network/tool restrictions), so I'm relying on static reading rather than a green build; the PR description says the full engine suite (12003 tests) is green, which I have no reason to doubt given the depth of the tests added.

…r, not only in the map it just left

Review round 5. removeAllOfDatabase dropped the map entry and signalled, but never zeroed the counter's own
value. A waiter that resolved that counter BEFORE the removal enters the monitor AFTER the one-shot notifyAll
has already fired, and what it re-reads there is the counter object - the drained map entry it would otherwise
consult is gone - so it saw a stale positive count and parked through a signal it could never be sent again.
Bounded rather than fatal (the fallback interval still expires, and the waiter's next call resolves no counter
at all), but it is precisely the wake-up that notification exists to deliver. The counter is now zeroed inside
the monitor, before the notify.

Regression test aPurgeRacingTheParkIsNeverMissed. Worth recording how it got there: the obvious version - one
waiter per round, purge immediately after - did NOT discriminate the fix at all, passing three runs in three
against the unfixed code, because the window is a handful of instructions and an unaligned waiter is almost
never inside it. Releasing 12 waiters and the purge from ONE gate, over 80 rounds, fails about one run in
three. The round is deliberately no larger than it needs to be: 24 waiters over 150 rounds reproduced at the
same rate for four times the thread churn, and this runs in the shared engine-suite JVM where that churn is a
cost every other test pays.

Also fixed a flake this branch introduced. theResidualDrainKeepsItsHardDeadline asserted that a wait bounded
by a 200 ms deadline came back inside 15 s; in the full suite it measured 24 s and failed, with the code
behaving correctly - after ~12000 tests in one JVM a stop-the-world pause of tens of seconds is not exotic,
and the class runs in 1.2 s in isolation. The deadline being honoured is already asserted by the return value;
the elapsed check is a tripwire against an UNBOUNDED wait and now has a bound that says so.

Full engine suite green (12004 tests).
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Round 5's finding is valid and fixed in 3a2778d: removeAllOfDatabase now zeroes the counter inside the monitor before notifying, so a waiter that resolved it before the removal finds the drained state on the object rather than parking through a signal that already fired.

Two things worth recording from writing the regression test, since both bear on how much the test is worth:

  • The obvious test did not discriminate the fix. One waiter per round with the purge fired immediately after passed three runs in three against the unfixed code - an unaligned waiter is almost never inside a window that is a handful of instructions wide. aPurgeRacingTheParkIsNeverMissed releases 12 waiters and the purge from one gate over 80 rounds, and fails about one run in three against a purge that notifies without zeroing. It is sized no larger than it needs to be: 24 waiters over 150 rounds reproduced at the same rate for four times the thread churn, which the shared engine-suite JVM pays for.
  • The full suite caught a flake this branch introduced, unrelated to your finding. theResidualDrainKeepsItsHardDeadline asserted that a wait bounded by a 200 ms deadline returned inside 15 s; in the suite it measured 24 s and failed, with the code behaving correctly - the class runs in 1.2 s in isolation, but after ~12000 tests in one JVM a stop-the-world pause of tens of seconds is not exotic. The deadline being honoured is already asserted by the return value; the elapsed check is a tripwire against an unbounded wait, and its bound now says so instead of doubling as a latency assertion.

Full engine suite green: 12004 tests, 0 failures.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

I read through the full diff plus the surrounding, unchanged parts of PageManagerFlushThread, FlushPageIndex and PageManager (checked out the merge commit locally rather than trusting the diff hunks alone), and traced the main races by hand: the guarded-wait shape in FlushPageIndex.awaitDrain/release, the per-database vs. JVM-wide accounting in addDeferredRAM/releaseResidualDeferredRAM, the suspendLock-guarded ordering between flushPagesFromQueueToDisk's defer decision and resumeFlushing/removeAllPagesOfDatabase's flag-clear+detach, and the placement of awaitDeferredBacklogUnderCap relative to the page-manager lock in publishPages/writePages.

Correctness. I didn't find a bug that survives the interleavings I traced. A few things I specifically stress-tested on paper and came away satisfied with:

  • The counter.wait()/counter.notifyAll() guarded-wait in FlushPageIndex is correct even though release()'s decrementAndGet() happens outside the synchronized block — AtomicInteger gives the needed visibility, and the monitor only has to make the notify ordering safe, which it does (re-reading counter.get() inside synchronized(counter) closes the "release lands between check and park" gap you called out in the javadoc).
  • removeAllOfDatabase zeroing the counter before notifyAll (not just notifying) is necessary, and the aPurgeRacingTheParkIsNeverMissed test genuinely exercises that window rather than being vacuous (I agree with the "one gate, many waiters" reasoning for why a single unaligned waiter wouldn't hit it).
  • The double-release race fixed in the round-4 commit (addDeferredRAM's clamp-at-zero getAndAccumulate instead of a plain null check) is real: a purge's releaseResidualDeferredRAM and a resume's Phase 1 per-page releases aren't mutually exclusive (different locks - replayDrainLock vs. nothing), and a null check on the map entry doesn't cover "reference read before removal, used after." The fix looks right, and the test asserting deferredRAMDriftRepairs.get() == 0 (rather than just that the total lands on zero) is the correct thing to assert — a clamped double-release would otherwise look identical to a correct run.
  • awaitDeferredBacklogUnderCap being called before lock() in publishPages, and the separate writePagesNoBackpressure split so publishPages doesn't pay the wait twice, both check out against the stated goal (never block a committer of an unrelated database inside the JVM-wide lock).
  • The suspendLock-guarded ordering (flag-clear/detach in resumeFlushing Phase 2 and in removeAllPagesOfDatabase, both using the same lock the defer path checks isSuspended under) correctly prevents a batch from being deferred into a queue that's already been forgotten.

One thing worth a sentence in the PR description rather than a code change: resumeFlushing's Phase 4 (releaseResidualDeferredRAM) and the flag-clear (Phase 2) are not inside the same try/finally as Phase 1's per-page loop, so an unexpected exception escaping Phase 1 (something other than the DatabaseMetadataException/InterruptedIOException/IOException it already handles per page) would abort Phase 2/3/4 entirely, leaving that database's remaining deferred batches undetached from pageIndex (permanent hang on close) and its residual RAM charge stuck until an eventual removeAllPagesOfDatabase. I want to flag this only because it's a real gap, not because it's new: the pre-PR code had the identical shape (same per-page try/finally, same unprotected Phase 2/3/4 tail), and the old blanket deferredByDatabase.isEmpty() → reset safety net wasn't reachable in that scenario either, so this PR doesn't regress anything here - the per-database residual tracking is if anything a strict improvement (self-heals at close instead of never). Not a blocker, just noting it's still open.

Design. Moving the cap enforcement from the drain side (stop draining everyone) to the producer side (hold only the suspended database's own committers, before the JVM-wide lock) is the right fix for #6200 — the analysis of why the issue's own proposed fix (selective re-queue) doesn't work is convincing (reordering a batch within its own database's queue reintroduces the #4544 stale-overwrite shape). Same for #6199: replacing Thread.sleep(1)/Thread.sleep(10) polling with a signal parked on the one counter that already goes down on every release is a clean way to remove the JVM-wide-lock-held sleep without adding a new lock.

Performance. The hot path (release()) still pays only a volatile decrement + comparison per page, taking the monitor exclusively on the page that drains the pipeline — as advertised. addDeferredRAM's positive branch is a single computeIfAbsent + addAndGet, and awaitDeferredBacklogUnderCap's fast path for a non-suspended database is two volatile map reads before the lock, which is negligible next to a page write.

Security. Nothing exposed here — this is purely internal flush-pipeline bookkeeping, no new input surface.

Test coverage. This is the strongest part of the PR. Issue6199DrainWakeupTest and Issue6200PerDatabaseDeferredBacklogTest don't just assert the happy path — they specifically race the signal against the park (300 iterations), race a purge against a resume (100 iterations, asserting the drift-repair counter stays zero rather than just the total), and race a purge against a poll (200 iterations). The commit messages document measured reproduction rates against the unfixed code (e.g. "fails about one run in three, around iteration 100"), which is exactly the kind of evidence that distinguishes a real regression test from a vacuous one. PageManagerFlushSuspendBackpressureTest was correctly moved to assert the new enforcement point (committer-side, per-database) rather than the old queue-draining shape.

Minor/nit-level, non-blocking:

Overall this is a very carefully reasoned concurrency fix with unusually good self-review discipline (the 6 rounds visible in the commit history each caught a genuine race, not a style nit) and the regression tests are the real thing. I'd be comfortable with this merging once CI is green.

… strands the rest of the resume

Review round 6 flagged this as pre-existing and non-blocking. Closing it rather than leaving it open, because
it sits inside the accounting this branch reworks and the cost is three lines.

resumeFlushing's Phase 1 contains every failure it expects, per page: a dropped file, an interrupt, an I/O
error. Anything else escaping it aborted Phases 2 to 4 outright. The batches deferred DURING Phase 1 - the
ones only Phase 2 detaches, since Phase 1 takes the pre-existing backlog on entry - then stayed in
deferredByDatabase with their pages pinned in pageIndex, so the next close of that database waited on a drain
that could never happen, and their charge stayed on the cap that throttles every suspended database.
setSuspended's own finally heals the suspension COUNT, which is exactly what makes the rest easy to miss.
Phases 2 to 4 now run in a finally; they are pure bookkeeping and cannot fail, and the exception still
propagates after them.

Also from the same round: the throttle WARNING reports the elapsed hold rather than the constant threshold
that triggered it, which is the number an operator came for.

The test is worth a note. The obvious version - trap a deferred batch, resume on the calling thread, assert
the state afterwards - PASSED against the unfixed code: Phase 1 detaches the pre-existing backlog itself, so
single-threaded there is nothing left for Phase 2 to lose. It only discriminates once a batch is deferred
WHILE Phase 1 runs, which needs the resume on its own thread and the defer path driven underneath it. In that
shape it fails 3 runs out of 3 without the fix.

Not taking one remaining suggestion from the round: the per-database gauge of item 2 of #6087 is deliberately
left to #6087 itself - this PR provides the number it needs (getDeferredRAMBytesOf), and wiring the Micrometer
tag belongs with the rest of that item.

Full engine suite green (12005 tests).
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Round 6's Phase-1 gap is closed in fa3fcad rather than left open - it sits inside the accounting this branch reworks and the fix is three lines. Phases 2 to 4 now run in a finally: they are pure bookkeeping, cannot fail, and the exception still propagates after them.

The test for it is worth a note, because the obvious version was useless. Trapping a deferred batch and resuming on the calling thread passed against the unfixed code: Phase 1 detaches the pre-existing backlog itself, so single-threaded there is nothing left for Phase 2 to lose. It only discriminates once a batch is deferred while Phase 1 runs - the resume on its own thread, the defer path driven underneath it - and in that shape it fails 3 runs out of 3 without the fix.

The WARNING now reports the elapsed hold instead of the constant threshold, as suggested.

On the last point: the per-database Micrometer gauge is deliberately left to #6087 (open) rather than wired here. This PR provides the number that item needs (PageManager.getDeferredRAMBytesOf), which was the blocker - the number did not exist per database - and tagging the gauge belongs with the rest of that item.

Full engine suite green: 12005 tests, 0 failures.

@codacy-production

codacy-production Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 medium

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
BestPractice 1 medium

View in Codacy

🟢 Metrics 47 complexity

Metric Results
Complexity 47

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.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

This is an unusually well-documented and self-critical PR — the javadoc essentially doubles as a design rationale, and the two new regression tests (Issue6199DrainWakeupTest, Issue6200PerDatabaseDeferredBacklogTest) directly target the races they claim to fix, including several "race the signal against the park N times" stress tests. I read FlushPageIndex.java, PageManager.java, and PageManagerFlushThread.java in full, plus all four touched/added test files.

Correctness

  • FlushPageIndex.awaitDrain — the guarded-wait pattern (re-read the counter inside synchronized(counter) before parking) correctly closes the classic "check-then-park" race with release()'s notifyAll(). The reuse of the per-database AtomicInteger itself as the monitor is a nice touch that avoids a second map of lock objects and the registration-order race that would come with it.
  • removeAllOfDatabase zeroing the counter before notifyAll(), while holding the counter's own monitor, correctly handles the case where a waiter resolves the counter reference just before the map entry is removed and enters the monitor just after the signal fires — aPurgeRacingTheParkIsNeverMissed stress-tests exactly this window (80 rounds × 12 threads) and the comments explain why a plain "notify without zeroing" would fail about 1/3 of the time. Good adversarial test design.
  • awaitDeferredBacklogUnderCap being called before the page-manager lock (in publishPages and writePages) is the crux of the The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200 fix, and the comments correctly identify why doing it one line later (inside lock()) would reintroduce the JVM-wide stall. This is verified by aDatabaseThatIsNotSuspendedIsNeverHeldByAnotherDatabaseBacklog.
  • The per-database vs. JVM-wide deferred RAM split (addDeferredRAM/releaseResidualDeferredRAM) correctly avoids the double-release hazard between a resume's per-page releases and a concurrent purge's bulk release, by making the per-database AtomicLong (not the total) the authority on what may still be taken — getAndAccumulate(releasing, (cur, amt) -> cur - Math.min(cur, amt)) is the right primitive here, and aPurgeRacingItsOwnResumeReleasesTheSameBytesOnlyOnce (100 iterations) plus the deferredRAMDriftRepairs counter (rather than just the total) actually catches a double-release instead of the clamp silently hiding it.

Minor / residual gap (not blocking)

  • In resumeFlushing, the new outer finally block (running Phases 2–4 even if Phase 1 throws) closes the "whole resume aborted" failure mode, but it doesn't retry or requeue pages that were mid-batch when an unexpected exception hits — those pages are silently dropped from deferred/batch.pages without going through removeFromFlushIndex/bumpFlushProgress. releaseResidualDeferredRAM in Phase 4 correctly zeroes the RAM accounting regardless, but the pageIndex per-database pending counter for those specific abandoned pages would stay elevated until the database eventually closes (bounded, and WAL durability is unaffected since notifyPageFlushed was never called for them either — so no data loss, just a stuck pendingOf() for that database until close). The new test (anUnexpectedFailureWhileWritingTheBacklogStillFinishesTheResume) happens to only exercise the trap as the last entry in the batch, so it doesn't cover a mid-batch abandonment. Given this only triggers on a genuinely unexpected exception (already a bug elsewhere) and is a strict improvement over the prior "abort everything" behavior, I wouldn't block on it, but it's worth a one-line callout in the javadoc if it's a known/accepted residual limitation rather than an oversight.
  • Pure style nit: PageManagerFlushThread.resumeFlushing's outer try { ... } finally { (around line 672) and the body of that finally are indented two spaces short of the surrounding method body (6 spaces instead of 4). No functional impact, just inconsistent with the rest of the file's formatting.

Performance

The stated goal (avoid Thread.sleep(1) under the JVM-wide page-manager lock, and stop letting one suspended database's backlog throttle unrelated databases) is achieved by construction: the drains now park on a per-database monitor instead of polling, and the deferred-backlog wait moved to the producer side, explicitly before the lock is taken. The bounded fallback intervals are kept as safety nets rather than the primary mechanism, which is the right call — no regression in worst-case behavior, and the common case goes from poll-latency-bound to signal-latency-bound.

Test coverage

Strong. The new tests exercise the actual race windows (not just the happy path) with repeated-iteration stress tests, and the modified PageManagerFlushSuspendBackpressureTest/Issue5326ApplyChangesPendingFlushTest were updated to match the moved enforcement point rather than just relaxed to pass. I did not execute the suite myself in this environment, but the PR description states the full engine module (11998 tests) was run green, including the other issue-specific regression tests this change touches.

Security

No concerns — this is internal flush-pipeline synchronization with no external input surface.

… of the deferred backlog

Review round 7 raised this as a residual of the previous commit's finally: Phases 2 to 4 now always run, but a
page failing mid-batch still left every page AFTER it in that batch without its release - keeping its pageIndex
entry, so the database's pending count stayed above zero and its next close waited out
arcadedb.flushAllPagesTimeout before giving up. Contained rather than documented: an unexpected failure is now
caught per page like the I/O ones, so the loop always reaches the end of the backlog, and the FIRST one is
re-raised once the backlog is drained and the suspension cleared, so the caller still learns the resume failed.

One case is left uncovered on purpose and now says so in the code: the per-page finally itself throwing. It
abandons the pages after it, bounded - the close gives up on the timeout and preserves the WAL, so they are
recovered on the next open rather than lost - and covering it would put a try/finally around the release of
every deferred page to defend against three field reads on a MutablePage.

Also from the same round: the indentation of the outer try/finally, off by two since the previous commit.

UNRELATED, found by the full suite and fixed because it is a test that cannot pass its own premise:
Issue5279ConcurrentUpdateTest.concurrentEdgeCreationBetweenOwnVerticesNeverConflicts tolerates one conflict
(the edge transaction runs at attempts=1) and then asserts the FULL edge count, so the run where the tolerated
conflict actually happens fails at the count - 160 against 161 - instead of at the tolerance meant to absorb
it. The expected count now subtracts the conflicts, which is what the tolerance already implies.
@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review of PR 6223

This is an unusually well-reasoned concurrency fix - the commit history shows the design being pressure-tested against real races (the aPurgeRacingItsOwnResumeReleasesTheSameBytesOnlyOnce, aBatchPolledWhileTheDatabaseIsPurgedIsNeverLeftDeferredForIt and aPurgeRacingTheParkIsNeverMissed tests all document reproducing the bug they guard against at a measured failure rate before the fix). A few notes below, mostly confirmations rather than blockers.

Code quality / design

  • Moving the issue-4728 cap enforcement from the drain side (flushPagesFromQueueToDisk) to the committer side (awaitDeferredBacklogUnderCap, called before PageManager.lock()) is the right fix for issue-6200 - it correctly separates the cap being JVM-wide because heap is, from the response needing to be, since only suspended databases can grow the backlog.
  • FlushPageIndex's per-database AtomicInteger doubling as its own monitor (awaitDrain/release) is a nice way to avoid a parallel lock-object map, and the guarded re-read of the counter inside the monitor correctly closes the release-vs-park race.
  • The addDeferredRAM/releaseResidualDeferredRAM split, with the per-database AtomicLong as authority for what can be released (via getAndAccumulate clamped at zero) is the correct fix for the double-release-drives-total-negative bug from round 4 - good catch that a null check on the map entry wasn't sufficient (the entry reference can be read before removal and used after).
  • repairNegativeDeferredRAM clamping-and-reporting rather than just clamping is a good call - a silent clamp would have made the double-release bug in round 4 indistinguishable from correct behavior in the regression test, and the test does correctly assert deferredRAMDriftRepairs.get() == 0 rather than only asserting the total is non-negative.

Potential residual risk (already documented, flagging for visibility)
In resumeFlushing's Phase 1, the per-page finally (addDeferredRAM / removeFromFlushIndex / bumpFlushProgress) is the one thing not wrapped in its own failure containment - if any of those three throws (e.g. a null page, as the test simulates), the exception escapes the per-page loop, abandons releasing every later page in the backlog, and replaces the wrapped unexpected exception with the raw one. The code comment acknowledges this explicitly as an accepted residual rather than an oversight, and the realistic trigger surface is narrow (three field/map reads on an already-validated MutablePage), so this reads like a reasonable trade-off - just flagging it since it is a real, if narrow, gap in the guarantee that resume always finishes Phases 2 through 4.

Worth double-checking
awaitDeferredBacklogUnderCap is documented as must never be called with the page-manager lock held. PageManager.writePages() now calls it unconditionally when asyncFlush is true, and two LSMTreeIndexCompacted call sites (around lines 240 and 285) pass asyncFlush=true. Worth confirming those compaction call sites don't hold any lock that resumeFlushing needs to make progress (suspendLock(database) / replayDrainLock(database)) - otherwise a compaction thread parked on the cap could deadlock against a resume trying to drain it. Given the rest of the PR's rigor this is likely already fine, but it wasn't verifiable purely from the diff.

Tests
Test coverage is thorough and the races are reproduced with measured failure rates against the unfixed code rather than just asserted against the fixed code, which is exactly right for this kind of change. A few of the new tests use short bounded-await windows (300-500 ms) to assert not-yet-released. Given this same PR had to loosen an unrelated timing assertion from 15s to 1 minute after it flaked on a stop-the-world pause in the full 12000-test suite (theResidualDrainKeepsItsHardDeadline), it might be worth a quick sanity check that these newer windows hold up under the same shared-JVM load - though the risk direction here is the test running slow rather than flaking false-red, since a scheduling stall only delays the release further.

Other
No new dependencies, no leftover System.out or TODOs, ATTRIBUTIONS.md/NOTICE not implicated. GlobalConfiguration javadoc for FLUSH_SUSPEND_MAX_DEFERRED_RAM is updated to match the new per-database throttling behavior.

Overall: solid fix for both issues, with the accounting correctness (the hardest part of this change) backed by tests that actually pin the races rather than just exercising the happy path.

…ce, and a stress test stops overclaiming

Review round 8, neither point a blocker.

The bounded awaits that assert a wait was RELEASED now allow 60 s rather than 15 s, and the drain fallback they
are measured against moves to ten minutes to keep the gap an order of magnitude wide. A generous bound on a wait
that is expected to succeed cannot turn a passing run red; a tight one can, which this branch already learned
when a 15 s bound met a 24 s stop-the-world pause in the shared 12000-test JVM. The short windows asserting
"not released yet" are left alone: a scheduling stall only delays the release further, so it strengthens them.

aPurgeRacingTheParkIsNeverMissed claimed to reproduce its bug "about one run in three". Re-measured after the
timeout change: 1 run in 12 on a loaded machine, against 2 in 6 measured earlier on an idle one. Samples that
small do not distinguish the two, so the javadoc now states both and says to rely on the lower one, and says
plainly that the guarantee rests on the argument in removeAllOfDatabase rather than on this test catching every
regression of it. A stress test that overstates its own power is worse than one that admits it.

Also answered in code rather than only in the PR thread: awaitDeferredBacklogUnderCap's javadoc now records
which locks its two entry points hold when they park, because "must not be called with the page-manager lock
held" is only half the requirement - the other half is that a parked caller must hold nothing the resume needs
to release the backlog it is waiting for. Checked: a committer arrives before publishPages takes the lock,
compaction arrives after updatePageVersion released it, nothing outside the flush thread can hold suspendLock or
replayDrainLock, the resume takes no database lock, and a parked waiter has released deferredRAMLock by
definition.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Round 8's "worth double-checking" is checked, and the answer is recorded in the code rather than only here: awaitDeferredBacklogUnderCap's javadoc now states which locks each entry point holds when it parks, because "must not hold the page-manager lock" is only half the requirement - the other half is holding nothing the resume needs to release the backlog being waited on.

  • A committer arrives through publishPages, before its lock().
  • Index compaction arrives through writePages, after updatePageVersion has taken and released that same lock - verified at both LSMTreeIndexCompacted call sites.
  • Nothing outside PageManagerFlushThread can hold suspendLock/replayDrainLock (both private), the resume takes no database lock, and a parked waiter has released deferredRAMLock by definition.
  • So a parked caller holds only its own transaction's file locks, which the resume never asks for. No cycle.

Worth noting this direction got less blocking, not more: before this PR a compaction thread could block unboundedly in queue.offer at the same point, and the old drain-side gate is precisely what filled that queue during a suspension.

On the timing note - acted on, and you were right to raise it:

  • The awaits asserting a wait was released now allow 60 s (fallback moved to 10 min to keep the gap an order of magnitude wide). A generous bound on an expected-success wait cannot turn a passing run red; a tight one can. The short "not released yet" windows are unchanged, since a stall only strengthens them.
  • Re-measuring after that change turned up something I had overclaimed: aPurgeRacingTheParkIsNeverMissed reproduces its bug in 1 run out of 12 on this (heavily loaded) machine, against the 2-in-6 I measured earlier on an idle one. The javadoc now states both figures, says to rely on the lower, and says plainly that the guarantee rests on the argument in removeAllOfDatabase rather than on this test catching every regression.

Separately, the full suite here also turned up two failures I did not chase into this PR, because neither is reachable from this change and both pass 3/3 in isolation: AsyncShutdownDrainTest.closeDoesNotHangOnAWedgedAsyncWorker (27.4 s against a 15 s bound - the same stall signature) and DeltaScanVectorSearchTest.deltaClearedAfterRebuild. Five earlier full-suite runs of this same branch were green on both. Flagging them so CI's verdict on a clean runner is the one that counts.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review of #6223 (tip: 697558a)

This has already been through eight rounds of very thorough review in this thread, and I re-traced the same core invariants against the current tip (guarded-wait in FlushPageIndex.awaitDrain/release, the addDeferredRAM/releaseResidualDeferredRAM clamped-take accounting, the suspendLock-ordering between flushPagesFromQueueToDisk's defer decision and resumeFlushing/removeAllPagesOfDatabase, and the placement of awaitDeferredBacklogUnderCap relative to PageManager.lock()). I didn't find a new correctness bug - every race raised in earlier rounds (double-release driving the total negative, the purge-vs-defer window in removeAllPagesOfDatabase, the counter not being zeroed before notifyAll, Phase 1's unexpected-exception abandoning Phases 2-4) is fixed in the current code and backed by a regression test that's documented as reproducing the pre-fix failure.

One correction to round 8's answer, in PageManagerFlushThread.java (awaitDeferredBacklogUnderCap javadoc, ~line 953-954):

index compaction arrives through writePages, after updatePageVersion has taken and released that same lock

PageManager.updatePageVersion does not take the page-manager lock itself - it's a plain method with no lock()/unlock() calls (only validateAndBumpVersions, the normal transaction-commit path, wraps it in lock()/unlock()). Both LSMTreeIndexCompacted call sites this sentence is about (LSMTreeIndexCompacted.java:239-240 and :284-285) call pageManager.updatePageVersion(currentPage, true) directly, bypassing validateAndBumpVersions entirely, so no lock is taken or released around it on that path.

The conclusion the javadoc is defending - that a compaction thread parked in awaitDeferredBacklogUnderCap can't be holding the page-manager lock - is still correct, just for a different and simpler reason than the one stated: lock()/unlock() are protected methods on PageManager (via LockContext), and com.arcadedb.index.lsm is a different package with no subclass access, so index code is structurally unable to acquire that lock at all, regardless of what updatePageVersion does internally. Worth fixing the sentence so a future reader (or refactor) doesn't trust the 'verified... after updatePageVersion has taken and released that lock' claim for a code path where it doesn't apply.

Everything else - design, performance, test coverage, security - matches what the last several rounds already confirmed; I don't have anything to add there. Nice work getting this level of scrutiny into a concurrency fix.

… lock is structural, not incidental

Review round 9 caught a wrong claim in the javadoc round 8 added. It said compaction reaches
awaitDeferredBacklogUnderCap "after updatePageVersion has taken and released that same lock", and
PageManager.updatePageVersion does not lock at all - only validateAndBumpVersions wraps it, and the two
LSMTreeIndexCompacted call sites bypass that and call updatePageVersion directly.

The conclusion held, for a better reason than the one written down: LockContext.lock() is PROTECTED, and
com.arcadedb.index.lsm neither shares the package nor subclasses PageManager, so index code cannot acquire that
lock however it is refactored. Recorded that instead - a reader who trusts the old sentence would be trusting a
property of one call path rather than of the type system.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Round 9 is right and the correction is in 893168f. Verified before changing it: PageManager.updatePageVersion contains no lock()/unlock() - only validateAndBumpVersions wraps it, and both LSMTreeIndexCompacted call sites bypass that and call updatePageVersion directly. My round-8 sentence asserted a property of one call path as if it were a guarantee.

The javadoc now records your reason instead, which is the stronger one: LockContext.lock() is protected, and com.arcadedb.index.lsm neither shares the package nor subclasses PageManager, so index code cannot acquire that lock however the path is refactored. That is a bar the type system enforces rather than something a future reader has to re-verify.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review of #6223

Went through the full diff (GlobalConfiguration, FlushPageIndex, PageManager, PageManagerFlushThread, and the four test files) plus the unchanged surrounding code (pendingOf/hasPendingOf, LockContext, callers of writePages) to check the concurrency claims rather than take the comments at their word. Overall this is a very solid, thoroughly-tested change; I did not find a correctness bug in the new locking/accounting.

What I verified specifically

  • The flush drain waits still poll, so the snapshot barrier holds the JVM-wide page-manager lock across 1 ms sleeps that #6133 made unnecessary #6199 drain wakeup: The counter-as-monitor design in FlushPageIndex is correct. release() only takes the monitor on the transition to drained (cheap hot path preserved), awaitDrain re-reads the count inside the monitor (closes the lost-wakeup window), and removeAllOfDatabase zeroes the counter object before notifyAll() so a waiter that resolves the counter just before the purge still observes the drained state after entering the monitor. The dedicated race tests (aReleaseRacingTheParkIsNeverMissed, aPurgeRacingTheParkIsNeverMissed) genuinely exercise the windows the comments describe rather than just re-testing the happy path.
  • The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200 per-database backpressure: awaitDeferredBacklogUnderCap is called before PageManager.lock() is taken (publishPages) and from a path that structurally cannot hold that lock (writePages from LSM compaction, since LockContext.lock()/unlock() are protected and no LSM class subclasses or shares a package with PageManager). Checked this by grepping every non-test caller of writePages and confirming only LSMTreeIndexCompacted passes asyncFlush=true, and that it never calls into PageManager's lock. Good.
  • Double-release race: addDeferredRAM's clamped getAndAccumulate on the per-database AtomicLong, combined with releaseResidualDeferredRAM's getAndSet(0), correctly prevents a purge racing its own resume from releasing the same bytes twice into the JVM-wide total (verified by walking aPurgeRacingItsOwnResumeReleasesTheSameBytesOnlyOnce, which asserts deferredRAMDriftRepairs stays at zero rather than relying on the negative-total clamp to hide it).
  • The Phase-1 exception-safety fix in resumeFlushing (catching Throwable per page and re-raising once the backlog is drained) is a real fix: previously an unexpected exception mid-backlog would skip Phases 2-4, permanently pinning pages in pageIndex and RAM in the deferred-charge cap. Good catch, covered by anUnexpectedFailureWhileWritingTheBacklogStillFinishesTheResume.

Minor, non-blocking notes

  1. Stale comment in EngineMetricsBinder.java:161 (not touched by this PR): "crossing arcadedb.flushSuspendMaxDeferredRAM throttles committing threads outright" describes the pre-The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200 behavior (every open database's committers throttled via queue backpressure). Post-The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200 it's only the committers of the suspended database(s). Worth a follow-up one-line fix so the metric doc doesn't mislead an operator reading it next to the per-database gauge this PR adds the plumbing for.
  2. Undefended cross-file invariant: a good chunk of the new accounting (PageManager.awaitDeferredBacklogUnderCap(List), the per-database split in PageManagerFlushThread) rests on "a batch/list of pages always belongs to exactly one database," which is documented in comments but not checked anywhere. A violation here wouldn't throw, it would silently mis-key the deferral/backpressure accounting, which is exactly the class of bug this PR spent most of its effort hunting elsewhere. A cheap assert (e.g. in the PagesToFlush constructor, or at the top of awaitDeferredBacklogUnderCap) would turn a future violation into a fast, loud test failure instead of a subtle heap-accounting drift, at zero production cost.
  3. Possible @tag("slow") candidates: per the project's tagging convention, Issue6200PerDatabaseDeferredBacklogTest (several loops of 80-200 iterations spawning 1-12 threads each round) and Issue6199DrainWakeupTest#aPurgeRacingTheParkIsNeverMissed (80 rounds x 12 threads) look like they could add noticeable wall-clock time to the default CI lane given the thread churn. Worth checking actual run time and tagging if it's material; I could not execute mvn test in this environment to measure it directly.
  4. The Issue5279ConcurrentUpdateTest assertion fix (accounting for tolerated conflicts in the Link count) looks correct and is a legitimate pre-existing flaky-test bug, but it's logically unrelated to The flush drain waits still poll, so the snapshot barrier holds the JVM-wide page-manager lock across 1 ms sleeps that #6133 made unnecessary #6199/The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200. If it hasn't already been split out, it might be worth its own commit for a cleaner history and easier bisecting, though this is a nitpick.

Test coverage

Strong. Two new dedicated regression classes with real adversarial race stress tests (not just single-shot happy-path checks), and the two existing tests whose assumptions this PR invalidates (PageManagerFlushSuspendBackpressureTest, Issue5326ApplyChangesPendingFlushTest) were updated in step rather than left silently stale.

Nice work on the exception-safety fix in particular, that's the kind of bug that's easy to miss in a big refactor and expensive to debug in production (a database permanently stuck unable to close).

…ed-RAM metric stops describing the old behaviour

Review round 10, both non-blocking.

The per-database accounting rests on "a batch carries the pages of ONE database" - the suspension check that
decides whether to defer, the deferred map's key, the RAM charge and the committer-side cap all read it off the
batch's FIRST page - and nothing checked it. A violation would throw nowhere: it would charge one database for
another's pages and hold the wrong committers, the exact quiet drift this branch spent its rounds removing.
Now asserted in the PagesToFlush constructor: zero cost in production (assertions off), loud in the test lanes,
which is where such a batch would first be written. Not an unconditional check - that would put an O(batch)
walk on the publication path to defend against a bug that has to be introduced there first.

The assert comes with a test that PROVES IT FIRES rather than assuming it, skipping itself under -da. An
assertion nobody has seen trip is worth what a test nobody has seen fail is worth.

EngineMetricsBinder's comment on arcadedb.engine.flush.deferred.bytes still described the pre-#6200 behaviour -
"throttles committing threads outright", which was true when the flush thread stopped draining for everybody.
It now says which committers are throttled, and points at getDeferredRAMBytesOf as the per-database split item
2 of #6087 will tag the gauge by.

NOT taking two suggestions from the same round:
- @tag("slow") for the two new classes: measured, they run in 1.2 s and 0.9 s, an order of magnitude under the
  "noticeably long" bar CLAUDE.md sets for that tag. A 26 s outlier observed once was the machine, not the test.
- Splitting the Issue5279ConcurrentUpdateTest assertion fix into its own commit: it is already isolated inside a
  commit whose message flags it as unrelated, and rebasing to split it would force-push over the commits this
  review thread references.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Round 10, all four notes:

1. Stale EngineMetricsBinder comment - fixed in 83cd922. It said crossing the cap "throttles committing threads outright", which was true when the flush thread stopped draining for everybody. It now says which committers, and points at getDeferredRAMBytesOf as the per-database split item 2 of #6087 will tag the gauge by.

2. Undefended "one batch, one database" invariant - good catch, and the framing is right: a violation throws nowhere and instead charges one database for another's pages, which is the exact drift this branch spent its rounds removing. Now asserted in the PagesToFlush constructor - zero cost in production, loud in the test lanes, where such a batch would first be written. Deliberately an assert rather than an unconditional check: the latter puts an O(batch) walk on the publication path to defend against a bug that has to be introduced there first.

It comes with a test that proves the assert fires (aBatchMixingTwoDatabasesIsRejectedLoudly, self-skipping under -da). An assertion nobody has seen trip is worth what a test nobody has seen fail is worth - which is the same standard the rest of this PR's tests were held to.

3. @Tag("slow") - measured, since you couldn't run it: Issue6200PerDatabaseDeferredBacklogTest is 1.2 s and Issue6199DrainWakeupTest 0.9 s, an order of magnitude under the "noticeably long / multi-second" bar CLAUDE.md sets for the tag. I did see a single 26 s outlier while the machine was still finishing a compile; re-measured 3× it is 1.18/1.20/1.20 s. Not tagging.

4. Splitting the Issue5279ConcurrentUpdateTest fix - agreed in principle, declining in practice: it is already isolated inside a commit whose message flags it as UNRELATED with the reasoning, and rebasing to split it now would force-push over the commits this review thread references by hash.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

This is a deep, carefully-reasoned fix for a real correctness/perf problem in the page-flush pipeline (poll-based drains + a backpressure cap whose response was global instead of per-database). The commit history shows the design already went through many rounds of internal review that closed several real races (the blanket-reset wiping a sibling's charge, the double-release driving the total negative, the purge/defer race, the purged-counter-not-zeroed race, the resume-abort leak, etc.), and the reasoning documented in the comments matches what the code actually does. I re-derived the key invariants independently and didn't find a new correctness bug. Specific notes below.

Correctness (spot-checked, no new issues found)

  • FlushPageIndex.awaitDrain/release: standard guarded-wait, re-reads the count inside the counter's own monitor, so a release landing between the caller's check and wait() can't be missed. removeAllOfDatabase zeroes the counter before notifyAll (not just removes it from the map), which is the right fix for the "waiter already resolved the old counter reference" case.
  • addDeferredRAM's release branch takes the amount to move off the JVM-wide total from the per-database AtomicLong via getAndAccumulate clamped at zero, rather than trusting delta blindly — that's what makes it safe against releaseResidualDeferredRAM and the per-page release racing each other (the double-release-goes-negative bug from round 4). I checked addDeferredRAMTotal's "signal only on downward crossing" logic against concurrent decrements: since each thread's getAndAdd return value is the value strictly before its own delta is applied, the sequence of (previous, previous+delta) pairs partitions the whole update history, so the crossing can't be missed by all threads simultaneously.
  • awaitDeferredBacklogUnderCap being called before PageManager.lock() (both from publishPages and from writePages for compaction) is the crux of the The deferred-flush backpressure of #4728 is JVM-wide: one suspended database's backlog stops the flush thread from draining the queue for every other database #6200 fix and is correctly placed at both call sites.
  • The PagesToFlush "one batch = one database" invariant is enforced with an assert (test-lanes only) rather than an unconditional check, which is a reasonable perf/safety tradeoff given it documents a real, previously-implicit invariant several other pieces of this code now rely on.

Style / nits

  • The comments are unusually dense and use ALL-CAPS for emphasis in a lot of places (e.g. FlushPageIndex.java, PageManagerFlushThread.java — "NO CAP CHECK HERE ANY MORE", "THE PER-DATABASE COUNTER IS THE AUTHORITY...", "ONE monitor for every suspended database..."). They're all genuinely explaining non-obvious why (races ruled out, invariants relied on elsewhere), which fits CLAUDE.md's comment guidance, but the shouting-caps style is a departure from the rest of the codebase's tone and makes these methods noticeably harder to skim than the surrounding code. Might be worth a pass to convert the ALL-CAPS emphasis to normal sentence case now that the design has settled — the content is worth keeping, the typography less so.
  • PageManagerFlushThread is picking up a lot of responsibility (drain signaling, per-database RAM accounting, the cap wait, warning/backoff logic). Not asking for a split given how interconnected the locking is, but worth keeping in mind if Backup phase-1 follow-ups: copy() drops settings on Export/Import, deferred-RAM metric unwired, no per-database compression override #6087's per-database gauge wiring adds much more to this class.

Test coverage

Good — Issue6199DrainWakeupTest and Issue6200PerDatabaseDeferredBacklogTest both target the actual race windows (not just the steady-state behavior), and the commit messages document that each new test was verified to fail against the pre-fix code, which is exactly the rigor CLAUDE.md asks for ("write a regression test"). The javadoc on aPurgeRacingTheParkIsNeverMissed honestly reports the repro rate as "1 in 12 on a loaded machine" rather than overclaiming — appreciated, that kind of test self-awareness is easy to skip. The Issue5279ConcurrentUpdateTest and Issue5326ApplyChangesPendingFlushTest fixes are correctly flagged as unrelated flakes found along the way rather than smuggled in silently.

Performance

The hot path (FlushPageIndex.release) still pays only a volatile decrement + comparison per page, taking the counter's monitor only on the batch that drains to zero — matches the "performance and lightweight on GC" mandate. awaitDeferredBacklogUnderCap's early-out (!isSuspended(db), two map reads) keeps the common (non-suspended) commit path cheap, which is the right default given only suspended databases can ever be over the cap.

Minor question (not a blocker)

awaitDeferredBacklogUnderCap is only invoked when asyncFlush is true, in both publishPages and writePages. Worth a one-line confirmation in the javadoc (or just for my own understanding) that synchronous flush callers can never accumulate against this cap — i.e. that there's no path where a suspended database's synchronous writes bypass the backpressure this PR adds.

Overall: solid, well-tested fix for both linked issues, consistent with the project's concurrency conventions (dedicated locks, no common ForkJoinPool usage, bounded waits with documented fallback intervals). Nothing here blocks merging from my read.

…ferred-backlog cap

Review round 11 asked whether a synchronous write can accumulate against the cap unbackpressured. It cannot,
and the javadoc now says why rather than leaving it to be re-derived: what the cap bounds is deferredByDatabase,
and flushPagesFromQueueToDisk is the SINGLE place anything is ever put there (verified - one computeIfAbsent in
the whole class). A synchronous writePages goes straight to flushPage without passing through the flush thread,
so it adds nothing to the backlog and has nothing to be held for. That is why the gate is on asyncFlush.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Round 11:

The synchronous-flush question - answered, and the answer is now in the javadoc (b410f45) rather than left to be re-derived. A synchronous write cannot accumulate against this cap: what the cap bounds is deferredByDatabase, and flushPagesFromQueueToDisk is the single place anything is ever put there (one computeIfAbsent in the whole class - grepped, not assumed). A synchronous writePages goes straight to flushPage without passing through the flush thread at all, so it adds nothing to the backlog and has nothing to be held for. That is exactly why the gate is on asyncFlush.

The ALL-CAPS style - declining, with evidence, because the premise is the other way round. Emphasis-caps is the established convention in these two files, not a departure from it: on main, untouched by this PR, PageManagerFlushThread has 10 such comments and PageManager has 64, including multi-line caps blocks like the snapshot barrier's // THE CLOCK STARTS HERE, NOT AT THE PUBLIC ENTRY POINT... and // MANAGE CONCURRENT ACCESS TO THE PAGES.... CLAUDE.md's instruction is to adhere to the existing code, and rewriting the new comments to sentence case would make them the odd ones out in their own file while adding diff noise to a change that has already been reviewed eleven times.

PageManagerFlushThread accumulating responsibility - agreed, and worth recording: it now owns the drain signalling, the per-database RAM accounting, the cap wait and the warn/backoff. #6087's gauge wiring should not add to it - it only needs to read getDeferredRAMBytesOf, which is already exposed on PageManager. If that item grows past a gauge read, splitting the accounting out is the natural seam.

Thanks for the eleven rounds - between them they turned up four genuine races that the first version of this PR shipped with.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

Reviewed the diff for GlobalConfiguration, FlushPageIndex, PageManager, PageManagerFlushThread, EngineMetricsBinder, and the new/updated tests. Traced the locking argument for awaitDeferredBacklogUnderCap / addDeferredRAM / releaseResidualDeferredRAM against suspendLock, replayDrainLock, and deferredRAMLock (lock-order and no-hold-on-park checks), and the guarded-wait shape of FlushPageIndex.awaitDrain against release() / removeAllOfDatabase().

Overall

This is careful, well-reasoned concurrency work, and the commit history already documents an unusually thorough self-review (11+ rounds catching real races: the double-release drift, the blanket-reset-wipes-a-sibling bug, the purge-vs-defer window, the Phase-1-exception-strands-Phase-2..4 bug, the counter-not-zeroed-before-notify bug). I went through the current diff independently looking for anything still open and did not find a new correctness bug in the locking or accounting logic - the invariants ("a batch carries the pages of ONE database", "suspendLock gates flag-clear against defer", "the per-database counter is the sole authority on what may be released") are consistently applied at every call site I checked, including the purge-races-its-own-resume and purge-races-a-defer scenarios.

A few smaller things worth a look before merge:

1. Test scaffolding duplication. PageManagerFlushSuspendBackpressureTest and Issue6200PerDatabaseDeferredBacklogTest both redefine PAGE_SIZE = 256 * 1024, CAP_MB = 1, CAP_BYTES, and near-identical cappedFlushThread() / single-page-enqueue helpers. Per the project's "reuse existing components" guidance, these could share a small test base or utility rather than being copy-pasted across two files - minor, but the constants are already drifting apart slightly (one file inlines the CAP_MB math, the other extracts CAP_BYTES).

2. Unrelated fix bundled in. The Issue5279ConcurrentUpdateTest change (counting out tolerated conflicts) is a legitimate fix but is unrelated to #6199/#6200; it's called out honestly in its own commit message as "found by the full suite" and kept together rather than split out to avoid a rebase, which is a reasonable tradeoff given the size of this branch. Just flagging it so it doesn't get lost in review as "in scope."

3. Per-commit overhead. awaitDeferredBacklogUnderCap now runs on every async publishPages/writePages call (a list access + an isSuspended map lookup before the two cheap-exit checks). This is the right place for it given the goal (must run outside the JVM-wide lock), and the cost is minimal, but it's worth confirming with a quick benchmark/perf pass that steady-state (non-suspended) throughput is unaffected, since this is a very hot path.

4. Verbosity of in-code documentation. The javadoc-per-invariant style (e.g., the multi-paragraph explanation on awaitDeferredBacklogUnderCap, addDeferredRAM, deferredRAMByDatabase) is dense, but given how many non-obvious races this class had, I'd lean toward keeping it. It's the kind of institutional memory that will save the next person from reintroducing exactly these bugs. Not a blocker, just noting the diff size is inflated substantially by comments rather than logic.

Test coverage

Strong. The two new regression test classes (Issue6199DrainWakeupTest, Issue6200PerDatabaseDeferredBacklogTest) use real racing threads with documented reproduction rates against the unfixed code rather than relying on sleeps-and-hope, and the timeout choices are explicitly justified against the shared 12000-test-JVM stop-the-world pause that caused a prior flake. deferredRAMDriftRepairs being asserted to stay at zero (rather than only asserting the total lands on zero) is a good touch - it prevents the negative-total clamp from silently hiding a future double-release regression.

Security / performance

No security concerns (no new external input handling). Performance impact is a deliberate, well-justified tradeoff: replacing polling sleeps with wait/notify reduces JVM-wide lock hold time (the actual bug being fixed), and the new per-commit cap check is O(1) map lookups gated by a suspended-database check that's false in the common case.

Nice work untangling a genuinely subtle set of races.

@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Round 12 - the one point I could act on was the perf question, so I measured it rather than reasoning about it.

3. Per-commit overhead of awaitDeferredBacklogUnderCap. Steady-state, non-suspended commit throughput, 40 000 single-document transactions per round after a 20 000-commit warm-up, current HEAD versus the identical build with the gate short-circuited at its first line:

round 0 round 1 round 2
with the gate 648 ms 636 ms 626 ms
gate disabled 643 ms 633 ms 619 ms

The gap is ~7 ms on 40 000 commits (~1%, ≈0.18 µs/commit) and the within-run spread is 22 ms, so it is not distinguishable from noise. That matches the shape of the code: on a non-suspended database the gate is a list access, a maxDeferredRAM <= 0 test and one CHM lookup, all before any monitor. (Probe deleted, not committed.)

1. Test scaffolding duplication - declining, deliberately. The two classes guard different issues (#4728's cap bound versus #6200's per-database scoping) and the fixtures have already diverged for good reasons: Issue6200PerDatabaseDeferredBacklogTest needs 256 KB pages for the cap arithmetic and 1 KB pages for the per-page-loop races, which the #4728 test has no use for. Sharing a base class would couple two independent regression guards so that a future fixture change to one has to be reasoned about for the other - the drift you spotted is the argument for keeping them apart, not for merging them. The cost is ~6 lines of constants in test code.

2 and 4 - nothing to do; agreed on both, and thanks for the note on keeping the in-code rationale.

That is every point across twelve rounds either fixed or answered, so I'll stop here unless something new lands. Between them the rounds caught four genuine races and two pre-existing test bugs that this branch would otherwise have shipped past.

@codacy-production

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 medium

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
BestPractice 1 medium

View in Codacy

🟢 Metrics 47 complexity

Metric Results
Complexity 47

View in Codacy

🟢 Coverage 81.71% diff coverage · -6.48% coverage variation

Metric Results
Coverage variation ✅ -6.48% coverage variation
Diff coverage ✅ 81.71% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (12468cb) 158224 124638 78.77%
Head commit (b410f45) 190963 (+32739) 138060 (+13422) 72.30% (-6.48%)

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 (#6223) 175 143 81.71%

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.

@codecov

codecov Bot commented Aug 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.71429% with 46 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.09%. Comparing base (12468cb) to head (b410f45).
⚠️ Report is 62 commits behind head on main.

Files with missing lines Patch % Lines
...va/com/arcadedb/engine/PageManagerFlushThread.java 71.63% 29 Missing and 11 partials ⚠️
.../main/java/com/arcadedb/engine/FlushPageIndex.java 85.71% 1 Missing and 2 partials ⚠️
...src/main/java/com/arcadedb/engine/PageManager.java 76.92% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6223      +/-   ##
==========================================
+ Coverage   69.99%   70.09%   +0.10%     
==========================================
  Files        1836     1837       +1     
  Lines      158224   158610     +386     
  Branches    33384    33464      +80     
==========================================
+ Hits       110746   111180     +434     
+ Misses      33625    33562      -63     
- Partials    13853    13868      +15     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@lvca lvca added this to the 26.9.1 milestone Aug 16, 2026
@lvca
lvca merged commit a2c243d into main Aug 16, 2026
31 of 33 checks passed
@lvca
lvca deleted the issue-6199-6200 branch August 16, 2026 18:34
lvca added a commit that referenced this pull request Aug 16, 2026
…-name grep never saw

Issue6199DrainWakeupTest.theResidualDrainKeepsItsHardDeadline is one of the two
failures #6260 was filed on, and it was the one site still carrying the fix this
PR argues against: #6223 had widened its bound to a flat 1 minute to survive the
pause. That is fine as far as it goes - a tripwire has room to be widened - but
leaving it there means the motivating repro is not actually running through the
mechanism built to handle it. It now discounts the stall like everything else,
which lets the tripwire come back down from 60s to 5s: still far above the honest
~200ms, still far below the forever an unbounded wait takes.

Finding it exposed a hole in how the other 40 were located. The original sweep
matched `assertThat(elapsed...)`, so every site that asserts on the expression
inline, or names the variable something else, was invisible to it. Re-swept on
`System.currentTimeMillis() - <anything>` instead, which turns up three more
real bounds among the benchmarks and printlns:

- AsyncWedgedWorkerStallTest - the backstop fires on the configured no-progress
  bound rather than waiting out the wedge. A tripwire
- Issue6200PerDatabaseDeferredBacklogTest - a database that is not suspended
  returns at once instead of waiting on another database's over-cap backlog. The
  bound IS the assertion: it is the whole difference between per-database and
  global backlog accounting
- WithAndUnwindTest - ~200 comparisons per UNWIND row with the predicate
  pushdown, not 200*200 without it

Left alone, as before: lower bounds (SQLScriptTest, SleepStatementExecutionTest,
CodeUtilsTest), which a stall only makes more true, and the @tag("benchmark")
classes, which are not in a CI lane.
lvca added a commit that referenced this pull request Aug 17, 2026
…the-world pauses (#6268)

* fix(#6260): a wall-clock bound measures the code, not the JVM's stop-the-world pauses (#6260)

Two engine tests went red in a full-suite run while behaving correctly:
AsyncShutdownDrainTest.closeDoesNotHangOnAWedgedAsyncWorker measured 27,396ms
for a close() bounded by a 1s timeout plus a 2s join, and
Issue6199DrainWakeupTest.theResidualDrainKeepsItsHardDeadline measured 24,143ms
for a wait bounded by 200ms. Late in a 12,000-test single-JVM run a
stop-the-world pause of tens of seconds is not exotic, and any bound with less
headroom than that is a coin flip on the JVM's mood.

Widening the numbers was not available as a fix. Several of these bounds are
discriminating a single shared 200ms deadline from ten independent per-row ones,
so they have to stay below 2s to mean anything at all; widening them deletes the
assertion. Instead the measurement itself is corrected: a daemon sampler parks
for 10ms at a time and accumulates however much longer each park actually took,
so the difference of two readings is the JVM-wide stall inside that interval.
Subtracting it leaves the time the JVM was actually running, which keeps every
bound exactly as tight as it was and immune to the pause.

Deliberately not discounted: time the measured thread spends sleeping, parked or
blocked. The sampler keeps ticking then, so a test that waits a second is still
charged a second - only a stall that also stops the sampler is taken out. The
sampler runs at default priority on purpose, so it suffers the same CPU
starvation the measured thread does; that half of the problem is invisible to a
GC-pause-only view.

The two assertion methods differ only in their failure message, and that is the
point: the message has to say what the number is for, so the next person to see
it go red knows whether loosening it is a repair or a cover-up.

- assertGaveUpWithin - the bound is a tripwire between a bounded operation and
  an unbounded one. Generous is free; a wider bound cannot turn a passing run red
- assertStayedUnder - the bound IS the assertion, standing in for a complexity
  claim with no other practical expression. Loosening it deletes the test

Applied across the engine suite: 40 elapsed-time assertions in 26 test classes.
Lower bounds (isGreaterThan) and short waits expected to time out are left alone
- a stall only makes those more true - and the two isBetween sites are split so
the floor keeps reading raw wall clock while only the ceiling is discounted.
Issue5587's gap-ratio comparison samples the stall counter alongside each
timestamp, so a pause landing in one half cannot skew it.

Three @timeout(30) annotations on tests whose own budget is already 16s or more
are raised to 120s: JUnit's timeout is plain wall clock and cannot be discounted,
so it has to be sized as a hang detector rather than as a latency bound.

* docs(#6260): record what the stall discount trades away, where its floor is, and why check() reads in that order

Review follow-ups, all documentation - no behaviour change.

- check() takes two non-atomic snapshots, and the order is load-bearing: sampling
  the stall AFTER the elapsed time means the stall window can only be wider than
  the elapsed one, so the discount can only come out too generous. Read the other
  way round it could come out too small and fail a run that was fine.
- The sampler is a daemon with no stop path on purpose, because a test JVM's life
  is the whole window anyone can measure. Said so, so anything longer-lived that
  wants to reuse it knows it needs a shutdown story first.
- The sensitivity the design trades away, written down rather than left to be
  rediscovered: the monitor cannot tell a stall from the measured thread's own
  work being slow on an oversubscribed box, so on a loaded runner a genuine
  regression can be discounted along with the noise. That is the deliberate
  trade, and it is why assertStayedUnder bounds want an order of magnitude of
  headroom rather than being tuned down to whatever currently passes.
- Nothing below tick + tolerance is ever discounted, so a bound tighter than
  ~20ms gets no help. Only PaginatedSparseVectorEngineBackpressureTest (50ms) is
  anywhere near that floor; noted it as the first place to look if it flakes, and
  what lowering the tolerance would cost every other measurement.

* fix(#6260): migrate the four remaining wall-clock bounds the variable-name grep never saw

Issue6199DrainWakeupTest.theResidualDrainKeepsItsHardDeadline is one of the two
failures #6260 was filed on, and it was the one site still carrying the fix this
PR argues against: #6223 had widened its bound to a flat 1 minute to survive the
pause. That is fine as far as it goes - a tripwire has room to be widened - but
leaving it there means the motivating repro is not actually running through the
mechanism built to handle it. It now discounts the stall like everything else,
which lets the tripwire come back down from 60s to 5s: still far above the honest
~200ms, still far below the forever an unbounded wait takes.

Finding it exposed a hole in how the other 40 were located. The original sweep
matched `assertThat(elapsed...)`, so every site that asserts on the expression
inline, or names the variable something else, was invisible to it. Re-swept on
`System.currentTimeMillis() - <anything>` instead, which turns up three more
real bounds among the benchmarks and printlns:

- AsyncWedgedWorkerStallTest - the backstop fires on the configured no-progress
  bound rather than waiting out the wedge. A tripwire
- Issue6200PerDatabaseDeferredBacklogTest - a database that is not suspended
  returns at once instead of waiting on another database's over-cap backlog. The
  bound IS the assertion: it is the whole difference between per-database and
  global backlog accounting
- WithAndUnwindTest - ~200 comparisons per UNWIND row with the predicate
  pushdown, not 200*200 without it

Left alone, as before: lower bounds (SQLScriptTest, SleepStatementExecutionTest,
CodeUtilsTest), which a stall only makes more true, and the @tag("benchmark")
classes, which are not in a CI lane.

* fix(#6260): the vector-rebuild bound is a complexity claim, not a tripwire

Review point, and it is right: LSMVectorIndexRebuildTest's "search must not
block on the async rebuild" was the one assertGaveUpWithin in the set where
nothing actually gives up. The rule the two method names encode is that a
tripwire separates a bounded operation from an unbounded one, and the thing it
separates here is a search served from the graph it already has from one that
waits for a rebuild - both finite, and the bound is the whole claim. That makes
it assertStayedUnder, which also lines it up with how every other "must not wait
on background work" assertion in the diff is categorized.

Also drops a dead local the same review asked to check for: WithAndUnwindTest
timed the inline-property path into inlineTimeMs and never asserted on it. It
predates this PR, but it sat in the method just converted and was the last raw
wall-clock measurement left there, so it went with the rest.

* fix(#6260): size AsyncWedgedWorkerStallTest's @timeout as a hang detector like its three siblings

Review point, and correct: this test's assertion was converted to a
stall-discounted 10s bound but its @timeout(30) was left behind, which makes it
the one place in the diff that still flakes on exactly the mechanism this PR
exists to remove. Against ~1-2s of honest work (a 50ms x 12-window backstop plus
a couple of latches), a 24s pause lands the total at ~26s and a 27s one puts it
over. Raised to 120s, the same rule the other three follow.

Not swept wholesale, deliberately. There are ~20 more @timeout annotations in
the engine suite under 45s, and bumping them all would be the blanket widening
this PR argues against: several of them ARE the assertion rather than a hang
detector - RangeFunctionTest's 5s bounds are the GHSA-xmjm range() guard, where
the whole claim is that the call returns rather than materialising the range.
Deciding which is which is the same per-assertion classification pass this PR
did for elapsed-time bounds, and it belongs with the rest of that work in #6270
rather than as an untested blind bump here.
lvca added a commit that referenced this pull request Aug 17, 2026
…sks, and a flush backlog stays inside its own database (#6290)

* fix(#6281): an index build waits for the async BATCH, not just its tasks, and a flush backlog stays inside its own database

Three independent follow-ups from #6259.

Item 1 - Issue5279ConcurrentInsertTest.sustainedConcurrentInsertsOnASingleBucketNeverConflict tolerated up to
two conflicts at attempts=1 and then demanded the exact full count. A conflict tolerated there means the record
was NOT written, so the two assertions contradict each other and the run that actually uses the tolerance fails
at the count (2000 against 2001) instead of passing at the tolerance meant to absorb it. Same trap PR #6223
fixed in the sibling Update class; the count now subtracts the conflicts. Both classes swept for the shape.

Item 2 - a silent, empty index. DatabaseAsyncExecutorImpl.isProcessing() answers about TASKS, while a worker
opens a transaction when it starts and keeps it open across up to ASYNC_TX_BATCH_SIZE (10240) of them. An
executor whose queues happen to be drained therefore reports itself idle while still holding every record of the
current batch uncommitted. TypeIndexBuilder.create() guarded with

  while (database.isAsyncProcessing()) database.async().waitCompletion();

so on the runs where that predicate answered false the guard was skipped entirely: the index was built by
scanning a bucket that did not contain those records, and they committed afterwards with no entry ever added for
them. The result is an index that is empty, readable, and reported healthy by CHECK DATABASE, while every lookup
answers nothing. Reproduced deterministically (index entries 0 of 200, "select from V where id = 42" empty).

The barrier is now unconditional - DatabaseInternal.waitForAsyncCompletion(), a do/while around waitCompletion(),
which is the only operation that closes the open batch - and is used by TypeIndexBuilder, ManualIndexBuilder and
REBUILD INDEX, which scans the buckets the same way. It reads the async field rather than async(), so a database
that never used the async API neither waits nor grows a thread pool. isProcessing() is deliberately left
answering about tasks: broadening it to "a transaction is open" would make it permanently true.

ACIDTransactionTest.indexCreationWhileAsyncMustFail was vacuous - create() has drained the async executor for
years, so its catch(NeedRetryException) never fired and its only assertion was the record count, which an empty
index satisfies just as well as a complete one. Renamed to indexCreatedWhileAsyncInsertsAreInFlightSurvivesACrash
and made to assert the index: countEntries() and a lookup for every record, after the crash and recovery.

Item 3 - per-database flush budget. arcadedb.pageFlushQueue was one JVM-wide ArrayBlockingQueue: #6259 took the
wait for room out of the page-manager lock, but one database's burst still consumed the admission budget of every
other database in the process. The bound is now per database, held in a single count per database that covers
both halves of an occupancy (reserved by a committer, then occupied by its batch until the flush thread polls
it), and the shared queue carries no capacity of its own. One queue rather than one per database keeps global
FIFO order for free - N queues would force the flush thread to choose between them on every poll, which is a
fairness policy and a starvation risk this design does not have. The cost, stated in the field Javadoc, is that
worst-case occupancy becomes pageFlushQueue x open databases batches.

Regression tests: Issue6281AsyncBatchIndexBuildTest (fails on the previous code with an empty index) and
Issue6281PerDatabaseFlushQueueTest.

* fix(#6281): review round 1 - the last two direct queue.offer call sites, and the two silent contract changes

- PageManagerFlushSuspendDeferRaceTest and FlushRobustnessTest were missed by the sweep that routed every other
  white-box enqueue through offerBatch(). Neither could go negative today - the fabricated batch is the only thing
  ever charged against that database's budget in its own flush-thread instance, so the decrement lands on a missing
  key and no-ops - but both skipped the accounting invariant offerBatch()'s javadoc says every enqueue must exercise.
- waitForAsyncCompletion() reads the async field without asyncLock while isAsyncProcessing() takes it: say why. The
  lock serializes the lazy creation in async(); the field is volatile and never reassigned, not even on close, so the
  read sees either no executor or the one and only one - and a lock there would be held across a blocking wait.
- Math.max(1, pageFlushQueue) is a real contract change now that ArrayBlockingQueue's constructor no longer rejects a
  non-positive value. Documented as deliberate in both the constructor and the setting: with admission as the only
  bound, a budget of 0 refuses every publication for ever, which is worse than the startup failure it replaces.
- Fixed a sentence dropped mid-edit in Issue6281AsyncBatchIndexBuildTest's javadoc.

* fix(#6281): review round 2 - the statsOnly branch needs the barrier too, and the rebuild claim was too strong

- The barrier now sits AHEAD of RebuildIndexStatement's statsOnly branch, which returns early: that branch
  rescans the same records to recompute the BM25 counters, so it undercounted them by the same window.
- Corrected the barrier's own comment on that path. It claimed a rebuild inside the window loses index entries,
  the way a CREATE INDEX does. It does not: those records staged their index operations when they were saved and
  applying them at commit repopulates what the scan could not see. A regression test written to catch a loss there
  passes with the call removed, which is why there is no such test - shipping one would have been the same vacuous
  coverage this PR removed from ACIDTransactionTest. What the window does cost is a rebuild computed over a partial
  view: the BM25 counters, the misplaced-record detection of #832, and the reported totals.
- Release notes for 26.9.1, including the behaviour change the review asked to be called out: worst-case
  flush-pipeline occupancy is now pageFlushQueue x open databases batches, so a deployment that sized
  pageFlushQueue against total heap should re-check it.

* fix(#6281): review round 3 - the barrier refuses to be called from inside the executor it waits for

A real regression this PR introduced, correctly caught in review.

waitCompletion() enqueues a marker on EVERY worker - the caller's own included - and blocks until each has run,
and the only consumer of a worker's queue is that worker. A worker that reaches the barrier parks on a marker
nobody can dequeue and is lost for the life of the process. RebuildIndexStatement.buildIndex() has refused
exactly this since issue #2097, but the barrier this PR added at the top of executeDDL() ran ahead of that
guard, and never reached it at all on the statsOnly branch: #2097's protection became dead code for the path it
was written for. Measured, with the guard removed: the surefire fork does not merely fail, it never finishes -
killed after 400s - because the lost worker takes the database's close with it.

- waitForAsyncCompletion() now refuses with NeedRetryException when the caller is one of this executor's own
  workers, using the same owner-checked `instanceof AsyncThread` test offerWaiting already uses. Refusing is the
  only honest answer: skipping the wait would put back the very bug the barrier closes, over the caller's own
  uncommitted batch, and committing that batch here would commit the enclosing task's writes mid-task, which is
  the per-task atomicity AsyncThread.executeTask guards. The guard now lives once, on the operation that cannot
  be satisfied, rather than once per call site that happens to remember it - TypeIndexBuilder and
  ManualIndexBuilder had no such guard at all.
- #2097's own refusal is hoisted to the top of executeDDL(), ahead of the barrier, so it still answers first with
  the message it was written for and its integration test still asserts a refusal from where it expects one.
  Issue2097AsyncRebuildIndexIT: 3 tests green.
- waitForAsyncCompletion()'s loop breaks on interrupt. waitCompletion() answers an interrupt by restoring the
  flag and returning, so the loop would otherwise spin: every further pass interrupted at its first queue offer,
  returning immediately. Pre-existing in the pattern this replaced, but worth closing now that it is shared API.
- Issue6281AsyncBatchIndexBuildTest gains theBarrierRefusesToBeCalledFromOneOfTheExecutorsOwnWorkers.

Not implemented, and why: a startup WARNING when many databases run with a non-default pageFlushQueue. The
database count is not known where the flush thread is built (one JVM-wide thread, constructed once), and the
throttle WARNING already names the database and reports the shared pipeline depth at the moment the budget
actually bites - which is the point at which an operator can act on it. The tuning change is in the config
javadoc and the release notes.

engine: 12112 tests, 0 failures.

* fix(#6281): review round 4 - detachPendingPages' comment still described the old queue

The only point raised, and correct: the walk in detachPendingPages() named ArrayBlockingQueue's iterator and
claimed the walk is bounded by arcadedb.pageFlushQueue. Both went stale with this PR - the queue is a
LinkedBlockingQueue and its depth is that setting times the number of open databases. The weak-consistency
argument for iterating without a snapshot still holds (LinkedBlockingQueue's iterator is weakly consistent
too), so only the bound and the class name needed correcting.

Swept the rest of the file: every other ArrayBlockingQueue mention is deliberately historical - the field
javadoc explaining what the queue used to be, the slotsInUse javadoc naming the property given up, and the
constructor explaining why the capacity clamp replaced its IllegalArgumentException.

* fix(#6281): review round 6 - pageFlushQueueLength changed scale, so publish the number that still means something

The one point raised, and a fair one. pageFlushQueueLength used to top out at arcadedb.pageFlushQueue, because
that setting WAS the queue's capacity - so "length >= pageFlushQueue" was a natural full-pipeline alert. With the
bound moved per database the field is a sum across every open database and can run to pageFlushQueue x open
databases, which makes that comparison mean nothing. A published field quietly changing scale is worse than one
that changes name.

- pageFlushQueueMaxPerDatabase joins it: the busiest single database's share of the pipeline, which is exactly
  what the setting bounds, so it is the field to alert on and the one that carries the old signal. Surfaced in
  the profiler JSON under that name and in the text dump as flushQueueMaxPerDb, next to flushQueue.
- Both fields document what they are, what they were, and which of them to compare against the setting.
- Release notes call the change out for anyone with an existing alert on the old field.

O(open databases) and read once per stats scrape - never on a write path.

* fix(#6281): review round 7 - the statsOnly claim was verifiable after all, and it was worse than stated

Three points raised, no blockers. The interesting one was the untested statsOnly claim, and checking it changed
what the claim should say.

- REBUILD INDEX ... WITH statsOnly = true recomputes the BM25 corpus counters by scanning the type and then
  OVERWRITING the counters with what the scan found. Run against an open async batch it finds nothing committed
  and writes "0 documents" over counters the records had already bumped when they were saved. Measured: 0 of 200
  documents counted with the barrier removed, 200 with it. So this is not "computed over a partial view" as the
  previous round's comment hedged - the counters are left wrong, every BM25 score is computed against a corpus of
  zero, and unlike the index-entry case it does not heal itself. Now has a regression test, and the comment and
  release note say what was measured instead of what was reasoned.
- The Math.max(1, pageFlushQueue) clamp has a test: a budget of 0 or -1 becomes 1 and admits exactly one batch.
  It used to be ArrayBlockingQueue's constructor that rejected a non-positive value, and there is no constructor
  left to reject it, so the clamp is now the only thing between a misconfiguration and a pipeline that refuses
  every publication for ever.
- PAGE_FLUSH_QUEUE's javadoc said "...until issue #6281, which made one database's write burst throttle the
  commits of unrelated databases", where "which" reads as if the issue caused the bug rather than fixed it.
  Reworded.

engine: 12204 tests, 0 failures.

* docs(#6281): review round 8 - name the new refusal and the shared-monitor trade in the release notes

Three points, all documentation, no blockers raised.

- The release notes now say that CREATE INDEX, a manual index create and REBUILD INDEX raise NeedRetryException
  when run on one of the async executor's own worker threads (awaitResponse=false over HTTP, say). One
  correction to the review's framing: this is not a path that "could silently proceed" before. From a worker,
  isAsyncProcessing() is true by construction - that worker is executing a task - so the old guard always
  entered its loop and always parked on a marker only that same worker could dequeue. The change is a hang
  becoming a clear refusal, which is worth saying plainly either way.
- Named the shared queueSlotLock trade in the same section: with many databases saturating their budgets at
  once, every poll wakes every waiter and each re-checks its own count. Deliberate, and the same shape as the
  deferred-RAM cap, but a different failure mode from the old single-queue design, so it should not have to be
  discovered.
- Collapsed the double blank lines the repeated merges left before two unrelated headers.

* fix(#6281): review rounds 9 and 10 - a stale batch can no longer spend a reopened database's budget

Both rounds independently found the same real edge case, and it is worth the fix.

LocalDatabase defines equality by database PATH, not by instance. removeAllPagesOfDatabase() emptied a closing
database's queued batches but deliberately left the wrappers in the queue, and their `database` field still
pointed at the closed instance - so a database dropped and recreated at the same path (a restore, a
re-provision, plenty of tests) would have the NEW instance's budget decremented when one of those wrappers was
finally polled. Assertion failure in the -ea lanes; silently one admission slot too many in production.

Two changes, and the test pins the first:

- removeAllPagesOfDatabase() now takes the emptied wrapper OUT of the queue. It carries no pages, so the poll
  would do nothing but release a slot belonging to a budget that has just been dropped. Removing it means the
  window does not exist rather than being survivable.
- A batch carries the AtomicInteger its slot was charged on, captured at offerBatch(), and the release
  decrements THAT rather than looking the database up again. Defence in depth, and measured as such: with the
  queue removal in place the new test passes even with this reverted, because it can no longer reach the
  release. Kept because the removal has to be remembered at every future path that could leave a batch queued
  across a close, and the capture does not. Safe without volatile - written before queue.offer, read after
  queue.poll, and a BlockingQueue gives happens-before between them.

Also from round 10: PageManagerFlushThread.queue drops from public to package-private. While it carried the
capacity a direct queue.offer was merely impolite; now that admission is the only bound and offerBatch is the
one place a slot is charged, a direct offer silently bypasses the accounting - which is what several white-box
tests were doing before this issue swept them. Nothing outside the package used it.

engine: 12205 tests, 0 failures. Full reactor builds.

* fix(#6281): review round 11 - BucketIndexBuilder is a fourth way into the bucket scan, and it was not covered

A real gap, correctly found. The barrier went into TypeIndexBuilder, ManualIndexBuilder and REBUILD INDEX, but
BucketIndexBuilder.create() is reachable on its own through the public Schema.buildBucketIndex(...) - and that
is how CHECK DATABASE ... FIX rebuilds an index it found damaged (DatabaseChecker). Reached that way it scanned
a bucket that did not yet contain whatever an async worker was still holding in its open batch, and produced
exactly the silently incomplete index this issue is about. The new test fails without the barrier: 0 entries of
200 records.

Paying the barrier twice on the paths that already did costs one marker round-trip per worker on an executor
that is drained by then; missing it once costs an index.

Also removed from that method a CountDownLatch, semaphoreToStart, that the pause tasks counted down and NOTHING
ever awaited - so the build began whether or not the workers had reached the pause it was meant to wait for.
What it was reaching for is what the barrier now provides properly, so it is gone rather than left sitting there
looking like a guard. The pause tasks themselves stay: they keep the workers from writing DURING the build,
which is a different job and one they still do.

engine: 12206 tests, 0 failures. Full reactor builds.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant