Skip to content

feat(server): prune stale thinking and oversized tool outputs on context overflow - #1126

Open
dusterbloom wants to merge 7 commits into
Luce-Org:mainfrom
dusterbloom:feat/server-overflow-context-prune
Open

dusterbloom wants to merge 7 commits into
Luce-Org:mainfrom
dusterbloom:feat/server-overflow-context-prune

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Prevents long tool-calling agent sessions (e.g. mini-swe-agent 2.2.4 on Terminal-Bench 4.0) from failing with HTTP 400 ContextWindowExceededError or starving into tiny finish=length turns when stale <think> reasoning or large tool dumps push a multi-turn conversation past max_ctx.

Root cause

Models like Qwen3.8-Flash-Next default to preserve_thinking=true so normal turns keep interleaved reasoning and 99%+ prefix-cache hit rates. Clients that run long single-user assistant+tool loops without compaction accumulate hundreds of thousands of tokens of old reasoning_content (e.g. photonic-waveguide-routing hit 262,158 tokens with ~88% stale <think> and only ~30K tokens of actual task/tool content).

What changed (4 files, zero new flags/env vars)

  • server/src/server/context_prune.h: pure header-only helper prune_messages_to_fit(...) invoked only when raw_tokens > max_ctx - min_reply (normal turns are 100% untouched):
    • Stage 1A (cache-stable): strips reasoning_content and <think>...</think> (including open-think ...</think> in tool_calls_replayed turns) strictly before a deterministic 32-message cut (floor((n - 4) / 32) * 32), keeping the recent 4..35 messages' thinking intact and keeping [0, cut) byte-identical across up to 16 consecutive turns so prefix caching immediately re-locks.
    • Stage 1B: if recent thinking alone still overflows, strips remaining historical assistant thinking.
    • Stage 2A/2B/2C: if still over budget, middle-truncates oversized tool outputs (UTF-8 boundary safe) at the same deterministic 32-message cut while preserving system and user messages verbatim.
    • Unprunable single-turn/user overflows still return the exact normal HTTP 400 ContextWindowExceededError.
  • server/src/server/http_server.cpp: hooks prune_messages_to_fit right after render_and_tokenize_request for non-routed, non-multimodal, non-PFlash requests and logs one [server] context-prune ... line when triggered.
  • server/test/unit/test_context_prune.cpp & server/CMakeLists.txt: standalone CPU unit test covering all stages, prefix invariance across consecutive turns, replayed <think>/...</think>, UTF-8 boundary safety, and untouched giant user prompts.

Verification

  • test_context_prune: PASS (-Wall -Wextra -Werror)
  • ctest -R 'test_context_prune|ServerUnitFixture': 573/573 PASS (0 failed)
  • .github/ci/check_commit_messages.py: 1/1 OK

View guided diff

@davide221 davide221 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review

Found 1 issue.

Copy to agent

Use the copy button in the top-right corner of the block, then paste into your agent.

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.

Repository: Luce-Org/lucebox
Reviewed commit: 239a469fcc4120ce87e383e2726f25f7f908db05
Verify the findings against the current code, run relevant checks for any fixes, and explain any findings you reject.

<file name="server/src/server/context_prune.h">

<violation number="1" line="51" end_line="55">
Clearing reasoning_sent lets TurnMemory replay the stripped reasoning, defeating Stage 1 for codec models

`strip_assistant_thinking` clears `reasoning_content` and sets `reasoning_sent = false` (line 53). The pruning candidate is then re-rendered through `HttpServer::render_messages_to_tokens`, which — for the Qwen/DeepSeek chat-codec path this PR targets (Qwen3.8-Flash-Next is the named failing case) — renders with `input.memory = &amp;turn_memory_` (http_server.cpp:3381) and consults `TurnMemory::lookup` for historical assistant turns (chat_codec.cpp:498, 1224, 1582).

`TurnMemory::lookup`'s contract (chat_codec.h:122-126): a remembered turn matches when content and calls are the same and the reasoning is the same, *unless the client sent no reasoning field* — i.e. `reasoning_sent == false` makes the reasoning compare a wildcard. With `reasoning_sent` forced to false, the stripped message is a lookup *hit* against the turn remembered from the previous turn's generation, and a hit replays 'the exact generated tokens in the prompt' (chat_codec.h:88-92) — the turn from the role line on, which for a thinking turn includes the original `&lt;think&gt;` reasoning. So the reasoning the stage just stripped is reinserted by the render, the token count barely drops, `try_fit` fails, and the request falls through to tool truncation and ultimately still returns HTTP 400 — the exact failure this PR exists to fix, in exactly the high-reasoning-accumulation scenario described (stale `&lt;think&gt;` was ~88% of tokens; truncating tool outputs cannot recover that).

To make a stripped turn actually render as-sent (without reasoning), the lookup must *miss*: leaving `reasoning_sent = true` with now-empty `reasoning_content` requires the remembered turn to also have empty reasoning, which it does not, so the codec renders the turn as sent and the prune takes effect. Note that clearing the flag is only reachable when `reasoning_content` was non-empty, which implies the client did send a reasoning field, so the original value was true.

Fact I could not fully check: the exact code path by which each codec (lines 498/1224/1582 in chat_codec.cpp) reassembles the remembered reasoning into the output tokens on a hit — I read the `TurnMemory` contract and call sites but not the surrounding replay logic. If every hit path re-renders reasoning from the current message rather than from the remembered `Turn`, this would be harmless; the `shows_thinking` gate at line 498 (independent of the message's `reasoning_sent`) suggests otherwise.

<suggestion>
    if (!m.reasoning_content.empty()) {
        // Keep reasoning_sent as sent (true): an empty-but-sent reasoning makes
        // TurnMemory::lookup miss, so the codec renders this turn as sent
        // instead of replaying the remembered turn with its original thinking.
        m.reasoning_content.clear();
        changed = true;
    }
</suggestion>
</violation>

</file>
Issue overview
  1. Clearing reasoning_sent lets TurnMemory replay the stripped reasoning, defeating Stage 1 for codec models · likely (server/src/server/context_prune.h:51-55)

Reviewed 239a469f · 2 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again

Comment on lines +51 to +55
if (!m.reasoning_content.empty()) {
m.reasoning_content.clear();
m.reasoning_sent = false;
changed = true;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clearing reasoning_sent lets TurnMemory replay the stripped reasoning, defeating Stage 1 for codec models · likely

strip_assistant_thinking clears reasoning_content and sets reasoning_sent = false (line 53). The pruning candidate is then re-rendered through HttpServer::render_messages_to_tokens, which — for the Qwen/DeepSeek chat-codec path this PR targets (Qwen3.8-Flash-Next is the named failing case) — renders with input.memory = &turn_memory_ (http_server.cpp:3381) and consults TurnMemory::lookup for historical assistant turns (chat_codec.cpp:498, 1224, 1582).

TurnMemory::lookup's contract (chat_codec.h:122-126): a remembered turn matches when content and calls are the same and the reasoning is the same, unless the client sent no reasoning field — i.e. reasoning_sent == false makes the reasoning compare a wildcard. With reasoning_sent forced to false, the stripped message is a lookup hit against the turn remembered from the previous turn's generation, and a hit replays 'the exact generated tokens in the prompt' (chat_codec.h:88-92) — the turn from the role line on, which for a thinking turn includes the original <think> reasoning. So the reasoning the stage just stripped is reinserted by the render, the token count barely drops, try_fit fails, and the request falls through to tool truncation and ultimately still returns HTTP 400 — the exact failure this PR exists to fix, in exactly the high-reasoning-accumulation scenario described (stale <think> was ~88% of tokens; truncating tool outputs cannot recover that).

To make a stripped turn actually render as-sent (without reasoning), the lookup must miss: leaving reasoning_sent = true with now-empty reasoning_content requires the remembered turn to also have empty reasoning, which it does not, so the codec renders the turn as sent and the prune takes effect. Note that clearing the flag is only reachable when reasoning_content was non-empty, which implies the client did send a reasoning field, so the original value was true.

Fact I could not fully check: the exact code path by which each codec (lines 498/1224/1582 in chat_codec.cpp) reassembles the remembered reasoning into the output tokens on a hit — I read the TurnMemory contract and call sites but not the surrounding replay logic. If every hit path re-renders reasoning from the current message rather than from the remembered Turn, this would be harmless; the shows_thinking gate at line 498 (independent of the message's reasoning_sent) suggests otherwise.

Checked (85%): Confirmed: TurnMemory::lookup (chat_codec.cpp:142) only rejects a remembered turn when reasoning_sent && reasoning differs, so clearing reasoning_sent in strip_assistant_thinking (context_prune.h:53) makes the stripped message a wildcard hit; the hit path (chat_codec.cpp:498-506) replays generated.text — the turn as generated, including its original <think> reasoning — and the prune re-render does run with input.memory set (http_server.cpp:3361, 3721-3728). Since the key (chat_codec.cpp:101-117) excludes reasoning, the stripped message still matches, so the stripped reasoning is reinserted and Stage 1 fails to reduce tokens in exactly the Qwen thinking-accumulation scenario the PR targets. Remaining uncertainty is only whether w.generated always emits the remembered reasoning tokens, which the Turn contract (chat_codec.h:88-108) strongly indicates.

Suggested change
if (!m.reasoning_content.empty()) {
m.reasoning_content.clear();
m.reasoning_sent = false;
changed = true;
}
if (!m.reasoning_content.empty()) {
// Keep reasoning_sent as sent (true): an empty-but-sent reasoning makes
// TurnMemory::lookup miss, so the codec renders this turn as sent
// instead of replaying the remembered turn with its original thinking.
m.reasoning_content.clear();
changed = true;
}

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files

Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.

View guided diff | Re-trigger cubic

Comment thread server/src/server/context_prune.h Resolved
Comment thread server/test/unit/test_context_prune.cpp Resolved
Comment thread server/test/unit/test_context_prune.cpp Resolved
Comment thread server/CMakeLists.txt Resolved
Comment thread server/src/server/context_prune.h Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants