[PR #5632] [MERGED] fix(storage): serialize message deletes against edits and make the edit's mirror write atomic #6856

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

📋 Pull Request Information

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

Base: staging ← Head: fix/5599-5600-edit-delete-races


📝 Commits (2)

  • eaebdd6 fix(storage): serialize message deletes against edits and make the edit's mirror write atomic
  • 591f661 test: make the race regressions deterministic per adversarial review

📊 Changes

2 files changed (+325 additions, -50 deletions)

View changed files

📝 packages/server/src/services/storage/chats.storage.ts (+110 -50)
➕ scripts/regressions/message-edit-delete-races.regression.ts (+215 -0)

📄 Description

Closes #5599. Closes #5600. The two concurrency findings from the #5592 Phase 2 review, fixed together — same file, same family.

#5599 — deletes now take the per-message patch queue

removeMessage and removeMessages were the only per-message mutations not serialized on the per-message patch queue, so a delete landing inside an in-flight edit's await gaps silently dropped the edit into a 404 Message not found. Both now take the queue. The bulk path gets a new withPatchQueues multi-acquire: one shared gate is installed on every affected id's queue synchronously before any await, so two concurrent multi-acquires order themselves strictly and a cycle cannot form (each 500-id chunk acquires and releases independently — cross-chunk atomicity was never promised).

#5600 — the edit's two writes are now one transaction

updateMessageContent wrote the messages row and its active-swipe mirror with awaited gaps between them and no transaction, so a crash — or just the 750 ms debounce flush landing in the window — persisted the edit on the message while the swipe kept the pre-edit text. Invisible in the live chat (the UI reads the message row, and swipe switching heals the pair), but the stale text survived into exports and branched chats. The messages-row write, memory-chunk invalidation, and swipe-mirror write now run inside one db.transaction; the store defers flushes while a transaction is active, so a mid-edit flush produces a consistent pair on disk. The store's transaction is ambient (AsyncLocalStorage), joins nested transactions, and messages/message_swipes are not durable-on-commit tables — so no extra synchronous disk flush lands on the hot edit path.

Adversarial verification (two independent reviewers ran before this PR opened)

They confirmed the fixes sound — reentrancy ruled out for every call path, the multi-acquire cycle-free, rollback restoring all three tables with the #5606 load-heal pairing intact — and caught three things that materially improved this PR:

  1. My original #5600 regression block was vacuous (it passed against the pre-fix code: the poll's macrotask yield drained the whole edit before the flush ran). Rebuilt with deterministic injection at the edit's own internal reads: a flush fired from the outer context in the exact window between the two writes, shard files snapshotted. Verified red pre-fix (the torn pair on disk), green post-fix (the store parks the flush until commit). The edit-vs-delete ordering block got the same treatment.
  2. A latent lock-order hazard, proven by experiment: this PR establishes "message queue → transaction slot" ordering, so a future db.transaction callback that calls a queue-taking message API would deadlock the store (no live path exists today — they checked all 21 transaction call sites). Mitigated the way the repo already handles its metadata-queue ordering: the lock order is now documented on withPatchQueue, and it's stated here for reviewers.
  3. A pre-existing store-level gate window (a plain write racing a transaction's opening can be silently reverted by that transaction's rollback) — not introduced here, filed as #5631.

One reviewer concern analyzed and accepted with a correction: "edits now stall behind long transactions like profile imports." Pre-change, every message write already waited out active transactions at the store's writable gate — the stall is not new; what's new is only that short edit-transactions serialize among themselves, which is negligible.

Validation done

  • New regression lane message-edit-delete-races — four blocks (queue-hold for single and bulk delete, mid-edit delete injection, mid-edit flush tear), each A/B-verified red against pre-fix code
  • Adjacent lanes green: lazy-chat-units, message-sharding (lazy + eager), autonomous-check-storage, open-issues
  • Server typecheck and prettier clean

Manually verify

  • Edit a message and immediately delete it from another tab/device — the edit should either apply-then-delete or the delete wins cleanly, never a spurious 404 mid-save
  • Edit a message, then export the chat and branch it — both must carry the edited text
  • Normal editing/swiping feels unchanged (the transaction adds no synchronous flush)

Summary by CodeRabbit

  • Bug Fixes

    • Improved message editing and deletion reliability during concurrent operations.
    • Ensured message edits and swipe content remain synchronized when saved together.
    • Prevented deletions from overriding or invalidating in-progress edits.
    • Preserved consistency during bulk message updates and deletions.
  • Tests

    • Added regression coverage for message edit/delete race conditions and transactional persistence.

🔄 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/5632 **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/5599-5600-edit-delete-races` --- ### 📝 Commits (2) - [`eaebdd6`](https://github.com/Pasta-Devs/Marinara-Engine/commit/eaebdd6bcc9542879f793bb7840e79944581f6e4) fix(storage): serialize message deletes against edits and make the edit's mirror write atomic - [`591f661`](https://github.com/Pasta-Devs/Marinara-Engine/commit/591f66136bba731a8a396d344ae223ae2ee1ae1b) test: make the race regressions deterministic per adversarial review ### 📊 Changes **2 files changed** (+325 additions, -50 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/services/storage/chats.storage.ts` (+110 -50) ➕ `scripts/regressions/message-edit-delete-races.regression.ts` (+215 -0) </details> ### 📄 Description Closes #5599. Closes #5600. The two concurrency findings from the #5592 Phase 2 review, fixed together — same file, same family. ## #5599 — deletes now take the per-message patch queue `removeMessage` and `removeMessages` were the only per-message mutations not serialized on the per-message patch queue, so a delete landing inside an in-flight edit's await gaps silently dropped the edit into a `404 Message not found`. Both now take the queue. The bulk path gets a new `withPatchQueues` multi-acquire: one shared gate is installed on every affected id's queue **synchronously before any await**, so two concurrent multi-acquires order themselves strictly and a cycle cannot form (each 500-id chunk acquires and releases independently — cross-chunk atomicity was never promised). ## #5600 — the edit's two writes are now one transaction `updateMessageContent` wrote the messages row and its active-swipe mirror with awaited gaps between them and no transaction, so a crash — or just the 750 ms debounce flush landing in the window — persisted the edit on the message while the swipe kept the pre-edit text. Invisible in the live chat (the UI reads the message row, and swipe switching heals the pair), but the stale text survived into **exports and branched chats**. The messages-row write, memory-chunk invalidation, and swipe-mirror write now run inside one `db.transaction`; the store defers flushes while a transaction is active, so a mid-edit flush produces a consistent pair on disk. The store's transaction is ambient (AsyncLocalStorage), joins nested transactions, and `messages`/`message_swipes` are not durable-on-commit tables — so no extra synchronous disk flush lands on the hot edit path. ## Adversarial verification (two independent reviewers ran before this PR opened) They confirmed the fixes sound — reentrancy ruled out for every call path, the multi-acquire cycle-free, rollback restoring all three tables with the #5606 load-heal pairing intact — and caught three things that materially improved this PR: 1. **My original #5600 regression block was vacuous** (it passed against the pre-fix code: the poll's macrotask yield drained the whole edit before the flush ran). Rebuilt with deterministic injection at the edit's own internal reads: a flush fired from the outer context in the exact window between the two writes, shard files snapshotted. Verified red pre-fix (the torn pair on disk), green post-fix (the store parks the flush until commit). The edit-vs-delete ordering block got the same treatment. 2. **A latent lock-order hazard, proven by experiment**: this PR establishes "message queue → transaction slot" ordering, so a future `db.transaction` callback that calls a queue-taking message API would deadlock the store (no live path exists today — they checked all 21 transaction call sites). Mitigated the way the repo already handles its metadata-queue ordering: the lock order is now documented on `withPatchQueue`, and it's stated here for reviewers. 3. **A pre-existing store-level gate window** (a plain write racing a transaction's opening can be silently reverted by that transaction's rollback) — not introduced here, filed as #5631. One reviewer concern analyzed and accepted with a correction: "edits now stall behind long transactions like profile imports." Pre-change, every message *write* already waited out active transactions at the store's writable gate — the stall is not new; what's new is only that short edit-transactions serialize among themselves, which is negligible. ## Validation done - New regression lane `message-edit-delete-races` — four blocks (queue-hold for single and bulk delete, mid-edit delete injection, mid-edit flush tear), each A/B-verified red against pre-fix code - Adjacent lanes green: `lazy-chat-units`, `message-sharding` (lazy + eager), `autonomous-check-storage`, `open-issues` - Server typecheck and prettier clean ## Manually verify - [ ] Edit a message and immediately delete it from another tab/device — the edit should either apply-then-delete or the delete wins cleanly, never a spurious 404 mid-save - [ ] Edit a message, then export the chat and branch it — both must carry the edited text - [ ] Normal editing/swiping feels unchanged (the transaction adds no synchronous flush) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved message editing and deletion reliability during concurrent operations. * Ensured message edits and swipe content remain synchronized when saved together. * Prevented deletions from overriding or invalidating in-progress edits. * Preserved consistency during bulk message updates and deletions. * **Tests** * Added regression coverage for message edit/delete race conditions and transactional persistence. <!-- 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:21 +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#6856
No description provided.