[PR #4124] [MERGED] Keep single-shot prompts intact when max_tokens eats the context window #6241

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

📋 Pull Request Information

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

Base: staging ← Head: fix/context-fit-drops-single-shot-prompt


📝 Commits (2)

  • 4910777 Keep single-shot prompts intact when max_tokens eats the context window
  • 1c65b43 Merge branch 'staging' into fix/context-fit-drops-single-shot-prompt

📊 Changes

3 files changed (+74 additions, -3 deletions)

View changed files

📝 package.json (+1 -1)
📝 packages/server/src/services/llm/base-provider.ts (+12 -2)
➕ scripts/regressions/context-fit.regression.ts (+61 -0)

📄 Description

Linked issue

Closes #4110

Why this change

A user reported Noodle generating posts with no character cards and no lorebook entries. Their captured request to the model explains why — the prompt body was never sent:

"messages": [
  { "role": "system", "content": "You write a fake social media timeline..." },
  { "role": "user",   "content": "# Content Uniqueness ... # JSON Output Format ..." }
],
"max_tokens": 32768

buildRefreshPrompt returns three messages: system rules, the context body (# Active Noodle Accounts, # Character Profiles, # World / Lore, the timeline), then the JSON-format instruction (noodle-public-prompt.service.ts:621). Only two arrived. The entire context body was deleted in transit, so the model received rules and an output schema with nothing to write about — and invented accounts (user_123, Kaelen_Storm) to fill the void. Those invented handles then failed validateNoodleGeneratedRefresh, so the refresh died two steps downstream with a "no usable response" error that pointed nowhere near the real problem.

The deletion happens in fitMessagesToContext:

  • findOldestRemovableConversationBlock (base-provider.ts:332) skips system messages and protects only the final message (index < messages.length - 1). Everything else is fair game.
  • When no message carries contextKind: "history", the fallback pass at :460 removes unmarked non-system messages anyway. Noodle sets contextKind nowhere, so its context body is the first thing deleted and the trailing instruction is the thing kept.
  • max_tokens is only reduced when the input budget has already fallen to the 128-token floor (:422). Between those two regimes there is a window where the budget is too small for the prompt but too large to trigger the reduction — so the output budget keeps its full value while the prompt is thrown away.

Concretely, a connection storing max_tokens: 32768 against a ~36k context window leaves ~3.3k tokens of input budget. A ~4k-token prompt exceeds it, so the body is deleted and max_tokens stays at 32768 — matching the captured request exactly, including the 1210 prompt tokens the local backend reported.

This is not Noodle-specific. Any single-shot prompt builder — summarizers, one-off generators — has no history to annotate and is exposed the same way.

Why it surfaced now (it is not a recent regression)

This looked like fallout from the recent Noodle work. It isn't — both code ingredients are old:

  • The trimmer preferring prompt deletion over shrinking max_tokens — a747a0cf7 (2026-05-07), "Prefer trimming old history over collapsing completion budget", which introduced the exact inputBudget <= reservedInputFloor gate this PR relaxes.
  • Noodle inheriting the connection's stored max_tokens rather than its own computed budget — 958e5534f (2026-07-16) and the service extraction in 0029d9551 (2026-07-18).

Neither matches the "worked in the morning, broken by evening" report, because the third ingredient is not code — it is prompt size. The body is deleted as soon as context tokens > usableWindow − max_tokens. With max_tokens: 32768 against a ~36k window that threshold sits near 3.3k tokens, and the Noodle context message grows on its own with normal use: the 48h recent-post window (up to 100 posts), recalled older memories, the number of invited characters, and lorebook context all add to it. No deploy is needed to cross the line — only continued use. It also explains the intermittency the reporter saw ("I refreshed a few times"): as the 48h window rolls, the prompt shrinks and grows, so the failure can appear to resolve itself and return.

This is why the bug is invisible on a typical dev setup. A connection with no stored max_tokens override, or a large context window, leaves an input budget of tens of thousands of tokens and never approaches the threshold. The trap is config-shaped, not version-shaped.

Worth stating plainly for planning purposes: the recent Noodle features (recalled memories, character schedules, enhanced timeline writing, lorebook context) are not buggy, but each one makes the prompt richer and therefore moves affected users closer to a threshold that already existed. That argues for the "fail loudly when the prompt cannot fit" follow-up rather than against the features.

What changed

  • base-provider.ts — a prompt with no contextKind: "history" message has nothing that is safe to drop, so the output budget yields instead: the existing max_tokens reduction now also applies when there is no removable history, before any message is deleted. The later fallback passes are untouched, so a prompt that genuinely cannot fit is still handled.
  • Conversations are unaffected. Chat, Game, generate, and Professor Mari all annotate their turns with contextKind: "history", so history trimming still runs first and a large valid response budget does not collapse to the floor.
  • scripts/regressions/context-fit.regression.ts (new, wired into pnpm regression:prompt) — asserts a Noodle-shaped single-shot prompt survives a 36864/32768 squeeze with its body intact and a usable reduced max_tokens; that a roomy window changes nothing; that an annotated conversation still trims history; and that an unconfigured context window touches nothing.

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

  • Manually verify the reported case: on a connection with a large stored max_tokens (e.g. 32768) and a context window only slightly larger, run a Noodle timeline refresh and confirm the outgoing request now contains three messages, with # Character Profiles and # World / Lore present.
  • Manually verify the generated posts reflect character cards and lorebook entries again, instead of generic invented content.
  • Manually verify a long chat conversation still trims oldest history as before and does not lose its system prompt or latest turn.
  • Manually verify a chat with a large max_tokens still returns full-length replies (the response budget should not collapse).
  • Manually verify the server log no longer shows [LLM context] Trimmed prompt ... for a normal Noodle refresh on that connection.

Automated, run locally:

  • pnpm --filter @marinara-engine/server exec tsx ../../scripts/regressions/context-fit.regression.ts — passes with this change, fails without it (verified by reverting base-provider.ts; it fails on "no message may be dropped from a single-shot prompt").
  • pnpm check — passes (one pre-existing unrelated client lint warning, 0 errors).

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

UI evidence (if applicable)


🔄 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/4124 **Author:** [@Gunterlie](https://github.com/Gunterlie) **Created:** 7/26/2026 **Status:** ✅ Merged **Merged:** 7/26/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/context-fit-drops-single-shot-prompt` --- ### 📝 Commits (2) - [`4910777`](https://github.com/Pasta-Devs/Marinara-Engine/commit/4910777eb9f48bd6c5c702d01bc5cb1c03a1787c) Keep single-shot prompts intact when max_tokens eats the context window - [`1c65b43`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1c65b4366ceda54e928089d83f036de027d25a4b) Merge branch 'staging' into fix/context-fit-drops-single-shot-prompt ### 📊 Changes **3 files changed** (+74 additions, -3 deletions) <details> <summary>View changed files</summary> 📝 `package.json` (+1 -1) 📝 `packages/server/src/services/llm/base-provider.ts` (+12 -2) ➕ `scripts/regressions/context-fit.regression.ts` (+61 -0) </details> ### 📄 Description ## Linked issue Closes #4110 ## Why this change A user reported Noodle generating posts with no character cards and no lorebook entries. Their captured request to the model explains why — the prompt body was never sent: ```json "messages": [ { "role": "system", "content": "You write a fake social media timeline..." }, { "role": "user", "content": "# Content Uniqueness ... # JSON Output Format ..." } ], "max_tokens": 32768 ``` `buildRefreshPrompt` returns **three** messages: system rules, the context body (`# Active Noodle Accounts`, `# Character Profiles`, `# World / Lore`, the timeline), then the JSON-format instruction (`noodle-public-prompt.service.ts:621`). Only two arrived. The entire context body was deleted in transit, so the model received rules and an output schema with nothing to write about — and invented accounts (`user_123`, `Kaelen_Storm`) to fill the void. Those invented handles then failed `validateNoodleGeneratedRefresh`, so the refresh died two steps downstream with a "no usable response" error that pointed nowhere near the real problem. The deletion happens in `fitMessagesToContext`: - `findOldestRemovableConversationBlock` (`base-provider.ts:332`) skips system messages and protects only the **final** message (`index < messages.length - 1`). Everything else is fair game. - When no message carries `contextKind: "history"`, the fallback pass at `:460` removes unmarked non-system messages anyway. Noodle sets `contextKind` nowhere, so its context body is the first thing deleted and the trailing instruction is the thing kept. - `max_tokens` is only reduced when the input budget has already fallen to the 128-token floor (`:422`). Between those two regimes there is a window where the budget is too small for the prompt but too large to trigger the reduction — so the output budget keeps its full value while the prompt is thrown away. Concretely, a connection storing `max_tokens: 32768` against a ~36k context window leaves ~3.3k tokens of input budget. A ~4k-token prompt exceeds it, so the body is deleted and `max_tokens` stays at 32768 — matching the captured request exactly, including the 1210 prompt tokens the local backend reported. This is not Noodle-specific. Any single-shot prompt builder — summarizers, one-off generators — has no history to annotate and is exposed the same way. ## Why it surfaced now (it is not a recent regression) This looked like fallout from the recent Noodle work. It isn't — both code ingredients are old: - **The trimmer preferring prompt deletion over shrinking `max_tokens`** — `a747a0cf7` (2026-05-07), *"Prefer trimming old history over collapsing completion budget"*, which introduced the exact `inputBudget <= reservedInputFloor` gate this PR relaxes. - **Noodle inheriting the connection's stored `max_tokens`** rather than its own computed budget — `958e5534f` (2026-07-16) and the service extraction in `0029d9551` (2026-07-18). Neither matches the "worked in the morning, broken by evening" report, because the third ingredient is not code — it is **prompt size**. The body is deleted as soon as `context tokens > usableWindow − max_tokens`. With `max_tokens: 32768` against a ~36k window that threshold sits near 3.3k tokens, and the Noodle context message grows on its own with normal use: the 48h recent-post window (up to 100 posts), recalled older memories, the number of invited characters, and lorebook context all add to it. No deploy is needed to cross the line — only continued use. It also explains the intermittency the reporter saw ("I refreshed a few times"): as the 48h window rolls, the prompt shrinks and grows, so the failure can appear to resolve itself and return. This is why the bug is invisible on a typical dev setup. A connection with no stored `max_tokens` override, or a large context window, leaves an input budget of tens of thousands of tokens and never approaches the threshold. The trap is config-shaped, not version-shaped. Worth stating plainly for planning purposes: the recent Noodle features (recalled memories, character schedules, enhanced timeline writing, lorebook context) are not buggy, but each one makes the prompt richer and therefore moves affected users closer to a threshold that already existed. That argues for the "fail loudly when the prompt cannot fit" follow-up rather than against the features. ## What changed - **`base-provider.ts`** — a prompt with no `contextKind: "history"` message has nothing that is safe to drop, so the output budget yields instead: the existing `max_tokens` reduction now also applies when there is no removable history, before any message is deleted. The later fallback passes are untouched, so a prompt that genuinely cannot fit is still handled. - Conversations are unaffected. Chat, Game, generate, and Professor Mari all annotate their turns with `contextKind: "history"`, so history trimming still runs first and a large valid response budget does not collapse to the floor. - **`scripts/regressions/context-fit.regression.ts`** (new, wired into `pnpm regression:prompt`) — asserts a Noodle-shaped single-shot prompt survives a 36864/32768 squeeze with its body intact and a usable reduced `max_tokens`; that a roomy window changes nothing; that an annotated conversation still trims history; and that an unconfigured context window touches nothing. ## 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 - [ ] Manually verify the reported case: on a connection with a large stored max_tokens (e.g. 32768) and a context window only slightly larger, run a Noodle timeline refresh and confirm the outgoing request now contains three messages, with `# Character Profiles` and `# World / Lore` present. - [ ] Manually verify the generated posts reflect character cards and lorebook entries again, instead of generic invented content. - [ ] Manually verify a long chat conversation still trims oldest history as before and does not lose its system prompt or latest turn. - [ ] Manually verify a chat with a large max_tokens still returns full-length replies (the response budget should not collapse). - [ ] Manually verify the server log no longer shows `[LLM context] Trimmed prompt ...` for a normal Noodle refresh on that connection. Automated, run locally: - `pnpm --filter @marinara-engine/server exec tsx ../../scripts/regressions/context-fit.regression.ts` — passes with this change, fails without it (verified by reverting `base-provider.ts`; it fails on "no message may be dropped from a single-shot prompt"). - `pnpm check` — passes (one pre-existing unrelated client lint warning, 0 errors). ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) ## UI evidence (if applicable) <!-- No UI changes; server-side context fitting only. --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:08:31 +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#6241
No description provided.