[GH-ISSUE #3402] [Issue]: Long chats stall for seconds after each response completes — O(n²) file-store scans in the post-generation path #1841

Closed
opened 2026-10-21 05:43:10 +07:00 by bsakaguchi · 0 comments
Owner

Originally created by @kolacheee on GitHub (Jul 9, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3402

Originally assigned to: @kolacheee on GitHub.

Summary

In a long chat, after an LLM response has fully streamed onto the screen there is a stall of several seconds — up to ~50 seconds at ~2000 messages (stopwatch-measured) — before the response is flagged complete and the input becomes ready again. The stall grows super-linearly with the chat's total message count, and is independent of prompt size (the reporter runs summaries + a "mark as new start" flag, so only ~100 messages / ~20–30k tokens are sent to the model). So it isn't the model call — it's server-side O(n²) post-generation work on the local machine, dominated by un-indexed full-table scans in the file-native storage backend (the default / installer backend). The user's own diagnosis (local post-processing that scales with total messages, not tokens) is correct; the macro theory is not the cause.

Expected behavior

After the last token streams, the small "finalize" step should be roughly constant-time (or at worst linear in the new message), so a chat with 2000 messages completes as fast as a small chat.

Actual behavior

The gap between "response finished streaming" and "input ready" grows super-linearly with total chat size — a few seconds in a large chat, ~50 s at ~2000 messages (measured twice with a stopwatch). It happens on every response and worsens as the chat grows. It is not the model (all tokens are already on screen); the client is simply blocked waiting for the server's done SSE while the server does quadratic work.

Steps to reproduce

  1. Use the default (file-native) storage backend — the installer default.
  2. Build a long chat (hundreds → thousands of messages; the reporter's worst case is 2000). RP mode with summaries + "new start" flag is the reporter's exact setup, but the hot path runs regardless of mode.
  3. Send a message and stopwatch the gap between the response finishing streaming and the input becoming usable again. It grows super-linearly with total message count, reaching tens of seconds.

Environment

  • Marinara Engine version: 2.1.1 (staging); also observed on earlier versions.
  • Install type: installer (Windows)
  • OS + version: Windows 11
  • Browser or app shell: Chrome
  • Backend: default file-native store (not SQLite)

Logs, screenshots, or video

No error — a UI stall. Reporter measured ~50 s at 2000 messages on two separate responses; prompt was ~30k tokens total (only ~100 messages sent via summaries + new-start).

Additional context

Verified against origin/staging. The client is not the bottleneck: the done SSE handler (packages/client/src/hooks/use-generate.ts:2324) that sets streaming=false / marks input ready is O(1) — it simply blocks on the server's done event (generate.routes.ts:~8050). Everything below runs after the last token and before that done.

Root primitive (the multiplier): the file-native store has no index. SelectQuery.run() maps a contextForRow over every row of the global table before applying the WHERE (packages/server/src/db/file-backed-store.ts:~1546 / the .rows(...).map(...) at ~line 39–42 of the class). So chats.getMessage(id) = db.select().from(messages).where(eq(messages.id, id)) (packages/server/src/services/storage/chats.storage.ts:851-852) is O(total messages), not O(1). And the in operator is evaluated as right.includes(left) (file-backed-store.ts:841), so inArray(messageSwipes.messageId, ids) scans every swipe row × the id array. messages/messageSwipes are single global JSON arrays across all chats.

#1 — O(n²) cachedPrompt eviction loop (runs on every response). packages/server/src/routes/generate.routes.ts:5500-5514:

const allMsgs = await chats.listMessages(input.chatId);                 // O(n^2) (see #2)
const assistantMsgIds = allMsgs.filter((m) => m.role === "assistant").map((m) => m.id);
const staleIds = assistantMsgIds.slice(0, -2);                          // ~n/2 ids
for (const staleId of staleIds) {
  const staleMsg = await chats.getMessage(staleId);                     // O(n) FULL SCAN, each iteration
  if (!staleMsg) continue;
  const staleExtra = typeof staleMsg.extra === "string" ? JSON.parse(staleMsg.extra) : (staleMsg.extra ?? {});
  if (!staleExtra.cachedPrompt) continue;                               // skip is AFTER the scan
  await chats.updateMessageExtra(staleId, { cachedPrompt: null });      // another O(n) scan+write
  ...
}

~n/2 iterations × an O(n) getMessage each = O(n²), on every completed generation (it's inside the always-on if (savedMsg?.id) block, not gated by mode). Critically, the getMessage scan happens before the if (!staleExtra.cachedPrompt) continue early-out, so the whole-table scans run even when there is nothing to evict. At n=2000 that's ~1M+ full-table row materializations per response — the strongest match for the 50 s stall (allocation + GC heavy).

#2 — O(n²) listMessages swipe count (called 2–3× per turn). packages/server/src/services/storage/chats.storage.ts:800-818 builds ids = all n message ids, then inArray(messageSwipes.messageId, ids) just to compute swipeCount. On the file store that's ids.includes(row.messageId) per swipe row over the global messageSwipes table → O(swipeRows × n) ≈ O(n²) per call. It's hit in the eviction path above (:5501) and again by RP auto-summary (runAutomaticRoleplaySummary → listMessages at generate.routes.ts:~5800), which the reporter runs — and it pays the quadratic cost even on turns where no summary fires.

Amplifiers (linear but heavy, same root): every message save re-serializes and atomically rewrites the entire global messages table (file-backed-store.ts saveFileSnapshots ~1505), and each insert does a full-table findDuplicateIndex (~1092) — O(total) per save.

Macro theory does not hold: resolveMacros (macro-engine.ts) is not in the completion hot path, and per-message display macro resolution was already linearized (#3118). The cost here is storage-layer table scans.

Suggested fixes (cheapest first):

  1. Eviction loop — stop re-fetching each stale id: reuse the allMsgs objects already in hand (they carry extra), or, since older messages were evicted on prior turns, evict only the newly-stale (3rd-from-last) assistant message. This removes the dominant O(n²) with a tiny, localized change.
  2. listMessages swipe count — replace the inArray(...ids) predicate with a Set/Map (build a Set of ids and filter, or group messageSwipes by messageId once), and consider skipping swipeCount on the eviction/auto-summary read paths that don't need it.
  3. Gate RP auto-summary's listMessages behind the cheap interval check so no heavy read happens on turns that won't summarize.
  4. Structural (highest leverage, larger blast radius): give the file-native store a primary-key index (Map<id, row>) — and ideally a chatId secondary index — so getMessage/eq/inArray/findDuplicateIndex stop scanning the whole global table. This collapses all the quadratics at once; SQLite-backend users don't hit this because those lookups are indexed.

Note: this is a code-level analysis that matches the reporter's empirical scaling (super-linear, tracks total messages not prompt size, ~50 s at 2000). A server-side CPU/async profile (or timing logs around generate.routes.ts:5500 and listMessages) would confirm the dominant contributor, but the two verified O(n²) paths are strong, deterministic matches.

Template check

  • I DID NOT read this template and provide the requested details.
Originally created by @kolacheee on GitHub (Jul 9, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3402 Originally assigned to: @kolacheee on GitHub. ## Summary In a long chat, after an LLM response has **fully streamed** onto the screen there is a stall of several seconds — up to **~50 seconds at ~2000 messages** (stopwatch-measured) — before the response is flagged complete and the input becomes ready again. The stall grows **super-linearly with the chat's *total* message count**, and is **independent of prompt size** (the reporter runs summaries + a "mark as new start" flag, so only ~100 messages / ~20–30k tokens are sent to the model). So it isn't the model call — it's **server-side O(n²) post-generation work** on the local machine, dominated by **un-indexed full-table scans in the file-native storage backend** (the default / installer backend). The user's own diagnosis (local post-processing that scales with total messages, not tokens) is correct; the macro theory is not the cause. ## Expected behavior After the last token streams, the small "finalize" step should be roughly constant-time (or at worst linear in the *new* message), so a chat with 2000 messages completes as fast as a small chat. ## Actual behavior The gap between "response finished streaming" and "input ready" grows super-linearly with total chat size — a few seconds in a large chat, ~50 s at ~2000 messages (measured twice with a stopwatch). It happens on **every** response and worsens as the chat grows. It is not the model (all tokens are already on screen); the client is simply blocked waiting for the server's `done` SSE while the server does quadratic work. ## Steps to reproduce 1. Use the default (file-native) storage backend — the installer default. 2. Build a long chat (hundreds → thousands of messages; the reporter's worst case is 2000). RP mode with summaries + "new start" flag is the reporter's exact setup, but the hot path runs regardless of mode. 3. Send a message and stopwatch the gap between the response finishing streaming and the input becoming usable again. It grows super-linearly with total message count, reaching tens of seconds. ## Environment - Marinara Engine version: 2.1.1 (staging); also observed on earlier versions. - Install type: installer (Windows) - OS + version: Windows 11 - Browser or app shell: Chrome - Backend: default **file-native** store (not SQLite) ## Logs, screenshots, or video No error — a UI stall. Reporter measured ~50 s at 2000 messages on two separate responses; prompt was ~30k tokens total (only ~100 messages sent via summaries + new-start). ## Additional context Verified against `origin/staging`. The client is not the bottleneck: the `done` SSE handler (`packages/client/src/hooks/use-generate.ts:2324`) that sets `streaming=false` / marks input ready is O(1) — it simply **blocks on the server's `done` event** (`generate.routes.ts:~8050`). Everything below runs after the last token and **before** that `done`. **Root primitive (the multiplier): the file-native store has no index.** `SelectQuery.run()` maps a `contextForRow` over **every row of the global table** before applying the `WHERE` (`packages/server/src/db/file-backed-store.ts:~1546` / the `.rows(...).map(...)` at ~line 39–42 of the class). So `chats.getMessage(id)` = `db.select().from(messages).where(eq(messages.id, id))` (`packages/server/src/services/storage/chats.storage.ts:851-852`) is **O(total messages)**, not O(1). And the `in` operator is evaluated as `right.includes(left)` (`file-backed-store.ts:841`), so `inArray(messageSwipes.messageId, ids)` scans every swipe row × the id array. `messages`/`messageSwipes` are single **global** JSON arrays across all chats. **#1 — O(n²) cachedPrompt eviction loop (runs on every response).** `packages/server/src/routes/generate.routes.ts:5500-5514`: ```js const allMsgs = await chats.listMessages(input.chatId); // O(n^2) (see #2) const assistantMsgIds = allMsgs.filter((m) => m.role === "assistant").map((m) => m.id); const staleIds = assistantMsgIds.slice(0, -2); // ~n/2 ids for (const staleId of staleIds) { const staleMsg = await chats.getMessage(staleId); // O(n) FULL SCAN, each iteration if (!staleMsg) continue; const staleExtra = typeof staleMsg.extra === "string" ? JSON.parse(staleMsg.extra) : (staleMsg.extra ?? {}); if (!staleExtra.cachedPrompt) continue; // skip is AFTER the scan await chats.updateMessageExtra(staleId, { cachedPrompt: null }); // another O(n) scan+write ... } ``` `~n/2` iterations × an O(n) `getMessage` each = **O(n²)**, on every completed generation (it's inside the always-on `if (savedMsg?.id)` block, not gated by mode). Critically, the `getMessage` scan happens **before** the `if (!staleExtra.cachedPrompt) continue` early-out, so the whole-table scans run even when there is nothing to evict. At n=2000 that's ~1M+ full-table row materializations per response — the strongest match for the 50 s stall (allocation + GC heavy). **#2 — O(n²) `listMessages` swipe count (called 2–3× per turn).** `packages/server/src/services/storage/chats.storage.ts:800-818` builds `ids` = all n message ids, then `inArray(messageSwipes.messageId, ids)` just to compute `swipeCount`. On the file store that's `ids.includes(row.messageId)` per swipe row over the global `messageSwipes` table → **O(swipeRows × n) ≈ O(n²)** per call. It's hit in the eviction path above (`:5501`) and again by RP auto-summary (`runAutomaticRoleplaySummary` → `listMessages` at `generate.routes.ts:~5800`), which the reporter runs — and it pays the quadratic cost **even on turns where no summary fires**. **Amplifiers (linear but heavy, same root):** every message save re-serializes and atomically rewrites the **entire global `messages` table** (`file-backed-store.ts saveFileSnapshots ~1505`), and each insert does a full-table `findDuplicateIndex` (`~1092`) — O(total) per save. **Macro theory does not hold:** `resolveMacros` (macro-engine.ts) is not in the completion hot path, and per-message *display* macro resolution was already linearized (#3118). The cost here is storage-layer table scans. **Suggested fixes (cheapest first):** 1. **Eviction loop** — stop re-fetching each stale id: reuse the `allMsgs` objects already in hand (they carry `extra`), or, since older messages were evicted on prior turns, evict only the newly-stale (3rd-from-last) assistant message. This removes the dominant O(n²) with a tiny, localized change. 2. **`listMessages` swipe count** — replace the `inArray(...ids)` predicate with a `Set`/`Map` (build a `Set` of ids and filter, or group `messageSwipes` by `messageId` once), and consider skipping `swipeCount` on the eviction/auto-summary read paths that don't need it. 3. **Gate RP auto-summary's `listMessages`** behind the cheap interval check so no heavy read happens on turns that won't summarize. 4. **Structural (highest leverage, larger blast radius):** give the file-native store a primary-key index (`Map<id, row>`) — and ideally a `chatId` secondary index — so `getMessage`/`eq`/`inArray`/`findDuplicateIndex` stop scanning the whole global table. This collapses all the quadratics at once; SQLite-backend users don't hit this because those lookups are indexed. Note: this is a code-level analysis that matches the reporter's empirical scaling (super-linear, tracks total messages not prompt size, ~50 s at 2000). A server-side CPU/async profile (or timing logs around `generate.routes.ts:5500` and `listMessages`) would confirm the dominant contributor, but the two verified O(n²) paths are strong, deterministic matches. ## Template check - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-21 05:43:10 +07:00
  • closed this issue
  • added the
    in-pr
    bug
    labels
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#1841
No description provided.