mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #4768] [Feature]: Replace flat entity name injection with a stable, searchable mechanism — reduce noise and enable prompt caching #2627
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#2627
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 @xDanteMD on GitHub (Aug 8, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4768
Originally assigned to: @kolacheee on GitHub.
What problem does this solve?
Professor Mari's conversation mode has two interconnected problems with the
<available_names>block in her system message:Noise at scale: Every generation injects ALL entity names (characters, personas, lorebooks, chats, presets) as a flat, unfiltered list. For users with large collections, this becomes thousands of tokens of context noise that the model cannot meaningfully process.
Cache invalidation: The name list is rebuilt from the DB on every generation (
professor-mari-prompt-context.ts:30-73). Even when no entities change, DB query ordering differences and re-serialization produce a different string, invalidating provider-side prompt caching.Both problems stem from the same design: a flat, dynamically-rebuilt name list injected into the system message on every generation.
Scale of the name list problem
These are comma-separated name lists wrapped in
<available_names>XML blocks — no descriptions, no metadata, just names. The model receives them regardless of whether the user's current conversation involves any of these entities.Cache impact
For a user with 1,000 characters, the system message is ~13,740 tokens. On Anthropic, this means ~13,740 tokens are re-priced on every generation instead of cache-hitting at the reduced rate. Over a conversation with 50 generations, that's ~687,000 tokens of unnecessary full-price billing.
The system message changes between generations because:
DEFAULT_CONVERSATION_PROMPTandMARI_ASSISTANT_PROMPTare stable<available_names>blocks are rebuilt from DB every generation (lines 30-73)<loaded_context>changes when new data is fetched via[fetch:]Why this is a problem
The model already has a fetch mechanism. Mari's
<data_access>instructions already tell her to use[fetch: type="character", name="Luna"]to retrieve full card data. The name list exists so Mari knows what's available to fetch — but a flat list of 1,000 names is not a useful lookup mechanism.No filtering or search. The model receives ALL names regardless of relevance. If the user asks about Luna, the model still sees 999 other character names it doesn't need.
Compounding cost. The noise problem and the caching problem compound each other — large name lists are both wasteful to inject AND wasteful to rebuild.
Proposed solution
Option A: Replace with searchable tool (recommended)
Replace the flat
<available_names>injection with a lightweight search tool that Mari can call when she needs to discover entities:This eliminates both problems: no names in the system message (no noise, no cache invalidation). The existing
[fetch:]command and<data_access>instructions provide the retrieval mechanism; this adds discovery.What already exists and can be reused:
[fetch:]command already retrieves full entity data by name<data_access>instruction block already teaches Mari the fetch patternapp_datatool schema covers CRUD operationschars.list(),lorebooksStore.list(), etc.) already existsWhat would need to be added:
[list_characters]/[search_characters]command handler incharacter-commands.tsOption B: Cap + cache (minimal change)
Keep the
<available_names>blocks but:This reduces noise from ~4,740 tokens to ~240 tokens and ensures cache hits when no entities change. Lower blast radius than Option A.
Option C: Stable prefix isolation
Move
<available_names>and<loaded_context>to separate messages at stable positions. This isolates changing content from stable content (MARI_ASSISTANT_PROMPT, ~9,000 tokens), allowing the provider to cache the stable prefix. The changing blocks would still miss cache, but the stable prefix (~9K tokens) would cache consistently.Recommended: Option A + B combined. Replace the flat list with a searchable tool for new users, with a capped fallback for backward compatibility. Cache the reduced list deterministically.
Alternatives considered
Related issues
assembleGenerationPromptinvoked twice per turn, redoing all expensive work including storage reads and DB queries. The name list rebuild is one instance of this broader redundancy problem.>unnecessarily escaped to>in XML wrap format, wasting tokens on every turn. Same class: token waste in the system prompt.{{context}},{{status}}, etc.). The name list could follow a similar pattern — user-controllable placement and sizing.Additional context
professor-mari-prompt-context.ts:30-34). This is a separate concern from token overhead — the caching problem exists even for small collections where the name list is trivial in size.PeekPromptModalalready shows token estimates per prompt section. A user inspecting their prompt would see the<available_names>block consuming thousands of tokens.WORKSPACE_TOOL_DEFINITIONS) with proper JSON schemas. The pattern for tool-based entity discovery already exists in the codebase.LLMUsageinterface already trackscachedPromptTokensandcacheWritePromptTokens, confirming that provider-side caching is a supported concern.*Research undertaken: codebase analysis of
professor-mari-prompt-context.ts(name list assembly at lines 30-73, full function at lines 20-92),seed-mari.ts(MARI_ASSISTANT_PROMPT, ~9K tokens, 380 lines, data_access instructions),character-commands.ts(existing bracket command handlers, 1,436 lines),workspace-agent.service.ts(WORKSPACE_TOOL_DEFINITIONS, tool definitions and execution loop),generate.routes.ts(conversation system prompt construction at lines 2441-2466),base-provider.ts(LLMUsage interface, cachedPromptTokens field, fitMessagesToContext at lines 395-582). Token estimates based on average entity name lengths (characters: ~12 chars, personas: ~10, lorebooks: ~20, chats: ~30, presets: ~15) with comma separators and XML wrapper overhead. Provider caching behavior verified against Anthropic and OpenAI documentation. Repo-wide search for related issues: #4240 (dynamic blocks break cache), #2302 (double prompt assembly), #2778 (Mari helper functions), #3377/#3380 (identity auto-injection duplication), #3108 (XML escape token waste), #3379/#3438 (placement macros). Prior research documented in github-issues/README.md.@kolacheee commented on GitHub (Aug 8, 2026):
@xDanteMD this FR and #4767 look solid, I will handle them 👍
@kolacheee commented on GitHub (Aug 8, 2026):
Quick note on how this is landing, because the fix comes in two parts and I don't want the first PR to read as the whole answer.
PR #4771 (up now) is the "stop the bleeding" half. It removes the two costs this issue actually measured: it moves the
<available_names>block and fetched data out of the system prefix into a stable tail injection, and dedupes + sorts + caps each list. That kills the per-turn prompt-cache invalidation and the token bloat on large libraries. What it deliberately does not claim to solve is discovery — a capped name list (any size, any ordering) can't help Mari find a character buried past the cap, and it was never going to resolve a fuzzy reference like "my chat with the vampire guy," since there's no name string to match. So please read #4771 as the caching/noise fix, not the discovery fix.The discovery fix is a dedicated follow-up PR, and it's the one that actually addresses the "hundreds of entities" scenario. The plan there is to make Mari's
fetchresolve in tiers instead of demanding an exact name:The good news is the semantic piece isn't from scratch — the engine already runs an embed → cosine-shortlist pipeline in production (it's what powers lorebook-entry matching today, via a zero-config local embedder). The follow-up extends that same machinery to characters, personas, lorebooks, chats, and presets. On a weak/ambiguous match Mari will be shown the actual list of semantic candidates ("I found three vampires — Dracula, Alucard, Vlad — which one?") rather than guessing from an alphabetical slice, and she'll only auto-open a result on a single strong hit.
tl;dr: #4771 fixes the cost, the next PR fixes the finding. Both are aimed at this issue.
@kolacheee commented on GitHub (Aug 9, 2026):
With #4778 and #4779 complete I think that solves the underlying problem so I'll be closing this issue, please do let us know if you have any feedback!