[GH-ISSUE #2612] [Issue]: file-backed-store transaction() rollback restores the whole table map — drops concurrent writes + clones all tables every call #1286

Closed
opened 2026-10-21 05:30:41 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @Romuromylus on GitHub (Jun 18, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2612

Originally assigned to: @Romuromylus on GitHub.

Summary

Severity: Medium — data-loss / concurrency + performance. FileTableStore.transaction() snapshots the entire table map at start and restores all of it on rollback. This (a) silently discards concurrent writes to tables the transaction never touched when the callback throws, and (b) deep-clones every row of all ~43 tables on every call — including the per-agent-turn memory write path — producing O(total-rows) allocation/GC churn on a hot path.

Expected behavior

A transaction rollback should revert only what the transaction changed, and the snapshot it takes for rollback should not clone tables the transaction will never mutate. Concurrent writes committed to unrelated tables during the transaction's await points must survive a rollback.

Actual behavior

transaction() deep-clones the whole table map synchronously at start, then awaits fn(tx), and on any throw reverts wholesale:

// packages/server/src/db/file-backed-store.ts (~848-863)
const tableSnapshot = new Map<string, Row[]>(
  Array.from(this.tables, ([table, rows]) => [table, rows.map((row) => ({ ...row }))]), // clones ALL tables every call
);
try {
  return await fn(tx); // tx === db; ops mutate the SAME live this.tables via microtasks
} catch (err) {
  this.tables = tableSnapshot; // reverts ALL tables, dropping concurrent writes to untouched tables
  throw err;
}

tx is the same db object, and each op resolves on a microtask (Promise.resolve().then(operation)), so every await inside fn yields the event loop. A concurrent non-transactional write (e.g. createMessage in chats.storage.ts:503) committed during that window lands in the live map but not in tableSnapshot, so the wholesale revert silently discards it — the losing request already received a resolved/success value. No mutex/queue serializes writes.

The same snapshot is the perf cost: transaction() is used by agents.storage.setMemories() (wrapped in db.transaction, called per agent turn via PATCH /memory/:agentType/:chatId for director/secret-plot-driver memory), lorebook create/update/remove, chat-folder reorder, and Mari applyPlan. On a profile with a large messages table, every such call shallow-clones every row of every table into a throwaway snapshot.

Steps to reproduce

  1. (Data-loss) During active generation on a chat, have an agent memory write / lorebook update transaction throw (e.g. a duplicate-key insert or post-validation failure) at the same moment another request commits a message/metadata write — observe the just-committed write vanish.
  2. (Perf) On a profile with a large accumulated messages/lorebook_entries dataset, run normal generation with a director/secret-plot agent so setMemories fires per turn — each turn deep-clones the entire dataset.

Environment

  • Marinara Engine version: staging @ 56f700cd (v2.0.0)
  • Install type: source
  • OS + version: n/a — static source audit
  • Browser or app shell: n/a

Logs, screenshots, or video

Static source audit, cited to file:line above.

Additional context

Fix sketch. Make the rollback snapshot lazy/copy-on-write: clone a table only the first time the transaction mutates it (track a dirty set), and on rollback restore only the dirty tables (or the specific rows touched). This fixes both facets at once — an untouched messages table is never cloned (kills the per-call O(total-rows) cost), and concurrent writes to untouched tables survive a rollback (kills the lost-write race). Alternatively, apply transaction mutations to a private working copy merged on success.

Regression notes. Not a regression — transaction() and the executable/op code are byte-identical on main (file-backed-store.ts), and setMemories uses db.transaction on main too. Long-standing behavior on both branches. Distinct from #2528 (flush serialization on the event loop), which is a different code path.

Template check

  • I DID NOT read this template and provide the requested details.
Originally created by @Romuromylus on GitHub (Jun 18, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2612 Originally assigned to: @Romuromylus on GitHub. ## Summary **Severity: Medium — data-loss / concurrency + performance.** `FileTableStore.transaction()` snapshots the **entire** table map at start and restores all of it on rollback. This (a) silently discards concurrent writes to tables the transaction never touched when the callback throws, and (b) deep-clones every row of all ~43 tables on every call — including the per-agent-turn memory write path — producing O(total-rows) allocation/GC churn on a hot path. ## Expected behavior A transaction rollback should revert only what the transaction changed, and the snapshot it takes for rollback should not clone tables the transaction will never mutate. Concurrent writes committed to unrelated tables during the transaction's `await` points must survive a rollback. ## Actual behavior `transaction()` deep-clones the whole table map synchronously at start, then awaits `fn(tx)`, and on any throw reverts wholesale: ```ts // packages/server/src/db/file-backed-store.ts (~848-863) const tableSnapshot = new Map<string, Row[]>( Array.from(this.tables, ([table, rows]) => [table, rows.map((row) => ({ ...row }))]), // clones ALL tables every call ); try { return await fn(tx); // tx === db; ops mutate the SAME live this.tables via microtasks } catch (err) { this.tables = tableSnapshot; // reverts ALL tables, dropping concurrent writes to untouched tables throw err; } ``` `tx` is the same `db` object, and each op resolves on a microtask (`Promise.resolve().then(operation)`), so every `await` inside `fn` yields the event loop. A concurrent non-transactional write (e.g. `createMessage` in `chats.storage.ts:503`) committed during that window lands in the live map but not in `tableSnapshot`, so the wholesale revert silently discards it — the losing request already received a resolved/success value. No mutex/queue serializes writes. The same snapshot is the perf cost: `transaction()` is used by `agents.storage.setMemories()` (wrapped in `db.transaction`, called per agent turn via `PATCH /memory/:agentType/:chatId` for director/secret-plot-driver memory), lorebook create/update/remove, chat-folder reorder, and Mari `applyPlan`. On a profile with a large `messages` table, every such call shallow-clones every row of every table into a throwaway snapshot. ## Steps to reproduce 1. (Data-loss) During active generation on a chat, have an agent memory write / lorebook update transaction throw (e.g. a duplicate-key insert or post-validation failure) at the same moment another request commits a message/metadata write — observe the just-committed write vanish. 2. (Perf) On a profile with a large accumulated `messages`/`lorebook_entries` dataset, run normal generation with a director/secret-plot agent so `setMemories` fires per turn — each turn deep-clones the entire dataset. ## Environment - Marinara Engine version: `staging @ 56f700cd` (v2.0.0) - Install type: source - OS + version: n/a — static source audit - Browser or app shell: n/a ## Logs, screenshots, or video Static source audit, cited to file:line above. ## Additional context **Fix sketch.** Make the rollback snapshot lazy/copy-on-write: clone a table only the first time the transaction mutates it (track a dirty set), and on rollback restore only the dirty tables (or the specific rows touched). This fixes both facets at once — an untouched `messages` table is never cloned (kills the per-call O(total-rows) cost), and concurrent writes to untouched tables survive a rollback (kills the lost-write race). Alternatively, apply transaction mutations to a private working copy merged on success. **Regression notes.** Not a regression — `transaction()` and the executable/op code are byte-identical on `main` (`file-backed-store.ts`), and `setMemories` uses `db.transaction` on `main` too. Long-standing behavior on both branches. Distinct from #2528 (flush serialization on the event loop), which is a different code path. ## Template check - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-21 05:30:41 +07:00
  • closed this issue
  • added the
    server
    bug
    labels
Author
Owner

@Romuromylus commented on GitHub (Jun 18, 2026):

Related to #2613 — same storage-concurrency lost-write family (rollback snapshot here, unqueued updateMetadata there).

<!-- gh-comment-id:4740873674 --> @Romuromylus commented on GitHub (Jun 18, 2026): Related to #2613 — same storage-concurrency lost-write family (rollback snapshot here, unqueued `updateMetadata` there).
Author
Owner

@Romuromylus commented on GitHub (Jun 18, 2026):

Fixed in #2623, merged to staging (e1132e5b). Closing manually since the PR targeted staging rather than the default branch.

<!-- gh-comment-id:4742294131 --> @Romuromylus commented on GitHub (Jun 18, 2026): Fixed in #2623, merged to `staging` (e1132e5b). Closing manually since the PR targeted `staging` rather than the default branch.
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#1286
No description provided.