[PR #5653] [MERGED] fix(storage): close the transaction opening gate atomically #6866

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5653
Author: @kolacheee
Created: 8/29/2026
Status: ✅ Merged
Merged: 8/29/2026
Merged by: @kolacheee

Base: staging ← Head: fix/5631-tx-gate-window


📝 Commits (3)

  • 1d325e2 fix(storage): close the transaction opening gate atomically
  • 0945a68 fix(storage): harden the reservation and make the gate regression stage the real erasure
  • 7f07757 test(storage): stage the gate race through a first-class store seam

📊 Changes

2 files changed (+250 additions, -19 deletions)

View changed files

📝 packages/server/src/db/file-backed-store.ts (+62 -19)
➕ scripts/regressions/tx-gate-window.regression.ts (+188 -0)

📄 Description

Closes #5631

Why

The file store's transaction rollback could silently revert a concurrent plain write. transaction() took its queue slot, then awaited the previous transaction and any in-flight flush before incrementing activeTransactionCount — and waitForWritableTurn honored only the active count. A plain write passing the gate inside that window could apply after the transaction took its first-mutation table snapshot; a rollback then restored the snapshot and the write vanished from memory with no error surfaced to its caller.

The nastier variant, which the regression pins explicitly: when the raced write targets a lazily-loaded chat unit, the rollback erases the freshly loaded rows too, while the unit stays marked loaded — rows that are safely on disk become invisible in memory for the rest of the session.

Found by the #5599/#5600 adversarial verification pass; it predates those fixes, but message edits now run in a transaction, so the window has more traffic near it.

The fix

A pendingTransactionCount, incremented synchronously with queue admission, closes the gate atomically:

  • waitForWritableTurn loops over both counters: while a transaction is active it waits on the idle waiters as before; in a pending-only window it waits on the transaction queue (the idle waiters only fire on active-count transitions, which a pending-only window never produces), re-checking after every wake.
  • The pending→active handoff is synchronous, so the combined count never dips to zero mid-reservation; the whole reservation-to-activation span sits in one try whose catch releases the count and the queue slot — which incidentally fixes a pre-existing theoretical hang (pre-fix, a rejecting in-flight-flush await left the queue slot taken forever).
  • Deliberately untouched: flush parking still waits only on active transactions, and the eviction guard is unchanged (eviction during a pending window is equivalent to eviction before the transaction was called). No new lock-ordering edge: the pending count is part of tx-slot acquisition, covered by the documented message-queue → tx-slot invariant exactly as before.

The regression, and how it earned its determinism

The write path is fully synchronous after its gate (lazy unit loads read shard files synchronously), so the real-world hazard is a one-tick scheduler placement no natural staging hits reliably — the first two drafts of this pin were provably vacuous, caught in review and by instrumented runs (the second draft paused a method on the _fileStore facade that the store never calls). The store now exposes afterWritableTurn in its existing test-hooks surface (the beforeTableWrite seam family): it runs after a plain write clears the gate and before its mutation applies, never for transaction-context writes. The regression arms it for the one raced insert and asserts the pause actually engaged, so the pin cannot silently go vacuous again.

A/B against "pre-fix store + seam only", two runs: with all assertions on it fails at the gate-ordering assert; with the ordering assert neutralized it fails at "the raced insert survives the rollback" — the silent erasure itself, observed. With the fix: green, including the seam-engagement assert.

Verification

  • 3-reviewer adversarial pass (deadlock/livelock audit, secondary count-consumer semantics, regression determinism). Verdicts: no deadlock cycle (every release path covered, flush I/O never takes the gate); the two behavioral costs are bounded and deliberate (theoretical writer starvation only under sustained overlapping transaction storms this codebase doesn't produce; plain writes now absorb flush latency when a transaction queues mid-flush); the reservation-leak and vacuous-pin findings were fixed in follow-up commits.
  • The same pass surfaced two pre-existing store defects, verified unchanged by this fix and filed separately per the atomic-PR discipline: #5651 (rollback erases rows lazily loaded by a concurrent read, unit stays marked loaded) and #5652 (check-once activeFlush await lets a second flush run concurrently with a transaction and persist uncommitted rows).
  • Full node regression suite: 164/165 locally — the sole failure is launcher/format-guard.regression.mjs, which dies with node: command not found from a spawned POSIX shell: a PATH problem in this Windows box's environment, unrelated (the guard doesn't import the store and is untouched here). CI's complete-node-regressions lane runs it on ubuntu.
  • pnpm check green.
  • Manual verification is not practical for a microtask-window race; the staged regression is the verification.

Summary by CodeRabbit

  • Bug Fixes

    • Improved transaction handling to prevent plain writes from racing with transactions.
    • Ensured writes wait appropriately during transaction activity and remain intact after transaction rollbacks.
    • Preserved access to lazily loaded persisted data during concurrent database operations.
  • Tests

    • Added regression coverage for transaction timing, concurrent writes, rollback behavior, and lazy-loaded data.

🔄 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/5653 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/29/2026 **Status:** ✅ Merged **Merged:** 8/29/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `fix/5631-tx-gate-window` --- ### 📝 Commits (3) - [`1d325e2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1d325e22d91c7508370a128203bf4713eaf46b5e) fix(storage): close the transaction opening gate atomically - [`0945a68`](https://github.com/Pasta-Devs/Marinara-Engine/commit/0945a686826e609d3b200306ba9fd091889c2903) fix(storage): harden the reservation and make the gate regression stage the real erasure - [`7f07757`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7f0775793e601a3cfaac8d808b85af53e0adc92e) test(storage): stage the gate race through a first-class store seam ### 📊 Changes **2 files changed** (+250 additions, -19 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/db/file-backed-store.ts` (+62 -19) ➕ `scripts/regressions/tx-gate-window.regression.ts` (+188 -0) </details> ### 📄 Description Closes #5631 ## Why The file store's transaction rollback could silently revert a concurrent plain write. `transaction()` took its queue slot, then *awaited* the previous transaction and any in-flight flush before incrementing `activeTransactionCount` — and `waitForWritableTurn` honored only the active count. A plain write passing the gate inside that window could apply **after** the transaction took its first-mutation table snapshot; a rollback then restored the snapshot and the write vanished from memory with no error surfaced to its caller. The nastier variant, which the regression pins explicitly: when the raced write targets a lazily-loaded chat unit, the rollback erases the freshly *loaded* rows too, while the unit stays marked loaded — rows that are safely on disk become invisible in memory for the rest of the session. Found by the #5599/#5600 adversarial verification pass; it predates those fixes, but message edits now run in a transaction, so the window has more traffic near it. ## The fix A `pendingTransactionCount`, incremented **synchronously with queue admission**, closes the gate atomically: - `waitForWritableTurn` loops over both counters: while a transaction is *active* it waits on the idle waiters as before; in a *pending-only* window it waits on the transaction queue (the idle waiters only fire on active-count transitions, which a pending-only window never produces), re-checking after every wake. - The pending→active handoff is synchronous, so the combined count never dips to zero mid-reservation; the whole reservation-to-activation span sits in one try whose catch releases the count and the queue slot — which incidentally fixes a pre-existing theoretical hang (pre-fix, a rejecting in-flight-flush await left the queue slot taken forever). - Deliberately untouched: flush parking still waits only on *active* transactions, and the eviction guard is unchanged (eviction during a pending window is equivalent to eviction before the transaction was called). No new lock-ordering edge: the pending count is part of tx-slot acquisition, covered by the documented message-queue → tx-slot invariant exactly as before. ## The regression, and how it earned its determinism The write path is **fully synchronous after its gate** (lazy unit loads read shard files synchronously), so the real-world hazard is a one-tick scheduler placement no natural staging hits reliably — the first two drafts of this pin were provably vacuous, caught in review and by instrumented runs (the second draft paused a method on the `_fileStore` facade that the store never calls). The store now exposes `afterWritableTurn` in its existing test-hooks surface (the `beforeTableWrite` seam family): it runs after a plain write clears the gate and before its mutation applies, never for transaction-context writes. The regression arms it for the one raced insert and **asserts the pause actually engaged**, so the pin cannot silently go vacuous again. A/B against "pre-fix store + seam only", two runs: with all assertions on it fails at the gate-ordering assert; with the ordering assert neutralized it fails at **"the raced insert survives the rollback"** — the silent erasure itself, observed. With the fix: green, including the seam-engagement assert. ## Verification - 3-reviewer adversarial pass (deadlock/livelock audit, secondary count-consumer semantics, regression determinism). Verdicts: no deadlock cycle (every release path covered, flush I/O never takes the gate); the two behavioral costs are bounded and deliberate (theoretical writer starvation only under sustained overlapping transaction storms this codebase doesn't produce; plain writes now absorb flush latency when a transaction queues mid-flush); the reservation-leak and vacuous-pin findings were fixed in follow-up commits. - The same pass surfaced two **pre-existing** store defects, verified unchanged by this fix and filed separately per the atomic-PR discipline: #5651 (rollback erases rows lazily loaded by a concurrent *read*, unit stays marked loaded) and #5652 (check-once `activeFlush` await lets a second flush run concurrently with a transaction and persist uncommitted rows). - Full node regression suite: 164/165 locally — the sole failure is `launcher/format-guard.regression.mjs`, which dies with `node: command not found` from a spawned POSIX shell: a PATH problem in this Windows box's environment, unrelated (the guard doesn't import the store and is untouched here). CI's `complete-node-regressions` lane runs it on ubuntu. - `pnpm check` green. - Manual verification is not practical for a microtask-window race; the staged regression is the verification. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved transaction handling to prevent plain writes from racing with transactions. * Ensured writes wait appropriately during transaction activity and remain intact after transaction rollbacks. * Preserved access to lazily loaded persisted data during concurrent database operations. * **Tests** * Added regression coverage for transaction timing, concurrent writes, rollback behavior, and lazy-loaded data. <!-- 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:26 +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#6866
No description provided.