Repository navigation
fix(#6199, #6200): the flush drains wake on the page, and one suspended database's backlog is its own - #6223
Conversation
…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.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 36 |
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.
Review of #6223 (fixes #6199, #6200)Solid piece of work. Both fixes replace poll-based waits with proper guarded Correctness
Design
Test coverageCoverage 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 One gap: I didn't see a test exercising the Nits
Overall: no blocking issues found. The one race in |
…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).
ReviewI read through the full diff ( Correctness / concurrency
One thing worth double-checking (not confirmed as a bug)
Performance
Test coverageExcellent. SecurityNone of this touches trust boundaries or external input - no concerns. Minor nits
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).
|
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.
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 Two tests: On the other nit: leaving Full engine suite green: 12002 tests, 0 failures. |
ReviewThis 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 Nits
Things I specifically checked and found sound
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.
|
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 ( 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): 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:
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
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).
|
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:
New regression test On the smaller notes:
Full engine suite green: 12003 tests, 0 failures. |
Review of #6223I read through the full diff ( Overall assessmentThis is a well-reasoned pair of fixes. The core ideas check out:
Minor finding (low severity, correctness of a latency guarantee, not of results)
```java There's a narrow window in ```java 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 - Trivial fix if you want to close it: Test coverageVery thorough for concurrency-sensitive code: the new 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 I was unable to run a full |
…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).
|
Round 5's finding is valid and fixed in 3a2778d: Two things worth recording from writing the regression test, since both bear on how much the test is worth:
Full engine suite green: 12004 tests, 0 failures. |
ReviewI read through the full diff plus the surrounding, unchanged parts of 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:
One thing worth a sentence in the PR description rather than a code change: 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 Performance. The hot path ( 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. 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).
|
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 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 ( Full engine suite green: 12005 tests, 0 failures. |
Not up to standards ⛔🔴 Issues
|
| Category | Results |
|---|---|
| BestPractice | 1 medium |
🟢 Metrics 47 complexity
Metric Results Complexity 47
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.
ReviewThis is an unusually well-documented and self-critical PR — the javadoc essentially doubles as a design rationale, and the two new regression tests ( Correctness
Minor / residual gap (not blocking)
PerformanceThe stated goal (avoid Test coverageStrong. The new tests exercise the actual race windows (not just the happy path) with repeated-iteration stress tests, and the modified SecurityNo 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.
|
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 Code quality / design
Potential residual risk (already documented, flagging for visibility) Worth double-checking Tests Other 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.
|
Round 8's "worth double-checking" is checked, and the answer is recorded in the code rather than only here:
Worth noting this direction got less blocking, not more: before this PR a compaction thread could block unboundedly in On the timing note - acted on, and you were right to raise it:
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: |
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 One correction to round 8's answer, in
The conclusion the javadoc is defending - that a compaction thread parked in 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.
|
Round 9 is right and the correction is in 893168f. Verified before changing it: The javadoc now records your reason instead, which is the stronger one: |
|
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
Minor, non-blocking notes
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.
|
Round 10, all four notes: 1. Stale 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 It comes with a test that proves the assert fires ( 3. 4. Splitting the |
ReviewThis 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)
Style / nits
Test coverageGood — PerformanceThe hot path ( Minor question (not a blocker)
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.
|
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 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
Thanks for the eleven rounds - between them they turned up four genuine races that the first version of this PR shipped with. |
ReviewReviewed the diff for OverallThis 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. 2. Unrelated fix bundled in. The 3. Per-commit overhead. 4. Verbosity of in-code documentation. The javadoc-per-invariant style (e.g., the multi-paragraph explanation on Test coverageStrong. The two new regression test classes ( Security / performanceNo security concerns (no new external input handling). Performance impact is a deliberate, well-justified tradeoff: replacing polling sleeps with Nice work untangling a genuinely subtle set of races. |
|
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
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 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: 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. |
Not up to standards ⛔🔴 Issues
|
| Category | Results |
|---|---|
| BestPractice | 1 medium |
🟢 Metrics 47 complexity
Metric Results Complexity 47
🟢 Coverage 81.71% diff coverage · -6.48% coverage variation
Metric Results Coverage variation ✅ -6.48% coverage variation Diff coverage ✅ 81.71% diff coverage 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 Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
…-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.
…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.
…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.
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:
waitAllPagesOfDatabaseAreFlushedpolls every 10 ms, and everyclose(),rename(), index compaction, backup suspension and the snapshot barrier's first drain goes through it;waitPendingPagesOfDatabaseUntilpolls 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 thoseThread.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 (andremoveAllOfDatabasenotifies on a purge), and both waits callFlushPageIndex.awaitDraininstead 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
waitis 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,
flushPagesFromQueueToDiskreturned without polling at all. The bounded queue then filled andscheduleFlushOfPagesthrottled the committing threads - of every open database, not just of the suspended one - and, becausepublishPagesholds 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
MutablePagecopies of the samePageIdpending 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.publishPages, and directly inwritePagesfor the asynchronous compaction writes that do not go throughpublishPages. 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.deferredRAMBytesis 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.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 thewait(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.enginemodule suite green (11998 tests), includingIssue6133PendingPagesPerDatabaseTest,Issue6125SnapshotBarrierAndCapTest,PageManagerFlushSuspendDeferRaceTest,PageManagerFlushSuspendRefCountTest,Issue5326ApplyChangesPendingFlushTest,FlushRobustnessTestandPageSnapshotTest.