[PR #634] [MERGED] fix(file-storage): make atomicWriteFile crash-safe and self-heal stale .bak #4707

Closed
opened 2026-10-22 04:09:59 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/634
Author: @Romuromylus
Created: 5/10/2026
Status: ✅ Merged
Merged: 5/10/2026
Merged by: @Romuromylus

Base: main ← Head: fix/file-storage-crash-safety


📝 Commits (2)

  • e940667 fix(file-storage): make atomicWriteFile crash-safe and self-heal stale .bak
  • d67d4f4 fix(file-storage): address CodeRabbit feedback

📊 Changes

1 file changed (+120 additions, -11 deletions)

View changed files

📝 packages/server/src/db/file-backed-store.ts (+120 -11)

📄 Description

Linked issue

Closes #631

Why this change

A hard crash mid-write could destroy data in two compounding ways:

  1. Both manifest.json and manifest.json.bak could be left filled with NUL bytes, blocking server startup until the user manually moved the corrupt files aside.
  2. Even when startup recovered via the .bak fallback, the recovered backup could be silently weeks out of date — copyFileSync errors during .bak refresh were swallowed, so failures had been quietly accumulating without anyone noticing. A real user reported losing about a week of chat messages and character edits this way after a single hard crash.

Root cause is in atomicWriteFile: .bak was written via plain copyFileSync with no fsync, in the same call that wrote the main file. NTFS allocates blocks and updates metadata immediately, but defers data writes through the cache manager — so a crash before the cache flushes leaves the file at the right size but zero-filled. And since the .bak and main writes ran back-to-back, both were simultaneously dirty in the page cache during the write window.

What changed

packages/server/src/db/file-backed-store.ts:

  • atomicWriteFile is now actually crash-safe. .bak is written via the same tmp + fsync + rename pattern as the main file, so the backup is durable on disk before the main file is touched. Best-effort directory fsync after the main rename. Future hard crashes lose at most the last few seconds of in-flight writes, not arbitrarily-old data.
  • Skip .bak refresh when main is NUL-corrupted. A first-byte check (looksNulFilled) prevents atomicWriteFile from copying a NUL-filled main into .bak. Without this, the heal save right after a recovery would destroy the very backup we just used to recover, opening a brief window where a second crash would lose data.
  • .bak refresh failures now log at error level instead of being swallowed. Any failure to durably refresh the backup is a real durability regression and should be visible to operators.
  • parseJsonFile reports staleness on fallback. When the main file is corrupt and we fall back to .bak, the log line now includes the modification-time delta between the two files (backup is 7d 4h older). Users see at startup if their recovered backup is significantly stale, instead of finding out from missing data days later.
  • Self-heal after fallback. When parseJsonFile recovers from .bak, the affected manifest / table is marked dirty so the next save rewrites the corrupt main file. Previously the corrupt main file persisted on disk forever, leaving the user permanently in a state where main is junk and .bak is load-bearing — every subsequent crash would trigger the fallback again.
  • Manifest-specific resilience. If both manifest.json and manifest.json.bak are unparseable at startup (the original bug pattern), log the error and continue with an empty manifest instead of crashing bootstrap. The manifest is regenerated from on-disk tables/*.json files on the next save, so blocking startup over a corrupt-but-recoverable manifest is overly strict — and this also unblocks recovery for users already hit by the existing bug, not just future writes.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

  • Manually verify the server starts normally and saves work as before in Conversation / Roleplay / Game modes.
  • Manually verify recovery path: kill the server during a save burst, simulate a corrupt main file by truncating manifest.json (or any tables/*.json) to NUL bytes of the original size, then restart and confirm the server recovers from .bak with an error-level log line that includes a staleness delta, and that the next save rewrites both main and .bak.
  • Manually verify the worst case: corrupt both manifest.json and manifest.json.bak. Server should log an error and continue with an empty manifest, then write a fresh one on the next save (table data unaffected).

Docs and release impact

  • No docs changes needed

Summary by CodeRabbit

  • Bug Fixes
    • Improved crash recovery and data durability for file-backed storage
    • Enhanced detection and restoration when data files become corrupted
    • Strengthened persistence guarantees during critical file operations

Review Change Stack


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/634 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 5/10/2026 **Status:** ✅ Merged **Merged:** 5/10/2026 **Merged by:** [@Romuromylus](https://github.com/Romuromylus) **Base:** `main` ← **Head:** `fix/file-storage-crash-safety` --- ### 📝 Commits (2) - [`e940667`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e940667cb69ebe6e31ff6e464a3e9eb80769e8d2) fix(file-storage): make atomicWriteFile crash-safe and self-heal stale .bak - [`d67d4f4`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d67d4f44b6f276b79c4960175782a4b9239d7d3e) fix(file-storage): address CodeRabbit feedback ### 📊 Changes **1 file changed** (+120 additions, -11 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/db/file-backed-store.ts` (+120 -11) </details> ### 📄 Description ## Linked issue Closes #631 ## Why this change A hard crash mid-write could destroy data in two compounding ways: 1. **Both `manifest.json` and `manifest.json.bak` could be left filled with NUL bytes**, blocking server startup until the user manually moved the corrupt files aside. 2. Even when startup recovered via the `.bak` fallback, the recovered backup could be **silently weeks out of date** — `copyFileSync` errors during `.bak` refresh were swallowed, so failures had been quietly accumulating without anyone noticing. A real user reported losing about a week of chat messages and character edits this way after a single hard crash. Root cause is in `atomicWriteFile`: `.bak` was written via plain `copyFileSync` with no `fsync`, in the same call that wrote the main file. NTFS allocates blocks and updates metadata immediately, but defers data writes through the cache manager — so a crash before the cache flushes leaves the file at the right size but zero-filled. And since the `.bak` and main writes ran back-to-back, both were simultaneously dirty in the page cache during the write window. ## What changed `packages/server/src/db/file-backed-store.ts`: - **`atomicWriteFile` is now actually crash-safe.** `.bak` is written via the same `tmp + fsync + rename` pattern as the main file, so the backup is durable on disk before the main file is touched. Best-effort directory `fsync` after the main rename. Future hard crashes lose at most the last few seconds of in-flight writes, not arbitrarily-old data. - **Skip `.bak` refresh when main is NUL-corrupted.** A first-byte check (`looksNulFilled`) prevents `atomicWriteFile` from copying a NUL-filled main into `.bak`. Without this, the heal save right after a recovery would destroy the very backup we just used to recover, opening a brief window where a second crash would lose data. - **`.bak` refresh failures now log at `error` level** instead of being swallowed. Any failure to durably refresh the backup is a real durability regression and should be visible to operators. - **`parseJsonFile` reports staleness on fallback.** When the main file is corrupt and we fall back to `.bak`, the log line now includes the modification-time delta between the two files (`backup is 7d 4h older`). Users see at startup if their recovered backup is significantly stale, instead of finding out from missing data days later. - **Self-heal after fallback.** When `parseJsonFile` recovers from `.bak`, the affected manifest / table is marked dirty so the next save rewrites the corrupt main file. Previously the corrupt main file persisted on disk forever, leaving the user permanently in a state where main is junk and `.bak` is load-bearing — every subsequent crash would trigger the fallback again. - **Manifest-specific resilience.** If both `manifest.json` and `manifest.json.bak` are unparseable at startup (the original bug pattern), log the error and continue with an empty manifest instead of crashing bootstrap. The manifest is regenerated from on-disk `tables/*.json` files on the next save, so blocking startup over a corrupt-but-recoverable manifest is overly strict — and this also unblocks recovery for users already hit by the existing bug, not just future writes. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes - Manually verify the server starts normally and saves work as before in Conversation / Roleplay / Game modes. - Manually verify recovery path: kill the server during a save burst, simulate a corrupt main file by truncating `manifest.json` (or any `tables/*.json`) to NUL bytes of the original size, then restart and confirm the server recovers from `.bak` with an `error`-level log line that includes a staleness delta, and that the next save rewrites both main and `.bak`. - Manually verify the worst case: corrupt both `manifest.json` and `manifest.json.bak`. Server should log an error and continue with an empty manifest, then write a fresh one on the next save (table data unaffected). ## Docs and release impact - [x] No docs changes needed <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved crash recovery and data durability for file-backed storage * Enhanced detection and restoration when data files become corrupted * Strengthened persistence guarantees during critical file operations [![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Pasta-Devs/Marinara-Engine/pull/634) <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:09:59 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#4707
No description provided.