Skip to content

fix(#6440): async flush pipeline strands WAL acks across a closed/reopened database - #6481

Merged
robfrank merged 5 commits into
mainfrom
fix/6440-gav-eligibility-slow-in-suite
Aug 20, 2026
Merged

robfrank merged 5 commits into
mainfrom
fix/6440-gav-eligibility-slow-in-suite

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Closes #6440

Summary

GAVEligibilityTest (and any test that repeatedly drop()s and create()s a database at the same path) paid up to TransactionManager's full 2000 ms retry budget on almost every close(), which is why it went from ~2s isolated to 35-60+ seconds inside the full opencypher suite in the issue's own measurements.

Root cause: a page is durably written to WAL during commit (WALFile.writeTransactionToFile increments WALFile.pagesToFlush), then handed to the async flush pipeline; only the pipeline's eventual disk write releases the ack (WALFile.notifyPageFlushed(), via MutablePage.takeWALFile()). Several spots in the flush pipeline correctly abandon a page - there's nothing left to write it to - without ever releasing that ack:

  • PageManager.flushPage()'s !database.isOpen() early return, and its DatabaseIsClosedException catch after the physical write already succeeded but the metadata update failed.
  • PageManagerFlushThread.flushPagesFromQueueToDisk()'s several "database closed mid-batch" branches, and its DatabaseMetadataException catches (file dropped).
  • PageManagerFlushThread.resumeFlushing()'s equivalents on the suspend/backup-resume path.

LocalDatabase.closeDurableParts() sets open = false before TransactionManager.close()'s retry loop runs, so any page still in flight at that instant is guaranteed to hit one of the paths above. TransactionManager.close() then waits its whole 2000 ms budget for a WAL counter nothing will ever decrement, before giving up and forcing the close anyway - for a drop(), where the files are about to be deleted regardless, that wait buys nothing but latency.

A second, related bug in the same area: PageManagerFlushThread.removeAllPagesOfDatabase and FlushPageIndex.removeAllOfDatabase matched pending pages with Database.equals(), which - like the rest of this class's bookkeeping - compares by path, not instance. A database closed and immediately reopened at the same path (exactly what a rapid drop()/create() cycle produces, e.g. a JUnit @BeforeEach/@AfterEach pair) could have its own still-queued batch wrongly discarded by a same-path sibling's belated cleanup. Fixed to match by reference identity, matching the precedent PagesToFlush.slotCharged already established for the sibling slotsInUse counter in #6281/#6303.

Investigation

The issue itself was an open-ended performance investigation ("nothing here is a diagnosis"), so most of the work was root-causing rather than implementing:

  1. Reproduced the reported slowdown by running the full com.arcadedb.query.opencypher package (8776 tests) and confirmed GAVEligibilityTest went from 1.9s isolated to 34-63s in-suite.
  2. jstack sampling during the slow window showed the test's main thread parked in TransactionManager.close()'s WAL-flush retry loop, sleeping through its full 20 x 100 ms budget.
  3. Bisecting the reproduction down showed it did not require the rest of the suite: a standalone loop that just creates a database at a fixed path, writes a few vertices, and drops it - nothing else running in the JVM - reproduced the same ~2000 ms stall roughly 1 time in 10.
  4. Live-sampled the flush pipeline's own bookkeeping (pageIndex, queue, slotsInUse) during a stall: all reported nothing pending, while the WAL file's own counter stayed stuck - proving the stall was a stranded ack, not a genuinely slow or backed-up flush.
  5. Instrumented WALFile's increment/decrement pairing directly, which pinpointed PageManager.flushPage()'s !database.isOpen() early return as the primary leak, then found the remaining smaller leaks (DatabaseMetadataException/DatabaseIsClosedException catches, resumeFlushing) by symmetry with the one already-correct sibling (removePagesOfFileFromBatch, which already acks on the same conditions).

Test plan

  • Added Issue6440FlushAckOnClosedDatabaseTest: white-box regression pinning that PageManager.flushPage() acks a page's WAL file when the database is already closed, and that a normal successful flush still acks exactly once (takeWALFile()'s exactly-once semantics).
  • Added Issue6440CrossInstanceFlushDiscardTest: white-box regression pinning that closing one database instance must not discard or evict a same-path sibling instance's still-pending pages/counters (PageManagerFlushThread.removeAllPagesOfDatabase, FlushPageIndex.removeAllOfDatabase). All three cases reproduce (fail) against the pre-fix code and pass after.
  • com.arcadedb.engine.** (828 tests) and com.arcadedb.database.** (262 tests) both green - no regressions in the surrounding flush/lifecycle machinery.
  • Full com.arcadedb.query.opencypher.** package (8776 tests, the original reproduction) rerun after the fix: GAVEligibilityTest now completes in ~1-3s (matching its isolated baseline) and zero tests anywhere in the run exhaust the 2000 ms retry budget.
  • mvn -o -pl engine -am compile clean.

Notes for reviewers

  • No public API changed; all changes are internal to the flush pipeline (PageManager, PageManagerFlushThread, FlushPageIndex).
  • The fix is deliberately conservative about when to ack: it only does so for !database.isOpen()/DatabaseMetadataException/DatabaseIsClosedException (nothing left to recover onto), never for a genuine IOException (where withholding the ack correctly preserves the WAL for recovery on the next open - untouched by this change).

…pened database

GAVEligibilityTest (and any test that repeatedly drop()s and create()s a database at
the same path) paid up to TransactionManager's full 2000 ms retry budget on almost
every close(), turning a ~2s class into one taking 35-60+ seconds inside the full
opencypher suite - the original report for this issue.

Root cause: a page is durably written to WAL during commit (incrementing
WALFile.pagesToFlush), then handed to the async flush pipeline; only the pipeline's
eventual disk write releases the WAL ack (WALFile.notifyPageFlushed, via
MutablePage.takeWALFile()). Several spots in the flush pipeline abandon a page -
correctly, there is nothing left to write it to - without ever releasing that ack:

- PageManager.flushPage()'s `!database.isOpen()` early return, and its
  DatabaseIsClosedException catch after a successful write but a failed metadata
  update.
- PageManagerFlushThread.flushPagesFromQueueToDisk()'s several "database closed
  mid-batch" branches, and its DatabaseMetadataException catches (file dropped).
- PageManagerFlushThread.resumeFlushing()'s equivalents for the suspend/backup path.

LocalDatabase.closeDurableParts() sets open=false BEFORE TransactionManager.close()'s
retry loop runs, so any page still in flight at that moment is guaranteed to hit one
of these paths. TransactionManager.close() then waits its whole budget for a WAL
counter that nothing will ever decrement, before giving up and forcing the close
anyway - for a drop(), where the files are about to be deleted regardless, that wait
buys nothing.

A second, related bug in the same area: PageManagerFlushThread.removeAllPagesOfDatabase
and FlushPageIndex.removeAllOfDatabase matched pending pages with Database.equals(),
which - like the rest of this class's bookkeeping - compares by PATH, not instance.
A database closed and immediately reopened at the same path (exactly what a rapid
drop()/create() cycle produces) could have its OWN still-open batch wrongly discarded
by a same-path sibling's belated cleanup. Fixed to match by reference identity.

Reproduced in isolation (a tight create/write/drop loop at a fixed path stalled
roughly 1 time in 10, even with the JVM otherwise idle) and root-caused precisely by
instrumenting the WAL increment/decrement pairing. Verified against the full
opencypher package (8776 tests): GAVEligibilityTest went from 34-63s down to ~1-3s,
matching its isolated baseline, with zero retry-budget exhaustions anywhere in the run.

Closes #6440
@mergify

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

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 17 complexity

Metric Results
Complexity 17

View in Codacy

🟢 Coverage 80.88% diff coverage · -6.52% coverage variation

Metric Results
Coverage variation ✅ -6.52% coverage variation
Diff coverage ✅ 80.88% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (55b9c93) 163107 130190 79.82%
Head commit (cbe062f) 195550 (+32443) 143331 (+13141) 73.30% (-6.52%)

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 (#6481) 68 55 80.88%

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 19, 2026

Copy link
Copy Markdown

Review

This is a well-investigated fix, and the root-cause writeup (stranded WAL acks in the abandon-paths of the flush pipeline) is convincing and well-supported by the two new regression tests. The takeWALFile()/exactly-once discipline is applied consistently everywhere it needs to be (PageManager.flushPage, all the abandon branches in PageManagerFlushThread, and the batch/queue purge), and it correctly avoids acking on a genuine IOException (where withholding the ack for WAL replay is still required). Nice reuse of the existing takeWALFile()/notifyPageFlushed() precedent from #4928 rather than inventing a new mechanism.

Possible remaining gap: FlushPageIndex.pending counter aliasing on insertion, not just removal

removeAllOfDatabase was correctly changed to match by reference identity (entry.getKey() == database) instead of equals(), to stop a same-path sibling's counter from being wiped by a belated cleanup of the old instance. However, the insertion side (counterOf(), used by put()/putAll()) is still equals()-based:

private AtomicInteger counterOf(final BasicDatabase database) {
  final AtomicInteger counter = pending.get(database);
  return counter != null ? counter : pending.computeIfAbsent(database, k -> new AtomicInteger());
}

Since pending is a plain ConcurrentHashMap<BasicDatabase, AtomicInteger> and LocalDatabase.equals()/hashCode() are path-based, pending.get(B) will happily return A's counter object if A's entry is still present when B's first page is scheduled - the map has no way to tell A and B apart. Walking through the interleaving the class's own new javadoc calls out ("that lock argument only holds within ONE instance"):

  1. A is closing; its pending entry (keyed by the A instance) still exists (possibly already decremented to 0, but not yet removed - removeAllOfDatabase is what removes it, not release()).
  2. B is opened at the same path and commits before A's teardown reaches removeAllPagesOfDatabase(A) (exactly the race this PR is fixing elsewhere - B can run fully concurrently with A's teardown, since they hold different ReentrantReadWriteLock instances).
  3. B's first put()/putAll() calls counterOf(B) -> pending.get(B) finds A's still-present entry (A.equals(B) is true) and returns A's AtomicInteger, keyed under A. B's page increments A's counter, not a fresh one.
  4. A's belated removeAllOfDatabase(A) now runs. The pages-map removal correctly ignores B's page (reference identity), but the counter loop finds entry.getKey() == A -> true (it really is A's key) -> removes and zeroes the counter B has just incremented into.
  5. pageIndex.pendingOf(B) (and hasPendingOf(B)) now reports 0/absent even though B's page is still genuinely indexed in pages and un-flushed.

That breaks the invariant the class's header explicitly relies on ("pendingOf() == 0 proves the pipeline is empty"), and the two callers that trust it are exactly the ones the header warns about: waitAllPagesOfDatabaseAreFlushed (close/drop) and waitPendingPagesOfDatabaseUntil (the snapshot t0 barrier) could both return "drained" for B while a page is still in flight - the "backup stamps its t0 over a half-written batch" scenario the class docs call out as the failure this bookkeeping exists to prevent.

The two new tests (flushIndexRemoveAllOfDatabaseMustNotEvictASamePathSiblingsEntry in particular) don't quite exercise this: they build open's entry in a pending map that never had closing in it, so counterOf(open) always gets a fresh entry. The failure mode above needs closing's entry to still be present before open's first page arrives.

If this interleaving is in fact reachable (I believe it is, given the PR's own description of B being creatable while A's teardown is still stalling), the fix looks like it needs to be symmetric: counterOf/put/putAll also need reference-identity semantics against pending, not just removeAllOfDatabase. Might be worth a regression test that mirrors flushIndexRemoveAllOfDatabaseMustNotEvictASamePathSiblingsEntry but calls put() for open before removeAllOfDatabase(closing), with closing's entry pre-seeded in pending (e.g. via a put() for closing first, then remove()'d down to 0 without going through removeAllOfDatabase) to reproduce the aliasing at insertion time.

Minor notes

  • removeAllOfDatabase's counter lookup is now a linear scan of pending.entrySet() instead of an O(1) remove(). Given pending is bounded by the number of currently-tracked (open + recently-closing) databases and this only runs once per close/drop, this is not a hot path and is fine performance-wise - just noting the complexity change for the record.
  • The new ackWalFileOfAbandonedPage helper is a nice consolidation of the repeated "grab and ack" pattern that had been growing across the several catch/abandon branches.

Test coverage

Good white-box coverage of the two documented failure modes (stranded ack on close, and same-path sibling page discard), including a "must still ack exactly once" sanity check on the happy path. As above, I think there's one more interleaving for the counter specifically that isn't covered yet.

…nsertion too

Claude's review correctly identified that fixing removeAllOfDatabase's removal
side alone was not sufficient: counterOf() (used by put()/putAll() on the commit
path) still resolved pending's counter with a plain, equals()-based map lookup,
so a brand-new database's first page could still land on a same-path sibling's
stale-but-not-yet-forgotten counter entry - which that sibling's own eventual
cleanup would then zero out from under the live instance.

Fixes it at the root: pending is now keyed by a small identity-only wrapper
(IdentityKey) instead of BasicDatabase directly, so every access - counterOf,
release, pendingOf, isTracked, awaitDrain, removeAllOfDatabase - agrees on
identity semantics, keeps O(1) complexity (no scan), and also simplifies
removeAllOfDatabase's counter removal back to a single map.remove() call.

Added a regression test that pre-seeds a same-path sibling's drained-but-still-
tracked counter entry before the live instance's first page arrives, confirmed
it fails against the previous (removal-only) fix, and passes with this one.
@robfrank

Copy link
Copy Markdown
Collaborator Author

Good catch, thanks. You're right that fixing removeAllOfDatabase's removal side alone left counterOf() (insertion, via put()/putAll()) still resolving pending with a plain equals()-based lookup, so a same-path sibling's stale-but-still-tracked entry could be handed to a brand-new instance's first page.

Fixed in c7d6f33 by keying pending on a small identity-only wrapper (IdentityKey) instead of BasicDatabase directly, so every access point - counterOf, release, pendingOf, isTracked, awaitDrain, removeAllOfDatabase - agrees on identity semantics. This also addresses your minor note: removeAllOfDatabase's counter removal is back to an O(1) map.remove() instead of the entrySet scan.

Added flushIndexCounterOfMustNotAliasASamePathSiblingsCounterOnInsertion, which pre-seeds a same-path sibling's drained-but-still-tracked entry before the live instance's first page arrives - exactly the interleaving you described. Confirmed it fails against the removal-only fix (expected: 1 but was: 0) and passes with the identity-keyed map.

@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Review

Nicely root-caused fix, and the inline comments do a lot of the reviewer's work already. A few notes below; nothing blocking.

Correctness

  • WAL-ack-on-abandon is sound. MutablePage.takeWALFile() is AtomicReference.getAndSet(null), so every new ackWalFileOfAbandonedPage() call site is exactly-once even when it races the normal success path (TransactionManager.notifyPageFlushed) or another abandon path on the same page. I traced all the new call sites in PageManager.flushPage() and PageManagerFlushThread (early !isOpen() return, DatabaseIsClosedException/DatabaseMetadataException catches, closed-mid-batch branches, resumeFlushing()) and confirmed each only fires on a 'nothing left to write this to' path, never on a genuine IOException - consistent with the stated policy of preserving the WAL for recovery on a real I/O failure.
  • IdentityKey fix is correctly scoped. pending's wrapper never escapes FlushPageIndex (no other code iterates/holds onto pending's keys), and all seven access points (counterOf, release, pendingOf, isTracked, awaitDrain, removeAllOfDatabase, plus the pages scan in removeAllPagesOfDatabase) were updated consistently. Good catch in the second commit that insertion (counterOf) needed the same identity semantics as removal - a removal-only fix would have left the aliasing bug reachable from the other direction, and the new flushIndexCounterOfMustNotAliasASamePathSiblingsCounterOnInsertion test pins exactly that.
  • Negative counter tolerance: notifyPageFlushed() does an unguarded decrementAndGet(), and callers only check > 0 / == 0, so even if some future edge case double-notified, it wouldn't wedge close() - it would just make the count go negative and read as 'drained.' Worth knowing, not worth changing here.

Minor / non-blocking

  • Small allocation on the hot path: counterOf, release, pendingOf, etc. now allocate a new IdentityKey(database) per call, including on the per-page flush/release path. It's a short-lived, non-escaping object so it should scalar-replace under escape analysis, but given this repo's stated performance mantra it might be worth a one-line note confirming this tradeoff was deliberate, or a quick allocation-profile check under the opencypher suite. Not asking for a change, just flagging since the project explicitly calls out GC pressure as a first-class concern.
  • Unrelated reformatting: the pages field declaration in FlushPageIndex lost its column-alignment spaces (ConcurrentHashMap<PageId, MutablePage> pages = became single-spaced). Harmless, but worth checking it doesn't fight the project's formatter on the next auto-format pass.
  • The DatabaseMetadataException | IOException combined catch in resumeFlushing()'s inner retry was split into two catches so only the metadata-exception one acks. Confirmed DatabaseMetadataException extends ArcadeDBException (not IOException), so the split doesn't change catch ordering/compilability, and behavior for the real-IOException path (log + Thread.interrupted(), no ack) is unchanged from before. Looks right.

Test coverage

Good white-box regression coverage for both bugs (Issue6440FlushAckOnClosedDatabaseTest, Issue6440CrossInstanceFlushDiscardTest), including a 'normal path still acks exactly once' sanity test so the fix can't be trivially over-corrected into a double-ack. Using reflection to bump WALFile.pagesToFlush directly to simulate the post-WAL-write/pre-flush state is a reasonable way to drive an otherwise hard-to-schedule race deterministically, and the PR description's own numbers (34-63s to 1-3s on the full opencypher suite) are a convincing before/after.

One gap: there's no test exercising flushPagesFromQueueToDisk's mid-batch 'database closed during iteration' branch (the one that now calls ackWalFileOfAbandonedPage inside the for (MutablePage remaining : ...) loop) or resumeFlushing()'s deferred-batch ack paths directly - both are covered by inference from the flushPage/removeAllPagesOfDatabase tests plus the full-suite rerun, but a targeted unit test for those two branches would close the loop the same way the existing tests do for the others. Not blocking given the strength of the existing evidence, but worth considering if there's ever a regression in that area specifically.

Overall: solid, conservative fix with unusually thorough investigation and documentation. No security or dependency concerns; changes are fully internal to the flush pipeline with no public API impact.

…meFlushing ack paths

Claude's review flagged that flushPagesFromQueueToDisk's mid-batch "database closed"
branch and resumeFlushing's deferred-batch equivalent were only covered by inference
(the full-suite before/after and the other white-box tests), not directly.

Added flushPagesFromQueueToDiskAcksABatchWhoseDatabaseIsAlreadyClosed and
resumeFlushingAcksADeferredBatchWhoseDatabaseIsAlreadyClosed, driving each through
the real PageManagerFlushThread entry points (flushPagesFromQueueToDisk, setSuspended)
rather than calling PageManager.flushPage directly. Verified both fail (temporarily
reverting their respective ack call, confirmed "expected: 0 but was: 1", then restored)
against the code without this PR's fix.

Also added a one-line note to IdentityKey's javadoc on the allocation tradeoff, per
the review's minor note - a short-lived, non-escaping wrapper, and strictly less than
the AtomicInteger the same call site already allocates on a miss.
@robfrank

Copy link
Copy Markdown
Collaborator Author

Addressed in 000a9f5:

  • Added flushPagesFromQueueToDiskAcksABatchWhoseDatabaseIsAlreadyClosed and resumeFlushingAcksADeferredBatchWhoseDatabaseIsAlreadyClosed, driving each through the real PageManagerFlushThread entry points (flushPagesFromQueueToDisk, setSuspended) rather than calling PageManager.flushPage directly. Verified both fail (expected: 0 but was: 1) by temporarily reverting their respective ackWalFileOfAbandonedPage call, then restored.
  • Added a one-line note to IdentityKey's javadoc confirming the allocation tradeoff was deliberate: a short-lived, non-escaping wrapper, and strictly less than the AtomicInteger the same call site already allocates on a miss.
  • On the pages field alignment: there's no longer a sibling field to align it with (pending's declaration now has a multi-paragraph javadoc block above it rather than sharing a line), so I left it as a plain single-spaced declaration rather than reintroducing padding that has nothing to line up against.

All 831 tests in com.arcadedb.engine still green, and the full com.arcadedb.query.opencypher package (8776 tests) rerun clean with GAVEligibilityTest at ~1s.

@claude

claude Bot commented Aug 19, 2026

Copy link
Copy Markdown

Review

This is a well-investigated fix, the root-causing writeup and the jstack/instrumentation methodology in the PR description are genuinely convincing, and the takeWALFile()/notifyPageFlushed() exactly-once pairing is used correctly and consistently everywhere the new ackWalFileOfAbandonedPage() helper is called (including the two racing callers in PageManager.flushPage() and PageManagerFlushThread, which is exactly the kind of place a double-release would otherwise sneak in).

I traced through TransactionManager.close()'s preserve/pendingAcks logic and LocalDatabase.closeDurableParts()'s ordering (the flush-wait runs, and preserveWalForRecovery is decided, before open flips to false) to check whether acking an abandoned page could cause the WAL to be deleted while the page's data was never actually durable. It looks safe: for a plain close() the "give-up" path already forces preserveWalFiles=true independent of the new acks, and for drop() the WAL files are deleted unconditionally (force=true) regardless of pending acks, so the new eager acks only shorten the wait, they don't change the final durability decision. Good.

Possible correctness gap: FlushPageIndex.pages wasn't given the same identity treatment as pending

removeAllOfDatabase() was fixed to purge pending by IdentityKey (a real improvement, and the counterOf() insertion-side fix in the second commit closes a genuine hole in the first pass). But the bulk purge of the pages map itself is still identity-based over the retained map keys, not over the map's live values:

pages.keySet().removeIf(pageId -> pageId.getDatabase() == database);

PageId.equals()/hashCode() go through database.equals() (path-based, per LocalDatabase), and pages is a plain ConcurrentHashMap<PageId, MutablePage>. ConcurrentHashMap.put() (like HashMap.put()) never replaces an already-present key on an equals-match, it only overwrites the value. So if a stale page from the closing instance A is still indexed at PageId(A, fileId, pageNumber) when a same-path sibling B later calls pages.put(PageId(B, fileId, pageNumber), pageB) for the same (fileId, pageNumber), the map keeps A's original PageId object as the key and just swaps in pageB as the value. When A's belated removeAllOfDatabase(A) then runs, pageId.getDatabase() == A is still true for that retained key, so the entry, whose value is now B's live page, gets evicted, exactly the "silently drops writes with no error, no WAL replay to fall back on" failure the new class javadoc calls out for pending.

counterOf()/put()/putAll() increment pending via IdentityKey, so the counter can't be aliased this way any more, but the pages entry backing it can still be silently stolen through this path, which would leave pendingOf() permanently non-zero for a page that no longer has a queue/index entry backing it (a different, self-inflicted hang than the one this issue fixes).

I want to flag the caveat honestly: I couldn't fully verify this is reachable through the normal DatabaseFactory open/close path, since the exclusive database.lck file lock is released only after removeAllPagesOfDatabase()'s catch-all purge has already run synchronously inside close(), which looks like it closes the window for the sequential "drop() then create()" pattern this PR's own tests use. But:

  • None of the new regression tests exercise a same-(fileId, pageNumber) collision between the closing and reopened instance (the pending-aliasing test intentionally uses two different page numbers, so it never touches this).
  • If there's a code path that can reach removeAllOfDatabase()/removeAllPagesOfDatabase() without going through that lock-file gate (e.g. some in-process/embedded reuse path, or simply future code that calls these lower-level methods directly, as the white-box tests already do), the aliasing is live.

Worth either: (a) adding a regression test that makes two same-path instances collide on the exact same (fileId, pageNumber) and asserting the live instance's page survives removeAllOfDatabase(), or (b) a short comment on pages/removeAllOfDatabase() explaining why the lock file makes this unreachable in practice, matching the level of rigor the surrounding javadoc already applies to pending.

Minor: two of the three "whole batch abandoned" branches skip removeFromFlushIndex

In flushPagesFromQueueToDisk(), the two early-return branches added around the !db.isOpen() / !pagesToFlush.database.isOpen() checks (before the per-page loop) call ackWalFileOfAbandonedPage() for every page but not removeFromFlushIndex(), unlike the third, pre-existing "closed mid-batch" branch inside the per-page loop, which does both together. It's not a leak, since removeAllPagesOfDatabase()'s later catch-all (pageIndex.removeAllOfDatabase(database)) still cleans these up, but it does mean pageIndex.pendingOf(database) stays inflated for a database that's already had its WAL acks released, for whatever gap exists until that catch-all runs. Tightening these two branches to also call removeFromFlushIndex() would make all three "abandoned batch" branches consistent and remove the temporary mismatch between "WAL says done" and "pageIndex says pending".

Nits

  • Test coverage for the primary bug (stranded WAL ack on !isOpen()/DatabaseMetadataException/DatabaseIsClosedException) is thorough and appropriately white-box, given these are genuine scheduling races that can't be forced through the public API. Good regression pinning, including the "acks exactly once" sanity check.
  • The IdentityKey allocation tradeoff is reasonably justified in the javadoc (short-lived, non-escaping, cheaper than the AtomicInteger already allocated on a miss).

Overall this looks like a solid, carefully-reasoned fix for the stated issue; the pages map gap above is the one thing I'd want resolved (or explicitly justified) before merging, since it's the same class of cross-instance aliasing bug this PR otherwise goes out of its way to eliminate.

…ounter fallout

Claude's third review found a deeper layer of the same aliasing:
removeAllOfDatabase's pages purge filtered by the RETAINED map key's database
identity, not the indexed page's. PageId collides as a map key across same-path
instances too (PageId.equals()/hashCode() go through path-based Database.equals()),
and Map.put() on an equals()-match keeps the ORIGINAL key object and only swaps
the value - textbook Java Map behavior. So when a same-path sibling indexes a
page at the exact same (fileId, pageNumber) a closing instance used, the map's
stored key is still the OLD instance's PageId even though the value is the new
instance's live page - filtering the bulk purge by that retained key's identity
would still evict the live page.

Fixed by filtering on the VALUE's own PageId (MutablePage.getPageId(), set when
that specific page object was created) instead of the map's retained key.

That same map-key collision exposed a second bug found while writing the
regression test: put()/putAll()'s "a later TX superseded a page still queued"
branch (#4544) always decremented the INCOMING page's counter when pages.put()
returned a replaced value - correct within one database, wrong across two: the
replaced value can belong to a different same-path instance, so the decrement
must target THAT instance's own counter, not the incoming page's, or a live
sibling's pending count is phantom-inflated forever.

Also tightened the two "whole batch abandoned" branches in
flushPagesFromQueueToDisk to release the pageIndex entry together with the WAL
ack (they already did the ack; the index release was previously left to
removeAllPagesOfDatabase's later catch-all), matching the third, pre-existing
branch and removing the temporary "WAL says done, pageIndex says pending" window
between them.

Added flushIndexRemoveAllOfDatabaseMustNotEvictASamePathSiblingsPageOnMapKeyCollision
and flushIndexPutMustReleaseTheReplacedPagesOwnCounterNotTheIncomingPages. Verified
both fail against the pre-fix code (temporarily reverted each fix in isolation,
confirmed the expected failure, restored) before finalizing.
@robfrank

Copy link
Copy Markdown
Collaborator Author

You're right, and the durability trace (preserve/pendingAcks decided before open flips) is a good sanity check to have on record - thanks for doing it.

Fixed in ae1574c:

  • removeAllOfDatabase's pages purge now filters on the VALUE's own PageId (MutablePage.getPageId()) instead of the retained map key, closing exactly the Map.put()-keeps-the-old-key gap you traced through.
  • While writing the regression test for that (two same-path instances colliding on the exact same (fileId, pageNumber)), I found a second bug the same collision exposes: put()/putAll()'s "a later TX superseded a page still queued" branch always decremented the incoming page's counter on a replace, which is wrong once the replaced value can belong to a different instance - it now decrements the replaced page's own counter instead.
  • Tightened both "whole batch abandoned" branches in flushPagesFromQueueToDisk to release the pageIndex entry together with the WAL ack, per your minor note.

Added flushIndexRemoveAllOfDatabaseMustNotEvictASamePathSiblingsPageOnMapKeyCollision and flushIndexPutMustReleaseTheReplacedPagesOwnCounterNotTheIncomingPages; verified both fail against the pre-fix code (temporarily reverted each in isolation, confirmed the expected failure, restored).

All 833 tests in com.arcadedb.engine green, full opencypher package (8776 tests) rerun clean, GAVEligibilityTest still ~1s.

@claude

claude Bot commented Aug 19, 2026

Copy link
Copy Markdown

Review

This is a well-investigated fix with excellent documentation of the root cause and a strong regression-test suite (the WAL-ack leak in PageManager.flushPage()/PageManagerFlushThread and the three rounds of same-path-instance aliasing fixes in FlushPageIndex are all convincingly reasoned and pinned by white-box tests). One correctness gap survived those rounds, though.

Possible bug: PageManagerFlushThread.removeAllPagesOfDatabase still evicts by equality, not identity

engine/src/main/java/com/arcadedb/engine/PageManagerFlushThread.java, in removeAllPagesOfDatabase (around line 1573-1574):

for (final MutablePage page : pagesToFlush.pages) {
  pageIndex.remove(page.getPageId());
  ...
  ackWalFileOfAbandonedPage(page);
}

FlushPageIndex.remove(PageId) does a plain pages.remove(pageId) — an equals()-based map removal, not the identity-safe removeIfSame(MutablePage) that removeFromFlushIndex() uses everywhere else in this same file (e.g. the finally in flushPagesFromQueueToDisk, resumeFlushing). Since PageId.equals()/hashCode() go through Database.equals() (path-based, confirmed in PageId.java), and Map.put() on an equals()-match keeps the original key object and only swaps the value (the exact mechanism this PR's third commit spent a lot of care documenting for FlushPageIndex.removeAllOfDatabase), the same collision applies here:

  1. Database closing queues a page P at PageId(closing, fileId, pageNumber) in both pageIndex and its own batch in queue, then starts closing while that batch is still unflushed.
  2. A new instance open, reopened at the same path, writes a page at the same (fileId, pageNumber). pageIndex.put(openPage) replaces the map's value but the map's stored key remains closing's original PageId object (textbook Map.put() behavior, per this PR's own reasoning elsewhere).
  3. removeAllPagesOfDatabase(closing) correctly finds closing's own batch in queue (reference-identity matched, already fixed), but then calls pageIndex.remove(page.getPageId()) using closing's PageId — which matches by equals() and deletes whatever is currently stored there, i.e. open's live, unflushed page. open's page is silently dropped from pageIndex without ever being flushed through this path, and — because the removed value is open's MutablePage, not closing's — ackWalFileOfAbandonedPage(page) (called with closing's own page object) never acks open's WAL entry either. open's own pending counter in FlushPageIndex.pending (now identity-keyed to open) is also never decremented for this page, since the removal's internal release() resolves pageId.getDatabase() (the retained stale key's database, i.e. closing), not open. That's the same "stranded ack / stuck counter" failure mode this whole PR exists to fix, just re-introduced one call site over.

The fix already exists in the file and is one line: use pageIndex.removeIfSame(page) (i.e. removeFromFlushIndex(page)) instead of pageIndex.remove(page.getPageId()) here, exactly as the rest of the pipeline does.

None of the five new tests in Issue6440CrossInstanceFlushDiscardTest exercise this: closingADatabaseMustNotDiscardAStillOpenSamePathSiblingsQueuedPage never gives closing its own queued batch (only open has one), so the buggy line's loop body never runs for a colliding page. It'd be worth adding a variant where both closing and open have pages queued at the same (fileId, pageNumber), and closing's own (still-open) batch is present in queue when removeAllPagesOfDatabase(closing) runs.

Secondary/lower-priority note

removePagesOfFileFromBatch (pre-existing, not touched by this PR) has the identical pattern — pageIndex.remove(page.getPageId()) instead of removeIfSame — and its guard (database.equals(pagesToFlush.database)) is itself path-based rather than reference-based. It wasn't introduced by this PR, but since this PR is already hardening this exact aliasing class throughout the file, it's worth a follow-up look (possibly in a separate PR/issue) rather than leaving one sibling method inconsistent with the rest.

Everything else looks solid

  • The ack-vs-withhold policy (DatabaseMetadataException/!isOpen()/DatabaseIsClosedException → ack; plain IOException → withhold, preserving WAL recovery) is applied consistently across PageManager.flushPage, flushPagesFromQueueToDisk, and resumeFlushing, and takeWALFile()'s exactly-once semantics make the added ack calls safe even where they're redundant with an existing success-path ack.
  • IdentityKey is a reasonable, well-justified way to fix the pending map's aliasing without an O(open databases) scan; the allocation cost is in cold/error paths or call sites invoked once per wait-check, not per-page hot loops, so the performance tradeoff documented in the Javadoc is fine.
  • No public API or dependency changes; nothing here raises security concerns.
  • Test coverage for the primary bug (stranded WAL ack on close) is thorough and directly pins the real interleaving through the actual entry points rather than only inferring from before/after timing, per the PR's own description of round 3 of review.

Nice piece of root-causing on a genuinely nasty async/identity bug — the one gap above is very much in the spirit of the aliasing class this PR already hunted down three times.

…quals()-based remove

Claude's fourth review found one more instance of the same map-key collision:
removeAllPagesOfDatabase evicted pageIndex entries with pageIndex.remove(page.getPageId()),
a plain equals()-based removal, instead of the identity-safe removeIfSame the rest
of the pipeline already uses (the finally in flushPagesFromQueueToDisk, resumeFlushing).

When a closing database's OWN queued batch collides at the same (fileId, pageNumber)
with a same-path sibling's later page - Map.put()'s "keep the old key on an equals()
match" behavior leaves the closing instance's PageId as the stored key even after
the sibling's page becomes the value - the unconditional remove(PageId) evicted (and
left unacked) the sibling's live page, exactly the stranded-ack failure this PR exists
to fix, reintroduced one call site over.

Fixed by using removeFromFlushIndex (removeIfSame) instead, which only ever removes
the exact page instance it was given.

Added closingADatabaseMustNotEvictASamePathSiblingsPageItsOwnQueuedBatchCollidesWith,
giving BOTH the closing and the reopened instance a queued batch at the same
(fileId, pageNumber). Verified it fails against the pre-fix code (temporarily reverted
to pageIndex.remove(page.getPageId()), confirmed the failure, restored).
@robfrank

Copy link
Copy Markdown
Collaborator Author

Good catch - confirmed and fixed in cbe062f: removeAllPagesOfDatabase now uses removeFromFlushIndex (removeIfSame) instead of the equals()-based pageIndex.remove(page.getPageId()), so it only ever removes the exact page instance it was given, never a same-path sibling's live page sitting at a colliding map key.

Added closingADatabaseMustNotEvictASamePathSiblingsPageItsOwnQueuedBatchCollidesWith, giving both the closing and the reopened instance a queued batch at the same (fileId, pageNumber) - exactly the scenario you traced. Verified it fails against the pre-fix code (temporarily reverted to pageIndex.remove(page.getPageId()), confirmed the failure, restored).

On the secondary note (removePagesOfFileFromBatch's identical pattern): agreed it's the same class of bug, but since it's pre-existing and not touched by this PR, I'll leave it as a follow-up rather than expand this PR's scope further, per your own framing of it as lower-priority.

This closes out review cycle 4 of 4 for this PR. All 834 tests in com.arcadedb.engine green, full opencypher package (8776 tests) rerun clean, GAVEligibilityTest ~1s. I'll stop here per the review-cycle budget; happy to keep iterating if you flag anything further; otherwise this is ready for a maintainer to merge.

@claude

claude Bot commented Aug 19, 2026

Copy link
Copy Markdown

Review

This is an exceptionally well-documented fix, and the iterative process visible in the commit history (five rounds of self-review catching progressively deeper layers of the same cross-instance aliasing) already closed most of the sharp edges a first pass would miss. Root-causing looks solid: the "ack must happen for !isOpen()/DatabaseMetadataException/DatabaseIsClosedException, never for a genuine IOException" policy is applied consistently across all three files, and takeWALFile()'s exactly-once semantics make the new call sites safe against the pre-existing racing callers.

Potential remaining gap: FlushPageIndex.releaseReplacedCounter can resurrect an already-purged sibling's counter

FlushPageIndex.java:182-186:

private void releaseReplacedCounter(final MutablePage replaced, final BasicDatabase incomingDatabase,
    final AtomicInteger incomingCounter) {
  final BasicDatabase replacedDatabase = replaced.getPageId().getDatabase();
  (replacedDatabase == incomingDatabase ? incomingCounter : counterOf(replacedDatabase)).decrementAndGet();
}

counterOf() is get-or-create (computeIfAbsent). If a same-path sibling A's removeAllOfDatabase(A) has already run (removing A's pending entry) by the time a racing B.put()/putAll() resolves the page it replaced back to A (i.e. B's pages.put() raced ahead of A's purge of that same map slot, which the class's own javadoc at lines 68-76 says is possible - the write-lock argument only holds within one instance), counterOf(A) here recreates a fresh entry for A and decrements it to -1.

Consequences:

It's not a correctness/hang risk (pendingOf()'s "negative behaves like drained" handling absorbs it, and nothing queries a closed instance's counter again), so this is low-severity and very narrow - it requires the exact interleave of a same-(fileId,pageNumber) collision racing a sibling's purge, which is presumably rare even under the drop()/create() hammering this PR targets. But given how much care went into closing the same class of bug everywhere else in this file, it seems worth closing too. Suggested fix: use a non-creating lookup here, since if the entry is already gone there's nothing meaningful left to decrement:

final AtomicInteger counter = pending.get(new IdentityKey(replacedDatabase));
if (counter != null)
  counter.decrementAndGet();

None of the added tests currently cover this specific ordering (they seed the sibling's counter as still-present before the collision, not already-removed), so a regression test would need to pre-run removeAllOfDatabase on the replaced page's database before triggering the collision, similar in spirit to flushIndexCounterOfMustNotAliasASamePathSiblingsCounterOnInsertion.

Everything else

  • Correctness: the !isOpen()/DatabaseMetadataException ack sites in PageManager.flushPage, PageManagerFlushThread.flushPagesFromQueueToDisk, and resumeFlushing all pair the WAL ack with the matching pageIndex release (via ackWalFileOfAbandonedPage + removeFromFlushIndex), avoiding the "WAL says done, pageIndex says pending" window called out in the comments. removeAllPagesOfDatabase's switch from pageIndex.remove(page.getPageId()) to removeIfSame (via removeFromFlushIndex) correctly closes the map-key-collision hole for that call site too.
  • Performance: the IdentityKey wrapper adds one short-lived allocation per pending access, including on the hot commit path (counterOf in put/putAll). Given it replaces what would otherwise need an O(open-databases) identity scan, and is documented as scalar-replaceable/escape-analysis-friendly, this is a reasonable and well-justified tradeoff - no algorithmic complexity regression anywhere (removeAllOfDatabase's full-index scan was already O(all pending pages) before this PR).
  • Security: none - purely internal engine bookkeeping, no external input or new attack surface.
  • Test coverage: thorough and genuinely white-box - each test in both new files is documented as having been verified to fail against the pre-fix code, which is exactly the right bar for a race this narrow. The distinct races (ack-on-close in flushPage, ack-on-close in the two PageManagerFlushThread batch paths, identity-based removeAllOfDatabase, map-key-collision in the pages purge, map-key-collision in removeAllPagesOfDatabase's per-page removal, and the counter-aliasing on insertion) are each pinned individually rather than relying on the full-suite before/after alone. The one gap is the releaseReplacedCounter-into-an-already-purged-sibling case noted above.
  • Style: consistent with the surrounding file's extremely thorough commenting convention; no complaints.

Nice piece of root-causing on a genuinely hard, low-probability race - the jstack/instrumentation methodology described in the PR body is exactly the right way to chase a stall like this down.

@codecov

codecov Bot commented Aug 20, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.13%. Comparing base (55b9c93) to head (cbe062f).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...va/com/arcadedb/engine/PageManagerFlushThread.java 60.00% 13 Missing and 1 partial ⚠️
...src/main/java/com/arcadedb/engine/PageManager.java 66.66% 0 Missing and 2 partials ⚠️
.../main/java/com/arcadedb/engine/FlushPageIndex.java 96.29% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6481      +/-   ##
==========================================
+ Coverage   71.10%   71.13%   +0.03%     
==========================================
  Files        1861     1861              
  Lines      163107   163163      +56     
  Branches    34437    34447      +10     
==========================================
+ Hits       115970   116067      +97     
+ Misses      32958    32918      -40     
+ Partials    14179    14178       -1     

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

@robfrank
robfrank merged commit da0a732 into main Aug 20, 2026
32 of 33 checks passed
@robfrank
robfrank deleted the fix/6440-gav-eligibility-slow-in-suite branch August 20, 2026 07:07
lvca added a commit that referenced this pull request Aug 20, 2026
…the WAL timer

A database fenced for recovery (#5053) is still isOpen()==true, but two places
only guarded against !isOpen(), not fencing:

- TransactionManager's once-a-second WAL housekeeping timer kept running against
  a fenced database, logging a misleading SEVERE "Error on transaction manager
  task" every second on top of the real fencing failure already logged.

- PageManager.flushPage() only guarded !isOpen(). Once fenced, any other page
  still in the async flush pipeline reached getFileManager()/getSchema(), which
  threw uncaught (not one of the exception types the pipeline's per-page catches
  expected), stranding that page's WAL ack forever - the same "stranded ack" bug
  class #6440/PR #6481 fixed for a plain close(), minus this one case. Confirmed
  against a real production log: every page that reached the pipeline after a
  fence landed got stuck the same way, spamming the exact same "fenced" exception
  30,000+ times until the process was restarted.

New BasicDatabase.isFencedForRecovery() default method, delegated through
ServerDatabase/RaftReplicatedDatabase.

Regression tests: TransactionManagerFencedTimerTaskTest, PageManagerFencedFlushAckTest
(both fail without the fix, pass with it).
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.

GAVEligibilityTest is 16x slower inside the full suite than alone (3.6s -> 57s), and most classes are not

1 participant