[PR #3403] [MERGED] perf(chat): remove O(n²) work in the post-generation completion path #5920

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/3403
Author: @kolacheee
Created: 7/9/2026
Status: ✅ Merged
Merged: 7/9/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/3402-completion-stall


📝 Commits (2)

  • 7d2b52d perf(chat): remove O(n^2) work in the post-generation completion path (#3402)
  • 9612781 Merge branch 'staging' into fix/3402-completion-stall

📊 Changes

3 files changed (+39 additions, -30 deletions)

View changed files

📝 CHANGELOG.md (+1 -0)
📝 packages/server/src/routes/generate.routes.ts (+10 -9)
📝 packages/server/src/services/storage/chats.storage.ts (+28 -21)

📄 Description

Linked issue

Closes #3402

Why this change

In a long chat, after a response finished streaming there was a stall — up to ~50 s at 2000 messages (stopwatch-measured) — before it flagged complete and the input became usable again. The stall scaled with total chat size, not prompt size (the reporter capped the prompt at ~30k tokens via summaries + new-start), so it wasn't the model — it was server-side O(n²) work that runs after the last token and gates the done SSE the client waits on. The two quadratics both stem from the un-indexed file-native store (SQLite users, with indexed lookups, weren't affected):

  1. cachedPrompt eviction looped over ~n/2 stale assistant ids calling chats.getMessage(staleId) each, and getMessage is a full-table scan in the file store → n/2 × O(n) = O(n²), on every response.
  2. listMessages / listMessagesPaginated counted swipes with inArray(messageSwipes.messageId, ids), which the file store evaluates as ids.includes() per swipe row (re-materializing the ids array each row) → O(swipeRows × ids) ≈ O(n²), and it's called 2–3× per completion (eviction + RP auto-summary + the client's refetch).

What changed

  • packages/server/src/routes/generate.routes.ts — the eviction loop now iterates the message objects already returned by chats.listMessages() (they carry extra) instead of re-getMessage-ing each stale id. Only messages that still hold a cachedPrompt do the bounded update + swipe cleanup — in steady state that's ~1 per turn. Removes the dominant n/2 × O(n).
  • packages/server/src/services/storage/chats.storage.ts — new countSwipesByMessageId(db, ids) helper: one scan of messageSwipes + a Set of the wanted ids → O(totalSwipes) instead of the inArray O(swipeRows × ids). Used by both listMessages and listMessagesPaginated. (inArray stays imported — it's still used for bounded, chunked game-state deletes.)

Both changes are behavior-preserving — identical swipe counts and identical eviction result. Net effect: the per-response completion cost drops from O(n²) to O(n).

Not addressed here (bigger blast radius, worth follow-ups): the file store's whole-table re-serialize on each save and per-insert findDuplicateIndex are O(total) but not quadratic; the real structural fix is a primary-key index in the file store so point lookups stop scanning the whole table. Filed context is in #3402.

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

Manual verification notes

  • Server typecheck passes: pnpm --filter @marinara-engine/server lint.
  • Manually verify the timing win on a large chat (hundreds–thousands of messages, file-native/default backend): stopwatch the gap between a response finishing streaming and the input becoming usable, before vs. after. It should go from super-linear (tens of seconds at ~2000) to roughly flat/linear.
  • Manually verify no behavior change: swipe indicators/counts still correct in the message list; regenerate/swipe still work; the cachedPrompt eviction still trims older messages (older responses shouldn't retain a stored cachedPrompt).

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

CHANGELOG updated (Fixed). No version bump.

UI evidence (if applicable)

N/A — server-side performance fix; no visual change (removes a stall).


🔄 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/3403 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 7/9/2026 **Status:** ✅ Merged **Merged:** 7/9/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/3402-completion-stall` --- ### 📝 Commits (2) - [`7d2b52d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7d2b52d764379e108e7d1f42b37a06ce2adb89e3) perf(chat): remove O(n^2) work in the post-generation completion path (#3402) - [`9612781`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9612781bd91af1878cb4778f92b04eeb1d2e08de) Merge branch 'staging' into fix/3402-completion-stall ### 📊 Changes **3 files changed** (+39 additions, -30 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+1 -0) 📝 `packages/server/src/routes/generate.routes.ts` (+10 -9) 📝 `packages/server/src/services/storage/chats.storage.ts` (+28 -21) </details> ### 📄 Description ## Linked issue Closes #3402 ## Why this change In a long chat, after a response finished streaming there was a stall — up to **~50 s at 2000 messages** (stopwatch-measured) — before it flagged complete and the input became usable again. The stall scaled with **total chat size, not prompt size** (the reporter capped the prompt at ~30k tokens via summaries + new-start), so it wasn't the model — it was **server-side O(n²) work** that runs after the last token and gates the `done` SSE the client waits on. The two quadratics both stem from the un-indexed file-native store (SQLite users, with indexed lookups, weren't affected): 1. **cachedPrompt eviction** looped over ~n/2 stale assistant ids calling `chats.getMessage(staleId)` each, and `getMessage` is a full-table scan in the file store → `n/2 × O(n)` = **O(n²)**, on every response. 2. **`listMessages` / `listMessagesPaginated`** counted swipes with `inArray(messageSwipes.messageId, ids)`, which the file store evaluates as `ids.includes()` per swipe row (re-materializing the ids array each row) → **O(swipeRows × ids)** ≈ O(n²), and it's called 2–3× per completion (eviction + RP auto-summary + the client's refetch). ## What changed - **`packages/server/src/routes/generate.routes.ts`** — the eviction loop now iterates the message objects already returned by `chats.listMessages()` (they carry `extra`) instead of re-`getMessage`-ing each stale id. Only messages that still hold a `cachedPrompt` do the bounded update + swipe cleanup — in steady state that's ~1 per turn. Removes the dominant `n/2 × O(n)`. - **`packages/server/src/services/storage/chats.storage.ts`** — new `countSwipesByMessageId(db, ids)` helper: one scan of `messageSwipes` + a `Set` of the wanted ids → **O(totalSwipes)** instead of the `inArray` `O(swipeRows × ids)`. Used by both `listMessages` and `listMessagesPaginated`. (`inArray` stays imported — it's still used for bounded, chunked game-state deletes.) Both changes are **behavior-preserving** — identical swipe counts and identical eviction result. Net effect: the per-response completion cost drops from **O(n²) to O(n)**. Not addressed here (bigger blast radius, worth follow-ups): the file store's whole-table re-serialize on each save and per-insert `findDuplicateIndex` are O(total) but not quadratic; the real structural fix is a primary-key index in the file store so point lookups stop scanning the whole table. Filed context is in #3402. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes - Server typecheck passes: `pnpm --filter @marinara-engine/server lint`. - **Manually verify the timing win** on a large chat (hundreds–thousands of messages, file-native/default backend): stopwatch the gap between a response finishing streaming and the input becoming usable, before vs. after. It should go from super-linear (tens of seconds at ~2000) to roughly flat/linear. - **Manually verify no behavior change:** swipe indicators/counts still correct in the message list; regenerate/swipe still work; the cachedPrompt eviction still trims older messages (older responses shouldn't retain a stored `cachedPrompt`). ## Docs and release impact - [ ] No docs changes needed - [x] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) CHANGELOG updated (Fixed). No version bump. ## UI evidence (if applicable) N/A — server-side performance fix; no visual change (removes a stall). --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:05:09 +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#5920
No description provided.