Repository navigation
fix(#4924,#4938): fail loud on interrupt instead of silently skipping… - #4965
Conversation
… I/O Two hot-path sites returned normally when the current thread was already interrupted, skipping the I/O they were meant to perform and silently losing committed data: - PageManager.concurrentPageAccess looped on !isInterrupted(), so an already-interrupted thread never ran the callback. In loadPage this cached a zero-filled page (poisoning the read cache and later passing the MVCC version check with version 0); in flushPage it skipped the write but still called notifyPageFlushed, decrementing the WAL pending count and letting the WAL be truncated for a page that never reached disk (#4924). - TransactionManager.writeTransactionToWAL broke out of its retry loop on InterruptedException and returned as if the WAL write had happened, so commit2ndPhase published the transaction's pages with no WAL record: unrecoverable on crash, and later transactions on the same pages raised WALVersionGap during recovery (#4938). Both now throw (InterruptedIOException / TransactionException) instead of returning silently. The interrupt is checked only before acquiring the per-page I/O slot, so an in-flight read/write is never torn, and the interrupt flag is left/kept set so upper layers still observe the cancellation. Throwing surfaces before any state mutation (cache insert, notifyPageFlushed, page publish), so durability is preserved via WAL replay rather than falsely acked. Regression test: InterruptedIOFailsLoudTest drives both paths deterministically (forced disk read with a cleared cache; forced-unavailable WAL slot) and asserts they throw; both tests fail on the pre-fix code.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 7 |
🟢 Coverage 77.78% diff coverage · -7.22% coverage variation
Metric Results Coverage variation ✅ -7.22% coverage variation Diff coverage ✅ 77.78% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (f8282b0) 134232 99762 74.32% Head commit (3ac36a3) 166138 (+31906) 111474 (+11712) 67.10% (-7.22%) 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 (#4965) 27 21 77.78% 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 ensures that thread interrupts during page access and WAL writes fail loudly by throwing an exception rather than silently skipping operations or proceeding as if they succeeded. Specifically, PageManager.concurrentPageAccess now throws an InterruptedIOException if the thread is interrupted before acquiring the I/O lock, and TransactionManager.writeTransactionToWAL throws a TransactionException upon encountering an InterruptedException. A new test class, InterruptedIOFailsLoudTest, has been added to verify these behaviors. I have no feedback to provide.
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.
|
Review: fail loud on interrupt instead of silently skipping I/O (issues 4924, 4938) Reviewed the diff against the surrounding code. This is a focused, correct, and well-motivated durability fix. The commit message is exemplary - it explains the failure mode, the fix, and how the tests reproduce it. Nice work. Correctness - the fixes are right
Points worth considering (non-blocking)
Tests
Small suggestion: the PR checklist boxes (mvn clean package, tests cover both scenarios) are unchecked - worth confirming the full engine test run is green before merge, since this touches a hot path exercised by nearly every commit. Overall: correct fix, good tests, clear rationale. LGTM with the notes above. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #4965 +/- ##
============================================
- Coverage 65.33% 65.33% -0.01%
- Complexity 814 816 +2
============================================
Files 1682 1682
Lines 134232 134335 +103
Branches 28713 28738 +25
============================================
+ Hits 87705 87764 +59
- Misses 34507 34540 +33
- Partials 12020 12031 +11 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…ssion to drop a dirty page Addresses the follow-up flagged in the PR review: once concurrentPageAccess fails loud on interrupt, an interrupted PageManagerFlushThread would have propagated InterruptedIOException into run()'s generic catch, dropping the page it was flushing (removed from pageIndex without reaching disk, its WAL entry already acked to the committer) and abandoning the rest of the batch in pageIndex, which also hangs waitAllPagesOfDatabaseAreFlushed on close. The flush thread now treats its own interruption as a shutdown request: clear the flag (concurrentPageAccess rejects any I/O while it is set), stop accepting new work, retry the write, and let the run() loop drain the queue before the thread exits. A foreign caller of flushPagesFromQueueToDisk still gets the exception rethrown, preserving its own cancellation semantics. The synchronous deferred-batch flush in setSuspended(false), which runs on the unsuspending (backup/HA) thread, gets the same protection: retry once with the flag cleared, then restore the flag so the caller still observes its own cancellation. Both scenarios are covered by deterministic regression tests that park the flush on the page's I/O slot, interrupt, and assert the page still reaches the disk with no pageIndex leak.
Review: fail loud on interrupt instead of silently skipping I/O (#4924, #4938)Solid, well-motivated durability fix. The core insight is correct and important: returning normally from an interrupted I/O path silently violates the WAL/durability contract (caching a zero-filled page, decrementing the WAL pending count for a page that never hit disk, or publishing pages with no WAL record). Converting these to loud failures before any state mutation is the right call, and checking the interrupt before slot acquisition (so an in-flight read/write is never torn) is exactly right. The comments are unusually good and explain the "why" clearly. A few points worth discussing: Correctness / edge cases
Compatibility
Minor
TestsCoverage is good and genuinely deterministic - both the primary fixes and the flush-thread follow-up are exercised, and the tests are written to fail on the pre-fix code. Nice touches: forcing a real disk read via
Nits
Note: I could not run Overall: a valuable correctness fix with strong tests and documentation. Addressing the unguarded-retry batch-leak in concern #1 is the main thing I would want resolved before merge. 🤖 Automated review by Claude. |
Addresses the follow-up review: the interrupt-policy retry of flushPage was outside any try, so a second failure (a fresh interrupt breaking the I/O-slot spin, a real I/O error, or the file being dropped concurrently) escaped to run()'s generic catch, aborting the batch and leaking the remaining pages in pageIndex - the exact failure mode the policy exists to prevent, moved to the double-fault path. The retry is now guarded with the same failure handling as the primary attempt: DatabaseMetadataException (file dropped) logs a WARNING and the batch continues; any other IOException logs a SEVERE noting the page is recovered from the WAL on restart (its entry was never acked via notifyPageFlushed), clears a possible re-interrupt, and the batch continues so every remaining page is flushed and released from pageIndex. Same containment for the deferred-batch retry in setSuspended(false): a DatabaseMetadataException there escaped to the backup/HA caller and skipped the unsuspend phases, leaving the database suspended with batches stranded in the deferred map. On the reviewer's unbounded-spin note: the retry is not unbreakable - the I/O-slot spin in concurrentPageAccess re-checks the interrupt flag on every iteration, so a fresh interrupt surfaces as a second InterruptedIOException and lands in the double-fault handling above. A slot held forever by hung I/O would still spin, but that risk is pre-existing and shared by every flush path, interrupted or not; now documented at the call site. New deterministic regression test: two-page batch, first page's I/O slot held busy, two interrupts (the second breaking the retry spin) - the second page must still reach the disk and pageIndex must be empty.
Review: fix(#4924,#4938) - fail loud on interrupt instead of silently skipping I/OThanks for this fix. This is a high-quality, carefully reasoned change to a subtle durability bug. The core invariant it establishes - an interrupt must never silently drop committed I/O - is exactly right, and the in-code comments documenting why each site behaves the way it does are excellent and will save future maintainers a lot of pain. Overall take: looks correct and ready to merge, with a few observations below (mostly minor / verify-only). What's good
Observations / questions
Nits
Nice work overall - the reasoning in the commit messages and comments is thorough and the fix is sound. (Note: I could not execute the test suite in this sandbox, so the above is a static review; the durability reasoning and control flow check out on inspection.) |
…flush; poll instead of sleep in tests From the latest review round: - setSuspended(false): the per-page finally restored the caller's interrupt flag after every retried page, so with N deferred pages the first interrupt caused one throw+clear+retry+restore cycle per remaining page. The flag is now consumed once for the whole Phase 1 flush and restored once at the end of the method, which also lets the Phase 3b re-enqueue run interrupt-free instead of tripping its InterruptedException handler and dropping detached batches. - PageManagerFlushThreadInterruptTest: replaced the fixed Thread.sleep windows with bounded polling on observable state - the interrupt policy CLEARS the thread's flag when it handles a fault, so a consumed flag proves the previous interrupt was processed and the next one cannot merge with it. 5 consecutive runs green, ~0.29s for the class (sub-second, so no @tag(slow) needed). Also documented the PageManager.INSTANCE isolation assumption (page numbers beyond any page the real flush thread touches). Cancellation blast-radius check (no code change needed): query timeouts never interrupt worker threads (the query engine only restores its own flag after catching InterruptedException); the cross-thread interrupters are forced-shutdown paths (async kill(), vector rebuild cancel) whose worker loops catch Throwable and route to the error callback with rollback; the HTTP layer translates exceptions through sendErrorResponse without leaking raw stack traces to the client.
Review: fix(#4924,#4938) fail loud on interrupt instead of silently skipping I/OThanks for this. Both fixes target genuine, serious durability bugs and the root-cause analysis in the description is excellent. I traced the changes end to end and the core reasoning holds up. Correctness (verified)
Test coverageStrong. Points worth considering (not blockers)
StyleConsistent with the codebase (final params/vars, brace-less single-statement ifs). The block comments are verbose, but given how subtle the interrupt/retry policy is, the extra context is justified. Overall: solid, correct fixes for real data-loss bugs with good regression coverage. The points above are refinements, not objections. Note I could not run |
…5012) * fix(#4928,#4930,#4931,#4932,#4955): storage/engine robustness bundle #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). * 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.
#4965) * fix(#4924,#4938): fail loud on interrupt instead of silently skipping I/O Two hot-path sites returned normally when the current thread was already interrupted, skipping the I/O they were meant to perform and silently losing committed data: - PageManager.concurrentPageAccess looped on !isInterrupted(), so an already-interrupted thread never ran the callback. In loadPage this cached a zero-filled page (poisoning the read cache and later passing the MVCC version check with version 0); in flushPage it skipped the write but still called notifyPageFlushed, decrementing the WAL pending count and letting the WAL be truncated for a page that never reached disk (#4924). - TransactionManager.writeTransactionToWAL broke out of its retry loop on InterruptedException and returned as if the WAL write had happened, so commit2ndPhase published the transaction's pages with no WAL record: unrecoverable on crash, and later transactions on the same pages raised WALVersionGap during recovery (#4938). Both now throw (InterruptedIOException / TransactionException) instead of returning silently. The interrupt is checked only before acquiring the per-page I/O slot, so an in-flight read/write is never torn, and the interrupt flag is left/kept set so upper layers still observe the cancellation. Throwing surfaces before any state mutation (cache insert, notifyPageFlushed, page publish), so durability is preserved via WAL replay rather than falsely acked. Regression test: InterruptedIOFailsLoudTest drives both paths deterministically (forced disk read with a cleared cache; forced-unavailable WAL slot) and asserts they throw; both tests fail on the pre-fix code. * fix(#4924): flush thread interrupt is a shutdown request, never permission to drop a dirty page Addresses the follow-up flagged in the PR review: once concurrentPageAccess fails loud on interrupt, an interrupted PageManagerFlushThread would have propagated InterruptedIOException into run()'s generic catch, dropping the page it was flushing (removed from pageIndex without reaching disk, its WAL entry already acked to the committer) and abandoning the rest of the batch in pageIndex, which also hangs waitAllPagesOfDatabaseAreFlushed on close. The flush thread now treats its own interruption as a shutdown request: clear the flag (concurrentPageAccess rejects any I/O while it is set), stop accepting new work, retry the write, and let the run() loop drain the queue before the thread exits. A foreign caller of flushPagesFromQueueToDisk still gets the exception rethrown, preserving its own cancellation semantics. The synchronous deferred-batch flush in setSuspended(false), which runs on the unsuspending (backup/HA) thread, gets the same protection: retry once with the flag cleared, then restore the flag so the caller still observes its own cancellation. Both scenarios are covered by deterministic regression tests that park the flush on the page's I/O slot, interrupt, and assert the page still reaches the disk with no pageIndex leak. * fix(#4924): contain retry failures in the flush thread interrupt policy Addresses the follow-up review: the interrupt-policy retry of flushPage was outside any try, so a second failure (a fresh interrupt breaking the I/O-slot spin, a real I/O error, or the file being dropped concurrently) escaped to run()'s generic catch, aborting the batch and leaking the remaining pages in pageIndex - the exact failure mode the policy exists to prevent, moved to the double-fault path. The retry is now guarded with the same failure handling as the primary attempt: DatabaseMetadataException (file dropped) logs a WARNING and the batch continues; any other IOException logs a SEVERE noting the page is recovered from the WAL on restart (its entry was never acked via notifyPageFlushed), clears a possible re-interrupt, and the batch continues so every remaining page is flushed and released from pageIndex. Same containment for the deferred-batch retry in setSuspended(false): a DatabaseMetadataException there escaped to the backup/HA caller and skipped the unsuspend phases, leaving the database suspended with batches stranded in the deferred map. On the reviewer's unbounded-spin note: the retry is not unbreakable - the I/O-slot spin in concurrentPageAccess re-checks the interrupt flag on every iteration, so a fresh interrupt surfaces as a second InterruptedIOException and lands in the double-fault handling above. A slot held forever by hung I/O would still spin, but that risk is pre-existing and shared by every flush path, interrupted or not; now documented at the call site. New deterministic regression test: two-page batch, first page's I/O slot held busy, two interrupts (the second breaking the retry spin) - the second page must still reach the disk and pageIndex must be empty. * fix(#4924): consume the caller interrupt once for the whole deferred flush; poll instead of sleep in tests From the latest review round: - setSuspended(false): the per-page finally restored the caller's interrupt flag after every retried page, so with N deferred pages the first interrupt caused one throw+clear+retry+restore cycle per remaining page. The flag is now consumed once for the whole Phase 1 flush and restored once at the end of the method, which also lets the Phase 3b re-enqueue run interrupt-free instead of tripping its InterruptedException handler and dropping detached batches. - PageManagerFlushThreadInterruptTest: replaced the fixed Thread.sleep windows with bounded polling on observable state - the interrupt policy CLEARS the thread's flag when it handles a fault, so a consumed flag proves the previous interrupt was processed and the next one cannot merge with it. 5 consecutive runs green, ~0.29s for the class (sub-second, so no @tag(slow) needed). Also documented the PageManager.INSTANCE isolation assumption (page numbers beyond any page the real flush thread touches). Cancellation blast-radius check (no code change needed): query timeouts never interrupt worker threads (the query engine only restores its own flag after catching InterruptedException); the cross-thread interrupters are forced-shutdown paths (async kill(), vector rebuild cancel) whose worker loops catch Throwable and route to the error callback with rollback; the HTTP layer translates exceptions through sendErrorResponse without leaking raw stack traces to the client. (cherry picked from commit a5b8174)
…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)
… I/O
Two hot-path sites returned normally when the current thread was already interrupted, skipping the I/O they were meant to perform and silently losing committed data:
Both now throw (InterruptedIOException / TransactionException) instead of returning silently. The interrupt is checked only before acquiring the per-page I/O slot, so an in-flight read/write is never torn, and the interrupt flag is left/kept set so upper layers still observe the cancellation. Throwing surfaces before any state mutation (cache insert, notifyPageFlushed, page publish), so durability is preserved via WAL replay rather than falsely acked.
Regression test: InterruptedIOFailsLoudTest drives both paths deterministically (forced disk read with a cleared cache; forced-unavailable WAL slot) and asserts they throw; both tests fail on the pre-fix code.
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