[PR #2540] [MERGED] perf(db): make the file-backed store flush async so it stops blocking the event loop #5643

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/2540
Author: @Romuromylus
Created: 6/9/2026
Status: ✅ Merged
Merged: 6/9/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/file-store-async-flush


📝 Commits (3)

  • 58ffdfd perf(db): make the file-backed store flush async so it stops blocking the event loop
  • 55aac5c fix(db): snapshot the dirty set before the async flush so interleaved writes aren't lost
  • e5dd8d0 Merge branch 'staging' into fix/file-store-async-flush

📊 Changes

1 file changed (+32 additions, -36 deletions)

View changed files

📝 packages/server/src/db/file-backed-store.ts (+32 -36)

📄 Description

Linked issue

Closes #2528

Why this change

The file-backed store's flush path was fully synchronous and ran O(total table size) work on the Node event loop:

markDirty() -> flush() -> saveFileSnapshots() -> atomicWriteFile() per dirty table

atomicWriteFile did copyFileSync (a whole-file .bak copy), writeFileSync, and three fsyncSync calls. messages is a single global file-backed table that markDirtys on every insert/update/delete, so during active chat each debounced flush synchronously re-serialized and whole-file-copied the entire messages table (multi-MB on a long transcript), blocking every other request on the shared server. The cost grows linearly with accumulated chat history; the 750ms debounce only prevents a write per op, not the O(table size) cost per flush.

What changed

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

  • Converted flushFile and atomicWriteFile to fs/promises (open + FileHandle.sync(), copyFile, writeFile, rename, unlink).
  • Made saveFileSnapshots async and await each atomicWriteFile (sequential — preserves ordering and bounds concurrent handles to one, matching prior behavior).
  • await the now-async saveFileSnapshots() in the already-async flush().
  • Dropped the now-unused sync fs imports (copyFileSync/fsyncSync/writeFileSync/renameSync/unlinkSync), keeping the ones still used by looksNulFilled/loadFileSnapshots/etc.

Crash-safety is preserved exactly: same tmp-path naming, same .bak refresh gating (refreshBackup && existsSync && !looksNulFilled), same fsync-before-rename on the .bak tmp / main tmp / parent dir, same cleanup-tmp-on-error then rethrow. The only behavioral change is that the multi-MB serialize→copy→fsync now yields the event loop instead of blocking it. JSON.stringify(rows) stays synchronous (the deeper per-chat-partitioning win is out of scope here).

All three atomicWriteFile/saveFileSnapshots call sites are awaited; flush()'s fire-and-forget callers (markDirty debounce, safety timer, beforeExit handler, controller) already used void this.flush() and still return a Promise, so no signature change is needed at any of them.

Not a regression: byte-identical on main; shared-engine perf characteristic.

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

pnpm check passes locally. Added a local-only node:test (file-backed-store-flush.test.ts, gitignored) driving the store through createFileNativeDB against a temp FILE_STORAGE_DIR:

  • Roundtrip: insert a row, flush() returns a Promise, the table JSON contains the row, and no .tmp-* files remain (atomic rename completed).
  • Backup double-buffer: a second write of the pre-existing table produces a valid .bak holding the prior version (proves copyFile → fsync → rename works through fs/promises).
  • Idempotency: a flush with nothing newly dirty does not throw and does not rewrite/corrupt the file.

Local run: 3/3 pass.

Still to verify manually against the deploy (non-regression smoke, not the gate): create a character + chat, send several messages, refresh and restart the service, and confirm all data persists (durable flush on shutdown via close() → flush(true)), with tables/messages.json valid and a .bak present after activity.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

🔄 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/2540 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 6/9/2026 **Status:** ✅ Merged **Merged:** 6/9/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/file-store-async-flush` --- ### 📝 Commits (3) - [`58ffdfd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/58ffdfd7776a709f3ef2731d922f20fa9084f3a8) perf(db): make the file-backed store flush async so it stops blocking the event loop - [`55aac5c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/55aac5cb6a5b788035071eb493cef269ac7df835) fix(db): snapshot the dirty set before the async flush so interleaved writes aren't lost - [`e5dd8d0`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e5dd8d083fb2d03b44349c4a7bb20a251ff802a9) Merge branch 'staging' into fix/file-store-async-flush ### 📊 Changes **1 file changed** (+32 additions, -36 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/db/file-backed-store.ts` (+32 -36) </details> ### 📄 Description ## Linked issue Closes #2528 ## Why this change The file-backed store's flush path was fully synchronous and ran O(total table size) work on the Node event loop: ``` markDirty() -> flush() -> saveFileSnapshots() -> atomicWriteFile() per dirty table ``` `atomicWriteFile` did `copyFileSync` (a whole-file `.bak` copy), `writeFileSync`, and three `fsyncSync` calls. `messages` is a single global file-backed table that `markDirty`s on every insert/update/delete, so during active chat each debounced flush synchronously re-serialized **and** whole-file-copied the entire `messages` table (multi-MB on a long transcript), blocking every other request on the shared server. The cost grows linearly with accumulated chat history; the 750ms debounce only prevents a write *per op*, not the O(table size) cost *per flush*. ## What changed `packages/server/src/db/file-backed-store.ts`: - Converted `flushFile` and `atomicWriteFile` to `fs/promises` (`open` + `FileHandle.sync()`, `copyFile`, `writeFile`, `rename`, `unlink`). - Made `saveFileSnapshots` async and `await` each `atomicWriteFile` (sequential — preserves ordering and bounds concurrent handles to one, matching prior behavior). - `await` the now-async `saveFileSnapshots()` in the already-async `flush()`. - Dropped the now-unused sync `fs` imports (`copyFileSync`/`fsyncSync`/`writeFileSync`/`renameSync`/`unlinkSync`), keeping the ones still used by `looksNulFilled`/`loadFileSnapshots`/etc. **Crash-safety is preserved exactly**: same tmp-path naming, same `.bak` refresh gating (`refreshBackup && existsSync && !looksNulFilled`), same fsync-before-rename on the `.bak` tmp / main tmp / parent dir, same cleanup-tmp-on-error then rethrow. The only behavioral change is that the multi-MB serialize→copy→fsync now yields the event loop instead of blocking it. `JSON.stringify(rows)` stays synchronous (the deeper per-chat-partitioning win is out of scope here). All three `atomicWriteFile`/`saveFileSnapshots` call sites are awaited; `flush()`'s fire-and-forget callers (markDirty debounce, safety timer, beforeExit handler, controller) already used `void this.flush()` and still return a Promise, so no signature change is needed at any of them. Not a regression: byte-identical on `main`; shared-engine perf characteristic. ## 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 `pnpm check` passes locally. Added a local-only node:test (`file-backed-store-flush.test.ts`, gitignored) driving the store through `createFileNativeDB` against a temp `FILE_STORAGE_DIR`: - **Roundtrip**: insert a row, `flush()` returns a Promise, the table JSON contains the row, and no `.tmp-*` files remain (atomic rename completed). - **Backup double-buffer**: a second write of the pre-existing table produces a valid `.bak` holding the prior version (proves `copyFile → fsync → rename` works through `fs/promises`). - **Idempotency**: a flush with nothing newly dirty does not throw and does not rewrite/corrupt the file. Local run: **3/3 pass**. Still to verify manually against the deploy (non-regression smoke, not the gate): create a character + chat, send several messages, refresh and restart the service, and confirm all data persists (durable flush on shutdown via `close() → flush(true)`), with `tables/messages.json` valid and a `.bak` present after activity. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:18:04 +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#5643
No description provided.