Repository navigation
fix(#4928,#4930,#4931,#4932,#4955): storage/engine robustness bundle - #5012
Conversation
#4928: a plain IOException from flushPage escaped the per-page loop and aborted the batch: the remaining pages were never flushed or retried, yet their pageIndex entries survived, so waitAllPagesOfDatabaseAreFlushed spun forever and close()/rename()/backup-suspend hung. The failure is now contained per page with the same policy as the #4965 interrupt double-fault (SEVERE log; the page's WAL entry was never acked, so it is recovered on the next open) and the batch continues. waitAllPagesOfDatabaseAreFlushed is bounded (60s) with a SEVERE escalation instead of an infinite spin. #4930: the ClosedChannelException reopen path could not tell 'closed by interrupt' from 'closed/dropped on purpose': a page mid-flight in the flush thread racing a DDL drop made the reopen RE-CREATE the deleted file (open() uses RandomAccessFile 'rw'), leaving a one-page ghost that FileManager re-registered on the next open. The reopen now refuses when the component was closed intentionally (open=false) or the OS file no longer exists, surfacing the condition to the caller. #4931: check() computed RIDs with int*int arithmetic that overflows for buckets beyond 2^31 positions (a 64GB bucket at 64KB pages); with fix=true the wrong-but-positive RID deleted an innocent record. Widened to long as scan() already does; the two log sites with the same overflow (plus a string-concat-instead-of-add bug) fixed too. #4932: deleteRecordInternal deliberately throws ConcurrentModificationException as a retry signal for concurrently-modified multi-page chunk chains, then swallowed it 60 lines later in its own generic catch: the slot pointer was zeroed, the delete reported success, the retry never happened and the remaining NEXT_CHUNK records were orphaned (permanent space leak). The retry signal is now rethrown, mirroring the existing RecordNotFoundException clause. #4955: getBestSlot/getRandomSlot snapshotted executorThreads without a null check, so scheduling async work concurrently with close()/kill() threw a raw NPE instead of the intended DatabaseOperationException that scheduleTask already produced for the same race. Tests: the batch-containment + no-resurrection test is red-first verified (on unfixed code the dropped file IS re-created on disk and the exception escapes); the bounded-wait test drives the timeout deterministically; the async-slot test asserts the intended exception after kill(). #4931 (needs a 64GB bucket) and #4932 (needs a mid-delete race) are trace-verified fixes mirroring existing correct code in the same file. Regression: engine + database packages green (114 classes, 562 tests).
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 24 |
🟢 Coverage 86.00% diff coverage · -6.86% coverage variation
Metric Results Coverage variation ✅ -6.86% coverage variation Diff coverage ✅ 86.00% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (ef0fdb3) 134798 100328 74.43% Head commit (d589a5e) 166675 (+31877) 112614 (+12286) 67.57% (-6.86%) 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 (#5012) 100 86 86.00% 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.
There was a problem hiding this comment.
Code Review
This pull request introduces a robustness bundle for the storage engine, addressing several critical defects: it bounds the page flush wait time to prevent infinite hangs during database close, contains per-page I/O errors to avoid aborting flush batches, prevents the recreation of deleted files during channel reopens, fixes integer overflows in RID arithmetic for large buckets, and ensures concurrent modification retry signals are not swallowed during multi-page record deletions. Additionally, it resolves a shutdown race in the async executor that could lead to a NullPointerException. Feedback on the changes suggests marking the mutable static field WAIT_FLUSH_TIMEOUT_MS as volatile to guarantee thread visibility when modified dynamically during tests.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| * Upper bound for {@link #waitAllPagesOfDatabaseAreFlushed}: generous enough for any healthy flush backlog | ||
| * (the bounded queue drains far faster), small enough that a wedged flush cannot hang close() forever (#4928). | ||
| */ | ||
| static long WAIT_FLUSH_TIMEOUT_MS = 60_000L; // non-final and package-private for the #4928 regression test |
There was a problem hiding this comment.
Since WAIT_FLUSH_TIMEOUT_MS is a mutable static field that is modified dynamically in tests (such as in FlushRobustnessTest.java), it should be marked volatile to ensure thread visibility. Without volatile, updates to this field made by a test thread might not be immediately visible to other threads executing waitAllPagesOfDatabaseAreFlushed, which could lead to flaky test results or incorrect timeout behavior in concurrent environments.
| static long WAIT_FLUSH_TIMEOUT_MS = 60_000L; // non-final and package-private for the #4928 regression test | |
| static volatile long WAIT_FLUSH_TIMEOUT_MS = 60_000L; // non-final and package-private for the #4928 regression test |
PR Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)Thanks for this bundle - the fixes are well-scoped, the comments explain the "why" clearly, and the red-first tests are a nice touch. Most changes are clean wins. I have one substantive correctness concern on the #4928 bounded-wait, plus a few smaller notes. 🔴 Main concern: the "recovered from the WAL on next open" guarantee does not hold on the
|
… lock file for recovery The Claude review's main concern was legitimate and serious, and its trace was exact: the bounded wait let close() proceed, close() set open=false (so the pending pages could never be written), transactionManager.close() then OS-deleted every WAL file unconditionally and the lock file was removed - so the 'recovered from the WAL on next open' promise in the SEVERE log was FALSE precisely on the close path, converting the old hang into silent loss of the most recent pages. Fixed by making a give-up close crash-equivalent: - waitAllPagesOfDatabaseAreFlushed returns whether everything reached the disk, and its timeout is now a NO-PROGRESS window read per call from arcadedb.flushAllPagesTimeout (SCOPE.DATABASE, default 60s, 0 = wait forever): the window resets whenever the pending-page count decreases, so a legitimate slow backlog on a large database can never trip it - only a genuinely wedged flush does. This also removes the mutable static the reviews flagged (and moots the volatile suggestion). - On false, LocalDatabase.closeInternal passes preserveWalFiles to transactionManager.close - the WAL files are closed but NOT deleted (they are the only durable copy of the unflushed pages) - and the lock file is kept as the unclean-shutdown marker, so the next open runs recovery and replays them. Every log/comment now states semantics that are actually true. - The per-page IOException containment comment now states the accepted tradeoff explicitly: durable via WAL replay on the next open, not repaired in place; until then an evicted page reads stale from disk. - getBestSlot/getRandomSlot also guard a zero-length array (nextInt(0) would throw IllegalArgumentException), per the review nit. New end-to-end test drives a real DatabaseFactory close with an unflushable page: the close completes (bounded), the WAL and lock file survive it, the reopen recovers the committed row, and the subsequent clean close deletes the WAL as before. Engine + database packages green.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #5012 +/- ##
============================================
+ Coverage 65.44% 65.79% +0.34%
- Complexity 822 823 +1
============================================
Files 1687 1687
Lines 134798 134872 +74
Branches 28822 28845 +23
============================================
+ Hits 88223 88743 +520
+ Misses 34507 33938 -569
- Partials 12068 12191 +123 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Code Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)Reviewed the full diff and traced the supporting code ( What I verified as correct
Concerns worth addressing1. (Medium) Non-close callers silently ignore the new 2. (Medium) No-progress detection can false-positive under sustained concurrent writes. The window resets only when 3. (Low) Test-coverage gap for #4931 and #4932. Both are acknowledged as trace-verified only, but these are the two highest-severity defects (deleting an innocent record under 4. (Low) Shared-singleton test hygiene. 5. (Nit) 6. (Nit) In the truly-wedged (non-IOException) case, a give-up close leaves the stuck Nice work overall - the fixes are correct and the crash-equivalent-close design is the right call. Addressing #1 (surfacing the give-up to the rename/backup callers) is the most valuable follow-up. |
Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)Thanks for this - it's an unusually well-documented PR. Each fix is tied to an issue, the inline comments explain why rather than what, and the red-first tests for #4928/#4930 plus the deterministic bounded-wait test are exactly the right level of rigor. I went through all five fixes carefully. Nothing here is a blocker; the notes below are one design point worth a decision and a few minor cleanups. Correctness of the individual fixes (all look right)
One design point worth a decision (not a blocker)
Before this PR those paths would hang forever on a wedged flush. Now, with the 60s default timeout, they will silently give up and proceed as if everything flushed. For Minor
Test coverageGood. #4928 (batch containment + no resurrection + bounded wait + WAL preserve/recover), #4930 and #4955 are all covered directly; #4931/#4932 are trace-verified against mirrored correct code in the same file, which is a reasonable call given a 64GB bucket / mid-delete race is impractical to reproduce in a unit test. Overall: solid, careful work. My only real ask is a decision on the ignored |
…s signal; #4931 unit test From the latest review round: - The four non-close callers of waitAllPagesOfDatabaseAreFlushed no longer ignore the give-up (the review's main point): PaginatedComponent.rename() throws IOException (renaming with pages in flight lets the flush thread write to the file under its old identity), and the two sparse-vector HA shipping sites plus the vector-index compaction throw as well (shipping with unflushed pages would send zero pages to followers). All four are retryable operations, so fail-and-retry is strictly safer than the old hang and than warn-and-proceed. - The no-progress window now resets on EITHER signal: pending-count decrease OR pages physically written (totalPagesWritten delta). On live callers (rename, backup-suspend, compaction shipping) sustained commits could keep the pending count from ever dipping below its minimum while the flusher worked flat out - with the dual signal only a flusher that writes nothing at all can trip the timeout. - #4931's arithmetic is extracted into LocalBucket.recordPosition() - now the single implementation for all four sites including scan() - with a unit test that pins the overflow boundary and demonstrates the innocent-record aliasing (the old int arithmetic mapped page 2_097_152 slot 42 onto position 42). #4932 stays trace-verified: deterministically forcing the chunk-chain retry signal needs internal page-format surgery disproportionate to a two-line catch-order fix mirroring the adjacent RecordNotFoundException clause. - A give-up close purges its stuck pageIndex entries from the shared flush thread (they reference a now-closed database and can never be flushed; their content is safe in the preserved WAL) - closing the small leak the review flagged - and the close-path test now asserts the purge. - Singleton test hygiene and the O(n) pending count per tick acknowledged as-is: the suite is sequential by configuration, and progress detection needs the count on what is a cold path. Regression: engine + database + sparse-vector packages green (129 classes, 630 tests).
Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)Overall this is a high-quality, carefully documented bundle. The comments explaining why each change is safe (WAL-recoverability, crash-equivalent close, retry-signal semantics) are excellent and make the diff reviewable. Test coverage is good, several tests are genuinely red-first, and the fixes for #4930 (refuse to re-create a dropped file on reopen), #4931 (widen RID arithmetic to Two substantive concerns on the #4928 bounded-wait design, and a nit. 1. The no-progress signal is JVM-global, so a busy sibling database can keep a wedged
|
…ops silent WAL loss Both substantive review points were legitimate; the second was the deepest catch of the whole PR series. 1. The flush-progress signal is now PER-DATABASE. The previous totalPagesWritten delta was JVM-global, so on a multi-database server a busy healthy sibling kept resetting a wedged database's no-progress window - close() never timed out, which is exactly the multi-tenant hang #4928 exists to prevent. PageManagerFlushThread now keeps a per-database counter of pages that LEFT the flush pipeline (bumped in both per-page finally blocks, cleaned up in removeAllPagesOfDatabase) and the wait resets its window only on THIS database's pending-count decrease or pipeline departures. 2. The clean close is now gated on WAL ACKS, not pipeline emptiness. The reviewer's trace was exact: a page whose flush failed and was contained leaves pageIndex without ever calling notifyPageFlushed and is never re-flushed in-process (confirmed); the next CLEAN close then saw pending == 0, decided everything was flushed, and force-deleted the very WAL holding the only durable copy - silent loss of a committed change after a mere transient I/O error. TransactionManager.close now checks getPendingPagesToFlush() across the WAL pool (the ground truth) before the delete sweep and preserves WAL + (via its new boolean return) the lock file whenever anything is unacked, so the next open recovers. This also covers the pre-existing interrupt double-fault path the review pointed at. To keep the gate honest, pages that legitimately never need flushing now release their acks: flushPage's file-dropped branch and the dropped-file purge in removePagesOfFileFromBatch call notifyPageFlushed (the content is irrelevant, the file is gone). File-CLOSED paths deliberately do NOT ack: if hit racily, the conservative outcome is a preserved WAL and one recovery pass, never a loss. 3. The stray 'Called at creation time' javadoc is back on the LocalBucket constructor it belongs to. New regression test drives the reviewer's exact scenario end to end: a committed change whose WAL page is acked-to-committer but never flushed, followed by a CLEAN close - the WAL and lock file must survive, the reopen recovers the row, and the subsequent genuinely-clean close deletes the WAL. Regression: engine + database + sparse-vector + vector packages green (161 classes, 809 tests).
Code Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)Reviewed the full diff, the surrounding call sites, and the WAL/flush interaction. This is a high-quality, unusually well-documented PR: every fix is anchored to a concrete failure trace, the comments explain the why rather than the what, and the iterative review commits show the design converging on genuinely safer close semantics (a give-up close is now crash-equivalent rather than silently lossy). The five fixes are logically independent and each is correct in isolation. Below are the things worth a second look before merge. Strengths
Points worth verifying
Minor / nits
Test coverageStrong. The red-first verification on Overall: solid, careful work that meaningfully hardens the flush/close/WAL path. My only substantive ask is confirming the double-ack race in point (1) cannot corrupt the pending-pages counter that the new ack-gate now trusts as ground truth. |
From the latest review round: - The double-ack race was real, and broader than the review's own framing: the flush loop does not remove pages from the batch LIST (only from pageIndex), so a batch polled between the dropped-file purge's queue snapshot and its lock acquisition is visited by BOTH the file-dropped flush branch and the purge - each acking the same page. Because WALFile.pagesToFlush is shared by all of a database's pages, the stolen ack could zero the counter while another page's committed change was still unflushed, letting the close-time ack gate delete the WAL that protected it - the silent-loss window this PR exists to close. Fixed structurally rather than with the suggested floor (a floor prevents a negative counter but not the ack theft at zero, and would mask future accounting bugs): MutablePage.walFile is now an AtomicReference with takeWALFile() (getAndSet null), and all three ack sites - the TransactionManager success path, the file-dropped flush branch and the dropped-file batch purge - release through it, so whichever path reaches the page first wins and every other ack is a structural no-op. Regression test acks the same page twice and asserts the pending count decreases exactly once. - The per-database counter map's javadoc now describes the real lifecycle: an entry is created on a database's first bounded wait (close, rename, backup-suspend, compaction shipping) and lives until close/drop - one bounded entry per open database, not a leak. - The config docstring now states that the window is per-database no-progress time, not total flush time: on a heavily loaded multi-database server a database starved by its siblings can give up, turning that close into recovery-on-next-open. Nits acknowledged without change: the package-private slot helpers and the reopen-path stat() are as reviewed; FlushRobustnessTest stays untagged at under a second total, watched if more cases accrue. Engine + database packages green.
Code review — storage/engine robustness bundle (#5012)Reviewed the full diff and traced the flush/close/ack paths in Correctness — looks good
Design consideration (documented tradeoff, worth surfacing to operators)The contained-
Not a blocker (the alternative was an infinite hang), but consider (a) a metric / Style — CLAUDE.md deviations (minor)
Documentation nitIn TestsGood coverage and genuinely adversarial. Two small notes:
Overall: well-reasoned, well-tested, and a clear net improvement to durability semantics. The FQN imports and the misplaced Javadoc are the only things I'd ask to fix before merge; the WAL-pinning point is worth a tracking issue rather than blocking this PR. |
…tion on close #4926 (HIGH, silent corruption): a 64KB page flush spans many disk sectors and the MVCC version header lives in sector 0. A torn write at power loss can persist the NEW version header while the delta sectors still hold the PREVIOUS content. Recovery's <= skip declared such a page 'already applied' and left it silently corrupt (new version, old bytes) despite an intact, fully-fsynced WAL - undetectable, since every later MVCC check accepts the page. The skip is now strictly <, and the equal-version case RE-APPLIES the WAL delta: idempotent when the page is intact (the delta carries absolute bytes for exactly that version), repairing when it is torn. Skipping STRICTLY older entries remains, as their delta would overwrite newer content. Red-first verified with a forged torn write (version header says v2, content still v1): the old code left the stale value behind forever, the fix recovers the committed one. #4934 (MEDIUM, unrecoverable committed data): a clean close deleted every WAL file even when the preceding data fsync FAILED - and after a failed fsync the OS may have dropped the dirty pages (fsyncgate semantics), so the WAL held the only durable copy. FileManager.syncFiles() now reports failure; a failed pre-close fsync makes the close crash-equivalent (WAL and lock file preserved via the #5012 machinery, recovery on next open), and the runtime WAL-rotation drop pass aborts when its pre-drop fsync fails, retrying on the next pass. Red-first verified: the old code deleted the WAL despite the failed fsync. Verified with the full commit-path sweep (union with the companion point-of-no-return branch): 372 classes, 2851 tests, 0 failures.
…tFileIds scope confirmed
The design concern was worth more than a comment - implemented the
suggested fence.
1a. Live/WAL divergence: the reviewer's window is real but PRE-EXISTING
(the old WAL-then-updatePages order had the identical exposure for any
non-validation failure) and this PR already NARROWED it by moving
validation - the reachable failure class - ahead of the append. The
residue (IOException while publishing) is now closed with the suggested
fence: LocalDatabase.fenceForRecovery(reason) is set in commit2ndPhase's
finally when a failure occurs AFTER the WAL append, BEFORE reset()
releases the file locks - the volatile write is therefore visible to
any transaction blocked on those locks, so no conflicting WAL record
for the same page versions can follow. The fence surfaces at the
checkDatabaseIsOpen choke point (every new operation) and at an
explicit guard before the WAL append (covers in-flight commits whose
reads bypass the choke point). Close still works: it is the recovery
entry point.
1b. Clean close vs crash: already answered by the #5012 ack gate, no new
code needed. The orphaned record's pages were never queued for flush,
so their WAL acks (bumped at append time) are never released -
getPendingPagesToFlush() > 0 makes the clean close preserve the WAL and
the lock file, and the next open replays the record. 'Durable on
restart' holds for both crash and clean close.
2. getFileIds() broadening confirmed intended, including the compacted
sub-index file: it adds no new serialization between transactions -
any transaction locking the compacted id also locks the mutable id, so
the contender set per index is unchanged - and compaction itself does
not take commit file locks for its appends (only splitIndex's
tryLockFile on the mutable id, which contended before this change
too). The reviewer's observation that this also fixes the latent
add(-1) for composite TypeIndex ids is correct.
3. TransactionException is now rethrown unwrapped by commit2ndPhase too
(same as phase 1, round 3), so first-class errors like the fence are
not buried under 'Transaction error on commit'.
4. java.util.TreeSet::new -> TreeSet::new (java.util.* was imported).
New test: fenced database refuses the WAL point of no return (WAL
byte-identical after the refused commit), fences new operations, and still
closes cleanly. The post-append fence trigger itself is wired in the
finally; forcing a real mid-publish IOException deterministically is not
feasible without fault-injection hooks, so the trigger is covered by code
path inspection and the fence mechanics by the test.
Regression: 118 classes, 577 tests, 0 failures.
… instance All three review findings were real; the first was a genuine regression in this PR and the reviewer's scenario was exact. 1. RED - redundant double-close stole another database's reference. closeInternal's lambda is documented-idempotent (early-return on !open) but the new release() ran unconditionally after it: dbA.close(); dbA.close(); decremented twice and tore the flush thread down under a still-open dbB - the exact failure this PR exists to eliminate, re-entered through the double-close door. The lambda now reports whether THIS call performed the close, and the whole tail (removeActiveDatabaseInstance, closeExecutor, release) is gated on it - taking the reviewer's suggestion including the arguably-belongs part. 2. ORANGE - acquire() rolls back its increment when startup() throws (e.g. ConfigurationException on negative MAX_PAGE_RAM). Without it the counter wedged at 1 with no flush thread and every later acquire ran against a dead manager the caller's catch could not repair. 3. ORANGE - same-path concurrent open double-release. When registerActiveInstance loses the race it closes the database itself, which (with fix 1) consumes the reference and records it in a per-instance flag; the factory's catch now releases only when the instance did NOT already consume its reference. The lifecycle reference is exactly-once per instance by construction - same pattern as the exactly-once WAL ack from #5012. Red-first: the double-close and startup-failure tests both fail on the pre-review code (1 failure + 1 error). The same-path race has no deterministic repro (it needs two threads between checkForActiveInstance and registerActiveInstance); it is covered by the exactly-once flag construction and the existing hammer test. Regression: engine + database packages green.
…uspenders own their windows PageManagerFlushThread.setSuspended(db, true) was putIfAbsent-based: only the FIRST caller owned the suspend flag, but suspendFlushAndExecute ran every caller's callback regardless (ArcadeData#4958). With two concurrent suspenders on the same database (SQL BACKUP DATABASE, the HA verify endpoint, HA snapshot serving - any combination), the non-owner (a) skipped waitForCurrentFlushToComplete, so it could read a page while a flush batch was mid-write, and (b) kept streaming while the owner's exit synchronously flushed the deferred batches to disk - torn reads either way. The suspension is now a per-database REFCOUNT: - setSuspended(db, true) increments the count under the existing per-database suspend lock; it returns true only for the first suspender (0 -> 1). - setSuspended(db, false) decrements; only the LAST release (1 -> 0) runs the resume (Phase 1 synchronous deferred flush, Phase 2 flag clear + detach, Phase 3 re-enqueue, all unchanged) and returns true. A non-last release just drops one reference and the database stays suspended for the remaining suspenders. An unbalanced release is a no-op instead of corrupting state. - A new suspender arriving while the last release is mid-way through the deferred-batch writes waits (timed, uninterruptible with interrupt-flag restore) until the resume completes, so a fresh window can never overlap those page writes. The gate (resumingDatabases) is cleared in a finally that also heals a stuck count if the resume ever escapes with an exception. - PageManager.suspendFlushAndExecute acquires/releases one reference per caller and now runs waitForCurrentFlushToComplete INSIDE the try, so an interrupt during the wait no longer leaks the suspension (pre-existing leak: the flag was set before the wait and never restored on throw). The wait is cheap for non-first suspenders (the flush thread is parked deferring). The ArcadeData#4728 deferred-RAM backpressure accounting and the ArcadeData#5012 per-database suspend bookkeeping are unchanged: batches deferred across overlapping windows are flushed exactly once, by the last suspender's exit. Decision on the HA SnapshotHttpHandler per-database lock (ArcadeData#5063 review round 5): it STAYS, documented as resource discipline rather than correctness. With refcounting it is no longer needed to own the suspension, but it serializes same-database zip streaming: two followers resyncing the same multi-GB database at once would double the read I/O and keep flushing suspended for the UNION of both windows, growing the deferred backlog toward the ArcadeData#4728 cap. TDD red-first: PageManagerFlushSuspendRefCountTest written and run against the pre-fix code (stash-run-unstash); all three methods failed on the exact defect: - overlappingSuspendersBothOwnTheirWindow: isPageFlushingSuspended was false after the first of two overlapping suspendFlushAndExecute callers exited while the second was still inside its callback (expected true, was false). - setSuspendedIsRefCounted: the first release of two suspenders cleared the flag (expected release to return false and the db to stay suspended). - suspendDuringResumeWaitsUntilDeferredFlushCompletes: a suspender acquired immediately while the resume was mid-way through the deferred writes (contract test for the new gate; pre-fix it became a non-owner). PageManagerFlushSuspendDeferRaceTest updated for the new semantics: the resume's count-check now takes the per-database lock, so it serializes behind the flush thread's paused suspended-check and the deferred batch is flushed synchronously in Phase 1 rather than re-enqueued; the assertion now accepts either outcome (flushed or re-enqueued) and still rejects the stranded case. The fake page's file id is now non-existent so the (now reachable) synchronous flush cannot write into a real file of the test database. Verification (all green): - engine: PageManagerFlushSuspendRefCountTest, PageManagerFlushSuspendDeferRaceTest, PageManagerFlushSuspendBackpressureTest, PageManagerFlushThreadInterruptTest, PageManagerDeleteFileFlushCoordinationTest, WalRecoveryCorrectnessTest, Issue4958StorageStatsTest, FlushRobustnessTest, PageManagerLifecycleRefCountTest, Issue4544FlushIndexIdentityTest, PageManagerFlushQueueRaceTest, PageManagerReadCache*Test (28 tests, 1 skipped stress test) - ha-raft: SnapshotHttpHandlerSuspendLockTest, SnapshotWriteStallTest, SnapshotThrottleTest (9 tests) - integration: BackupDatabaseTest (4 tests, drives FullBackupFormat's suspendFlushAndExecute end-to-end)
…5012) * fix(#4928,#4930,#4931,#4932,#4955): storage/engine robustness bundle aborted the batch: the remaining pages were never flushed or retried, yet their pageIndex entries survived, so waitAllPagesOfDatabaseAreFlushed spun forever and close()/rename()/backup-suspend hung. The failure is now contained per page with the same policy as the #4965 interrupt double-fault (SEVERE log; the page's WAL entry was never acked, so it is recovered on the next open) and the batch continues. waitAllPagesOfDatabaseAreFlushed is bounded (60s) with a SEVERE escalation instead of an infinite spin. interrupt' from 'closed/dropped on purpose': a page mid-flight in the flush thread racing a DDL drop made the reopen RE-CREATE the deleted file (open() uses RandomAccessFile 'rw'), leaving a one-page ghost that FileManager re-registered on the next open. The reopen now refuses when the component was closed intentionally (open=false) or the OS file no longer exists, surfacing the condition to the caller. buckets beyond 2^31 positions (a 64GB bucket at 64KB pages); with fix=true the wrong-but-positive RID deleted an innocent record. Widened to long as scan() already does; the two log sites with the same overflow (plus a string-concat-instead-of-add bug) fixed too. ConcurrentModificationException as a retry signal for concurrently-modified multi-page chunk chains, then swallowed it 60 lines later in its own generic catch: the slot pointer was zeroed, the delete reported success, the retry never happened and the remaining NEXT_CHUNK records were orphaned (permanent space leak). The retry signal is now rethrown, mirroring the existing RecordNotFoundException clause. check, so scheduling async work concurrently with close()/kill() threw a raw NPE instead of the intended DatabaseOperationException that scheduleTask already produced for the same race. Tests: the batch-containment + no-resurrection test is red-first verified (on unfixed code the dropped file IS re-created on disk and the exception escapes); the bounded-wait test drives the timeout deterministically; the async-slot test asserts the intended exception after kill(). #4931 (needs a 64GB bucket) and #4932 (needs a mid-delete race) are trace-verified fixes mirroring existing correct code in the same file. Regression: engine + database packages green (114 classes, 562 tests). * review(#5012): a give-up close is crash-equivalent - preserve WAL and lock file for recovery The Claude review's main concern was legitimate and serious, and its trace was exact: the bounded wait let close() proceed, close() set open=false (so the pending pages could never be written), transactionManager.close() then OS-deleted every WAL file unconditionally and the lock file was removed - so the 'recovered from the WAL on next open' promise in the SEVERE log was FALSE precisely on the close path, converting the old hang into silent loss of the most recent pages. Fixed by making a give-up close crash-equivalent: - waitAllPagesOfDatabaseAreFlushed returns whether everything reached the disk, and its timeout is now a NO-PROGRESS window read per call from arcadedb.flushAllPagesTimeout (SCOPE.DATABASE, default 60s, 0 = wait forever): the window resets whenever the pending-page count decreases, so a legitimate slow backlog on a large database can never trip it - only a genuinely wedged flush does. This also removes the mutable static the reviews flagged (and moots the volatile suggestion). - On false, LocalDatabase.closeInternal passes preserveWalFiles to transactionManager.close - the WAL files are closed but NOT deleted (they are the only durable copy of the unflushed pages) - and the lock file is kept as the unclean-shutdown marker, so the next open runs recovery and replays them. Every log/comment now states semantics that are actually true. - The per-page IOException containment comment now states the accepted tradeoff explicitly: durable via WAL replay on the next open, not repaired in place; until then an evicted page reads stale from disk. - getBestSlot/getRandomSlot also guard a zero-length array (nextInt(0) would throw IllegalArgumentException), per the review nit. New end-to-end test drives a real DatabaseFactory close with an unflushable page: the close completes (bounded), the WAL and lock file survive it, the reopen recovers the committed row, and the subsequent clean close deletes the WAL as before. Engine + database packages green. * review(#5012): non-close callers abort on flush give-up; dual progress signal; #4931 unit test From the latest review round: - The four non-close callers of waitAllPagesOfDatabaseAreFlushed no longer ignore the give-up (the review's main point): PaginatedComponent.rename() throws IOException (renaming with pages in flight lets the flush thread write to the file under its old identity), and the two sparse-vector HA shipping sites plus the vector-index compaction throw as well (shipping with unflushed pages would send zero pages to followers). All four are retryable operations, so fail-and-retry is strictly safer than the old hang and than warn-and-proceed. - The no-progress window now resets on EITHER signal: pending-count decrease OR pages physically written (totalPagesWritten delta). On live callers (rename, backup-suspend, compaction shipping) sustained commits could keep the pending count from ever dipping below its minimum while the flusher worked flat out - with the dual signal only a flusher that writes nothing at all can trip the timeout. - #4931's arithmetic is extracted into LocalBucket.recordPosition() - now the single implementation for all four sites including scan() - with a unit test that pins the overflow boundary and demonstrates the innocent-record aliasing (the old int arithmetic mapped page 2_097_152 slot 42 onto position 42). #4932 stays trace-verified: deterministically forcing the chunk-chain retry signal needs internal page-format surgery disproportionate to a two-line catch-order fix mirroring the adjacent RecordNotFoundException clause. - A give-up close purges its stuck pageIndex entries from the shared flush thread (they reference a now-closed database and can never be flushed; their content is safe in the preserved WAL) - closing the small leak the review flagged - and the close-path test now asserts the purge. - Singleton test hygiene and the O(n) pending count per tick acknowledged as-is: the suite is sequential by configuration, and progress detection needs the count on what is a cold path. Regression: engine + database + sparse-vector packages green (129 classes, 630 tests). * review(#5012): per-database progress signal; ack-gated clean close stops silent WAL loss Both substantive review points were legitimate; the second was the deepest catch of the whole PR series. 1. The flush-progress signal is now PER-DATABASE. The previous totalPagesWritten delta was JVM-global, so on a multi-database server a busy healthy sibling kept resetting a wedged database's no-progress window - close() never timed out, which is exactly the multi-tenant hang #4928 exists to prevent. PageManagerFlushThread now keeps a per-database counter of pages that LEFT the flush pipeline (bumped in both per-page finally blocks, cleaned up in removeAllPagesOfDatabase) and the wait resets its window only on THIS database's pending-count decrease or pipeline departures. 2. The clean close is now gated on WAL ACKS, not pipeline emptiness. The reviewer's trace was exact: a page whose flush failed and was contained leaves pageIndex without ever calling notifyPageFlushed and is never re-flushed in-process (confirmed); the next CLEAN close then saw pending == 0, decided everything was flushed, and force-deleted the very WAL holding the only durable copy - silent loss of a committed change after a mere transient I/O error. TransactionManager.close now checks getPendingPagesToFlush() across the WAL pool (the ground truth) before the delete sweep and preserves WAL + (via its new boolean return) the lock file whenever anything is unacked, so the next open recovers. This also covers the pre-existing interrupt double-fault path the review pointed at. To keep the gate honest, pages that legitimately never need flushing now release their acks: flushPage's file-dropped branch and the dropped-file purge in removePagesOfFileFromBatch call notifyPageFlushed (the content is irrelevant, the file is gone). File-CLOSED paths deliberately do NOT ack: if hit racily, the conservative outcome is a preserved WAL and one recovery pass, never a loss. 3. The stray 'Called at creation time' javadoc is back on the LocalBucket constructor it belongs to. New regression test drives the reviewer's exact scenario end to end: a committed change whose WAL page is acked-to-committer but never flushed, followed by a CLEAN close - the WAL and lock file must survive, the reopen recovers the row, and the subsequent genuinely-clean close deletes the WAL. Regression: engine + database + sparse-vector + vector packages green (161 classes, 809 tests). * review(#5012): WAL ack released exactly once per page; doc fixes From the latest review round: - The double-ack race was real, and broader than the review's own framing: the flush loop does not remove pages from the batch LIST (only from pageIndex), so a batch polled between the dropped-file purge's queue snapshot and its lock acquisition is visited by BOTH the file-dropped flush branch and the purge - each acking the same page. Because WALFile.pagesToFlush is shared by all of a database's pages, the stolen ack could zero the counter while another page's committed change was still unflushed, letting the close-time ack gate delete the WAL that protected it - the silent-loss window this PR exists to close. Fixed structurally rather than with the suggested floor (a floor prevents a negative counter but not the ack theft at zero, and would mask future accounting bugs): MutablePage.walFile is now an AtomicReference with takeWALFile() (getAndSet null), and all three ack sites - the TransactionManager success path, the file-dropped flush branch and the dropped-file batch purge - release through it, so whichever path reaches the page first wins and every other ack is a structural no-op. Regression test acks the same page twice and asserts the pending count decreases exactly once. - The per-database counter map's javadoc now describes the real lifecycle: an entry is created on a database's first bounded wait (close, rename, backup-suspend, compaction shipping) and lives until close/drop - one bounded entry per open database, not a leak. - The config docstring now states that the window is per-database no-progress time, not total flush time: on a heavily loaded multi-database server a database starved by its siblings can give up, turning that close into recovery-on-next-open. Nits acknowledged without change: the package-private slot helpers and the reopen-path stat() are as reviewed; FlushRobustnessTest stays untagged at under a second total, watched if more cases accrue. Engine + database packages green. (cherry picked from commit 0788a88)
…tion on close #4926 (HIGH, silent corruption): a 64KB page flush spans many disk sectors and the MVCC version header lives in sector 0. A torn write at power loss can persist the NEW version header while the delta sectors still hold the PREVIOUS content. Recovery's <= skip declared such a page 'already applied' and left it silently corrupt (new version, old bytes) despite an intact, fully-fsynced WAL - undetectable, since every later MVCC check accepts the page. The skip is now strictly <, and the equal-version case RE-APPLIES the WAL delta: idempotent when the page is intact (the delta carries absolute bytes for exactly that version), repairing when it is torn. Skipping STRICTLY older entries remains, as their delta would overwrite newer content. Red-first verified with a forged torn write (version header says v2, content still v1): the old code left the stale value behind forever, the fix recovers the committed one. #4934 (MEDIUM, unrecoverable committed data): a clean close deleted every WAL file even when the preceding data fsync FAILED - and after a failed fsync the OS may have dropped the dirty pages (fsyncgate semantics), so the WAL held the only durable copy. FileManager.syncFiles() now reports failure; a failed pre-close fsync makes the close crash-equivalent (WAL and lock file preserved via the #5012 machinery, recovery on next open), and the runtime WAL-rotation drop pass aborts when its pre-drop fsync fails, retrying on the next pass. Red-first verified: the old code deleted the WAL despite the failed fsync. Verified with the full commit-path sweep (union with the companion point-of-no-return branch): 372 classes, 2851 tests, 0 failures. (cherry picked from commit 00bae69)
…tFileIds scope confirmed
The design concern was worth more than a comment - implemented the
suggested fence.
1a. Live/WAL divergence: the reviewer's window is real but PRE-EXISTING
(the old WAL-then-updatePages order had the identical exposure for any
non-validation failure) and this PR already NARROWED it by moving
validation - the reachable failure class - ahead of the append. The
residue (IOException while publishing) is now closed with the suggested
fence: LocalDatabase.fenceForRecovery(reason) is set in commit2ndPhase's
finally when a failure occurs AFTER the WAL append, BEFORE reset()
releases the file locks - the volatile write is therefore visible to
any transaction blocked on those locks, so no conflicting WAL record
for the same page versions can follow. The fence surfaces at the
checkDatabaseIsOpen choke point (every new operation) and at an
explicit guard before the WAL append (covers in-flight commits whose
reads bypass the choke point). Close still works: it is the recovery
entry point.
1b. Clean close vs crash: already answered by the #5012 ack gate, no new
code needed. The orphaned record's pages were never queued for flush,
so their WAL acks (bumped at append time) are never released -
getPendingPagesToFlush() > 0 makes the clean close preserve the WAL and
the lock file, and the next open replays the record. 'Durable on
restart' holds for both crash and clean close.
2. getFileIds() broadening confirmed intended, including the compacted
sub-index file: it adds no new serialization between transactions -
any transaction locking the compacted id also locks the mutable id, so
the contender set per index is unchanged - and compaction itself does
not take commit file locks for its appends (only splitIndex's
tryLockFile on the mutable id, which contended before this change
too). The reviewer's observation that this also fixes the latent
add(-1) for composite TypeIndex ids is correct.
3. TransactionException is now rethrown unwrapped by commit2ndPhase too
(same as phase 1, round 3), so first-class errors like the fence are
not buried under 'Transaction error on commit'.
4. java.util.TreeSet::new -> TreeSet::new (java.util.* was imported).
New test: fenced database refuses the WAL point of no return (WAL
byte-identical after the refused commit), fences new operations, and still
closes cleanly. The post-append fence trigger itself is wired in the
finally; forcing a real mid-publish IOException deterministically is not
feasible without fault-injection hooks, so the trigger is covered by code
path inspection and the fence mechanics by the test.
Regression: 118 classes, 577 tests, 0 failures.
(cherry picked from commit 73a413a)
… instance All three review findings were real; the first was a genuine regression in this PR and the reviewer's scenario was exact. 1. RED - redundant double-close stole another database's reference. closeInternal's lambda is documented-idempotent (early-return on !open) but the new release() ran unconditionally after it: dbA.close(); dbA.close(); decremented twice and tore the flush thread down under a still-open dbB - the exact failure this PR exists to eliminate, re-entered through the double-close door. The lambda now reports whether THIS call performed the close, and the whole tail (removeActiveDatabaseInstance, closeExecutor, release) is gated on it - taking the reviewer's suggestion including the arguably-belongs part. 2. ORANGE - acquire() rolls back its increment when startup() throws (e.g. ConfigurationException on negative MAX_PAGE_RAM). Without it the counter wedged at 1 with no flush thread and every later acquire ran against a dead manager the caller's catch could not repair. 3. ORANGE - same-path concurrent open double-release. When registerActiveInstance loses the race it closes the database itself, which (with fix 1) consumes the reference and records it in a per-instance flag; the factory's catch now releases only when the instance did NOT already consume its reference. The lifecycle reference is exactly-once per instance by construction - same pattern as the exactly-once WAL ack from #5012. Red-first: the double-close and startup-failure tests both fail on the pre-review code (1 failure + 1 error). The same-path race has no deterministic repro (it needs two threads between checkForActiveInstance and registerActiveInstance); it is covered by the exactly-once flag construction and the existing hammer test. Regression: engine + database packages green. (cherry picked from commit 60caa57)
…own their windows PageManagerFlushThread.setSuspended(db, true) was putIfAbsent-based: only the FIRST caller owned the suspend flag, but suspendFlushAndExecute ran every caller's callback regardless (#4958). With two concurrent suspenders on the same database (SQL BACKUP DATABASE, the HA verify endpoint, HA snapshot serving - any combination), the non-owner (a) skipped waitForCurrentFlushToComplete, so it could read a page while a flush batch was mid-write, and (b) kept streaming while the owner's exit synchronously flushed the deferred batches to disk - torn reads either way. The suspension is now a per-database REFCOUNT: - setSuspended(db, true) increments the count under the existing per-database suspend lock; it returns true only for the first suspender (0 -> 1). - setSuspended(db, false) decrements; only the LAST release (1 -> 0) runs the resume (Phase 1 synchronous deferred flush, Phase 2 flag clear + detach, Phase 3 re-enqueue, all unchanged) and returns true. A non-last release just drops one reference and the database stays suspended for the remaining suspenders. An unbalanced release is a no-op instead of corrupting state. - A new suspender arriving while the last release is mid-way through the deferred-batch writes waits (timed, uninterruptible with interrupt-flag restore) until the resume completes, so a fresh window can never overlap those page writes. The gate (resumingDatabases) is cleared in a finally that also heals a stuck count if the resume ever escapes with an exception. - PageManager.suspendFlushAndExecute acquires/releases one reference per caller and now runs waitForCurrentFlushToComplete INSIDE the try, so an interrupt during the wait no longer leaks the suspension (pre-existing leak: the flag was set before the wait and never restored on throw). The wait is cheap for non-first suspenders (the flush thread is parked deferring). The #4728 deferred-RAM backpressure accounting and the #5012 per-database suspend bookkeeping are unchanged: batches deferred across overlapping windows are flushed exactly once, by the last suspender's exit. Decision on the HA SnapshotHttpHandler per-database lock (#5063 review round 5): it STAYS, documented as resource discipline rather than correctness. With refcounting it is no longer needed to own the suspension, but it serializes same-database zip streaming: two followers resyncing the same multi-GB database at once would double the read I/O and keep flushing suspended for the UNION of both windows, growing the deferred backlog toward the #4728 cap. TDD red-first: PageManagerFlushSuspendRefCountTest written and run against the pre-fix code (stash-run-unstash); all three methods failed on the exact defect: - overlappingSuspendersBothOwnTheirWindow: isPageFlushingSuspended was false after the first of two overlapping suspendFlushAndExecute callers exited while the second was still inside its callback (expected true, was false). - setSuspendedIsRefCounted: the first release of two suspenders cleared the flag (expected release to return false and the db to stay suspended). - suspendDuringResumeWaitsUntilDeferredFlushCompletes: a suspender acquired immediately while the resume was mid-way through the deferred writes (contract test for the new gate; pre-fix it became a non-owner). PageManagerFlushSuspendDeferRaceTest updated for the new semantics: the resume's count-check now takes the per-database lock, so it serializes behind the flush thread's paused suspended-check and the deferred batch is flushed synchronously in Phase 1 rather than re-enqueued; the assertion now accepts either outcome (flushed or re-enqueued) and still rejects the stranded case. The fake page's file id is now non-existent so the (now reachable) synchronous flush cannot write into a real file of the test database. Verification (all green): - engine: PageManagerFlushSuspendRefCountTest, PageManagerFlushSuspendDeferRaceTest, PageManagerFlushSuspendBackpressureTest, PageManagerFlushThreadInterruptTest, PageManagerDeleteFileFlushCoordinationTest, WalRecoveryCorrectnessTest, Issue4958StorageStatsTest, FlushRobustnessTest, PageManagerLifecycleRefCountTest, Issue4544FlushIndexIdentityTest, PageManagerFlushQueueRaceTest, PageManagerReadCache*Test (28 tests, 1 skipped stress test) - ha-raft: SnapshotHttpHandlerSuspendLockTest, SnapshotWriteStallTest, SnapshotThrottleTest (9 tests) - integration: BackupDatabaseTest (4 tests, drives FullBackupFormat's suspendFlushAndExecute end-to-end) (cherry picked from commit e3fd04a)
#4928: a plain IOException from flushPage escaped the per-page loop and aborted the batch: the remaining pages were never flushed or retried, yet their pageIndex entries survived, so waitAllPagesOfDatabaseAreFlushed spun forever and close()/rename()/backup-suspend hung. The failure is now contained per page with the same policy as the #4965 interrupt double-fault (SEVERE log; the page's WAL entry was never acked, so it is recovered on the next open) and the batch continues. waitAllPagesOfDatabaseAreFlushed is bounded (60s) with a SEVERE escalation instead of an infinite spin.
#4930: the ClosedChannelException reopen path could not tell 'closed by interrupt' from 'closed/dropped on purpose': a page mid-flight in the flush thread racing a DDL drop made the reopen RE-CREATE the deleted file (open() uses RandomAccessFile 'rw'), leaving a one-page ghost that FileManager re-registered on the next open. The reopen now refuses when the component was closed intentionally (open=false) or the OS file no longer exists, surfacing the condition to the caller.
#4931: check() computed RIDs with int*int arithmetic that overflows for buckets beyond 2^31 positions (a 64GB bucket at 64KB pages); with fix=true the wrong-but-positive RID deleted an innocent record. Widened to long as scan() already does; the two log sites with the same overflow (plus a string-concat-instead-of-add bug) fixed too.
#4932: deleteRecordInternal deliberately throws
ConcurrentModificationException as a retry signal for concurrently-modified multi-page chunk chains, then swallowed it 60 lines later in its own generic catch: the slot pointer was zeroed, the delete reported success, the retry never happened and the remaining NEXT_CHUNK records were orphaned (permanent space leak). The retry signal is now rethrown, mirroring the existing RecordNotFoundException clause.
#4955: getBestSlot/getRandomSlot snapshotted executorThreads without a null check, so scheduling async work concurrently with close()/kill() threw a raw NPE instead of the intended DatabaseOperationException that scheduleTask already produced for the same race.
Tests: the batch-containment + no-resurrection test is red-first verified (on unfixed code the dropped file IS re-created on disk and the exception escapes); the bounded-wait test drives the timeout deterministically; the async-slot test asserts the intended exception after kill(). #4931 (needs a 64GB bucket) and #4932 (needs a mid-delete race) are trace-verified fixes mirroring existing correct code in the same file. Regression: engine + database packages green (114 classes, 562 tests).
What does this PR do?
A brief description of the change being made with this pull request.
Motivation
What inspired you to submit this pull request?
Related issues
A list of issues either fixed, containing architectural discussions, otherwise relevant
for this Pull Request.
Additional Notes
Anything else we should know when reviewing?
Checklist
mvn clean packagecommand