mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #3402] [Issue]: Long chats stall for seconds after each response completes — O(n²) file-store scans in the post-generation path #1841
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#1841
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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
doneSSE while the server does quadratic work.Steps to reproduce
Environment
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: thedoneSSE handler (packages/client/src/hooks/use-generate.ts:2324) that setsstreaming=false/ marks input ready is O(1) — it simply blocks on the server'sdoneevent (generate.routes.ts:~8050). Everything below runs after the last token and before thatdone.Root primitive (the multiplier): the file-native store has no index.
SelectQuery.run()maps acontextForRowover every row of the global table before applying theWHERE(packages/server/src/db/file-backed-store.ts:~1546/ the.rows(...).map(...)at ~line 39–42 of the class). Sochats.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 theinoperator is evaluated asright.includes(left)(file-backed-store.ts:841), soinArray(messageSwipes.messageId, ids)scans every swipe row × the id array.messages/messageSwipesare 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:~n/2iterations × an O(n)getMessageeach = O(n²), on every completed generation (it's inside the always-onif (savedMsg?.id)block, not gated by mode). Critically, thegetMessagescan happens before theif (!staleExtra.cachedPrompt) continueearly-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²)
listMessagesswipe count (called 2–3× per turn).packages/server/src/services/storage/chats.storage.ts:800-818buildsids= all n message ids, theninArray(messageSwipes.messageId, ids)just to computeswipeCount. On the file store that'sids.includes(row.messageId)per swipe row over the globalmessageSwipestable → O(swipeRows × n) ≈ O(n²) per call. It's hit in the eviction path above (:5501) and again by RP auto-summary (runAutomaticRoleplaySummary→listMessagesatgenerate.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
messagestable (file-backed-store.ts saveFileSnapshots ~1505), and each insert does a full-tablefindDuplicateIndex(~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):
allMsgsobjects already in hand (they carryextra), 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.listMessagesswipe count — replace theinArray(...ids)predicate with aSet/Map(build aSetof ids and filter, or groupmessageSwipesbymessageIdonce), and consider skippingswipeCounton the eviction/auto-summary read paths that don't need it.listMessagesbehind the cheap interval check so no heavy read happens on turns that won't summarize.Map<id, row>) — and ideally achatIdsecondary index — sogetMessage/eq/inArray/findDuplicateIndexstop 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:5500andlistMessages) would confirm the dominant contributor, but the two verified O(n²) paths are strong, deterministic matches.Template check