Repository navigation
fix(#6440): async flush pipeline strands WAL acks across a closed/reopened database - #6481
Conversation
…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
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 17 |
🟢 Coverage 80.88% diff coverage · -6.52% coverage variation
Metric Results Coverage variation ✅ -6.52% coverage variation Diff coverage ✅ 80.88% diff coverage 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.
ReviewThis 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 Possible remaining gap:
|
…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.
|
Good catch, thanks. You're right that fixing Fixed in c7d6f33 by keying Added |
ReviewNicely root-caused fix, and the inline comments do a lot of the reviewer's work already. A few notes below; nothing blocking. Correctness
Minor / non-blocking
Test coverage Good white-box regression coverage for both bugs ( One gap: there's no test exercising 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.
|
Addressed in 000a9f5:
All 831 tests in |
ReviewThis is a well-investigated fix, the root-causing writeup and the jstack/instrumentation methodology in the PR description are genuinely convincing, and the I traced through Possible correctness gap:
|
…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.
|
You're right, and the durability trace (preserve/pendingAcks decided before Fixed in ae1574c:
Added All 833 tests in |
ReviewThis is a well-investigated fix with excellent documentation of the root cause and a strong regression-test suite (the WAL-ack leak in Possible bug:
|
…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).
|
Good catch - confirmed and fixed in cbe062f: Added On the secondary note ( This closes out review cycle 4 of 4 for this PR. All 834 tests in |
ReviewThis 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 Potential remaining gap:
|
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
…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).
Closes #6440
Summary
GAVEligibilityTest(and any test that repeatedlydrop()s andcreate()s a database at the same path) paid up toTransactionManager's full 2000 ms retry budget on almost everyclose(), 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.writeTransactionToFileincrementsWALFile.pagesToFlush), then handed to the async flush pipeline; only the pipeline's eventual disk write releases the ack (WALFile.notifyPageFlushed(), viaMutablePage.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 itsDatabaseIsClosedExceptioncatch after the physical write already succeeded but the metadata update failed.PageManagerFlushThread.flushPagesFromQueueToDisk()'s several "database closed mid-batch" branches, and itsDatabaseMetadataExceptioncatches (file dropped).PageManagerFlushThread.resumeFlushing()'s equivalents on the suspend/backup-resume path.LocalDatabase.closeDurableParts()setsopen = falsebeforeTransactionManager.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 adrop(), where the files are about to be deleted regardless, that wait buys nothing but latency.A second, related bug in the same area:
PageManagerFlushThread.removeAllPagesOfDatabaseandFlushPageIndex.removeAllOfDatabasematched pending pages withDatabase.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 rapiddrop()/create()cycle produces, e.g. a JUnit@BeforeEach/@AfterEachpair) 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 precedentPagesToFlush.slotChargedalready established for the siblingslotsInUsecounter 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:
com.arcadedb.query.opencypherpackage (8776 tests) and confirmedGAVEligibilityTestwent from 1.9s isolated to 34-63s in-suite.jstacksampling during the slow window showed the test'smainthread parked inTransactionManager.close()'s WAL-flush retry loop, sleeping through its full 20 x 100 ms budget.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.WALFile's increment/decrement pairing directly, which pinpointedPageManager.flushPage()'s!database.isOpen()early return as the primary leak, then found the remaining smaller leaks (DatabaseMetadataException/DatabaseIsClosedExceptioncatches,resumeFlushing) by symmetry with the one already-correct sibling (removePagesOfFileFromBatch, which already acks on the same conditions).Test plan
Issue6440FlushAckOnClosedDatabaseTest: white-box regression pinning thatPageManager.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).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) andcom.arcadedb.database.**(262 tests) both green - no regressions in the surrounding flush/lifecycle machinery.com.arcadedb.query.opencypher.**package (8776 tests, the original reproduction) rerun after the fix:GAVEligibilityTestnow 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 compileclean.Notes for reviewers
PageManager,PageManagerFlushThread,FlushPageIndex).!database.isOpen()/DatabaseMetadataException/DatabaseIsClosedException(nothing left to recover onto), never for a genuineIOException(where withholding the ack correctly preserves the WAL for recovery on the next open - untouched by this change).