mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2302] [Issue]: Full prompt assembly runs twice every turn (redundant storage reads, lorebook scan, and embedding round-trips) #1137
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#1137
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 @Romuromylus on GitHub (Jun 5, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2302
Originally assigned to: @SpicyMarinara on GitHub.
Summary
Severity: High — Performance. On the normal (non-
directMessages) generation path,assembleGenerationPromptis invoked twice every turn — once before pre-generation agents and once after, to splice inagentData. Only theagentDatainjection differs, yet the second call redoes all the expensive work from scratch: storage reads, the full lorebook keyword scan, macro/regex passes, and (worst case) the embedding round-trips.Expected behavior
The
agentData-independent work (characters, persona, preset bundle, lorebook scan, summary, memory-recall block, embeddings) should be computed once per turn and reused. When agents are disabled or produced noagentData, the second assembly should be skipped entirely.Actual behavior
src/engine/generation/start-generation.tscallsassembleGenerationPromptat line 2808 (pre-agents) and again at line 2871 (post-agents):directMessagesis null for normal user turns (requestMessagesreturns null unlessinput.messagesis passed, line 913), so the!directMessagesblock runs on essentially every user-driven chat/game turn. The second call is unconditional within that block — when agents are disabled (agentsEnabled = false -> runtime = null) there is no early return, so it still runs withagentData: undefined.Each
assembleGenerationPrompt(prompt-assembly.ts:2833) redoes everything:loadCharacters(2844),loadPersona(2845),loadSelectedPromptPreset(2847, which reads preset + sections + groups + choiceBlocks),scanActiveLorebooksviascanLorebooksForPositions(2889, which runsloadLorebookEntriesForActivationBatch+ the full keyword/semantic scan over every active entry × full history), macro resolution, regex application across history, andbuildMemoryRecallBlock(2892).No cross-call mitigation exists:
memoizedEmbeddingSource(prompt-assembly.ts:1885, used at 2846) allocates a newMap()per assembly call, so its dedup never spans the two calls.llm.embed(llm-api.ts:40) has no cache — every embed is a freshinvoke("llm_embed")round-trip.storage.get/storage.list(storage-api.ts:350/358) have no client-side cache — every call hits the backend/SQLite.So all storage reads, the lorebook scan, and the macro/regex passes run twice per turn. When semantic-lorebook recall and memory recall are enabled, the chat-context embedding (
resolveSemanticChatEmbedding,active-lorebook-scanner.ts:839) and the memory-recall query embedding (buildMemoryRecallBlock,prompt-assembly.ts:1847) are each computed twice — directly on the turn's latency-critical path.Steps to reproduce
input.messages), with agents enabled and a semantic lorebook + memory recall configured.Impact area
Environment
47b16701Logs, screenshots, or video
Static source audit; claims cited to file:line above.
Regression notes
Found via static audit of the refactor branch; not verified against main. The duplicated embedding round-trips are conditional on semantic-lorebook/memory-recall being enabled; with those off it degrades to a duplicated (cheaper) local storage-read + scan pass.
Additional context
Suggested fix: hoist a single per-turn embedding memo (or pass the same
memoizedEmbeddingSourceinstance into both calls) so chat-context and memory-recall embeddings are computed at most once per turn; and/or restructureassembleGenerationPromptto return a reusable intermediate soagentDatacan be injected into an already-built assembly without re-running the expensive stages. Skip the second assembly entirely when agents are disabled or produced noagentData.Template check
Please uncheck the box below before submitting so we know you read the template. It is intentionally pre-checked:
@Romuromylus commented on GitHub (Jun 5, 2026):
Compounds with #2284: when memory recall is enabled, the memory-recall embedding that #2284 flags as blocking every turn is one of the two embedding round-trips that this issue runs twice per turn. Fixing the double-assembly here roughly halves that embed cost; fixing #2284 (defer + incremental + batch) addresses the per-turn blocking. They are best fixed together. Also adjacent: #2285 (lorebook vectorization batching) and #2286 (memory-recall working-set cap).
@SpicyMarinara commented on GitHub (Jun 6, 2026):
Is that a bot spam, what. Anyway, no adding AgentRelay. Let's just reuse what we gather.
@SpicyMarinara commented on GitHub (Jun 6, 2026):
Fixed on
refactorin5775f354.What changed:
Validation:
pnpm typecheckcargo check --manifest-path src-tauri/Cargo.tomlpnpm check:architecturecargo test --manifest-path src-tauri/Cargo.toml -p marinara-engine refresh_chat_memories_reuses_existing_complete_chunksClosing as completed.