Skip to content

fix(#6259): a committer waits for flush-queue room before the page-manager lock, not inside it - #6269

Merged
lvca merged 2 commits into
mainfrom
issue-6259
Aug 17, 2026
Merged

lvca merged 2 commits into
mainfrom
issue-6259

Conversation

@lvca

@lvca lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member

Fixes #6259.

The bug

PageManager.publishPages holds the JVM-wide page-manager lock across both halves of publication - the synchronous page write and the scheduleFlushOfPages enqueue - and it has to: the snapshot t0 barrier (#6075/#6125) takes that same lock precisely so that from there on no committer can put a page on disk or into the flush pipeline, which is what makes its residual drain converge by construction.

The enqueue blocked, though:

// TRY TO INSERT THE PAGE IN THE QUEUE UNTIL THE THREAD IS STILL RUNNING
while (running) {
  if (queue.offer(new PagesToFlush(pages), 1, TimeUnit.SECONDS))
    return;
}

So whenever the bounded flush queue (arcadedb.pageFlushQueue, default 512, 8 under the low-ram profile) filled, the committing thread parked in that offer holding a lock every committer in the process needs. The queue fills whenever commits outrun the disk for a moment: a write burst, a slow or contended volume, an fsync spike, a compaction landing at the wrong time. No suspension, no backup, no HA involved - this is the non-suspension twin of #6200, which removed one trigger for this stall and left the other in place.

The result was that one database's write burst serialized the commits of every unrelated database in the JVM, including databases on a different, idle volume whose pages could have been written immediately.

The fix

The bounded queue is meant to backpressure the writers it belongs to; that part is right. What was wrong is only that the wait was served while holding a JVM-wide lock, so it was charged to everybody. The enqueue cannot move out of the lock without reintroducing the gap #6125 removed - so the wait moves ahead of it, exactly the shape #6200 established for the deferred-RAM cap ("the ceiling is global because heap is; the response must not be").

A committer now reserves its flush-queue slot before lock() and reaches the enqueue one line later with the slot already its own, so the offer inside the lock cannot block. The blocking offer stays as the safety net it always was.

if (asyncFlush) {
  awaitDeferredBacklogUnderCap(pagesToWrite);   // #6200
  flushSlotReserved = reserveFlushQueueSlot(pagesToWrite);   // #6259
}
lock();

Deliberately not a semaphore

The issue's own proposal suggested expressing the wait as "a permit/semaphore sized to the queue". This does not do that, and the difference is the point.

A permit count has to be kept in step with the queue by hand at every enqueue and every poll, and a single missed release silently shrinks the pipeline for the life of the process - an invisible, permanent bug with no symptom anyone would trace back. Admission here is derived from the queue's own size plus a counter of slots promised but not yet used:

if (queue.size() + reservations >= queueCapacity)
  return false;

so size + reservations <= capacity holds by construction, the holder of a reservation is guaranteed a free slot, and a batch that reaches the queue by any other route - a white-box test, a future call site - narrows admission instead of corrupting the bound. The cost is one ArrayBlockingQueue.size() per publication, which takes the same internal lock the offer on the next line takes anyway (and poll(timeout) releases that lock while it waits, so it is never held against a publication).

Signalled, not polled

The flush thread wakes a waiting committer the moment it polls a batch - before writing it, because the slot is free from that point, and a slow write should delay the writes rather than the admission of the next committer. When nobody is waiting (the normal state of a queue that is not full) the signal costs one volatile read per batch, the same shape as the drain signal of #6199.

Two paths the issue did not mention

Both would have reintroduced the bug in a narrower window, so both go through the same admission:

  • The resume's Phase 3b re-enqueue. A resume can carry thousands of deferred batches back into the queue. Without a reservation it could fill the queue under a committer that is holding one, putting that committer's offer back inside the page-manager lock.
  • The shutdown sentinel, which occupies a queue slot like any other batch - but is never allowed to wait for one, since the run loop already exits on its own once running is false and the queue is drained.

Observability

Adds flushQueueWaits to the page-manager stats and to both Profiler outputs. pageFlushQueueLength is an instant, sampled between two bursts as easily as during one; this is cumulative evidence that commits were actually held. A committer held for more than 10 s also says so once, at WARNING, naming the queue and the configuration key.

Verification

Issue6259FlushQueueAdmissionTest, 4 tests. The central one pins the invariant rather than the symptom, as the issue asked: while a committer is waiting for queue room, another thread must be able to take the page-manager lock. The flush thread is wedged on the batch monitor its write loop takes - a real code path, stopping the pipeline exactly where a stalled disk would - and always released on a deadline of its own, since a flush thread left wedged would hang every other test sharing the JVM.

That test was verified red against the previous shape: with the reservation removed it fails at exactly that assertion, having waited out the full 60 s for a lock the committer was holding while parked in offer.

The other three cover the mechanism: exactly arcadedb.pageFlushQueue callers are admitted and the next one waits; a reserved slot cannot be taken by another committer; and no path out of a publication leaves a reservation behind (a leak is silent and permanent, so it is asserted rather than inspected, with an assert guarding the fail-open direction).

  • Full engine suite green: 12090 tests, 0 failures, 0 errors.
  • Issue6125SnapshotBarrierAndCapTest green - it is what proves the publication lock still covers the enqueue.
  • Issue6200PerDatabaseDeferredBacklogTest and the whole flush-suspend suite green.
  • No measurable cost: 40000 commits took 629/639/637 ms and 645/656/629 ms with the admission step, against 638/633/640 ms and 652/642/641 ms without.

Follow-up left open

Making the flush queue per-database remains worth measuring: it would bound each database's backlog independently and remove the cross-database coupling at its source. It does not fix this bug on its own - a committer that blocks on its OWN full queue while holding the JVM-wide lock still stalls everyone - so it would have to be combined with the admission control in this PR regardless, which is why it is not bundled here.

…nager lock, not inside it

publishPages holds the JVM-wide page-manager lock across BOTH halves of publication - the
synchronous page write and the scheduleFlushOfPages enqueue - and it has to: the snapshot t0
barrier (#6075/#6125) takes that same lock precisely so no committer can put a page on disk OR
into the flush pipeline from there on. The enqueue blocked, though:

  while (running) { if (queue.offer(new PagesToFlush(pages), 1, SECONDS)) return; }

So whenever the bounded flush queue filled - a write burst, a slow or contended volume, an fsync
spike, no suspension or backup involved - the committing thread parked in that offer holding a
lock every committer in the process needs, and one database's burst serialized the commits of
every unrelated database in the JVM, including ones on idle volumes whose pages could have been
written immediately.

The queue is meant to backpressure the writers it belongs to; what was wrong is only that the wait
was charged to everybody. So the wait moves ahead of the lock, the shape #6200 established for the
deferred-RAM cap: a committer reserves its queue slot before lock() and reaches the enqueue with
the slot already its own, so the offer inside the lock cannot block. The enqueue itself does not
move, so the barrier's convergence argument is untouched.

Admission is derived from the queue's OWN size plus a reservation counter (size + reservations <
capacity) rather than from a Semaphore mirroring the queue: a permit count has to be kept in step
by hand at every enqueue and every poll, and one missed release silently shrinks the pipeline for
the life of the process, while reading the queue tells the truth by construction - a batch that
reaches it by any other route narrows admission instead of corrupting the bound. The flush thread
signals a free slot the moment it POLLS a batch, before writing it, so a slow disk delays the
writes and not the admission of the next committer.

The resume's re-enqueue of deferred batches and the shutdown sentinel go through the same
admission: a resume can carry thousands of batches, and without a reservation it could fill the
queue under a committer holding one, putting that committer's offer back inside the lock.

Also adds flushQueueWaits to the page-manager stats and the Profiler. Queue length is an instant,
sampled between two bursts as easily as during one; this is cumulative evidence that commits were
actually held.

The regression test pins the invariant rather than the symptom - while a committer waits for queue
room, another thread must still be able to take the page-manager lock - and was verified red
against the previous shape. Full engine suite green (12090 tests). 40000 commits took 629-656 ms
with the admission step and 633-652 ms without.
@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 30 complexity

Metric Results
Complexity 30

View in Codacy

🟢 Coverage 87.07% diff coverage · -6.53% coverage variation

Metric Results
Coverage variation ✅ -6.53% coverage variation
Diff coverage ✅ 87.07% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (4359848) 158758 125225 78.88%
Head commit (0b7d89a) 191199 (+32441) 138321 (+13096) 72.34% (-6.53%)

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 (#6269) 116 101 87.07%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

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

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review: fix(#6259) - committer waits for flush-queue room before the page-manager lock, not inside it

I traced the concurrency invariants by hand (the size + reservations <= capacity bound, reservation hand-off across publishPages -> writePagesNoBackpressure -> scheduleFlushOfPages, the resumeFlushing re-enqueue path, and closeAndJoin's shutdown sentinel) and didn't find a correctness bug. mvn wasn't runnable in this sandbox, so I couldn't execute the new test suite myself - the description's numbers (12090 tests green, the new test verified red against the pre-fix shape) are the evidence for that; worth a maintainer re-run before merge if that hasn't already happened in CI.

Correctness
The core admission-control invariant holds: every reservation is granted only while queue.size() + queueReservations < queueCapacity, and every reservation is resolved exactly once, either by converting into an offer() (net effect on the sum: zero, since size+1 and reservations-1 happen together) or by being given back via releaseQueueReservation(false). I walked all the paths that acquire a reservation - PageManager.reserveFlushQueueSlot (via publishPages/writePages), resumeFlushing's Phase 3b re-enqueue, and closeAndJoin's sentinel - and each has a try/finally that releases on every exit, including the interrupted and empty-batch cases. The 'double counting' window between a successful offer() and the matching releaseQueueReservation in scheduleFlushOfPages's finally only makes tryReserveQueueSlot more conservative for concurrent callers (never grants an extra slot), so it can't cause over-admission.

The wait/notify pattern in reserveQueueSlot()/signalQueueSlotAvailable() rechecks the real condition (queue.size() + reservations) under the queueSlotLock monitor before parking, not a boolean flag set by the signaler - so the if (queueSlotWaiters.get() == 0) return; fast path in the signal can't cause a permanently missed wakeup; at worst it costs one extra queueSlotWaitPollMillis (100ms default) tick, which matches what the comment on that field claims.

One thing worth double-checking against CI rather than my read of the code: Issue6259FlushQueueAdmissionTest.noPathLeavesAReservationBehind calls flush.closeAndJoin() on a PageManagerFlushThread built via smallQueueFlushThread(...) that was never start()ed. That relies on Thread.join() returning immediately for a thread in NEW state, which is correct per the Thread javadoc, but it's a slightly implicit assumption worth a one-line comment if it isn't already obvious to future readers of that test.

Design
The 'derive admission from queue.size() + reservations instead of a semaphore' choice is well justified in the comments (a missed release() on a semaphore is silent and permanent; reading the queue's own size is self-correcting). The reservation hand-off protocol (flushSlotReserved flows from publishPages outside the lock, through writePagesNoBackpressure, into scheduleFlushOfPages, which owns it from that point) is documented clearly enough at each hop that I could verify it without running the code.

Minor nits (non-blocking)

  • PageManagerFlushThread.java: the new field-alignment for DEFAULT_QUEUE_SLOT_WAIT_POLL_MILLIS / QUEUE_SLOT_WARN_MILLIS doesn't line up the = columns the way the surrounding fields do (around lines 78-84). Purely cosmetic.
  • The publishPages/writePagesNoBackpressure 'insurance' release paths (if (flushSlotReserved && !handedOver)) are dead code today per the PR's own comment ('nothing between the reservation and the call below can throw'). That's a reasonable defensive choice given how much this hinges on ownership transfer being exactly right, but it's worth flagging so a future refactor that does introduce a throwing call between the reservation and the hand-off doesn't assume the insurance already covers it - it only covers the state at the moment it was written.

Test coverage
Issue6259FlushQueueAdmissionTest is a strong regression test: it pins the invariant (lock available while a committer waits for queue room) rather than a symptom, and the description states it was verified red against the pre-fix code. The other three tests (exact admission count, reservation exclusivity, no-leak-on-any-exit-path) cover the mechanism well. I'd only add a concurrent-stress variant (many threads racing reserveQueueSlot/release against a small queue) to catch any TOCTOU regression in tryReserveQueueSlot's CAS loop under heavier contention than the deterministic single-threaded-per-step tests exercise - not blocking, since the invariant argument holds analytically, but it would be cheap insurance for future refactors of this class.

Performance / Security
No concerns. The added cost is one ArrayBlockingQueue.size() call per publication (already documented as sharing the queue's internal lock with the offer right after it) and the benchmark numbers in the PR description show no measurable regression. No security-relevant surface changed.

Overall: a well-reasoned, well-tested fix for a real cross-database stall. Nothing here blocks merge from my read.

Follow-up to the code review of #6269. Nothing it raised was blocking; these are the four points
it made, applied.

- A concurrent-stress test for the CAS loop of tryReserveQueueSlot, which the deterministic tests
  could not reach. Phase 1 races 12 threads on reservations alone, so the assertion is exact - with
  nothing enqueued the bound IS the number of reservations held at once - and it also asserts the
  race actually contended, or it would prove nothing. Phase 2 then runs the whole path (reserve,
  enqueue, drain) concurrently so the two halves of the sum move against each other, and asserts
  the accounting returns to zero. Verified red against a naive time-of-check/time-of-use version of
  the loop: it fails in 0.2 s, which is the regression a future refactor of this class would make.

- A note on why closeAndJoin returns immediately in noPathLeavesAReservationBehind: the flush
  thread there was constructed but never started, and join() on a NEW thread returns at once. What
  that assertion is about is the shutdown flag, not the join.

- The two "insurance" release paths now say what they cover going FORWARD rather than only that
  they are unreachable today: any statement a later refactor inserts between the reservation and
  the hand-off. The one in writePagesNoBackpressure is in fact reachable today - putPageInReadCache
  does I/O - and now says so.

- Column alignment of the two new constants.
@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

Went through PageManager.java, PageManagerFlushThread.java, Profiler.java, and the new Issue6259FlushQueueAdmissionTest in detail, tracing the reservation lifecycle through every exit path.

Correctness of the core mechanism

The admission control is the interesting part, and it holds up:

  • The queue.size() + reservations invariant. tryReserveQueueSlot() reads queue.size() and queueReservations non-atomically (two independent reads), then CASes the reservation count. I traced whether this could ever over-admit (the only direction that matters for safety): the CAS on reservations is exact via compare-and-swap, and the only staleness risk is on the queue.size() read. Because scheduleFlushOfPages release decrement always happens strictly after the queue.offer() that occupies the slot (both writes originate from the same thread, and ArrayBlockingQueue internal lock plus the AtomicInteger decrement are both synchronization actions), any observer that sees the decremented reservations is guaranteed to also see the incremented queue.size(). So the transition window only ever makes the computed sum larger than reality (briefly double-counted between offer() succeeding and the reservation being released), never smaller - it can cause a spurious wait, never an over-admission. Good.
  • Hand-off/release bookkeeping. Checked every path a reservation can take: publishPages -> writePagesNoBackpressure -> scheduleFlushOfPages (async), the synchronous-flush branch, resumeFlushing Phase 3b re-enqueue loop, and the shutdown sentinel in closeAndJoin. Each uses the same handedOver/try-finally pattern, and each releases exactly once. I specifically chased a suspicion that an early break in the Phase 3b loop (on shutdown or interrupt) would skip addDeferredRAM for the remaining un-visited batches and leak the deferred-RAM cap (a different counter than the queue reservation) - but releaseResidualDeferredRAM(database), called unconditionally in the outer finally, zeroes out whatever residual is left for that database and reconciles the JVM-wide total, so that case is already covered as the safety net the comment says it is. No leak there either.
  • wait/notify correctness in reserveQueueSlot/signalQueueSlotAvailable. Standard check-under-monitor-then-wait pattern; the queueSlotWaiters == 0 fast path in the signaller cannot cause a lost wakeup because a waiter always re-checks tryReserveQueueSlot() a second time after incrementing the waiter count and entering the same monitor the signaller needs for notifyAll() - so a concurrent poll+signal either lands before that second check (visible via the queue own lock) or blocks on the monitor until the waiter is genuinely inside wait().

No correctness bug found in the mechanism itself. It is a genuinely tricky bit of lock-free bookkeeping and the invariant reasoning in the comments matches what the code actually does, which is not always true of comments this size.

Minor / non-blocking observations

  • queueSlotWaits is incremented unconditionally before the slow-path loop in reserveQueueSlot(), including the harmless edge case where running is already false on entry and the loop body never executes - so the stat counts a wait that lasted ~0ms during shutdown. Cosmetic only, not worth a special case.
  • Issue6259FlushQueueAdmissionTest is not tagged @Tag("slow"). It is mostly fast (in-memory CAS races), but it does have a couple of deliberate await(500, MILLISECONDS) blocks used to assert "did not complete yet", plus thread start/join overhead across its 5 tests. Per CLAUDE.md guidance ("functional regression tests that take noticeably long"), might be worth a quick timing check to see whether it is a candidate for the slow lane - not a big deal either way given it is well under CI usual budget for a handful of threaded tests.
  • Small naming asymmetry: the new stat is flushQueueWaits on PPageManagerStats/PageManagerFlushThread, but surfaces as pageFlushQueueWaits in the JSON profiler output (matching the sibling pageFlushQueueLength naming there). Consistent with the existing convention in the file (e.g. deferredRAMBytes maps to "deferredRAM" in JSON), so just flagging for awareness, not asking for a change.

Verification

Was not able to run mvn in this review sandbox (tool execution required approval that was not available in this context), so verification here is static: reading the full diff plus the invariant reasoning above rather than executing the test suite. The PR description states the full engine suite (12090 tests) plus the targeted #6125/#6200 regression suites pass, and the new test theAdmissionBoundHoldsUnderContention specifically stress-tests the CAS bound under 12-way contention, which is the right test for the trickiest part of this change. That CI run (and a fresh one on the final diff) should be the actual gate before merge.

Summary

Solid, well-scoped fix for a real production issue (JVM-wide commit stalls caused by one database write burst). The design choice to derive admission from the queue own size rather than a hand-maintained semaphore is the right call, for exactly the reason given: no silent permanent leak from a missed release. No blocking issues found.

@codecov

codecov Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.86207% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.15%. Comparing base (4359848) to head (0b7d89a).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...va/com/arcadedb/engine/PageManagerFlushThread.java 75.64% 9 Missing and 10 partials ⚠️
...src/main/java/com/arcadedb/engine/PageManager.java 74.28% 6 Missing and 3 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6269      +/-   ##
==========================================
+ Coverage   70.11%   70.15%   +0.04%     
==========================================
  Files        1838     1838              
  Lines      158758   158846      +88     
  Branches    33489    33511      +22     
==========================================
+ Hits       111318   111444     +126     
+ Misses      33572    33537      -35     
+ Partials    13868    13865       -3     

☔ 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 17, 2026
@lvca
lvca merged commit d6da828 into main Aug 17, 2026
46 of 48 checks passed
@lvca
lvca deleted the issue-6259 branch August 17, 2026 00:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

publishPages blocks the committers of every database inside the JVM-wide page-manager lock whenever the flush queue fills

1 participant