Repository navigation
Conversation
…rite recovery gap Async flush coalesces several committed versions into a single physical page write, so a page can go v1(on-disk) -> v2 -> v3 -> v4 with only the v4 flush reaching the platter. If that flush tears (the version-header sector persists, the data sectors do not), the #4926/#5052 equal-version re-apply repairs only v4's delta region: the v2/v3 entries are skipped as strictly-older and their regions stay silently torn. The version header alone cannot tell a torn page from an intact one. Design (no data-file format change): - PaginatedComponentFile.write() now also maintains an 8-byte slot (page version int + CRC32C of the raw page bytes int) at pageNumber*8 in a '.pcrc' sidecar file, written BEFORE the page bytes so a persisted slot always describes the newest attempted write, and fsynced under the same force() barrier as the data file. CRC32C is hardware-accelerated (java.util.zip.CRC32C) and the work happens on the flush thread, not in the commit latency path. Gated by arcadedb.pageChecksum (default true); sidecar channels open lazily so the fd count only grows for actively written files. - A page-header extension was rejected after verification: component file versions carry per-component semantics (LocalBucket.purposeForVersion treats v>=1 as EXTERNAL_PROPERTY and maxRecordsInPageForVersion keys the slot table on the same integer), so a cross-cutting "has checksum" gate cannot ride that version without redesigning component versioning across every component type; PAGE_HEADER_SIZE is also a static constant compiled into 17+ classes including the just-stabilized commit path. The sidecar achieves the same detection with a migration story that trivially holds: databases without a sidecar (older versions, disabled flag) recover exactly as before, slots fill in as pages flush, and no offline migration exists or is needed. - Recovery (TransactionManager.checkIntegrity) pre-scans the WAL for the per-page maximum retained version, then verifies each WAL-referenced page once (RecoveryPageVerifier): slot absent -> unverifiable, standard rules; slot version > disk version -> the tear kept the OLD header and the standard rules provably repair; equal version + CRC match -> verified intact; otherwise the page is flagged TORN, but only when the WAL retains an entry at the disk version or newer - a stale checksum (e.g. a sidecar restored from a backup) can never trigger a replay that would end below the version the disk already claims. - A torn page's FULL retained WAL delta chain is replayed in transaction order: the strictly-older skip and the version-gap abort are bypassed for that page only, and only during recovery (HA/Raft replay passes a null verifier and is untouched). Correctness rests on the fsync-before-WAL-drop barrier (#4509/#4934): any entry already dropped from the WAL is durably contained in the on-disk page, so in-order application of every retained entry over the disk bytes reconstructs exactly the newest committed state. - Sidecar lifecycle: FileManager scans by extension whitelist, so old and new versions alike ignore '.pcrc' (downgrade-safe); drop() deletes it and rename() (LSM compaction temp-suffix removal) carries it along; force() tolerates a thread interrupt (flag cleared and restored, closed channel reopened once) and a sidecar fsync failure is contained as a WARNING - it never vetoes the data file's fsync verdict, since a stale slot only degrades to a guarded repair replay. Red-first evidence (PageChecksumRecoveryTest, forged torn write in the WalRecoveryCorrectnessTest style): three documents in one page updated by three separate transactions (v2/v3/v4, disjoint byte regions) with flushing suspended, kill, version header forged to v4 over the v1 content. Before the fix recovery produced {doc1=A1, doc2=A2, doc3=B3} - the exact #5054 silent corruption, only the newest coalesced version repaired; after, the full chain replay restores {B1, B2, B3}. Also covered: the tear with a persisted equal-version slot (CRC mismatch as direct evidence), the missing-sidecar migration path, the slot-matches-disk flush contract, and a corrupted sidecar on a cleanly-closed database (verification is recovery-only). Verified with the full engine+database battery (624 tests, green) plus the LSM compaction/drop suites exercising the sidecar rename/drop lifecycle. Two earlier battery rounds surfaced real issues, both resolved: the sidecar force initially threw ClosedByInterruptException when the main channel's interrupt retry restored the flag before the sidecar fsync (now interrupt-shielded and contained), and the sidecar-creation latency inside the per-page interlock widened a latent race in Issue4712/Issue4510's test setup (fixed by draining the async setup flush, see the companion test commit).
…Apply tests Issue4712ReplicatedWriteLockTest planted a fake per-page interlock entry in PageManager.pendingFlushPages while the async flush of its own 10-document setup transaction could still be INSIDE concurrentPageAccess for an equal PageId (LocalDatabase.equals is path-based, so equality spans the helper's database instances). When that in-flight flush completed, its finally-remove deleted the test's fake entry, the applier thread proceeded without ever blocking and the "must not complete within 500ms" assertion failed. Issue4510ForceApplyPartialDeltaTest had the sibling race on the read side: the post-apply reload could be served the stale setup-transaction page from the flush-queue index (getCachedPageFromMutablePageInQueue) instead of the just-written disk content. Both races are latent on main; the per-page checksum sidecar (#5054) made them frequent by adding the sidecar-file creation to the first flush of the page, inside the same interlock window the tests race against. Draining the flush pipeline (waitAllPagesOfDatabaseAreFlushed) after the setup transaction makes both tests deterministic: verified 8/8 green runs (previously failing most isolated runs with the sidecar timing) and a full engine+database battery.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 57 |
🟢 Coverage 82.05% diff coverage · -7.22% coverage variation
Metric Results Coverage variation ✅ -7.22% coverage variation Diff coverage ✅ 82.05% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (fba3902) 135322 100946 74.60% Head commit (b2a9ed7) 167310 (+31988) 112733 (+11787) 67.38% (-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 (#5078) 156 128 82.05% Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified:
<covered lines added or modified>/<coverable lines added or modified> * 100%
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
There was a problem hiding this comment.
Code Review
This pull request introduces per-page CRC32C checksums stored in a .pcrc sidecar file to detect and repair torn page writes during crash recovery, resolving issue #5054. The changes span configuration, file management, transaction recovery, and tests. The review feedback highlights two important improvements: first, explicitly closing the checksum sidecar file before dropping it in PaginatedComponentFile.java to prevent file locking issues on Windows; second, downgrading the log level from SEVERE to WARNING in TransactionManager.java when a stale checksum is encountered to prevent false monitoring alerts.
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.
| @Override | ||
| public void drop() throws IOException { | ||
| super.drop(); | ||
| // Best-effort removal of the checksum sidecar: an orphan sidecar is harmless (nothing scans for it), | ||
| // but deleting it keeps the database directory clean and avoids a stale sidecar being adopted if a | ||
| // future file re-uses the exact same name. | ||
| final File sidecar = new File(filePath + CHECKSUM_FILE_EXT); | ||
| if (sidecar.exists() && !sidecar.delete()) | ||
| LogManager.instance().log(this, Level.WARNING, "Error on deleting checksum sidecar file '%s'", null, sidecar); | ||
| } |
There was a problem hiding this comment.
If drop() is called on an open file, the checksum sidecar file may still be open. On Windows, attempting to delete an open file will fail due to file locking, leading to orphaned .pcrc files or a failed drop operation. Explicitly calling closeChecksumFile() before super.drop() ensures the sidecar is closed and can be safely deleted on all platforms.
@Override
public void drop() throws IOException {
closeChecksumFile();
super.drop();
// Best-effort removal of the checksum sidecar: an orphan sidecar is harmless (nothing scans for it),
// but deleting it keeps the database directory clean and avoids a stale sidecar being adopted if a
// future file re-uses the exact same name.
final File sidecar = new File(filePath + CHECKSUM_FILE_EXT);
if (sidecar.exists() && !sidecar.delete())
LogManager.instance().log(this, Level.WARNING, \"Error on deleting checksum sidecar file '%s'\", null, sidecar);
}| if (maxWalVersion == null || maxWalVersion < diskVersion) { | ||
| LogManager.instance().log(this, Level.SEVERE, | ||
| "Page %d of file '%s' fails its checksum (disk v.%d, checksum v.%d) but the WAL retains no entry at that version or newer: the checksum is considered stale and the page is recovered with the standard rules", | ||
| null, pageNumber, file.getFileName(), diskVersion, slotVersion); | ||
| return false; | ||
| } |
There was a problem hiding this comment.
Logging a stale checksum at Level.SEVERE is inappropriate because it is a safe, expected fallback path (the page is guaranteed to be intact due to the fsync-before-WAL-drop barrier). In contrast, a genuine torn write (which is a critical corruption event) is logged at Level.WARNING at line 1090. Logging this benign condition at SEVERE can trigger false alerts in log monitoring systems. It should be logged at Level.WARNING or Level.INFO.
| if (maxWalVersion == null || maxWalVersion < diskVersion) { | |
| LogManager.instance().log(this, Level.SEVERE, | |
| "Page %d of file '%s' fails its checksum (disk v.%d, checksum v.%d) but the WAL retains no entry at that version or newer: the checksum is considered stale and the page is recovered with the standard rules", | |
| null, pageNumber, file.getFileName(), diskVersion, slotVersion); | |
| return false; | |
| } | |
| if (maxWalVersion == null || maxWalVersion < diskVersion) { | |
| LogManager.instance().log(this, Level.WARNING, | |
| \"Page %d of file '%s' fails its checksum (disk v.%d, checksum v.%d) but the WAL retains no entry at that version or newer: the checksum is considered stale and the page is recovered with the standard rules\", | |
| null, pageNumber, file.getFileName(), diskVersion, slotVersion); | |
| return false; | |
| } |
|
Review: per-page CRC32C checksums (issue 5054) I reviewed the full diff, the surrounding Correctness (verified, no blockers)
Performance
Behavioral note: verification is not gated by the flag Tests One small suggestion: since this touches the durability barrier and does per-page I/O, a @tag("slow") might be warranted if the suite elapsed time is noticeable (the multi-version scenario spins up/kills a DB several times) - optional, at your discretion. Nits
Overall: solid, safe, and well-tested. My only real ask is documenting the extra-fsync throughput cost in the release note and considering the flag-gating of verification; the allocation cleanup is a nice-to-have. |
|
On standby by design decision (Luca): the sidecar-per-data-file approach doubles the open-file-descriptor count, which matters on databases with many buckets/files. Converting to draft while the design is reconsidered. Alternatives to evaluate when this resumes:
The recovery/replay machinery, the red-first tests and the correctness argument in this PR are design-independent and reusable whichever storage layout wins. Review-round responses are paused; the round-1 findings (flush-path allocations, flag-gating of verification, throughput number) fold into the redesign. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #5078 +/- ##
==========================================
Coverage 65.62% 65.62%
+ Complexity 842 841 -1
==========================================
Files 1687 1687
Lines 135322 135507 +185
Branches 28959 28996 +37
==========================================
+ Hits 88799 88926 +127
- Misses 34413 34454 +41
- Partials 12110 12127 +17 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Deferred to a dedicated design-first campaign (not part of the 2026-07 audit follow-up, which is now complete). This stays a DRAFT. The blocking decision is the storage layout - the current .pcrc sidecar-per-data-file doubles the open-fd count (Luca's concern); the alternatives to weigh at kickoff are: a single consolidated per-database checksum file, interleaved checksum pages inside the data file (zero extra files), or the page-header route behind an engine-wide format epoch. The recovery/replay machinery, the red-first multi-version torn-write tests, and the correctness argument here are layout-independent and carry over to whichever wins. |
|
This will be postponed |
Follow-up to #4926 / #5052 from the 2026-07 audit backlog. Closes #5054.
What does this PR do?
#5054 (implemented, red-first). Async flush coalesces several committed versions into a single physical page write, so a page can go v1(on-disk) -> v2 -> v3 -> v4 with only the v4 flush reaching the platter. If that flush tears, the #5052 equal-version re-apply repairs only v4's delta region: v2/v3 entries are skipped as strictly-older and their byte regions stay silently torn. The version header alone cannot distinguish this page from an intact one.
Every page flush now also maintains an 8-byte slot (page version + CRC32C of the raw page bytes) in a
.pcrcsidecar file next to each data file, written BEFORE the page bytes and fsynced under the sameforce()barrier. During crash recovery a pre-scan collects the per-page maximum retained WAL version, and each WAL-referenced page is verified once: a page whose checksum reveals a torn write gets its FULL retained WAL delta chain replayed in transaction order (the strictly-older skip and the version-gap abort are bypassed for that page only). Correctness rests on the fsync-before-WAL-drop barrier (#4509/#4934): a dropped entry is always durably contained in the on-disk page, so in-order application of every retained entry reconstructs exactly the newest committed state. A guard refuses the repair when the WAL retains no entry at or above the disk version, so a stale checksum (e.g. a sidecar restored from a backup) can never downgrade an intact page.Red-first evidence (
PageChecksumRecoveryTest): three documents in one page updated by three separate transactions (v2/v3/v4, disjoint byte regions) with flushing suspended, kill, version header forged to v4 over the v1 content. Before the fix recovery produced{doc1=A1, doc2=A2, doc3=B3}- the exact #5054 silent corruption; after, the full chain replay restores{B1, B2, B3}. Also covered: the tear with a persisted equal-version slot (CRC mismatch as direct positive evidence), the missing-sidecar migration path, the slot-matches-disk flush contract, and a corrupted sidecar on a cleanly-closed database (verification is recovery-only).Design decisions (design-first item)
.pcrcsidecar per data file (8 bytes per page atpageNumber * 8), NOT a page-header extension. The header extension was analyzed and rejected: component file versions carry per-component semantics (LocalBucket.purposeForVersiontreats v>=1 as EXTERNAL_PROPERTY andmaxRecordsInPageForVersionkeys the slot table on the same integer), so a cross-cutting "has checksum" gate cannot ride that version without redesigning component versioning across every component type;PAGE_HEADER_SIZEis additionally a static constant compiled into 17+ classes including the just-stabilized commit path, and the WAL/replication deltas carry absolute in-page offsets. The sidecar needs no version gating at all.java.util.zip.CRC32C(hardware-accelerated) over the full raw page bytes exactly as written, version stored alongside so a slot can be matched to the page state it describes.PaginatedComponentFile.write()- every write site (flush thread, sync flush, recovery/replicatedwritePageWithLock) is covered automatically - BEFORE the page bytes, so a persisted slot always describes the newest attempted write. Cost is on the flush thread, not commit latency. Gated byarcadedb.pageChecksum(default true). A sidecar write/fsync failure is contained as a WARNING: checksums are advisory and must never veto the data file's fsync verdict.TransactionManager.checkIntegritypasses aRecoveryPageVerifierintoapplyChanges; the HA/Raft replay callers pass null and are untouched). Read-path verification behind a config flag was deliberately left out to keep the hot read path unchanged; it can be added later (noted below).FileManagerscans the directory by extension whitelist, so old and NEW versions alike ignore.pcrc(downgrade-safe).drop()deletes the sidecar;rename()(LSM compaction temp-suffix removal) carries it along; HA file transfers that omit it only lose verification, never data.Per-issue verdict
Test evidence
PageChecksumRecoveryTest(new, 5 tests): red-first on main for the two torn-write cases ({A1, A2, B3}observed pre-fix), green with the fix.com.arcadedb.engine.**+com.arcadedb.database.**): 624 tests, 0 failures, 0 errors (1 pre-existing skip).LSMTreeIndexCompactionTest,LSMTreeCompactionCorrectnessTest,DropIndexTest,Issue4960LSMReloadCompactionCounterTest): green - exercises the sidecar rename/drop lifecycle.WalRecoveryCorrectnessTest,WALVersionGapRecoveryTest,Issue4508TornWALRecoveryTest,Issue4510ForceApplyPartialDeltaTest,ACIDTransactionTest): green.ClosedByInterruptExceptionwhen the main channel's interrupt retry restored the flag first (now interrupt-shielded like the main channel), and the sidecar-creation latency inside the per-page interlock made a latent race inIssue4712ReplicatedWriteLockTest/Issue4510ForceApplyPartialDeltaTestfrequent - their fake-interlock/reload setup raced the async flush of their own setup transaction (LocalDatabase.equalsis path-based, so the race spans helper database instances). Fixed by draining the flush pipeline after setup (second commit); verified 8/8 green isolated runs.Conflict-risk notes
docs/release-26.7.2.md: expected to conflict with sibling audit PRs (append-style entries); trivial to resolve.TransactionManager.applyChanges: touched by fix(#4926,#4934): torn-write repair on recovery; fsync-gated WAL dele… #5052 recently; this PR builds directly on that code (comment block updated in place). Sibling PRs touching recovery would conflict here.PaginatedComponentFile: new sidecar members andwrite()/force()/close()/rename()/drop()additions; low conflict risk.Follow-up candidates (not in scope)
PaginatedComponentFile.write()leave no slots for their pages (verification simply skips them); wiring them in would extend coverage.Checklist
mvn clean packagecommand (engine module + full engine/database battery)