Skip to content

fix(#4928,#4930,#4931,#4932,#4955): storage/engine robustness bundle - #5012

Merged
lvca merged 7 commits into
mainfrom
fix/4928-flush-and-quick-wins
Jul 6, 2026
Merged

lvca merged 7 commits into
mainfrom
fix/4928-flush-and-quick-wins

Conversation

@lvca

@lvca lvca commented Jul 6, 2026

Copy link
Copy Markdown
Member

#4928: a plain IOException from flushPage escaped the per-page loop and aborted the batch: the remaining pages were never flushed or retried, yet their pageIndex entries survived, so waitAllPagesOfDatabaseAreFlushed spun forever and close()/rename()/backup-suspend hung. The failure is now contained per page with the same policy as the #4965 interrupt double-fault (SEVERE log; the page's WAL entry was never acked, so it is recovered on the next open) and the batch continues. waitAllPagesOfDatabaseAreFlushed is bounded (60s) with a SEVERE escalation instead of an infinite spin.

#4930: the ClosedChannelException reopen path could not tell 'closed by interrupt' from 'closed/dropped on purpose': a page mid-flight in the flush thread racing a DDL drop made the reopen RE-CREATE the deleted file (open() uses RandomAccessFile 'rw'), leaving a one-page ghost that FileManager re-registered on the next open. The reopen now refuses when the component was closed intentionally (open=false) or the OS file no longer exists, surfacing the condition to the caller.

#4931: check() computed RIDs with int*int arithmetic that overflows for buckets beyond 2^31 positions (a 64GB bucket at 64KB pages); with fix=true the wrong-but-positive RID deleted an innocent record. Widened to long as scan() already does; the two log sites with the same overflow (plus a string-concat-instead-of-add bug) fixed too.

#4932: deleteRecordInternal deliberately throws
ConcurrentModificationException as a retry signal for concurrently-modified multi-page chunk chains, then swallowed it 60 lines later in its own generic catch: the slot pointer was zeroed, the delete reported success, the retry never happened and the remaining NEXT_CHUNK records were orphaned (permanent space leak). The retry signal is now rethrown, mirroring the existing RecordNotFoundException clause.

#4955: getBestSlot/getRandomSlot snapshotted executorThreads without a null check, so scheduling async work concurrently with close()/kill() threw a raw NPE instead of the intended DatabaseOperationException that scheduleTask already produced for the same race.

Tests: the batch-containment + no-resurrection test is red-first verified (on unfixed code the dropped file IS re-created on disk and the exception escapes); the bounded-wait test drives the timeout deterministically; the async-slot test asserts the intended exception after kill(). #4931 (needs a 64GB bucket) and #4932 (needs a mid-delete race) are trace-verified fixes mirroring existing correct code in the same file. Regression: engine + database packages green (114 classes, 562 tests).

What does this PR do?

A brief description of the change being made with this pull request.

Motivation

What inspired you to submit this pull request?

Related issues

A list of issues either fixed, containing architectural discussions, otherwise relevant
for this Pull Request.

Additional Notes

Anything else we should know when reviewing?

Checklist

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

#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).
@lvca lvca added this to the 26.7.2 milestone Jul 6, 2026
@lvca lvca self-assigned this Jul 6, 2026
@mergify

mergify Bot commented Jul 6, 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 6, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 24 complexity

Metric Results
Complexity 24

View in Codacy

🟢 Coverage 86.00% diff coverage · -6.86% coverage variation

Metric Results
Coverage variation ✅ -6.86% coverage variation
Diff coverage ✅ 86.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (ef0fdb3) 134798 100328 74.43%
Head commit (d589a5e) 166675 (+31877) 112614 (+12286) 67.57% (-6.86%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#5012) 100 86 86.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@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 introduces a robustness bundle for the storage engine, addressing several critical defects: it bounds the page flush wait time to prevent infinite hangs during database close, contains per-page I/O errors to avoid aborting flush batches, prevents the recreation of deleted files during channel reopens, fixes integer overflows in RID arithmetic for large buckets, and ensures concurrent modification retry signals are not swallowed during multi-page record deletions. Additionally, it resolves a shutdown race in the async executor that could lead to a NullPointerException. Feedback on the changes suggests marking the mutable static field WAIT_FLUSH_TIMEOUT_MS as volatile to guarantee thread visibility when modified dynamically during tests.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

* Upper bound for {@link #waitAllPagesOfDatabaseAreFlushed}: generous enough for any healthy flush backlog
* (the bounded queue drains far faster), small enough that a wedged flush cannot hang close() forever (#4928).
*/
static long WAIT_FLUSH_TIMEOUT_MS = 60_000L; // non-final and package-private for the #4928 regression test

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.

medium

Since WAIT_FLUSH_TIMEOUT_MS is a mutable static field that is modified dynamically in tests (such as in FlushRobustnessTest.java), it should be marked volatile to ensure thread visibility. Without volatile, updates to this field made by a test thread might not be immediately visible to other threads executing waitAllPagesOfDatabaseAreFlushed, which could lead to flaky test results or incorrect timeout behavior in concurrent environments.

Suggested change
static long WAIT_FLUSH_TIMEOUT_MS = 60_000L; // non-final and package-private for the #4928 regression test
static volatile long WAIT_FLUSH_TIMEOUT_MS = 60_000L; // non-final and package-private for the #4928 regression test

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

PR Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)

Thanks for this bundle - the fixes are well-scoped, the comments explain the "why" clearly, and the red-first tests are a nice touch. Most changes are clean wins. I have one substantive correctness concern on the #4928 bounded-wait, plus a few smaller notes.

🔴 Main concern: the "recovered from the WAL on next open" guarantee does not hold on the close() path (#4928)

Both the new bounded-wait timeout and the per-page IOException swallow rest on the same promise: an unflushed page's WAL entry was never acked, so it is replayed on the next open. That is true at runtime, but not on a clean close, and waitAllPagesOfDatabaseAreFlushed(...) is called precisely from LocalDatabase.close() (LocalDatabase.java:2062).

Trace for the timeout branch:

  1. waitAllPagesOfDatabaseAreFlushed times out with pages still pending in pageIndex and returns.
  2. close() continues and sets open=false (LocalDatabase.java:2067). From here PageManager.flushPage early-returns on !database.isOpen() (PageManager.java:394-397), so the pending pages are never written.
  3. transactionManager.close(false) runs and, after moving all active WAL files to the inactive pool, OS-deletes every .wal file unconditionally (TransactionManager.java:154,163,167-172; with dropFiles=false the !dropFiles guard in cleanWALFiles at TransactionManager.java:815 closes the files regardless of getPendingPagesToFlush()).

Net effect: on the timeout branch the still-pending pages are lost, not recovered - the opposite of what the SEVERE log and code comment promise. The old infinite spin, however ugly, never let close() proceed with unflushed pages, so this is a real behavior change from "hang" to "silent loss of the most recent pages."

This is admittedly the pathological branch (dead flush thread / unwritable disk), and hanging forever is also bad. Two things would make it safer and honest:

  • Make the timeout a GlobalConfiguration value rather than a hardcoded 60_000L. On a large DB on slow storage a legitimate flush backlog at close could exceed 60s, turning a healthy close into data loss. A config knob (defaulting high) lets operators tune it and removes the "shared mutable static poked by a test" smell (below).
  • Reword the SEVERE log / comment so it does not over-promise WAL recovery on the close path, since close deletes the WAL that would do the recovering.

The same caveat applies to the per-page IOException swallow (PageManagerFlushThread.java:282-289): at runtime the WAL file is retained because getPendingPagesToFlush() > 0 blocks its drop, but the page is also never re-flushed (notifyPageFlushed never reached), so once the read cache evicts it, readers see stale on-disk content until a restart replays the WAL. This mirrors the pre-existing interrupt double-fault policy (:268-278), so it is a consistent accepted tradeoff, but worth being explicit that the page is only durable-via-WAL, not repaired in place.

🟡 Minor

  • WAIT_FLUSH_TIMEOUT_MS as a mutable package-private static (PageManagerFlushThread.java:71): JVM-wide and mutated by FlushRobustnessTest in a try/finally. If any other flush-related test runs concurrently in the same JVM it would observe the 500ms value and could give up early. A GlobalConfiguration entry read per-call (or an instance field) avoids both the shared-global hazard and the test reaching into production statics.
  • getRandomSlot/getBestSlot ([engine] Async getBestSlot NPE races database shutdown instead of throwing the intended DatabaseOperationException #4955): null-snapshot fix is correct and the message matches scheduleTask. Very minor: ThreadLocalRandom.nextInt(threads.length) throws IllegalArgumentException if threads.length == 0; presumably unreachable, but a comment on the non-empty invariant would help if it can ever be zero-length pre-shutdown.

✅ Looks good

Test coverage

Well covered for #4928/#4930/#4955. Given the concern above, a test that drives LocalDatabase.close() (not just the standalone flush thread) with a page that cannot be flushed, asserting the intended durability outcome, would have surfaced the WAL-deleted-on-close interaction. #4931/#4932 are reasonably left as trace-verified given the setup cost.

Overall: solid, low-risk fixes for four of the five issues. I'd like the #4928 close-path durability semantics clarified (config-driven timeout + honest log/comment, and ideally not deleting WAL that still protects pending pages) before merge.

… lock file for recovery

The Claude review's main concern was legitimate and serious, and its trace
was exact: the bounded wait let close() proceed, close() set open=false (so
the pending pages could never be written), transactionManager.close() then
OS-deleted every WAL file unconditionally and the lock file was removed -
so the 'recovered from the WAL on next open' promise in the SEVERE log was
FALSE precisely on the close path, converting the old hang into silent loss
of the most recent pages.

Fixed by making a give-up close crash-equivalent:

- waitAllPagesOfDatabaseAreFlushed returns whether everything reached the
  disk, and its timeout is now a NO-PROGRESS window read per call from
  arcadedb.flushAllPagesTimeout (SCOPE.DATABASE, default 60s, 0 = wait
  forever): the window resets whenever the pending-page count decreases, so
  a legitimate slow backlog on a large database can never trip it - only a
  genuinely wedged flush does. This also removes the mutable static the
  reviews flagged (and moots the volatile suggestion).

- On false, LocalDatabase.closeInternal passes preserveWalFiles to
  transactionManager.close - the WAL files are closed but NOT deleted (they
  are the only durable copy of the unflushed pages) - and the lock file is
  kept as the unclean-shutdown marker, so the next open runs recovery and
  replays them. Every log/comment now states semantics that are actually
  true.

- The per-page IOException containment comment now states the accepted
  tradeoff explicitly: durable via WAL replay on the next open, not
  repaired in place; until then an evicted page reads stale from disk.

- getBestSlot/getRandomSlot also guard a zero-length array (nextInt(0)
  would throw IllegalArgumentException), per the review nit.

New end-to-end test drives a real DatabaseFactory close with an
unflushable page: the close completes (bounded), the WAL and lock file
survive it, the reopen recovers the committed row, and the subsequent
clean close deletes the WAL as before. Engine + database packages green.
@codecov

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.00000% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.79%. Comparing base (ef0fdb3) to head (d589a5e).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ndex/sparsevector/PaginatedSparseVectorEngine.java 0.00% 2 Missing and 2 partials ⚠️
...main/java/com/arcadedb/database/LocalDatabase.java 75.00% 1 Missing and 2 partials ⚠️
...dedb/database/async/DatabaseAsyncExecutorImpl.java 50.00% 1 Missing and 2 partials ⚠️
...src/main/java/com/arcadedb/engine/LocalBucket.java 57.14% 3 Missing ⚠️
...va/com/arcadedb/engine/PageManagerFlushThread.java 91.17% 1 Missing and 2 partials ⚠️
...src/main/java/com/arcadedb/engine/PageManager.java 66.66% 1 Missing and 1 partial ⚠️
...n/java/com/arcadedb/engine/PaginatedComponent.java 0.00% 1 Missing and 1 partial ⚠️
...va/com/arcadedb/engine/PaginatedComponentFile.java 50.00% 1 Missing and 1 partial ⚠️
...n/java/com/arcadedb/engine/TransactionManager.java 87.50% 1 Missing and 1 partial ⚠️
...java/com/arcadedb/index/vector/LSMVectorIndex.java 0.00% 1 Missing and 1 partial ⚠️
... and 1 more
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5012      +/-   ##
============================================
+ Coverage     65.44%   65.79%   +0.34%     
- Complexity      822      823       +1     
============================================
  Files          1687     1687              
  Lines        134798   134872      +74     
  Branches      28822    28845      +23     
============================================
+ Hits          88223    88743     +520     
+ Misses        34507    33938     -569     
- Partials      12068    12191     +123     

☔ View full report in Codecov by Harness.
📢 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.

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Code Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)

Reviewed the full diff and traced the supporting code (PageManager.flushPage, TransactionManager.cleanWALFiles, PaginatedComponentFile.reopenChannelUnderWriteLock, and every caller of waitAllPagesOfDatabaseAreFlushed). Overall this is a high-quality, well-reasoned bundle: each fix is narrowly scoped, the comments explain the why and the accepted tradeoffs, and the WAL-preservation path checks out.

What I verified as correct

Concerns worth addressing

1. (Medium) Non-close callers silently ignore the new false return. waitAllPagesOfDatabaseAreFlushed is also called by PaginatedComponent.rename(), PaginatedSparseVectorEngine (x2), and LSMVectorIndex - none of which preserve the WAL. Before this PR they hung; now, on a give-up, they proceed to rename/backup/compact with pages still pending flush, and there is no crash-equivalent safety net on those paths (only LocalDatabase.closeInternal inspects the boolean). This trades an infinite hang for a possible silent inconsistency in those flows. Suggest at minimum logging a WARNING at those call sites, or documenting the accepted risk there.

2. (Medium) No-progress detection can false-positive under sustained concurrent writes. The window resets only when pending < lastPending, and lastPending ratchets downward monotonically. On the live callers (rename/backup-suspend), if incoming commits outpace the flusher for longer than the window, pending may never dip below its earlier minimum and the wait gives up even though flushing is actively happening. For close() this is fine (no new writes), but for the live callers consider gating on a monotonic "pages actually flushed" counter (e.g. totalPagesWritten delta) rather than "did the pending count decrease".

3. (Low) Test-coverage gap for #4931 and #4932. Both are acknowledged as trace-verified only, but these are the two highest-severity defects (deleting an innocent record under fix=true; a permanent space leak). #4931 in particular is testable without a 64GB bucket by extracting/checking the RID arithmetic, and #4932 could be driven with a spy that forces the multi-page chunk path to throw the retry signal. Worth a regression test given the blast radius.

4. (Low) Shared-singleton test hygiene. FlushRobustnessTest mutates PageManager.INSTANCE.getFlushThread().pageIndex (JVM-wide singleton). The db-keyed filtering mitigates cross-test interference, and cleanup is in finally, but if engine tests ever move to parallel class execution this becomes fragile. Fine as-is, just flagging.

5. (Nit) waitAllPagesOfDatabaseAreFlushed now full-scans pageIndex every 10ms (counting) instead of breaking on first match. Only runs on close/rename/backup so not a hot path, but O(n) per tick on a large pending index. Acceptable given progress detection needs the count.

6. (Nit) In the truly-wedged (non-IOException) case, a give-up close leaves the stuck pageIndex entry in the shared flush thread referencing a now-closed database - a small leak. The real IOException path removes it in finally, so this only affects the pathological hang case; not blocking.

Nice work overall - the fixes are correct and the crash-equivalent-close design is the right call. Addressing #1 (surfacing the give-up to the rename/backup callers) is the most valuable follow-up.

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)

Thanks for this - it's an unusually well-documented PR. Each fix is tied to an issue, the inline comments explain why rather than what, and the red-first tests for #4928/#4930 plus the deterministic bounded-wait test are exactly the right level of rigor. I went through all five fixes carefully. Nothing here is a blocker; the notes below are one design point worth a decision and a few minor cleanups.

Correctness of the individual fixes (all look right)

One design point worth a decision (not a blocker)

waitAllPagesOfDatabaseAreFlushed now returns a boolean, but only the LocalDatabase.closeInternal path consumes it. The other four callers ignore the return value:

  • PaginatedComponent.rename() (PaginatedComponent.java:88)
  • PaginatedSparseVectorEngine (lines 688, 1012)
  • LSMVectorIndex (line 3942, which ships the new component to HA followers)

Before this PR those paths would hang forever on a wedged flush. Now, with the 60s default timeout, they will silently give up and proceed as if everything flushed. For rename() that means moving a file whose pages never reached disk; for the LSMVectorIndex path it means potentially shipping an incomplete component to followers. The no-progress window makes this only trigger on a genuinely stuck flush (a healthy slow backlog resets the window), so it's a narrow edge - and arguably "proceed" is no worse than the previous "hang forever". But the behavior change is now implicit at those call sites. Consider either (a) having those callers react to a false return, or (b) at minimum a one-line comment at each ignoring call site noting the timeout now applies there too, so a future reader doesn't assume the wait is still unbounded.

Minor

  • Duplicate Javadoc block: PageManagerFlushThread.waitAllPagesOfDatabaseAreFlushed now has two stacked /** ... */ comments (the original at ~143-149 and the new @return block at ~150-157). Only the second is the effective Javadoc; the first becomes a dangling comment. Worth merging into one.
  • Stale throws: flushPagesFromQueueToDisk still declares throws IOException, but every IOException path is now caught internally. Harmless, but could be dropped for clarity (the single caller in run() catches Throwable anyway).
  • Per-iteration cost of the wait loop: the pending count no longer breaks on the first match, so each 10ms tick is a full O(n) scan of the JVM-wide pageIndex instead of an early-exit. Negligible in practice (only during close/rename/backup), just noting it since the previous code was intentionally short-circuiting.
  • Test isolation: FlushRobustnessTest and the WAL-preserve test mutate the shared PageManager.INSTANCE.getFlushThread().pageIndex and rely on finally cleanup to unwedge subsequent tests' closes. The cleanup is correctly in finally, so this is fine, just inherently a bit fragile against a future refactor.

Test coverage

Good. #4928 (batch containment + no resurrection + bounded wait + WAL preserve/recover), #4930 and #4955 are all covered directly; #4931/#4932 are trace-verified against mirrored correct code in the same file, which is a reasonable call given a 64GB bucket / mid-delete race is impractical to reproduce in a unit test.

Overall: solid, careful work. My only real ask is a decision on the ignored boolean at the four non-close call sites.

…s signal; #4931 unit test

From the latest review round:

- The four non-close callers of waitAllPagesOfDatabaseAreFlushed no longer
  ignore the give-up (the review's main point): PaginatedComponent.rename()
  throws IOException (renaming with pages in flight lets the flush thread
  write to the file under its old identity), and the two sparse-vector HA
  shipping sites plus the vector-index compaction throw as well (shipping
  with unflushed pages would send zero pages to followers). All four are
  retryable operations, so fail-and-retry is strictly safer than the old
  hang and than warn-and-proceed.

- The no-progress window now resets on EITHER signal: pending-count
  decrease OR pages physically written (totalPagesWritten delta). On live
  callers (rename, backup-suspend, compaction shipping) sustained commits
  could keep the pending count from ever dipping below its minimum while
  the flusher worked flat out - with the dual signal only a flusher that
  writes nothing at all can trip the timeout.

- #4931's arithmetic is extracted into LocalBucket.recordPosition() - now
  the single implementation for all four sites including scan() - with a
  unit test that pins the overflow boundary and demonstrates the
  innocent-record aliasing (the old int arithmetic mapped page 2_097_152
  slot 42 onto position 42). #4932 stays trace-verified: deterministically
  forcing the chunk-chain retry signal needs internal page-format surgery
  disproportionate to a two-line catch-order fix mirroring the adjacent
  RecordNotFoundException clause.

- A give-up close purges its stuck pageIndex entries from the shared flush
  thread (they reference a now-closed database and can never be flushed;
  their content is safe in the preserved WAL) - closing the small leak the
  review flagged - and the close-path test now asserts the purge.

- Singleton test hygiene and the O(n) pending count per tick acknowledged
  as-is: the suite is sequential by configuration, and progress detection
  needs the count on what is a cold path.

Regression: engine + database + sparse-vector packages green
(129 classes, 630 tests).
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)

Overall this is a high-quality, carefully documented bundle. The comments explaining why each change is safe (WAL-recoverability, crash-equivalent close, retry-signal semantics) are excellent and make the diff reviewable. Test coverage is good, several tests are genuinely red-first, and the fixes for #4930 (refuse to re-create a dropped file on reopen), #4931 (widen RID arithmetic to long), #4932 (rethrow the ConcurrentModificationException retry signal), and #4955 (null-guard the executor-thread snapshot) all look correct and mirror existing patterns in their files.

Two substantive concerns on the #4928 bounded-wait design, and a nit.

1. The no-progress signal is JVM-global, so a busy sibling database can keep a wedged close() from ever timing out

waitAllPagesOfDatabaseAreFlushed uses pageManager.getTotalPagesWritten() as its progress signal, but totalPagesWritten is an AtomicLong on the singleton PageManager.INSTANCE, incremented for every page of every database sharing the JVM-wide flush thread. On the ArcadeDB server, many databases share that one flush thread.

Consequence: if database A's pages are genuinely wedged (unwritable disk for A's files) but database B is healthy and actively committing, getTotalPagesWritten() keeps advancing, so the written > lastWritten branch resets lastProgressAt on every iteration and A's close() never trips the timeout - exactly the multi-tenant hang #4928 is meant to prevent.

Note that on the close() path there are no new commits for the closing database, so pending is monotonically non-increasing and the pending < lastPending signal alone is sufficient there. The global written signal is only really needed for the live callers (rename / backup-suspend / compaction shipping) where sustained commits keep pending from dipping. Consider making the progress signal per-database (e.g. a per-DB flushed-page counter, or count how many of this database's pages left pageIndex since the last check) so the window reflects progress on the database actually being waited on.

2. A page contained by the new IOException handler is dropped from pageIndex and never re-flushed - a later clean close then deletes the WAL that protects it

The new per-page catch in flushPagesFromQueueToDisk logs SEVERE and falls through to the finally, which calls removeFromFlushIndex(page). So after a transient IOException, the page is gone from pageIndex and (as far as I can see) is never re-enqueued for flush. The comment correctly notes the change is still durable via the WAL because notifyPageFlushed was not reached.

But that guarantee only lasts until the next clean close:

  1. Page P fails to flush (transient I/O error) -> removed from pageIndex, still only in the WAL.
  2. Later, a normal close() runs -> waitAllPagesOfDatabaseAreFlushed sees pending == 0 (P is gone from the index) -> returns true -> preserveWalForRecovery = false.
  3. TransactionManager.close(drop, false) reaches the OS-level branch and force-deletes every *.wal by filename, regardless of ack state.
  4. Next open: P's change is gone entirely - silent data loss.

So the fix correctly trades the old hang for progress, but "recovered from the WAL on restart" only holds if the process actually restarts/recovers before the next clean close; a clean close in between can silently discard the un-flushed change, because the close's "all flushed?" check is driven by pageIndex, which this handler just emptied. Could you confirm whether such an IOException-dropped page is ever re-flushed, and if not, whether the clean-close WAL deletion should be gated on "were all pages actually acked" rather than "is pageIndex empty"? (Same reasoning applies to the pre-existing interrupt double-fault path just above it.)

3. Nit: stray Javadoc now documents the wrong member

In LocalBucket, the pre-existing /** Called at creation time. */ block now sits immediately above the new recordPosition(...) helper, so it documents that static helper (which is not "called at creation time") and leaves the LocalBucket(...) constructor it was meant for undocumented. Move or drop that stray block.

Minor observations (non-blocking)

  • FlushRobustnessTest.closeWithUnflushablePagesPreservesWalAndRecoversOnNextOpen injects a fabricated PageId into the shared PageManager.INSTANCE.getFlushThread().pageIndex. Cleanup is in finally, but this mutates JVM-wide singleton state from a test - worth awareness if these ever run in parallel with others in the same JVM.
  • Good call surfacing [storage] ClosedChannelException recovery in PaginatedComponentFile resurrects intentionally closed/dropped files #4930's two distinct refusal reasons (closed-on-purpose vs OS file gone) as separate messages.
  • The getRandomSlot zero-length guard for nextInt(0) is a nice defensive touch even if "unreachable today".

Nice work overall - concerns 1 and 2 are about the completeness of the #4928 durability story rather than the correctness of the mechanical changes.

lvca added 2 commits July 6, 2026 11:38
…ops silent WAL loss

Both substantive review points were legitimate; the second was the deepest
catch of the whole PR series.

1. The flush-progress signal is now PER-DATABASE. The previous
   totalPagesWritten delta was JVM-global, so on a multi-database server a
   busy healthy sibling kept resetting a wedged database's no-progress
   window - close() never timed out, which is exactly the multi-tenant hang
   #4928 exists to prevent. PageManagerFlushThread now keeps a per-database
   counter of pages that LEFT the flush pipeline (bumped in both per-page
   finally blocks, cleaned up in removeAllPagesOfDatabase) and the wait
   resets its window only on THIS database's pending-count decrease or
   pipeline departures.

2. The clean close is now gated on WAL ACKS, not pipeline emptiness. The
   reviewer's trace was exact: a page whose flush failed and was contained
   leaves pageIndex without ever calling notifyPageFlushed and is never
   re-flushed in-process (confirmed); the next CLEAN close then saw
   pending == 0, decided everything was flushed, and force-deleted the very
   WAL holding the only durable copy - silent loss of a committed change
   after a mere transient I/O error. TransactionManager.close now checks
   getPendingPagesToFlush() across the WAL pool (the ground truth) before
   the delete sweep and preserves WAL + (via its new boolean return) the
   lock file whenever anything is unacked, so the next open recovers. This
   also covers the pre-existing interrupt double-fault path the review
   pointed at.

   To keep the gate honest, pages that legitimately never need flushing now
   release their acks: flushPage's file-dropped branch and the dropped-file
   purge in removePagesOfFileFromBatch call notifyPageFlushed (the content
   is irrelevant, the file is gone). File-CLOSED paths deliberately do NOT
   ack: if hit racily, the conservative outcome is a preserved WAL and one
   recovery pass, never a loss.

3. The stray 'Called at creation time' javadoc is back on the LocalBucket
   constructor it belongs to.

New regression test drives the reviewer's exact scenario end to end: a
committed change whose WAL page is acked-to-committer but never flushed,
followed by a CLEAN close - the WAL and lock file must survive, the reopen
recovers the row, and the subsequent genuinely-clean close deletes the WAL.
Regression: engine + database + sparse-vector + vector packages green
(161 classes, 809 tests).
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Code Review: storage/engine robustness bundle (#4928, #4930, #4931, #4932, #4955)

Reviewed the full diff, the surrounding call sites, and the WAL/flush interaction. This is a high-quality, unusually well-documented PR: every fix is anchored to a concrete failure trace, the comments explain the why rather than the what, and the iterative review commits show the design converging on genuinely safer close semantics (a give-up close is now crash-equivalent rather than silently lossy). The five fixes are logically independent and each is correct in isolation. Below are the things worth a second look before merge.

Strengths

  • #4928 design is sound end to end. The no-progress window (reset on either this database's pending-count decrease or pages leaving the pipeline) correctly avoids false timeouts on a slow-but-progressing backlog, and making the signal per-database (flushedPagesPerDatabase) rather than JVM-global is the right call for multi-tenant servers - the comment at PageManagerFlushThread explains exactly why a global counter would let a busy sibling mask a wedged database.
  • The ack-gate in TransactionManager.close is the key correctness insight. Gating WAL deletion on getPendingPagesToFlush() > 0 (ground truth) rather than pipeline emptiness (what the caller's wait observes) closes the real data-loss window: a contained flush failure removes the page from pageIndex but never acks it, so pipeline-empty != durable. Moving the active pool to inactive before the check keeps it consistent with the reflection-based test.
  • #4931 correctly extracts recordPosition() as the single implementation for all four sites, and the incidental (pageNum*max) + pos string-concatenation bug in the two SEVERE log lines was a real latent defect worth fixing.
  • #4930, #4932, #4955 are all minimal, mirror adjacent correct code, and surface the intended exception instead of a raw NPE / ghost file / swallowed retry signal.

Points worth verifying

  1. Possible double-ack of WALFile.pagesToFlush (data-loss direction). notifyPageFlushed() is an unfloored decrementAndGet(). This PR adds two new ack sites (PageManager.flushPage file-dropped branch, and removePagesOfFileFromBatch) in addition to the existing success-path ack. Each page should be acked exactly once, but a page that is concurrently (a) dequeued and flushed via the file-dropped branch and (b) purged from its pending batch by a DDL drop could be decremented twice, driving the counter negative. Because WAL files are shared across a database's pages, a negative counter on one WALFile can mask a different page's legitimately-pending ack (net zero), which would make the ack-gate delete a WAL that still holds an unflushed committed page. This requires a specific drop-vs-flush race, but given the whole point of this PR is to close exactly that class of silent-loss window, it would be worth either confirming the batch purge and the flush loop cannot touch the same page concurrently, or adding a floor (updateAndGet(v -> Math.max(0, v - 1))) as defense in depth.

  2. flushedPagesPerDatabase entry retention for non-close callers. waitAllPagesOfDatabaseAreFlushed does computeIfAbsent(database, ...), but the map is only cleaned in removeAllPagesOfDatabase (close/drop). So rename(), sparse-vector compaction, and LSM vector compaction each insert an entry that lives until the database closes. It is one bounded entry per database, so not a leak in practice, but the Javadoc claiming entries "are dropped in removeAllPagesOfDatabase" slightly under-describes the lifecycle for those callers.

  3. Multi-tenant give-up under sustained load. With the per-database signal, if the shared flush thread is saturated flushing sibling databases and this database's pages never get dequeued for flushAllPagesTimeout (60s default), the wait gives up and the close becomes crash-equivalent (WAL + lock preserved, recovery on next open). That is the safe outcome, but on a heavily loaded server it could turn ordinary closes into recovery-on-reopen more often than operators expect. Might be worth a one-line note in the config docstring that the timeout is per-database no-progress, not total flush time.

Minor / nits

  • getRandomSlot/getBestSlot widened from private to package-private purely for the test - fine and documented, and being explicit that the shutdown race is the only reason (the zero-length guard is "unreachable today") is honest and good.
  • new File(filePath).exists() on every channel reopen adds a stat syscall, but only on the post-ClosedChannelException recovery path, so negligible.
  • Per CLAUDE.md, FlushRobustnessTest drives real DatabaseFactory create/open/close cycles with 300ms no-progress windows; each of the two WAL-preservation methods spends a few hundred ms plus a reopen. Not multi-second, so probably below the @Tag("slow") bar, but worth keeping an eye on if more cases are added.

Test coverage

Strong. The red-first verification on #4928/#4930 (the dropped file is re-created on unfixed code), the deterministic bounded-wait test, the ack-gate reproduction of the reviewer's exact scenario, and the #4931 overflow-boundary unit test (including the innocent-record aliasing at page 2_097_152 slot 42) are all convincing. #4932 staying trace-verified rather than reproduced is a reasonable tradeoff given the page-format surgery a deterministic chunk-chain race would require, since the fix just mirrors the adjacent RecordNotFoundException rethrow. The one gap relative to the fixes shipped: there is no test exercising the two new notifyPageFlushed ack-release sites (file-dropped flush branch, batch purge), which is where point (1) above lives.

Overall: solid, careful work that meaningfully hardens the flush/close/WAL path. My only substantive ask is confirming the double-ack race in point (1) cannot corrupt the pending-pages counter that the new ack-gate now trusts as ground truth.

From the latest review round:

- The double-ack race was real, and broader than the review's own framing:
  the flush loop does not remove pages from the batch LIST (only from
  pageIndex), so a batch polled between the dropped-file purge's queue
  snapshot and its lock acquisition is visited by BOTH the file-dropped
  flush branch and the purge - each acking the same page. Because
  WALFile.pagesToFlush is shared by all of a database's pages, the stolen
  ack could zero the counter while another page's committed change was
  still unflushed, letting the close-time ack gate delete the WAL that
  protected it - the silent-loss window this PR exists to close.

  Fixed structurally rather than with the suggested floor (a floor prevents
  a negative counter but not the ack theft at zero, and would mask future
  accounting bugs): MutablePage.walFile is now an AtomicReference with
  takeWALFile() (getAndSet null), and all three ack sites - the
  TransactionManager success path, the file-dropped flush branch and the
  dropped-file batch purge - release through it, so whichever path reaches
  the page first wins and every other ack is a structural no-op. Regression
  test acks the same page twice and asserts the pending count decreases
  exactly once.

- The per-database counter map's javadoc now describes the real lifecycle:
  an entry is created on a database's first bounded wait (close, rename,
  backup-suspend, compaction shipping) and lives until close/drop - one
  bounded entry per open database, not a leak.

- The config docstring now states that the window is per-database
  no-progress time, not total flush time: on a heavily loaded multi-database
  server a database starved by its siblings can give up, turning that close
  into recovery-on-next-open.

Nits acknowledged without change: the package-private slot helpers and the
reopen-path stat() are as reviewed; FlushRobustnessTest stays untagged at
under a second total, watched if more cases accrue.

Engine + database packages green.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Code review — storage/engine robustness bundle (#5012)

Reviewed the full diff and traced the flush/close/ack paths in PageManagerFlushThread, TransactionManager, LocalDatabase, MutablePage, and LocalBucket. This is a strong, high-signal PR: the bug analyses are exact, the fixes mirror existing correct code, and the WAL-preservation reasoning (give-up close made crash-equivalent, ack-gated clean close, exactly-once takeWALFile()) is sound. The red-first verification and end-to-end recovery tests are exactly right. Below are findings ranked by importance — most are minor; nothing here is a blocker.

Correctness — looks good

  • The exactly-once ack via AtomicReference.getAndSet(null) in takeWALFile() correctly closes the double-ack race across the three paths (success / file-dropped flush branch / batch purge). Verified all three sites route through it.
  • The ack gate in TransactionManager.close iterates inactiveWALFilePool after active files are moved to inactive, so it sees the whole pool — the ground-truth check is complete.
  • #4931 overflow: extracting recordPosition() as the single long-widened implementation for all four sites (incl. scan()) is the right call, and the boundary test pins the innocent-record aliasing well.
  • #4932 catch-order fix and #4955 null/zero-length guards are correct and minimal.

Design consideration (documented tradeoff, worth surfacing to operators)

The contained-IOException page is durable only via WAL replay on the next open and is never re-flushed in-process. Two follow-on effects the comments acknowledge but that deserve operator visibility:

  1. Once the read cache evicts that page, in-session readers see the stale on-disk version of a committed change until restart.
  2. That page keeps pendingPagesToFlush > 0 on its WAL file, and cleanWALFiles only recycles a file when getPendingPagesToFlush() == 0 (TransactionManager.java:858). So a single transient I/O error can pin a WAL file and block recycling for the lifetime of the process — unbounded WAL growth until restart on a long-running server.

Not a blocker (the alternative was an infinite hang), but consider (a) a metric / SEVERE-rate alert so operators notice a stuck page rather than discovering it via disk pressure, or (b) a bounded background re-flush attempt so a transient error self-heals without a restart.

Style — CLAUDE.md deviations (minor)

  • MutablePage.java: walFile is declared as java.util.concurrent.atomic.AtomicReference<WALFile> inline. CLAUDE.md: "don't use fully qualified names if possible, always import the class and just use the name." Please add the import. Same for the FQNs in the new tests (java.lang.reflect.Field, java.util.concurrent.atomic.AtomicInteger, com.arcadedb.database.DatabaseFactory).
  • The class Javadoc of MutablePage still states "not thread safe … must not be used by multiple threads." The whole point of this change is that walFile is now touched concurrently by the flush paths. A one-line note that walFile is the deliberate exception would prevent future confusion.

Documentation nit

In PageManagerFlushThread, the large return-semantics Javadoc block ended up orphaned above bumpFlushProgress (which has its own one-line Javadoc), and the older "Waits until all the pages…" block sits above it too — so waitAllPagesOfDatabaseAreFlushed itself now has no adjacent Javadoc, and bumpFlushProgress has two doc comments stacked over it. Move the @return block back down onto waitAllPagesOfDatabaseAreFlushed.

Tests

Good coverage and genuinely adversarial. Two small notes:

  • FlushRobustnessTest mutates the shared static PageManager.INSTANCE.getFlushThread().pageIndex and relies on finally cleanup. A failure before the finally (or an assertion that throws mid-setup) could leak a stuck pageIndex entry into the JVM-wide flush thread and perturb sibling tests. Acknowledged as sequential-by-config, but an isolated flush-thread instance where possible (as the first test already does) would be more robust than poking the singleton.
  • Per CLAUDE.md's tagging guidance: these run <1s so untagged is fine, but the two end-to-end tests that spin up a DatabaseFactory, close, and reopen are the kind of thing that tends to accrete — keep an eye on @Tag("slow") if more cases land.

Overall: well-reasoned, well-tested, and a clear net improvement to durability semantics. The FQN imports and the misplaced Javadoc are the only things I'd ask to fix before merge; the WAL-pinning point is worth a tracking issue rather than blocking this PR.

@lvca
lvca merged commit 0788a88 into main Jul 6, 2026
27 of 31 checks passed
lvca added a commit that referenced this pull request Jul 6, 2026
…tion on close

#4926 (HIGH, silent corruption): a 64KB page flush spans many disk sectors
and the MVCC version header lives in sector 0. A torn write at power loss
can persist the NEW version header while the delta sectors still hold the
PREVIOUS content. Recovery's <= skip declared such a page 'already applied'
and left it silently corrupt (new version, old bytes) despite an intact,
fully-fsynced WAL - undetectable, since every later MVCC check accepts the
page. The skip is now strictly <, and the equal-version case RE-APPLIES the
WAL delta: idempotent when the page is intact (the delta carries absolute
bytes for exactly that version), repairing when it is torn. Skipping
STRICTLY older entries remains, as their delta would overwrite newer
content. Red-first verified with a forged torn write (version header says
v2, content still v1): the old code left the stale value behind forever,
the fix recovers the committed one.

#4934 (MEDIUM, unrecoverable committed data): a clean close deleted every
WAL file even when the preceding data fsync FAILED - and after a failed
fsync the OS may have dropped the dirty pages (fsyncgate semantics), so the
WAL held the only durable copy. FileManager.syncFiles() now reports
failure; a failed pre-close fsync makes the close crash-equivalent (WAL and
lock file preserved via the #5012 machinery, recovery on next open), and
the runtime WAL-rotation drop pass aborts when its pre-drop fsync fails,
retrying on the next pass. Red-first verified: the old code deleted the WAL
despite the failed fsync.

Verified with the full commit-path sweep (union with the companion
point-of-no-return branch): 372 classes, 2851 tests, 0 failures.
lvca added a commit that referenced this pull request Jul 6, 2026
…tFileIds scope confirmed

The design concern was worth more than a comment - implemented the
suggested fence.

1a. Live/WAL divergence: the reviewer's window is real but PRE-EXISTING
    (the old WAL-then-updatePages order had the identical exposure for any
    non-validation failure) and this PR already NARROWED it by moving
    validation - the reachable failure class - ahead of the append. The
    residue (IOException while publishing) is now closed with the suggested
    fence: LocalDatabase.fenceForRecovery(reason) is set in commit2ndPhase's
    finally when a failure occurs AFTER the WAL append, BEFORE reset()
    releases the file locks - the volatile write is therefore visible to
    any transaction blocked on those locks, so no conflicting WAL record
    for the same page versions can follow. The fence surfaces at the
    checkDatabaseIsOpen choke point (every new operation) and at an
    explicit guard before the WAL append (covers in-flight commits whose
    reads bypass the choke point). Close still works: it is the recovery
    entry point.

1b. Clean close vs crash: already answered by the #5012 ack gate, no new
    code needed. The orphaned record's pages were never queued for flush,
    so their WAL acks (bumped at append time) are never released -
    getPendingPagesToFlush() > 0 makes the clean close preserve the WAL and
    the lock file, and the next open replays the record. 'Durable on
    restart' holds for both crash and clean close.

2.  getFileIds() broadening confirmed intended, including the compacted
    sub-index file: it adds no new serialization between transactions -
    any transaction locking the compacted id also locks the mutable id, so
    the contender set per index is unchanged - and compaction itself does
    not take commit file locks for its appends (only splitIndex's
    tryLockFile on the mutable id, which contended before this change
    too). The reviewer's observation that this also fixes the latent
    add(-1) for composite TypeIndex ids is correct.

3.  TransactionException is now rethrown unwrapped by commit2ndPhase too
    (same as phase 1, round 3), so first-class errors like the fence are
    not buried under 'Transaction error on commit'.

4.  java.util.TreeSet::new -> TreeSet::new (java.util.* was imported).

New test: fenced database refuses the WAL point of no return (WAL
byte-identical after the refused commit), fences new operations, and still
closes cleanly. The post-append fence trigger itself is wired in the
finally; forcing a real mid-publish IOException deterministically is not
feasible without fault-injection hooks, so the trigger is covered by code
path inspection and the fence mechanics by the test.

Regression: 118 classes, 577 tests, 0 failures.
lvca added a commit that referenced this pull request Jul 7, 2026
… instance

All three review findings were real; the first was a genuine regression in
this PR and the reviewer's scenario was exact.

1. RED - redundant double-close stole another database's reference.
   closeInternal's lambda is documented-idempotent (early-return on !open)
   but the new release() ran unconditionally after it: dbA.close();
   dbA.close(); decremented twice and tore the flush thread down under a
   still-open dbB - the exact failure this PR exists to eliminate,
   re-entered through the double-close door. The lambda now reports
   whether THIS call performed the close, and the whole tail
   (removeActiveDatabaseInstance, closeExecutor, release) is gated on it -
   taking the reviewer's suggestion including the arguably-belongs part.

2. ORANGE - acquire() rolls back its increment when startup() throws
   (e.g. ConfigurationException on negative MAX_PAGE_RAM). Without it the
   counter wedged at 1 with no flush thread and every later acquire ran
   against a dead manager the caller's catch could not repair.

3. ORANGE - same-path concurrent open double-release. When
   registerActiveInstance loses the race it closes the database itself,
   which (with fix 1) consumes the reference and records it in a
   per-instance flag; the factory's catch now releases only when the
   instance did NOT already consume its reference. The lifecycle reference
   is exactly-once per instance by construction - same pattern as the
   exactly-once WAL ack from #5012.

Red-first: the double-close and startup-failure tests both fail on the
pre-review code (1 failure + 1 error). The same-path race has no
deterministic repro (it needs two threads between checkForActiveInstance
and registerActiveInstance); it is covered by the exactly-once flag
construction and the existing hammer test.

Regression: engine + database packages green.
hoogenbj pushed a commit to Locstat/arcadedb that referenced this pull request Jul 7, 2026
…uspenders own their windows

PageManagerFlushThread.setSuspended(db, true) was putIfAbsent-based: only the
FIRST caller owned the suspend flag, but suspendFlushAndExecute ran every
caller's callback regardless (ArcadeData#4958). With two concurrent suspenders on the
same database (SQL BACKUP DATABASE, the HA verify endpoint, HA snapshot
serving - any combination), the non-owner (a) skipped
waitForCurrentFlushToComplete, so it could read a page while a flush batch was
mid-write, and (b) kept streaming while the owner's exit synchronously flushed
the deferred batches to disk - torn reads either way.

The suspension is now a per-database REFCOUNT:

- setSuspended(db, true) increments the count under the existing per-database
  suspend lock; it returns true only for the first suspender (0 -> 1).
- setSuspended(db, false) decrements; only the LAST release (1 -> 0) runs the
  resume (Phase 1 synchronous deferred flush, Phase 2 flag clear + detach,
  Phase 3 re-enqueue, all unchanged) and returns true. A non-last release just
  drops one reference and the database stays suspended for the remaining
  suspenders. An unbalanced release is a no-op instead of corrupting state.
- A new suspender arriving while the last release is mid-way through the
  deferred-batch writes waits (timed, uninterruptible with interrupt-flag
  restore) until the resume completes, so a fresh window can never overlap
  those page writes. The gate (resumingDatabases) is cleared in a finally that
  also heals a stuck count if the resume ever escapes with an exception.
- PageManager.suspendFlushAndExecute acquires/releases one reference per
  caller and now runs waitForCurrentFlushToComplete INSIDE the try, so an
  interrupt during the wait no longer leaks the suspension (pre-existing
  leak: the flag was set before the wait and never restored on throw). The
  wait is cheap for non-first suspenders (the flush thread is parked
  deferring).

The ArcadeData#4728 deferred-RAM backpressure accounting and the ArcadeData#5012 per-database
suspend bookkeeping are unchanged: batches deferred across overlapping windows
are flushed exactly once, by the last suspender's exit.

Decision on the HA SnapshotHttpHandler per-database lock (ArcadeData#5063 review round
5): it STAYS, documented as resource discipline rather than correctness. With
refcounting it is no longer needed to own the suspension, but it serializes
same-database zip streaming: two followers resyncing the same multi-GB
database at once would double the read I/O and keep flushing suspended for the
UNION of both windows, growing the deferred backlog toward the ArcadeData#4728 cap.

TDD red-first: PageManagerFlushSuspendRefCountTest written and run against the
pre-fix code (stash-run-unstash); all three methods failed on the exact defect:
- overlappingSuspendersBothOwnTheirWindow: isPageFlushingSuspended was false
  after the first of two overlapping suspendFlushAndExecute callers exited
  while the second was still inside its callback (expected true, was false).
- setSuspendedIsRefCounted: the first release of two suspenders cleared the
  flag (expected release to return false and the db to stay suspended).
- suspendDuringResumeWaitsUntilDeferredFlushCompletes: a suspender acquired
  immediately while the resume was mid-way through the deferred writes
  (contract test for the new gate; pre-fix it became a non-owner).

PageManagerFlushSuspendDeferRaceTest updated for the new semantics: the
resume's count-check now takes the per-database lock, so it serializes behind
the flush thread's paused suspended-check and the deferred batch is flushed
synchronously in Phase 1 rather than re-enqueued; the assertion now accepts
either outcome (flushed or re-enqueued) and still rejects the stranded case.
The fake page's file id is now non-existent so the (now reachable) synchronous
flush cannot write into a real file of the test database.

Verification (all green):
- engine: PageManagerFlushSuspendRefCountTest, PageManagerFlushSuspendDeferRaceTest,
  PageManagerFlushSuspendBackpressureTest, PageManagerFlushThreadInterruptTest,
  PageManagerDeleteFileFlushCoordinationTest, WalRecoveryCorrectnessTest,
  Issue4958StorageStatsTest, FlushRobustnessTest, PageManagerLifecycleRefCountTest,
  Issue4544FlushIndexIdentityTest, PageManagerFlushQueueRaceTest,
  PageManagerReadCache*Test (28 tests, 1 skipped stress test)
- ha-raft: SnapshotHttpHandlerSuspendLockTest, SnapshotWriteStallTest,
  SnapshotThrottleTest (9 tests)
- integration: BackupDatabaseTest (4 tests, drives FullBackupFormat's
  suspendFlushAndExecute end-to-end)
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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…tion on close

#4926 (HIGH, silent corruption): a 64KB page flush spans many disk sectors
and the MVCC version header lives in sector 0. A torn write at power loss
can persist the NEW version header while the delta sectors still hold the
PREVIOUS content. Recovery's <= skip declared such a page 'already applied'
and left it silently corrupt (new version, old bytes) despite an intact,
fully-fsynced WAL - undetectable, since every later MVCC check accepts the
page. The skip is now strictly <, and the equal-version case RE-APPLIES the
WAL delta: idempotent when the page is intact (the delta carries absolute
bytes for exactly that version), repairing when it is torn. Skipping
STRICTLY older entries remains, as their delta would overwrite newer
content. Red-first verified with a forged torn write (version header says
v2, content still v1): the old code left the stale value behind forever,
the fix recovers the committed one.

#4934 (MEDIUM, unrecoverable committed data): a clean close deleted every
WAL file even when the preceding data fsync FAILED - and after a failed
fsync the OS may have dropped the dirty pages (fsyncgate semantics), so the
WAL held the only durable copy. FileManager.syncFiles() now reports
failure; a failed pre-close fsync makes the close crash-equivalent (WAL and
lock file preserved via the #5012 machinery, recovery on next open), and
the runtime WAL-rotation drop pass aborts when its pre-drop fsync fails,
retrying on the next pass. Red-first verified: the old code deleted the WAL
despite the failed fsync.

Verified with the full commit-path sweep (union with the companion
point-of-no-return branch): 372 classes, 2851 tests, 0 failures.

(cherry picked from commit 00bae69)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…tFileIds scope confirmed

The design concern was worth more than a comment - implemented the
suggested fence.

1a. Live/WAL divergence: the reviewer's window is real but PRE-EXISTING
    (the old WAL-then-updatePages order had the identical exposure for any
    non-validation failure) and this PR already NARROWED it by moving
    validation - the reachable failure class - ahead of the append. The
    residue (IOException while publishing) is now closed with the suggested
    fence: LocalDatabase.fenceForRecovery(reason) is set in commit2ndPhase's
    finally when a failure occurs AFTER the WAL append, BEFORE reset()
    releases the file locks - the volatile write is therefore visible to
    any transaction blocked on those locks, so no conflicting WAL record
    for the same page versions can follow. The fence surfaces at the
    checkDatabaseIsOpen choke point (every new operation) and at an
    explicit guard before the WAL append (covers in-flight commits whose
    reads bypass the choke point). Close still works: it is the recovery
    entry point.

1b. Clean close vs crash: already answered by the #5012 ack gate, no new
    code needed. The orphaned record's pages were never queued for flush,
    so their WAL acks (bumped at append time) are never released -
    getPendingPagesToFlush() > 0 makes the clean close preserve the WAL and
    the lock file, and the next open replays the record. 'Durable on
    restart' holds for both crash and clean close.

2.  getFileIds() broadening confirmed intended, including the compacted
    sub-index file: it adds no new serialization between transactions -
    any transaction locking the compacted id also locks the mutable id, so
    the contender set per index is unchanged - and compaction itself does
    not take commit file locks for its appends (only splitIndex's
    tryLockFile on the mutable id, which contended before this change
    too). The reviewer's observation that this also fixes the latent
    add(-1) for composite TypeIndex ids is correct.

3.  TransactionException is now rethrown unwrapped by commit2ndPhase too
    (same as phase 1, round 3), so first-class errors like the fence are
    not buried under 'Transaction error on commit'.

4.  java.util.TreeSet::new -> TreeSet::new (java.util.* was imported).

New test: fenced database refuses the WAL point of no return (WAL
byte-identical after the refused commit), fences new operations, and still
closes cleanly. The post-append fence trigger itself is wired in the
finally; forcing a real mid-publish IOException deterministically is not
feasible without fault-injection hooks, so the trigger is covered by code
path inspection and the fence mechanics by the test.

Regression: 118 classes, 577 tests, 0 failures.
(cherry picked from commit 73a413a)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
… instance

All three review findings were real; the first was a genuine regression in
this PR and the reviewer's scenario was exact.

1. RED - redundant double-close stole another database's reference.
   closeInternal's lambda is documented-idempotent (early-return on !open)
   but the new release() ran unconditionally after it: dbA.close();
   dbA.close(); decremented twice and tore the flush thread down under a
   still-open dbB - the exact failure this PR exists to eliminate,
   re-entered through the double-close door. The lambda now reports
   whether THIS call performed the close, and the whole tail
   (removeActiveDatabaseInstance, closeExecutor, release) is gated on it -
   taking the reviewer's suggestion including the arguably-belongs part.

2. ORANGE - acquire() rolls back its increment when startup() throws
   (e.g. ConfigurationException on negative MAX_PAGE_RAM). Without it the
   counter wedged at 1 with no flush thread and every later acquire ran
   against a dead manager the caller's catch could not repair.

3. ORANGE - same-path concurrent open double-release. When
   registerActiveInstance loses the race it closes the database itself,
   which (with fix 1) consumes the reference and records it in a
   per-instance flag; the factory's catch now releases only when the
   instance did NOT already consume its reference. The lifecycle reference
   is exactly-once per instance by construction - same pattern as the
   exactly-once WAL ack from #5012.

Red-first: the double-close and startup-failure tests both fail on the
pre-review code (1 failure + 1 error). The same-path race has no
deterministic repro (it needs two threads between checkForActiveInstance
and registerActiveInstance); it is covered by the exactly-once flag
construction and the existing hammer test.

Regression: engine + database packages green.
(cherry picked from commit 60caa57)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…own their windows

PageManagerFlushThread.setSuspended(db, true) was putIfAbsent-based: only the
FIRST caller owned the suspend flag, but suspendFlushAndExecute ran every
caller's callback regardless (#4958). With two concurrent suspenders on the
same database (SQL BACKUP DATABASE, the HA verify endpoint, HA snapshot
serving - any combination), the non-owner (a) skipped
waitForCurrentFlushToComplete, so it could read a page while a flush batch was
mid-write, and (b) kept streaming while the owner's exit synchronously flushed
the deferred batches to disk - torn reads either way.

The suspension is now a per-database REFCOUNT:

- setSuspended(db, true) increments the count under the existing per-database
  suspend lock; it returns true only for the first suspender (0 -> 1).
- setSuspended(db, false) decrements; only the LAST release (1 -> 0) runs the
  resume (Phase 1 synchronous deferred flush, Phase 2 flag clear + detach,
  Phase 3 re-enqueue, all unchanged) and returns true. A non-last release just
  drops one reference and the database stays suspended for the remaining
  suspenders. An unbalanced release is a no-op instead of corrupting state.
- A new suspender arriving while the last release is mid-way through the
  deferred-batch writes waits (timed, uninterruptible with interrupt-flag
  restore) until the resume completes, so a fresh window can never overlap
  those page writes. The gate (resumingDatabases) is cleared in a finally that
  also heals a stuck count if the resume ever escapes with an exception.
- PageManager.suspendFlushAndExecute acquires/releases one reference per
  caller and now runs waitForCurrentFlushToComplete INSIDE the try, so an
  interrupt during the wait no longer leaks the suspension (pre-existing
  leak: the flag was set before the wait and never restored on throw). The
  wait is cheap for non-first suspenders (the flush thread is parked
  deferring).

The #4728 deferred-RAM backpressure accounting and the #5012 per-database
suspend bookkeeping are unchanged: batches deferred across overlapping windows
are flushed exactly once, by the last suspender's exit.

Decision on the HA SnapshotHttpHandler per-database lock (#5063 review round
5): it STAYS, documented as resource discipline rather than correctness. With
refcounting it is no longer needed to own the suspension, but it serializes
same-database zip streaming: two followers resyncing the same multi-GB
database at once would double the read I/O and keep flushing suspended for the
UNION of both windows, growing the deferred backlog toward the #4728 cap.

TDD red-first: PageManagerFlushSuspendRefCountTest written and run against the
pre-fix code (stash-run-unstash); all three methods failed on the exact defect:
- overlappingSuspendersBothOwnTheirWindow: isPageFlushingSuspended was false
  after the first of two overlapping suspendFlushAndExecute callers exited
  while the second was still inside its callback (expected true, was false).
- setSuspendedIsRefCounted: the first release of two suspenders cleared the
  flag (expected release to return false and the db to stay suspended).
- suspendDuringResumeWaitsUntilDeferredFlushCompletes: a suspender acquired
  immediately while the resume was mid-way through the deferred writes
  (contract test for the new gate; pre-fix it became a non-owner).

PageManagerFlushSuspendDeferRaceTest updated for the new semantics: the
resume's count-check now takes the per-database lock, so it serializes behind
the flush thread's paused suspended-check and the deferred batch is flushed
synchronously in Phase 1 rather than re-enqueued; the assertion now accepts
either outcome (flushed or re-enqueued) and still rejects the stranded case.
The fake page's file id is now non-existent so the (now reachable) synchronous
flush cannot write into a real file of the test database.

Verification (all green):
- engine: PageManagerFlushSuspendRefCountTest, PageManagerFlushSuspendDeferRaceTest,
  PageManagerFlushSuspendBackpressureTest, PageManagerFlushThreadInterruptTest,
  PageManagerDeleteFileFlushCoordinationTest, WalRecoveryCorrectnessTest,
  Issue4958StorageStatsTest, FlushRobustnessTest, PageManagerLifecycleRefCountTest,
  Issue4544FlushIndexIdentityTest, PageManagerFlushQueueRaceTest,
  PageManagerReadCache*Test (28 tests, 1 skipped stress test)
- ha-raft: SnapshotHttpHandlerSuspendLockTest, SnapshotWriteStallTest,
  SnapshotThrottleTest (9 tests)
- integration: BackupDatabaseTest (4 tests, drives FullBackupFormat's
  suspendFlushAndExecute end-to-end)

(cherry picked from commit e3fd04a)
@robfrank
robfrank deleted the fix/4928-flush-and-quick-wins branch August 26, 2026 09:10
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