Skip to content

fix(#4926,#4934): torn-write repair on recovery; fsync-gated WAL dele… - #5052

Merged
lvca merged 2 commits into
mainfrom
fix/4926-4934-4936-wal-recovery
Jul 6, 2026
Merged

lvca merged 2 commits into
mainfrom
fix/4926-4934-4936-wal-recovery

Conversation

@lvca

@lvca lvca commented Jul 6, 2026

Copy link
Copy Markdown
Member

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

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

…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 lvca self-assigned this Jul 6, 2026
@lvca lvca added this to the 26.7.2 milestone 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 0 complexity

Metric Results
Complexity 0

View in Codacy

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

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

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (cd0a3cc) 134936 100437 74.43%
Head commit (a9117af) 166742 (+31806) 112073 (+11636) 67.21% (-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 (#5052) 10 9 90.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 improves WAL and recovery correctness by repairing torn page writes (re-applying WAL deltas when the log version equals the on-disk page version) and preserving the WAL and lock files as crash-equivalent if a data fsync fails during database close or WAL rotation. Additionally, comprehensive unit tests have been added to verify these behaviors. The review feedback suggests adhering to the Google Java Style Guide by adding braces to single-statement conditional blocks in LocalDatabase.java and TransactionManager.java.

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.

Comment on lines +2068 to +2073
if (!drop && !fileManager.syncFiles())
// #4934: the fsync failed, so the OS may have dropped the dirty pages (fsyncgate semantics) - the
// pages the wait above considered flushed may never reach the platter. Deleting the WAL below would
// then make the committed data unrecoverable after a power loss, with only a log line as evidence.
// Treat the close as crash-equivalent instead: preserve WAL + lock file, recover on next open.
dataSafeOnDisk = false;

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

According to the Google Java Style Guide (Section 4.1.1), braces {} are required for all if statements, even when the body contains only a single statement or a multi-line comment. Adding braces improves readability and prevents potential bugs during future modifications.

Suggested change
if (!drop && !fileManager.syncFiles())
// #4934: the fsync failed, so the OS may have dropped the dirty pages (fsyncgate semantics) - the
// pages the wait above considered flushed may never reach the platter. Deleting the WAL below would
// then make the committed data unrecoverable after a power loss, with only a log line as evidence.
// Treat the close as crash-equivalent instead: preserve WAL + lock file, recover on next open.
dataSafeOnDisk = false;
if (!drop && !fileManager.syncFiles()) {
// #4934: the fsync failed, so the OS may have dropped the dirty pages (fsyncgate semantics) - the
// pages the wait above considered flushed may never reach the platter. Deleting the WAL below would
// then make the committed data unrecoverable after a power loss, with only a log line as evidence.
// Treat the close as crash-equivalent instead: preserve WAL + lock file, recover on next open.
dataSafeOnDisk = false;
}
References
  1. Google Java Style Guide Section 4.1.1: Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement. (link)

Comment on lines +875 to +878
if (!database.getFileManager().syncFiles())
// #4934: the fsync failed - the data this WAL protects may never reach the disk. Dropping
// the WAL now would make it unrecoverable; abort this pass, the rotation retries later.
return false;

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

According to the Google Java Style Guide (Section 4.1.1), braces {} are required for all if statements, even when the body contains only a single statement or a multi-line comment. Adding braces improves readability and prevents potential bugs during future modifications.

Suggested change
if (!database.getFileManager().syncFiles())
// #4934: the fsync failed - the data this WAL protects may never reach the disk. Dropping
// the WAL now would make it unrecoverable; abort this pass, the rotation retries later.
return false;
if (!database.getFileManager().syncFiles()) {
// #4934: the fsync failed - the data this WAL protects may never reach the disk. Dropping
// the WAL now would make it unrecoverable; abort this pass, the rotation retries later.
return false;
}
References
  1. Google Java Style Guide Section 4.1.1: Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement. (link)

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: torn-write repair on recovery; fsync-gated WAL deletion (#4926, #4934)

Overall this is a careful, well-reasoned durability fix. The comments are excellent (they explain the why, the failure mode, and the fsyncgate semantics), the ordering of the lazy fsync-before-drop is correct, and both fixes are backed by red-first regression tests. Nice work. A few observations below, mostly one substantive limitation to confirm and some minor nits.

Correctness / design

1. Torn-write repair is partial when a page accumulated multiple unflushed versions (please confirm this is acceptable).
The equal-version re-apply repairs only the last transaction's delta region [changesFrom, changesTo]. Consider a page fully durable at v1, then transactions v2, v3, v4 that each touch different regions and stay in memory (async flush), then a single 64KB flush of v4 tears:

  • disk header = v4 (sector 0 persisted), but regions changed by v2/v3 are still torn/old.
  • Recovery replays the WAL: the v2 entry (2 < 4) and v3 entry (3 < 4) are skipped as "superseded", only v4 (4 == 4) is re-applied.
  • Net result: the page carries v4 but the v2/v3 regions remain stale -> still silently corrupt.

The strictly-< skip is correct in the non-torn case (an old delta must not clobber newer content), so this is a genuine tension you cannot resolve from the version header alone. The fix clearly improves on <= (which never repaired anything) and covers the exact scenario in #4926, but it is worth stating explicitly whether the multi-version-accumulation case is in scope or a documented known limitation. If pages can bump several versions between flushes (they can, given async flushing), this partial-repair edge deserves a note in the issue/release doc.

2. Idempotency of re-apply side effects - verified OK, flagging for the record. Re-applying an equal-version entry now runs the full apply path, including component.updatePageCount(...) and LSMVectorIndex.applyReplicatedPageUpdate(...). I checked the latter: it rebuilds location metadata from absolute page offsets, so re-applying identical bytes is idempotent. Good - no regression there.

cleanWALFiles return-on-fsync-failure - looks correct

return false on a failed fsync aborts the pass before any file.drop() (the fsync is lazy, right before the first drop, and dataSynced stays false). The only syncDataOnDrop=true caller (runtime rotation) ignores the return value, so the pool simply stays non-empty and the next scheduled pass retries - exactly the intended behavior. it.remove() is not reached for the un-dropped file, so nothing is lost.

LocalDatabase.closeInternal - behavior preserved

The refactor to dataSafeOnDisk keeps syncFiles() called in every non-drop path (short-circuit !drop && !syncFiles()), and drop still skips the sync. Equivalent to the old flow plus the new failed-fsync -> preserve-WAL branch. Clean.

Tests

  • Both tests are self-validating (the diskVersion == 1 assert guards the page-offset/endianness assumptions, so a layout mismatch fails loudly rather than passing silently). Good defensive testing.
  • Style (CLAUDE.md): the test uses fully-qualified names inline - java.lang.reflect.Field, java.nio.channels.FileChannel. CLAUDE.md asks to "always import the class and just use the name."
  • @tag: if either test runs into multi-second territory (create+flush+kill+reopen+recovery), consider @Tag("slow") per the repo convention. Please confirm the runtime; if sub-second, ignore.
  • PageManager.INSTANCE.getFlushThread().setSuspended(db, true) return value is not checked - if suspension ever fails to engage, the "data never reaches disk" precondition would not hold and the test could go flaky. A cheap assertThat(...).isTrue() would harden it.
  • Minor: trailing double blank line before the final } in the test class.

None of these are blockers. The main ask is confirming the scope of the partial-repair limitation (point 1).

…test hardening

Claude's main point was correct: the equal-version re-apply repairs only the
NEWEST coalesced version's delta region. Async flush can merge v2/v3/v4 into
one physical page write, so if that write tears, the v2/v3 regions (skipped
as strictly-older) can stay torn while only v4 is repaired. The version
header alone cannot distinguish a torn page from an intact one, so the
complete fix needs per-page checksums (the longer-term direction #4926
itself notes) - too large and too risky to fold into this targeted PR on the
engine's most delicate path. Documented as a known limitation in the recovery
code comment and the release notes, and filed as follow-up #5054. This fix
still strictly improves on the old <= skip (which repaired nothing) and fully
covers the single-flush case.

Gemini (braces, Section 4.1.1): added braces to the two #4934 ifs where a
multi-line comment sits between the condition and its single statement -
exactly the readability trap braces prevent. CLAUDE.md permits braces on
single-statement ifs (it only does not require them), so this honors both.

Test nits (Claude): imported the inline FQNs (Field, FileChannel), asserted
setSuspended(...) actually engaged so the 'data never reaches disk'
precondition cannot silently fail, and removed the trailing double blank
line. Runtime is 0.34s for both tests, so no @tag(slow).

Idempotency of the equal-version re-apply (updatePageCount,
applyReplicatedPageUpdate) was independently confirmed by the reviewer.
Both regression tests still green.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: fix(#4926,#4934) - torn-write repair on recovery; fsync-gated WAL delete

Overall this is a careful, well-reasoned durability fix. The reasoning in the code comments is excellent, the two changes are logically independent and both correct, and each ships a red-first regression test. A few observations below, none blocking.

Correctness - looks solid

  • <= -> < in TransactionManager.applyChanges ([storage] Torn 64KB page write + version-based replay skip loses committed deltas even with full WAL fsync #4926). The core insight is right: at equal version the WAL delta carries the absolute bytes for exactly that version, so re-applying is idempotent on an intact page and repairing on a torn one. The strictly-older skip is correctly preserved (its delta would clobber newer content), and the equal-version case falls through cleanly - the > version + 1 gap check is false at equality, so no interaction with the forceApply path. Verified PAGE_VERSION_OFFSET == 0, so the test forge of bytes 0-3 genuinely simulates a torn sector-0 write.

  • fsync-gated WAL delete ([storage] Clean close deletes all WAL files even when the preceding data fsync failed #4934). syncFiles() now returns success, and both consumers react correctly: LocalDatabase.closeInternal flips dataSafeOnDisk/preserveWalForRecovery so a failed pre-close fsync becomes crash-equivalent (WAL + lock file kept), and the runtime rotation path aborts the drop pass with return false. I traced all cleanWALFiles callers: the early return false only fires on the first file sync (before any file.drop()), so no partial WAL deletion, and every caller either ignores the return (rotation, retried next second) or treats false as "pool not empty" - both correct.

  • The syncFiles() false result only occurs on an actual IOException from force(), so there is no risk of spuriously preserving the WAL on every clean close.

Performance considerations

  • Re-applying at equal version means recovery/Raft-replay now performs a writePageWithLock + cache eviction for pages it previously skipped. This is write amplification on the replay path (crash recovery, follower catch-up, snapshot install re-apply). It is idempotent and correct, and recovery is rare, so the trade-off is reasonable - but worth flagging for the HA catch-up hot path where already-applied entries can be re-shipped. A one-line note in the comment that this is an accepted cost would help future readers.

Known limitation - honestly documented

The multi-version accumulation gap (v1 on disk, coalesced v2->v3->v4 flush tears, only v4 region repaired) is clearly called out and tracked in #5054. Good to see it stated rather than hidden. Nit: the comment block at TransactionManager.java:486-487 has an awkward mid-sentence wrap ("an / unconditional / in-order replay") - looks like an editing artifact; worth reflowing.

Test coverage

  • Both regression tests are genuinely red-first and target the exact defect. tornPageWriteIsRepairedByWalReplayAtEqualVersion self-validates the offset assumption (assertThat(diskVersion).isEqualTo(1) before forging), which is a nice touch.
  • cleanCloseAfterFailedFsyncPreservesWal relies on reflection into the private channel field of PaginatedComponentFile. Brittle to refactors, but consistent with the "break a file to force fsync failure" approach and hard to do otherwise - acceptable.
  • Gaps: the runtime WAL-rotation abort path (cleanWALFiles(...syncDataOnDrop=true) returning false) is not directly exercised - only the close path of [storage] Clean close deletes all WAL files even when the preceding data fsync failed #4934 is. And the multi-version torn case is untested (acknowledged as a known limitation, so fair). Consider adding a focused test for the rotation-abort branch since it is a distinct code path from the close path.

Minor

  • Both new tests create/reopen databases and run fast enough to stay unannotated, so no @Tag needed - consistent with the guidance.

Nice work - the fix is correct, minimal, and the comments make the durability reasoning auditable. My only real asks are the comment reflow and a test for the rotation-abort branch.

@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.44%. Comparing base (cd0a3cc) to head (a9117af).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...n/java/com/arcadedb/engine/TransactionManager.java 33.33% 1 Missing and 1 partial ⚠️
...main/java/com/arcadedb/database/LocalDatabase.java 75.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5052      +/-   ##
============================================
- Coverage     65.45%   65.44%   -0.01%     
+ Complexity      839      838       -1     
============================================
  Files          1687     1687              
  Lines        134936   134939       +3     
  Branches      28857    28859       +2     
============================================
- Hits          88319    88312       -7     
- Misses        34536    34546      +10     
  Partials      12081    12081              

☔ 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.

robfrank pushed a commit that referenced this pull request Aug 14, 2026
…test hardening

Claude's main point was correct: the equal-version re-apply repairs only the
NEWEST coalesced version's delta region. Async flush can merge v2/v3/v4 into
one physical page write, so if that write tears, the v2/v3 regions (skipped
as strictly-older) can stay torn while only v4 is repaired. The version
header alone cannot distinguish a torn page from an intact one, so the
complete fix needs per-page checksums (the longer-term direction #4926
itself notes) - too large and too risky to fold into this targeted PR on the
engine's most delicate path. Documented as a known limitation in the recovery
code comment and the release notes, and filed as follow-up #5054. This fix
still strictly improves on the old <= skip (which repaired nothing) and fully
covers the single-flush case.

Gemini (braces, Section 4.1.1): added braces to the two #4934 ifs where a
multi-line comment sits between the condition and its single statement -
exactly the readability trap braces prevent. CLAUDE.md permits braces on
single-statement ifs (it only does not require them), so this honors both.

Test nits (Claude): imported the inline FQNs (Field, FileChannel), asserted
setSuspended(...) actually engaged so the 'data never reaches disk'
precondition cannot silently fail, and removed the trailing double blank
line. Runtime is 0.34s for both tests, so no @tag(slow).

Idempotency of the equal-version re-apply (updatePageCount,
applyReplicatedPageUpdate) was independently confirmed by the reviewer.
Both regression tests still green.

(cherry picked from commit a9117af)
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