[GH-ISSUE #2302] [Issue]: Full prompt assembly runs twice every turn (redundant storage reads, lorebook scan, and embedding round-trips) #1137

Closed
opened 2026-10-21 05:27:40 +07:00 by bsakaguchi · 3 comments
Owner

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, assembleGenerationPrompt is invoked twice every turn — once before pre-generation agents and once after, to splice in agentData. Only the agentData injection 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 no agentData, the second assembly should be skipped entirely.

Actual behavior

src/engine/generation/start-generation.ts calls assembleGenerationPrompt at line 2808 (pre-agents) and again at line 2871 (post-agents):

let assembly = await assembleGenerationPrompt(deps.storage, { chat, storedMessages, connection, ..., embeddingSource: generationEmbeddingSource(deps.llm, connection), ... });
...
assembly = await assembleGenerationPrompt(deps.storage, { ..., agentData: runtime?.agentData, embeddingSource: generationEmbeddingSource(deps.llm, connection), ... });

directMessages is null for normal user turns (requestMessages returns null unless input.messages is passed, line 913), so the !directMessages block 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 with agentData: undefined.

Each assembleGenerationPrompt (prompt-assembly.ts:2833) redoes everything: loadCharacters (2844), loadPersona (2845), loadSelectedPromptPreset (2847, which reads preset + sections + groups + choiceBlocks), scanActiveLorebooks via scanLorebooksForPositions (2889, which runs loadLorebookEntriesForActivationBatch + the full keyword/semantic scan over every active entry × full history), macro resolution, regex application across history, and buildMemoryRecallBlock (2892).

No cross-call mitigation exists:

  • memoizedEmbeddingSource (prompt-assembly.ts:1885, used at 2846) allocates a new Map() per assembly call, so its dedup never spans the two calls.
  • llm.embed (llm-api.ts:40) has no cache — every embed is a fresh invoke("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

  1. Use a normal chat or game turn (no input.messages), with agents enabled and a semantic lorebook + memory recall configured.
  2. Generate a reply.
  3. Observe the full prompt assembly (storage reads, lorebook scan, two embedding round-trips) runs twice for a single turn.

Impact area

  • Chat mode
  • Roleplay mode
  • Game mode
  • Runtime systems: generation, world-state, visuals, tracker, or haptics
  • React-free engine behavior, contracts, agents, or capability ports

Environment

  • Branch or commit: refactor @ 47b16701
  • Run mode: Tauri desktop (same engine in server mode)
  • OS + version: not relevant (static source audit)
  • Node + pnpm versions: not relevant
  • Rust version, if relevant: not relevant
  • Remote Runtime URL configured? not relevant (applies to both)
  • Provider, model, or integration, if relevant: any; impact is largest with a remote embedding provider

Logs, 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 memoizedEmbeddingSource instance into both calls) so chat-context and memory-recall embeddings are computed at most once per turn; and/or restructure assembleGenerationPrompt to return a reusable intermediate so agentData can be injected into an already-built assembly without re-running the expensive stages. Skip the second assembly entirely when agents are disabled or produced no agentData.

Template check

Please uncheck the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
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, `assembleGenerationPrompt` is invoked **twice every turn** — once before pre-generation agents and once after, to splice in `agentData`. Only the `agentData` injection 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 no `agentData`, the second assembly should be skipped entirely. ## Actual behavior `src/engine/generation/start-generation.ts` calls `assembleGenerationPrompt` at **line 2808** (pre-agents) and again at **line 2871** (post-agents): ```ts let assembly = await assembleGenerationPrompt(deps.storage, { chat, storedMessages, connection, ..., embeddingSource: generationEmbeddingSource(deps.llm, connection), ... }); ... assembly = await assembleGenerationPrompt(deps.storage, { ..., agentData: runtime?.agentData, embeddingSource: generationEmbeddingSource(deps.llm, connection), ... }); ``` `directMessages` is null for normal user turns (`requestMessages` returns null unless `input.messages` is passed, line 913), so the `!directMessages` block 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 with `agentData: undefined`. Each `assembleGenerationPrompt` (`prompt-assembly.ts:2833`) redoes everything: `loadCharacters` (2844), `loadPersona` (2845), `loadSelectedPromptPreset` (2847, which reads preset + sections + groups + choiceBlocks), `scanActiveLorebooks` via `scanLorebooksForPositions` (2889, which runs `loadLorebookEntriesForActivationBatch` + the full keyword/semantic scan over every active entry × full history), macro resolution, regex application across history, and `buildMemoryRecallBlock` (2892). No cross-call mitigation exists: - `memoizedEmbeddingSource` (`prompt-assembly.ts:1885`, used at 2846) allocates a **new `Map()` per assembly call**, so its dedup never spans the two calls. - `llm.embed` (`llm-api.ts:40`) has no cache — every embed is a fresh `invoke("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 1. Use a normal chat or game turn (no `input.messages`), with agents enabled and a semantic lorebook + memory recall configured. 2. Generate a reply. 3. Observe the full prompt assembly (storage reads, lorebook scan, two embedding round-trips) runs twice for a single turn. ## Impact area - [x] Chat mode - [x] Roleplay mode - [x] Game mode - [x] Runtime systems: generation, world-state, visuals, tracker, or haptics - [x] React-free engine behavior, contracts, agents, or capability ports ## Environment - Branch or commit: refactor @ 47b16701 - Run mode: Tauri desktop (same engine in server mode) - OS + version: not relevant (static source audit) - Node + pnpm versions: not relevant - Rust version, if relevant: not relevant - Remote Runtime URL configured? not relevant (applies to both) - Provider, model, or integration, if relevant: any; impact is largest with a remote embedding provider ## Logs, 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 `memoizedEmbeddingSource` instance into both calls) so chat-context and memory-recall embeddings are computed at most once per turn; and/or restructure `assembleGenerationPrompt` to return a reusable intermediate so `agentData` can be injected into an already-built assembly without re-running the expensive stages. Skip the second assembly entirely when agents are disabled or produced no `agentData`. ## Template check Please uncheck the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-21 05:27:40 +07:00
Author
Owner

@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).

<!-- gh-comment-id:4630584155 --> @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).
Author
Owner

@SpicyMarinara commented on GitHub (Jun 6, 2026):

Is that a bot spam, what. Anyway, no adding AgentRelay. Let's just reuse what we gather.

<!-- gh-comment-id:4637990650 --> @SpicyMarinara commented on GitHub (Jun 6, 2026): Is that a bot spam, what. Anyway, no adding AgentRelay. Let's just reuse what we gather.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 6, 2026):

Fixed on refactor in 5775f354.

What changed:

  • Prompt assembly now returns a reusable per-turn prompt context.
  • Normal generation skips the second prompt assembly entirely when agents are disabled or produce no prompt data.
  • When agents do produce prompt data, the second pass rebuilds final prompt placement from the cached context instead of repeating character/persona/preset loads, lorebook scans, Memory Recall scoring, regex prep, and embedding lookups.
  • The generation turn now shares one memoized embedding source across prompt assembly and agent runtime.

Validation:

  • pnpm typecheck
  • cargo check --manifest-path src-tauri/Cargo.toml
  • pnpm check:architecture
  • cargo test --manifest-path src-tauri/Cargo.toml -p marinara-engine refresh_chat_memories_reuses_existing_complete_chunks

Closing as completed.

<!-- gh-comment-id:4638053598 --> @SpicyMarinara commented on GitHub (Jun 6, 2026): Fixed on `refactor` in `5775f354`. What changed: - Prompt assembly now returns a reusable per-turn prompt context. - Normal generation skips the second prompt assembly entirely when agents are disabled or produce no prompt data. - When agents do produce prompt data, the second pass rebuilds final prompt placement from the cached context instead of repeating character/persona/preset loads, lorebook scans, Memory Recall scoring, regex prep, and embedding lookups. - The generation turn now shares one memoized embedding source across prompt assembly and agent runtime. Validation: - `pnpm typecheck` - `cargo check --manifest-path src-tauri/Cargo.toml` - `pnpm check:architecture` - `cargo test --manifest-path src-tauri/Cargo.toml -p marinara-engine refresh_chat_memories_reuses_existing_complete_chunks` Closing as completed.
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#1137
No description provided.