Skip to content

fix(#4924,#4938): fail loud on interrupt instead of silently skipping… - #4965

Merged
lvca merged 5 commits into
mainfrom
fix/4924-4938-interrupt-must-throw
Jul 5, 2026
Merged

lvca merged 5 commits into
mainfrom
fix/4924-4938-interrupt-must-throw

Conversation

@lvca

@lvca lvca commented Jul 4, 2026

Copy link
Copy Markdown
Member

… 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

  • I have run the build using mvn clean package command
  • My unit tests cover both failure and success scenarios

… 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.
@lvca lvca added this to the 26.8.1 milestone Jul 4, 2026
@lvca lvca self-assigned this Jul 4, 2026
@mergify

mergify Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 7 complexity

Metric Results
Complexity 7

View in Codacy

🟢 Coverage 77.78% diff coverage · -7.22% coverage variation

Metric Results
Coverage variation ✅ -7.22% coverage variation
Diff coverage ✅ 77.78% diff coverage

View coverage diff in Codacy

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@claude

claude Bot commented Jul 4, 2026

Copy link
Copy Markdown

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

  • PageManager.concurrentPageAccess: the throw happens before any state mutation. In flushPage it precedes notifyPageFlushed, so an interrupted flush can no longer decrement the WAL pending count for a page that never reached disk. In loadPage it precedes putPageInReadCache, so no zero-filled page can poison the read cache. Both hold.
  • TransactionManager.writeTransactionToWAL: the caller in TransactionContext.commit2ndPhase writes the WAL before updatePages publishes the pages. Throwing TransactionException here correctly aborts the commit before any page is published, so durability is preserved via WAL replay. This directly closes the WALVersionGap-on-recovery path in 4938.
  • Restoring/leaving the interrupt flag set in both sites is the right JDK-idiomatic choice so upper layers still observe the cancellation.

Points worth considering (non-blocking)

  1. Behavior change for legitimate cancellation paths. Interrupted reads/WAL writes now throw where they previously returned silently. Any place that interrupts an engine thread to cancel work (query timeouts, forced shutdown) will now surface InterruptedIOException/TransactionException instead of a silent (buggy) return. This is the intended improvement, but worth a sanity check that query-cancellation callers wrap/handle these cleanly rather than logging them as unexpected internal errors. The normal DB shutdown path uses the graceful SHUTDOWN_THREAD marker (closeAndJoin), not interrupts, so it is unaffected - good.

  2. Background flush thread interruption. If the PageManagerFlushThread itself is ever interrupted mid-flush, flushPage now throws InterruptedIOException, which propagates to run()s generic catch(Throwable) -> logs SEVERE and drops the batch page from the index without flushing (and in the setSuspended(false) deferred path, InterruptedIOException is an IOException, caught/logged WARNING, page removed). The flag stays set until the next queue.poll(...) throws and triggers running=false, so it does not spin - but the current batch page is still lost in that abnormal case. Not a regression versus the old silent-skip, but the durability gap for the flush thread own interruption is not fully closed here. Possibly a follow-up.

Tests

  • interruptedPageLoadThrowsInsteadOfCachingZeroPage is well constructed: it flushes + evicts the cache so the read is a genuine disk read through concurrentPageAccess, asserts the throw, then verifies the cache was not poisoned (real version >= 1) and the row still reads back as 42. Good positive-and-negative coverage.
  • interruptedWalWriteThrowsInsteadOfCommittingWithoutWal reaches into activeWALFilePool via reflection to force the retry/sleep path. A bit fragile (mutating live shared state on an open DB), but isolated per TestHelper DB with no concurrent writers and properly restored in finally. Acceptable for a deterministic regression test.
  • Both clear the interrupt flag in finally so the framework is not left interrupted - important, and done correctly.

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

codecov Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 74.07407% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.33%. Comparing base (f8282b0) to head (3ac36a3).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...va/com/arcadedb/engine/PageManagerFlushThread.java 69.56% 6 Missing and 1 partial ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…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.
@claude

claude Bot commented Jul 4, 2026

Copy link
Copy Markdown

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

  1. Unguarded retry in PageManagerFlushThread (line ~241). In the catch (InterruptedIOException) block the retry pageManager.flushPage(page) is outside a try, so if it throws again it escapes the per-page handling:

    • A second InterruptedIOException (thread re-interrupted between Thread.interrupted() and the retry) or an IOException propagates straight to run()'s catch (Throwable). The finally still runs removeFromFlushIndex(page), but the remaining pages of the batch are not flushed and leak in pageIndex - which the PR itself notes would hang waitAllPagesOfDatabaseAreFlushed on close. This is the exact failure mode the change tries to prevent, moved to a rarer double-fault path.
    • A DatabaseMetadataException on the retry (file dropped) also escapes, whereas the primary path handles it gracefully and continues the batch. Consider wrapping the retry so its failure modes match the primary path (log + continue, no batch abort).
  2. No bound on the retry spin. After clearing the flag, the retried flushPage re-enters concurrentPageAccess, which now spins while(true) on Thread.yield() until the slot frees. If the slot holder never releases (hung I/O), the flush thread cannot exit and join()/shutdown hangs, with the interrupt flag now cleared so it can't even be re-broken. This risk existed pre-change for the non-interrupted spin, but the fix removes the one escape hatch (interrupt) for this thread. Probably acceptable given real I/O slots are short-lived, but worth a comment or a bounded backoff.

Compatibility

  1. Behavior change on the read hot path. loadPage now throws InterruptedIOException where it previously returned a (bad) zero page. Any caller that intentionally interrupts an engine worker (e.g. query cancellation mid-scan) will now surface an exception instead of silently getting a page. This is the correct behavior, but it's a broad change - worth confirming the query-cancellation / async-executor paths treat this IOException subclass as a clean cancellation rather than logging it as an unexpected error.

Minor

  1. The deferred-batch path in setSuspended(false) restores the interrupt flag after each page, so every subsequent page in the batch re-enters the interrupt catch and retries. Functionally fine, just mildly wasteful; a one-line note on the intentional restore-vs-clear asymmetry between the two flush sites would help future readers (the flush-thread path clears and leaves it clear; this path restores it for the caller).

Tests

Coverage 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 removeAllReadPagesOfDatabase, nulling activeWALFilePool to force the retry/sleep path, and occupying the pendingFlushPages slot to make interrupt timing deterministic. Suggestions:

  • Add an assertion in interruptedWalWriteThrowsInsteadOfCommittingWithoutWal (or a companion end-to-end test) that a full db.transaction(...) whose commit is interrupted leaves no partially-published pages / raises no later WALVersionGap on reopen - verify the durability outcome, not just that the method throws.
  • Consider a test for the double-fault retry path in concern build support #1 to pin down the intended behavior.
  • The tests reach into private fields via reflection (activeWALFilePool, pendingFlushPages) and synthesize MutablePages that bypass the commit path (so notifyPageFlushed decrements a counter never incremented). It works, but is tightly coupled to internals - a brief comment noting the synthetic-page caveat would help maintenance.

Nits

  • throw new TransactionException(...) reuses the already-imported class - good, no new imports needed there.
  • PR description still has the unfilled template sections (What/Motivation/Related issues) below the (excellent) top summary.

Note: I could not run mvn test in this environment, so I did not confirm the new tests pass locally - please make sure CI is green.

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.

lvca added 2 commits July 4, 2026 13:08
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.
@claude

claude Bot commented Jul 4, 2026

Copy link
Copy Markdown

Review: fix(#4924,#4938) - fail loud on interrupt instead of silently skipping I/O

Thanks 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

  • Correct ordering of the guard. In concurrentPageAccess, throwing before putIfAbsent and before callback.access() means an in-flight read/write is never torn, and the throw surfaces before putPageInReadCache / notifyPageFlushed / page publish. The durability argument (recover from WAL rather than falsely ack) holds.
  • The flush-thread policy is the right call. Treating the flush thread's own interrupt as a shutdown request (clear flag, running=false, retry, drain the queue) rather than a license to drop a dirty page whose WAL entry was already acked is correct, and the follow-up commits that contain the retry double-fault (so it can't escape to run()'s generic catch and leak pageIndex entries / hang waitAllPagesOfDatabaseAreFlushed) close a real gap.
  • Test coverage is strong. Three deterministic regression tests driving the interrupt at precise points (busy I/O slot, forced-unavailable WAL slot, double interrupt, deferred-batch unsuspend), each asserting both the throw and the absence of state corruption (no poisoned cache page, no pageIndex leak, page still reaches disk). Noting that each test fails on pre-fix code is the right discipline.

Observations / questions

  1. Behavior-change blast radius on query cancellation (verify). Previously an interrupted loadPage silently returned a zero page; now any interrupted read throws InterruptedIOException. That's the correct fix, but query-cancellation / timeout paths that interrupt worker threads will now see InterruptedIOException surface where they didn't before. Worth confirming those paths catch/translate it cleanly and don't leak a raw stack trace to the client. Not a blocker, but a good smoke-test.

  2. Deferred-batch path restores the interrupt flag inside the per-page loop. In setSuspended(false), the finally { Thread.currentThread().interrupt(); } runs per page. If the first deferred page was interrupted, every subsequent deferred page re-enters flushPage with the flag set, immediately throws InterruptedIOException, gets caught, cleared, retried, and restored again - one throw+retry cycle per remaining page. Correct, but a bit wasteful. Consider clearing once, flushing the whole deferred batch, then restoring the flag once at the end. Minor; interrupt-during-unsuspend is rare.

  3. Timing-based tests may be CI-flaky. PageManagerFlushThreadInterruptTest relies on Thread.sleep(50/100) + a reflectively-held pendingFlushPages slot to land the interrupt while the flush thread spins. Because the interrupt flag persists until concurrentPageAccess re-checks it, the timing is more robust than it first looks, but the fixed sleeps used to wait for the thread to reach the spin are still heuristic under a loaded CI box. If these ever flake, prefer a latch / poll on observable state over Thread.sleep. Also worth checking whether they warrant @Tag("slow") per CLAUDE.md (they look sub-second, so probably fine).

  4. Shared PageManager.INSTANCE in tests. The tests mutate the singleton's pendingFlushPages via reflection and spin up a private PageManagerFlushThread against PageManager.INSTANCE. They use page numbers beyond the existing ones to avoid colliding with the DB's real flush thread, which is reasonable - just flagging it as a latent isolation risk if page-numbering assumptions ever change.

  5. flushPagesFromQueueToDisk != this rethrow. The if (Thread.currentThread() != this) throw e; guard only triggers for a foreign caller (today: the tests). In production run() always calls it on this, so the branch is effectively defensive-only - just noting it isn't exercised outside the test harness.

Nits

  • The PR description still contains the unfilled template sections ("What does this PR do?", "Motivation", etc.) below the real writeup - worth cleaning up before merge.

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.
@claude

claude Bot commented Jul 5, 2026

Copy link
Copy Markdown

Review: fix(#4924,#4938) fail loud on interrupt instead of silently skipping I/O

Thanks 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)

  • concurrentPageAccess now throws InterruptedIOException before acquiring the per-page slot and before any state mutation. In loadPage the throw happens inside the read callback, so putPageInReadCache is never reached: no zero-page poisoning. In flushPage the throw is inside the write callback, so notifyPageFlushed (WAL pending decrement) is never reached: durability is preserved via WAL replay. Correct.
  • writeTransactionToWAL throwing TransactionException propagates cleanly: in TransactionContext.commit2ndPhase the WAL write happens before updatePages publishes the pages. The throw is caught in the commit catch block, committed stays false, and the finally calls reset() instead of resetAndFireCallbacks(), so the transaction is aborted with no pages published. Correct.
  • The interrupt flag is preserved/restored in every path (Thread.currentThread().interrupt() in TransactionManager, restoreCallerInterrupt in setSuspended), so upper layers still observe cancellation.

Test coverage

Strong. InterruptedIOFailsLoudTest drives both original paths deterministically and asserts the pre-fix silent-skip is gone; the flush-thread follow-up tests cover the shutdown-drain, double-fault, and deferred-unsuspend policies including the "no page leaks in pageIndex" invariant that would otherwise hang close(). Failure and success paths both covered.

Points worth considering (not blockers)

  1. Scope of the behavior change is broader than the two issues. concurrentPageAccess is on the shared read/write path, so any interrupted thread doing page I/O now throws, not just the flush thread and commit path: DatabaseAsyncExecutor workers, the query-parallelism pool, and user script threads (Gremlin/Polyglot) interrupted mid-read will now surface InterruptedIOException where they previously returned silently. This is strictly more correct (the old silent read returned a zero page), but it is worth a quick scan of interrupt-driven cancellation paths to confirm they treat InterruptedIOException as expected cancellation rather than logging it as a scary I/O error.

  2. The retry swallows a genuine (non-interrupt) disk error. In both the flush-thread handler (catch IOException e2) and setSuspended (catch DatabaseMetadataException | IOException e2), a real disk failure during the retry is downgraded to a log line, whereas the primary attempt lets a plain IOException propagate to run(). The WAL-recovery justification is sound for the interrupt case, but a persistent disk fault during shutdown would now be masked as a log rather than propagated. Consider distinguishing "retry re-interrupted" (InterruptedIOException, contain and continue) from "retry hit a genuine disk error" (arguably should still surface), since InterruptedIOException extends IOException and both currently land in the same catch.

  3. White-box test fragility. PageManagerFlushThreadInterruptTest mutates the shared PageManager.INSTANCE.pendingFlushPages singleton and relies on page-number isolation from the real flush thread, plus spin-loops on queue.isEmpty() and interrupt-flag-consumed state. It is well-commented and deadline-bounded, but it is timing-sensitive and shares global state, so it may be a flakiness candidate under loaded CI. Given the up-to-10s joins, consider whether @Tag("slow") fits the CLAUDE.md guidance.

Style

Consistent 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 mvn test in this environment, so please confirm the two new test classes pass in CI (the description states they fail on pre-fix code, which is the right check).

@lvca
lvca merged commit a5b8174 into main Jul 5, 2026
21 of 26 checks passed
@lvca
lvca deleted the fix/4924-4938-interrupt-must-throw branch July 5, 2026 00:57
lvca added a commit that referenced this pull request Jul 6, 2026
…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.
robfrank pushed a commit that referenced this pull request Aug 14, 2026
#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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant