[PR #5722] [MERGED] fix(storage): close two residual transaction-isolation gaps in the file-backed store #6900

Closed
opened 2026-10-23 04:14:43 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5722
Author: @kolacheee
Created: 9/1/2026
Status: ✅ Merged
Merged: 9/1/2026
Merged by: @kolacheee

Base: staging ← Head: fix/5651-5652-store-transaction-isolation


📝 Commits (3)

  • e246450 fix(storage): close two residual transaction-isolation gaps (#5651, #5652)
  • 5ed5f12 fix(storage): close the adversarial-review findings on the isolation fixes
  • c5903bd test(storage): stage the isolation regression on lifecycle signals

📊 Changes

3 files changed (+432 additions, -8 deletions)

View changed files

📝 CHANGELOG.md (+2 -0)
📝 packages/server/src/db/file-backed-store.ts (+53 -8)
➕ scripts/regressions/store-transaction-isolation.regression.ts (+377 -0)

📄 Description

Linked issue

Closes #5651, closes #5652.

Why this change

The #5631 verification pass left two residual transaction-isolation gaps in the file-backed store, both silent-data bugs in narrow but reachable interleavings. #5651: reads never take the write gate, so a concurrent request can lazily load a cold chat unit mid-transaction. That load runs outside the transaction's AsyncLocalStorage context, so the snapshot mirror in mergeLoadedRows (and the heal-mark mirror in recordLoadHealMarks) never engaged — the loaded rows landed in the live table after the transaction's first-mutation snapshot, and a rollback restored the snapshot, erasing persisted rows while loadedUnits still said the unit was resident. The chat stayed invisible until restart. #5652: transaction()'s opening flush wait was check-once. With two flushes parked on the same activeFlush (the second subscribed first), the second flush's recursion re-enters on resolve, captures the dirty set, and installs a new activeFlush before the transaction's continuation resumes — which then sailed past its consumed check and ran its callback concurrently with the fresh flush's I/O. saveFileSnapshots reads live tables, so uncommitted rows could be persisted to disk, and a rollback then left them there with no dirty mark.

What changed

  • #5651 — the store now tracks the active transaction's context in a field (activeTransactionContext; the transaction queue admits at most one), and both load-effect sites resolve their target context through a shared loadEffectTransactionContext() helper: the loader's own ALS context when present, otherwise the active transaction's. Out-of-context loads now mirror into the running transaction's snapshot and heal-mark maps exactly like in-context ones, so rollback preserves them.
  • #5652 — the opening wait is now while (this.activeFlush) await this.activeFlush;. The recursing flush installs its new activeFlush synchronously before its first await, so a re-check after every wake always observes it; the transaction can no longer slip between one flush ending and the next one starting.

Plus two adjacent defects in the same class, confirmed by an adversarial review of the first commit and closed here (second commit):

  • flush()'s own wait on active transactions was also check-once — the mirror image of #5652. A transaction queued behind the one the flush is waiting out wakes on a one-hop microtask chain while the flush's wake is two-hop, so the queued transaction activates first. The pendingTransactionFlush handoff rescues that ordering while the store is open, but it is deliberately skipped once writesClosed — so during shutdown the woken flush ran saveFileSnapshots concurrently with the next transaction's callback and could persist uncommitted rows whose dirty marks the rollback then erased. That wait is now a loop too.
  • The snapshot mirror refilled the transaction's rollback snapshot with snapshot.push(...mirrored) — a spread that overflows the call stack past ~100k–120k rows (eviction is off by default, so resident messages grow monotonically), and the throw landed after the length = 0 truncation, leaving an empty snapshot that a rollback would install as the live messages table. The line predates this PR, but the #5651 fix widens its reachability to every concurrent request's lazy load, so it is fixed in the same change: the merged array is built fully before the snapshot is touched, refilled with a loop.
  • New staged regression scripts/regressions/store-transaction-isolation.regression.ts reproduces all four interleavings deterministically: Parts 1–2 for #5651/#5652 (promise gates plus a one-shot beforeTableWrite mid-write hold from FileNativeStoreTestHooks), Part 3 for the spread overflow (a 200k-row unit lazily loaded mid-transaction), Part 4 for the close-path flush overlap (an overlap detector in the beforeTableWrite hook plus an on-disk assert that a rolled-back brand-new unit leaves no shard file), with anti-vacuity asserts that the staged holds and parks actually engaged.

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 lint and the server production build are green locally (re-run after the rebase onto the merged #5718/#5720 staging); format:check fails repo-wide on this Windows checkout (pre-existing autocrlf CRLF; touched files were run through Prettier directly).
  • The regression's teeth were verified for each of the four fixes independently — every surgical revert fails on exactly its own assertion: #5651 helper revert → "rollback must not erase rows a concurrent read lazily loaded mid-transaction"; #5652 while→if revert → "the transaction callback must not run concurrently with the second flush's I/O"; mirror spread revert → RangeError: Maximum call stack size exceeded; flush-wait while→if revert → "a flush parked behind a transaction must not run its I/O concurrently with the next transaction's callback (close path)". Restored code passes all four parts.
  • All sibling store lanes re-verified green after both commits: tx-gate-window, lazy-chat-units, message-sharding, file-backed-shutdown, storage-writer-lock.
  • A two-lens adversarial review (transaction/flush interleaving incl. close/starvation; lazy-load mirror semantics incl. commit/eviction interplay) ran over the first commit with independent verification of every finding: 2 findings raised, 2 confirmed against the code, both fixed in the second commit as described above. The verifiers also re-derived the failure chains end-to-end (including the on-disk damage paths through saveShardedTable's known-shard guard and the rollback's dirty-map restore).
  • Please verify manually: none beyond CI — the change is server-internal with no UI surface; the regression lanes are the behavioral contract.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

CHANGELOG updated under [Unreleased] → Fixed. No user-facing docs touched, so nothing new for the docs-i18n batch.

UI evidence (if applicable)

Not applicable — server-internal storage fix.

Summary by CodeRabbit

  • Bug Fixes
    • Improved transaction isolation during concurrent reads, writes, flushes, and shutdown.
    • Prevented rollbacks from removing data loaded during an active transaction.
    • Improved reliability when handling large datasets, including during rollback and snapshot operations.
  • Tests
    • Added regression coverage for transaction coordination, shutdown behavior, concurrent loading, and large datasets.
  • Documentation
    • Updated the unreleased changelog with the transaction-isolation fixes.

🔄 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/5722 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 9/1/2026 **Status:** ✅ Merged **Merged:** 9/1/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `fix/5651-5652-store-transaction-isolation` --- ### 📝 Commits (3) - [`e246450`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e246450e27b5a868d7c1a76b78506c3a3318830d) fix(storage): close two residual transaction-isolation gaps (#5651, #5652) - [`5ed5f12`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5ed5f12666bbc4fd72c2955a680bd0e7a7d3ed26) fix(storage): close the adversarial-review findings on the isolation fixes - [`c5903bd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c5903bd0437ac807b5885e49a33ce6cf380fe4cb) test(storage): stage the isolation regression on lifecycle signals ### 📊 Changes **3 files changed** (+432 additions, -8 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+2 -0) 📝 `packages/server/src/db/file-backed-store.ts` (+53 -8) ➕ `scripts/regressions/store-transaction-isolation.regression.ts` (+377 -0) </details> ### 📄 Description ## Linked issue Closes #5651, closes #5652. ## Why this change The #5631 verification pass left two residual transaction-isolation gaps in the file-backed store, both silent-data bugs in narrow but reachable interleavings. **#5651:** reads never take the write gate, so a concurrent request can lazily load a cold chat unit mid-transaction. That load runs outside the transaction's `AsyncLocalStorage` context, so the snapshot mirror in `mergeLoadedRows` (and the heal-mark mirror in `recordLoadHealMarks`) never engaged — the loaded rows landed in the live table *after* the transaction's first-mutation snapshot, and a rollback restored the snapshot, erasing persisted rows while `loadedUnits` still said the unit was resident. The chat stayed invisible until restart. **#5652:** `transaction()`'s opening flush wait was check-once. With two flushes parked on the same `activeFlush` (the second subscribed first), the second flush's recursion re-enters on resolve, captures the dirty set, and installs a *new* `activeFlush` before the transaction's continuation resumes — which then sailed past its consumed check and ran its callback concurrently with the fresh flush's I/O. `saveFileSnapshots` reads live tables, so uncommitted rows could be persisted to disk, and a rollback then left them there with no dirty mark. ## What changed - **#5651** — the store now tracks the active transaction's context in a field (`activeTransactionContext`; the transaction queue admits at most one), and both load-effect sites resolve their target context through a shared `loadEffectTransactionContext()` helper: the loader's own ALS context when present, otherwise the active transaction's. Out-of-context loads now mirror into the running transaction's snapshot and heal-mark maps exactly like in-context ones, so rollback preserves them. - **#5652** — the opening wait is now `while (this.activeFlush) await this.activeFlush;`. The recursing flush installs its new `activeFlush` synchronously before its first await, so a re-check after every wake always observes it; the transaction can no longer slip between one flush ending and the next one starting. **Plus two adjacent defects in the same class, confirmed by an adversarial review of the first commit and closed here (second commit):** - `flush()`'s own wait on active transactions was *also* check-once — the mirror image of #5652. A transaction queued behind the one the flush is waiting out wakes on a one-hop microtask chain while the flush's wake is two-hop, so the queued transaction activates first. The `pendingTransactionFlush` handoff rescues that ordering while the store is open, but it is deliberately skipped once `writesClosed` — so during shutdown the woken flush ran `saveFileSnapshots` concurrently with the next transaction's callback and could persist uncommitted rows whose dirty marks the rollback then erased. That wait is now a loop too. - The snapshot mirror refilled the transaction's rollback snapshot with `snapshot.push(...mirrored)` — a spread that overflows the call stack past ~100k–120k rows (eviction is off by default, so resident messages grow monotonically), and the throw landed *after* the `length = 0` truncation, leaving an empty snapshot that a rollback would install as the live messages table. The line predates this PR, but the #5651 fix widens its reachability to every concurrent request's lazy load, so it is fixed in the same change: the merged array is built fully before the snapshot is touched, refilled with a loop. - New staged regression `scripts/regressions/store-transaction-isolation.regression.ts` reproduces all four interleavings deterministically: Parts 1–2 for #5651/#5652 (promise gates plus a one-shot `beforeTableWrite` mid-write hold from `FileNativeStoreTestHooks`), Part 3 for the spread overflow (a 200k-row unit lazily loaded mid-transaction), Part 4 for the close-path flush overlap (an overlap detector in the `beforeTableWrite` hook plus an on-disk assert that a rolled-back brand-new unit leaves no shard file), with anti-vacuity asserts that the staged holds and parks actually engaged. ## 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 lint` and the server production build are green locally (re-run after the rebase onto the merged #5718/#5720 staging); `format:check` fails repo-wide on this Windows checkout (pre-existing autocrlf CRLF; touched files were run through Prettier directly). - The regression's teeth were verified for **each of the four fixes independently** — every surgical revert fails on exactly its own assertion: #5651 helper revert → "rollback must not erase rows a concurrent read lazily loaded mid-transaction"; #5652 `while`→`if` revert → "the transaction callback must not run concurrently with the second flush's I/O"; mirror spread revert → `RangeError: Maximum call stack size exceeded`; flush-wait `while`→`if` revert → "a flush parked behind a transaction must not run its I/O concurrently with the next transaction's callback (close path)". Restored code passes all four parts. - All sibling store lanes re-verified green after both commits: `tx-gate-window`, `lazy-chat-units`, `message-sharding`, `file-backed-shutdown`, `storage-writer-lock`. - A two-lens adversarial review (transaction/flush interleaving incl. close/starvation; lazy-load mirror semantics incl. commit/eviction interplay) ran over the first commit with independent verification of every finding: 2 findings raised, 2 confirmed against the code, both fixed in the second commit as described above. The verifiers also re-derived the failure chains end-to-end (including the on-disk damage paths through `saveShardedTable`'s known-shard guard and the rollback's dirty-map restore). - **Please verify manually:** none beyond CI — the change is server-internal with no UI surface; the regression lanes are the behavioral contract. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) CHANGELOG updated under **[Unreleased] → Fixed**. No user-facing docs touched, so nothing new for the `docs-i18n` batch. ## UI evidence (if applicable) Not applicable — server-internal storage fix. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved transaction isolation during concurrent reads, writes, flushes, and shutdown. * Prevented rollbacks from removing data loaded during an active transaction. * Improved reliability when handling large datasets, including during rollback and snapshot operations. * **Tests** * Added regression coverage for transaction coordination, shutdown behavior, concurrent loading, and large datasets. * **Documentation** * Updated the unreleased changelog with the transaction-isolation fixes. <!-- 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-23 04:14:43 +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#6900
No description provided.