[PR #7446] [MERGED] fix(chats): read a long chat's swipes in one batch so exports don't freeze the server #7737

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/7446
Author: @SpicyMarinara
Created: 10/11/2026
Status: ✅ Merged
Merged: 10/12/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/chat-export-freeze


📝 Commits (6)

  • bebe1ed fix(chats): read a long chat's swipes in one batch for export, branch, import and scene fork
  • 94965cb fix(scene): read swipes only for the messages a cut-off scene fork copies
  • f0fdbd2 fix(chats): reuse the batched swipes for receipt targets and the branch prefix
  • 01627ff Merge remote-tracking branch 'origin/staging' into fix/chat-export-freeze
  • 1cb0798 Merge branch 'staging' into fix/chat-export-freeze
  • 01710c9 Merge branch 'staging' into fix/chat-export-freeze

📊 Changes

5 files changed (+232 additions, -9 deletions)

View changed files

📝 CHANGELOG.md (+1 -0)
📝 packages/server/src/routes/chats.routes.ts (+5 -6)
📝 packages/server/src/routes/scene.routes.ts (+7 -1)
📝 packages/server/src/services/storage/chats.storage.ts (+18 -2)
➕ scripts/regressions/chat-export-swipes-batch.regression.ts (+201 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

Closes #7445

Why this change

  • Exporting a very long chat froze the whole server. Other tabs, other users and live replies got no answer until the export finished.
  • Cause: the export read each message's swipes with its own query, and on the file-backed store every such query scans all swipes. The time grew with the square of the message count, and the awaits never let other requests run.
  • Measured over real HTTP (GET /api/chats/:id/export?format=jsonl) on the same seeded data. Half the messages have 2 swipes. Each message has about 500 characters.
Messages Export on staging Ping waited on staging Export with this PR Ping waited with this PR
3,000 1.45 s 1.35 s 0.08 s 0.04 s
12,000 21.5 s 21.4 s 0.29 s 0.17 s
  • Other whole-chat copies had the same per-message read. Measured in-process at 6,000 messages:
Path Staging This PR
Branch 16.9 s 5.1 s
JSONL import 20.6 s 8.9 s

The rest of that time is the batch insert of the copied messages (see "Left as is" below).

What changed

  • chats.storage.ts: new getSwipesByMessageId(ids) reads every swipe once through the existing listSwipesByMessageIds. It groups them per message and sorts each list by index, the same order getSwipes used.
  • serializeChatTranscript (JSONL export, which also serves the bulk ZIP export) reads all swipes in one batch before the message loop.
  • POST /api/chats/:id/branch reads the copied prefix's swipes in one batch. The loop now walks that prefix directly, so the upToMessageId break is gone. The copied set is unchanged.
  • remapRoleplayInterruptionTargets (used by branch and JSONL import) reads the new chat's swipes once and finds receipt targets in that batch. Before, it ran one read per message and one more per receipt. Updates in the loop change only extra, so the swipe ids and indexes it reads stay correct.
  • POST /api/scene/fork reads swipes once for the messages it copies.
  • No setImmediate yields. After the batch read, a 12,000-message JSONL export holds the loop for about 0.12 s warm. The plain-text export, whose code this PR does not change, holds it for 0.06 s on the same chat. Yielding inside the JSONL loop would save at most about 0.06 s, so it was left out.
  • New regression scripts/regressions/chat-export-swipes-batch.regression.ts:
    • A fixture with attachments, three swipes with the middle one active, a hidden message, an interruption receipt, swipes stored out of index order and a message without swipe rows. Its export must match what per-message getSwipes returns for every message. A branch and a JSONL import of it must copy the same swipes in the same order.
    • It counts swipe-table reads for export, branch, JSONL import and scene fork of a 40-message chat and requires fewer than 10 each. Staging needs 42, 83, 41 and 41. With this PR it is 3, 5, 2 and 2. The check uses no timing.
    • It fails on staging and passes with this PR.
  • CHANGELOG.md: one entry under Unreleased.

Left as is (same pattern ruled out or not whole-chat)

  • createMessagesBatch checks uniqueness against every stored row for each inserted row (findUniqueViolation in file-backed-store.ts). This is a store-level insert cost, not a per-message swipe read. It is most of the remaining branch and import time: 4.5 s to insert 6,000 messages into a second chat. It needs its own issue.
  • prepareRoleplayInterruptionExtraForCopy makes one read per interruption receipt, not per message. Receipts are rare.
  • bulkSetHiddenFromAI and its undo, advanced-memory.ts visibility writes, and the cachedPrompt cleanup in generate.routes.ts read swipes per message alongside per-swipe writes on a bounded set. None of them reads a whole chat.
  • Professor Mari history has no per-message swipe read.

Claim boundary (import/export is risky work)

  • Core claim: the same chat produces byte-identical export output, and identical branch, import and scene-fork copies, while swipe reads no longer grow with chat length.
  • Byte-for-byte check against staging. The same seeded data was run on staging and on this branch. The fixture covers attachments, swipes with a middle one active, hidden messages, an interruption receipt and a whisper, swipes stored out of order, a message without swipe rows, swipe extras with thinking and a private note, macros, and a 600-message chat. All 16 outputs were identical:
    • JSONL (default, and with reasoning and private notes), text, Markdown and HTML for both chats
    • JSONL exports of a full branch, a branch cut at a message, a branch of the long chat, a JSONL import, a scene clone, and a scene clone cut at a message, with fresh ids normalized
  • The 3,000 and 12,000-message JSONL exports above were also byte-identical between staging and this branch.
  • Not tested: game-mode segment edits in exports. That code path is unchanged; only where its swipes come from changed. Scene fork in convert mode copies the same way as clone, but only clone was run.

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

Commands run by the agent:

  • pnpm check (exit 0 on the merged branch head)
  • pnpm --filter @marinara-engine/server exec tsc --noEmit -p tsconfig.json
  • node scripts/run-regressions.mjs --filter <file> for: chat-export-swipes-batch (fails on staging, passes here), bulk-export-zips, chat-branch-lineage, chat-story-export, export-budget-413, roleplay-interrupt-storage, scene-package-origin, one-request-dice-branch, message-sharding, message-trash, large-native-json-import, native-export-memory, autonomous-check-storage, capability-gm-verbs, conversation-game-slash, sillytavern-group-import, roleplay-user-private-storage, roleplay-whisper-hidden-recipient, spatial-only-message-visibility, tracker-manual-edit-base, game-inventory-turn, open-issues, persona-api-normalization, assigned-issues-5474-5502, profile-apply-hide-summarised. All passed.
  • Local CodeRabbit (coderabbit review --agent --committed --base-commit <merge-base>), three runs:
    • Run 1 found 1 issue: the scene fork read swipes past an upToMessageId cutoff. Fixed.
    • Run 2 found 4 issues. Fixed: the branch loop now walks the batch's prefix, and receipt targets are found in the batch (reported twice). Also fixed: the read-count check could have counted unrelated reads, so it now uses a bound well below the message count instead of comparing two chat sizes.
    • Run 3 found 0 issues. No findings were dismissed.

Manual verification notes

  • Manually verify in the browser that exporting a long chat (thousands of messages) as JSONL downloads quickly, and that another tab stays responsive while it runs.
  • Manually verify that re-importing that JSONL export keeps every swipe and the selected swipe on each message.
  • Manually verify that Branch from a message in the middle of a long chat copies the messages up to it with all their swipes, and that the selected swipe stays selected.
  • Manually verify that cloning an active scene into its own chat, both whole and from a message, keeps each message's swipes.
  • Manually verify that a Roleplay chat with an interruption still shows the interruption correctly after a branch and after a JSONL export and import.

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.md has an Unreleased entry. No files under docs/ changed.

UI evidence (if applicable)

Not applicable. This is a server-only change.

Summary by CodeRabbit

  • Performance
    • Exporting, branching, importing JSONL chats, and copying scenes is faster for long chats. Exporting a 12,000-message chat now takes under a second, down from about 20 seconds.
    • These operations are less likely to freeze the server or block other tabs and replies.
  • Bug Fixes
    • Chat exports, branches, imports, and scene copies better preserve swipe order and content.

🔄 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/7446 **Author:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Created:** 10/11/2026 **Status:** ✅ Merged **Merged:** 10/12/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/chat-export-freeze` --- ### 📝 Commits (6) - [`bebe1ed`](https://github.com/Pasta-Devs/Marinara-Engine/commit/bebe1ed6fed1fb60cb3dc318792f9ced9ac780c2) fix(chats): read a long chat's swipes in one batch for export, branch, import and scene fork - [`94965cb`](https://github.com/Pasta-Devs/Marinara-Engine/commit/94965cbec339d5121fe7161a23b28c85817540f0) fix(scene): read swipes only for the messages a cut-off scene fork copies - [`f0fdbd2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f0fdbd23e1d34d364310fcb79d9f4560bc5b1485) fix(chats): reuse the batched swipes for receipt targets and the branch prefix - [`01627ff`](https://github.com/Pasta-Devs/Marinara-Engine/commit/01627ffa4cbdf3be59952a4034ed5c2ec6dbafd4) Merge remote-tracking branch 'origin/staging' into fix/chat-export-freeze - [`1cb0798`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1cb0798f756245e1b3d4a116e2520c173935cea3) Merge branch 'staging' into fix/chat-export-freeze - [`01710c9`](https://github.com/Pasta-Devs/Marinara-Engine/commit/01710c994e724c2a770134c038b144b168a74be5) Merge branch 'staging' into fix/chat-export-freeze ### 📊 Changes **5 files changed** (+232 additions, -9 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+1 -0) 📝 `packages/server/src/routes/chats.routes.ts` (+5 -6) 📝 `packages/server/src/routes/scene.routes.ts` (+7 -1) 📝 `packages/server/src/services/storage/chats.storage.ts` (+18 -2) ➕ `scripts/regressions/chat-export-swipes-batch.regression.ts` (+201 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. <!-- See CONTRIBUTING.md § Branches. --> ## Linked issue Closes #7445 ## Why this change - Exporting a very long chat froze the whole server. Other tabs, other users and live replies got no answer until the export finished. - Cause: the export read each message's swipes with its own query, and on the file-backed store every such query scans all swipes. The time grew with the square of the message count, and the awaits never let other requests run. - Measured over real HTTP (`GET /api/chats/:id/export?format=jsonl`) on the same seeded data. Half the messages have 2 swipes. Each message has about 500 characters. | Messages | Export on staging | Ping waited on staging | Export with this PR | Ping waited with this PR | | --- | --- | --- | --- | --- | | 3,000 | 1.45 s | 1.35 s | 0.08 s | 0.04 s | | 12,000 | 21.5 s | 21.4 s | 0.29 s | 0.17 s | - Other whole-chat copies had the same per-message read. Measured in-process at 6,000 messages: | Path | Staging | This PR | | --- | --- | --- | | Branch | 16.9 s | 5.1 s | | JSONL import | 20.6 s | 8.9 s | The rest of that time is the batch insert of the copied messages (see "Left as is" below). ## What changed - `chats.storage.ts`: new `getSwipesByMessageId(ids)` reads every swipe once through the existing `listSwipesByMessageIds`. It groups them per message and sorts each list by index, the same order `getSwipes` used. - `serializeChatTranscript` (JSONL export, which also serves the bulk ZIP export) reads all swipes in one batch before the message loop. - `POST /api/chats/:id/branch` reads the copied prefix's swipes in one batch. The loop now walks that prefix directly, so the `upToMessageId` break is gone. The copied set is unchanged. - `remapRoleplayInterruptionTargets` (used by branch and JSONL import) reads the new chat's swipes once and finds receipt targets in that batch. Before, it ran one read per message and one more per receipt. Updates in the loop change only `extra`, so the swipe ids and indexes it reads stay correct. - `POST /api/scene/fork` reads swipes once for the messages it copies. - No `setImmediate` yields. After the batch read, a 12,000-message JSONL export holds the loop for about 0.12 s warm. The plain-text export, whose code this PR does not change, holds it for 0.06 s on the same chat. Yielding inside the JSONL loop would save at most about 0.06 s, so it was left out. - New regression `scripts/regressions/chat-export-swipes-batch.regression.ts`: - A fixture with attachments, three swipes with the middle one active, a hidden message, an interruption receipt, swipes stored out of index order and a message without swipe rows. Its export must match what per-message `getSwipes` returns for every message. A branch and a JSONL import of it must copy the same swipes in the same order. - It counts swipe-table reads for export, branch, JSONL import and scene fork of a 40-message chat and requires fewer than 10 each. Staging needs 42, 83, 41 and 41. With this PR it is 3, 5, 2 and 2. The check uses no timing. - It fails on staging and passes with this PR. - `CHANGELOG.md`: one entry under Unreleased. ### Left as is (same pattern ruled out or not whole-chat) - `createMessagesBatch` checks uniqueness against every stored row for each inserted row (`findUniqueViolation` in `file-backed-store.ts`). This is a store-level insert cost, not a per-message swipe read. It is most of the remaining branch and import time: 4.5 s to insert 6,000 messages into a second chat. It needs its own issue. - `prepareRoleplayInterruptionExtraForCopy` makes one read per interruption receipt, not per message. Receipts are rare. - `bulkSetHiddenFromAI` and its undo, `advanced-memory.ts` visibility writes, and the `cachedPrompt` cleanup in `generate.routes.ts` read swipes per message alongside per-swipe writes on a bounded set. None of them reads a whole chat. - Professor Mari history has no per-message swipe read. ### Claim boundary (import/export is risky work) - Core claim: the same chat produces byte-identical export output, and identical branch, import and scene-fork copies, while swipe reads no longer grow with chat length. - Byte-for-byte check against staging. The same seeded data was run on staging and on this branch. The fixture covers attachments, swipes with a middle one active, hidden messages, an interruption receipt and a whisper, swipes stored out of order, a message without swipe rows, swipe extras with thinking and a private note, macros, and a 600-message chat. All 16 outputs were identical: - JSONL (default, and with reasoning and private notes), text, Markdown and HTML for both chats - JSONL exports of a full branch, a branch cut at a message, a branch of the long chat, a JSONL import, a scene clone, and a scene clone cut at a message, with fresh ids normalized - The 3,000 and 12,000-message JSONL exports above were also byte-identical between staging and this branch. - Not tested: game-mode segment edits in exports. That code path is unchanged; only where its swipes come from changed. Scene fork in `convert` mode copies the same way as `clone`, but only `clone` was run. ## 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` Commands run by the agent: - `pnpm check` (exit 0 on the merged branch head) - `pnpm --filter @marinara-engine/server exec tsc --noEmit -p tsconfig.json` - `node scripts/run-regressions.mjs --filter <file>` for: `chat-export-swipes-batch` (fails on staging, passes here), `bulk-export-zips`, `chat-branch-lineage`, `chat-story-export`, `export-budget-413`, `roleplay-interrupt-storage`, `scene-package-origin`, `one-request-dice-branch`, `message-sharding`, `message-trash`, `large-native-json-import`, `native-export-memory`, `autonomous-check-storage`, `capability-gm-verbs`, `conversation-game-slash`, `sillytavern-group-import`, `roleplay-user-private-storage`, `roleplay-whisper-hidden-recipient`, `spatial-only-message-visibility`, `tracker-manual-edit-base`, `game-inventory-turn`, `open-issues`, `persona-api-normalization`, `assigned-issues-5474-5502`, `profile-apply-hide-summarised`. All passed. - Local CodeRabbit (`coderabbit review --agent --committed --base-commit <merge-base>`), three runs: - Run 1 found 1 issue: the scene fork read swipes past an `upToMessageId` cutoff. Fixed. - Run 2 found 4 issues. Fixed: the branch loop now walks the batch's prefix, and receipt targets are found in the batch (reported twice). Also fixed: the read-count check could have counted unrelated reads, so it now uses a bound well below the message count instead of comparing two chat sizes. - Run 3 found 0 issues. No findings were dismissed. ### Manual verification notes - Manually verify in the browser that exporting a long chat (thousands of messages) as JSONL downloads quickly, and that another tab stays responsive while it runs. - Manually verify that re-importing that JSONL export keeps every swipe and the selected swipe on each message. - Manually verify that **Branch** from a message in the middle of a long chat copies the messages up to it with all their swipes, and that the selected swipe stays selected. - Manually verify that cloning an active scene into its own chat, both whole and from a message, keeps each message's swipes. - Manually verify that a Roleplay chat with an interruption still shows the interruption correctly after a branch and after a JSONL export and import. ## 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.md` has an Unreleased entry. No files under `docs/` changed. ## UI evidence (if applicable) Not applicable. This is a server-only change. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Performance** * Exporting, branching, importing JSONL chats, and copying scenes is faster for long chats. Exporting a 12,000-message chat now takes under a second, down from about 20 seconds. * These operations are less likely to freeze the server or block other tabs and replies. * **Bug Fixes** * Chat exports, branches, imports, and scene copies better preserve swipe order and content. <!-- 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-24 04:07:00 +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#7737
No description provided.