Repository navigation
feat(server): prune stale thinking and oversized tool outputs on context overflow - #1126
dusterbloom wants to merge 7 commits into
Conversation
davide221
left a comment
There was a problem hiding this comment.
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 = &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.
<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
- 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
| if (!m.reasoning_content.empty()) { | ||
| m.reasoning_content.clear(); | ||
| m.reasoning_sent = false; | ||
| changed = true; | ||
| } |
There was a problem hiding this comment.
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.
| 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; | |
| } |
There was a problem hiding this comment.
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
…misses and convert tests to CppUnit
…preserve KVFlash pager
Summary
Prevents long tool-calling agent sessions (e.g.
mini-swe-agent 2.2.4on Terminal-Bench 4.0) from failing with HTTP 400ContextWindowExceededErroror starving into tinyfinish=lengthturns when stale<think>reasoning or large tool dumps push a multi-turn conversation pastmax_ctx.Root cause
Models like Qwen3.8-Flash-Next default to
preserve_thinking=trueso normal turns keep interleaved reasoning and 99%+ prefix-cache hit rates. Clients that run long single-userassistant+toolloops without compaction accumulate hundreds of thousands of tokens of oldreasoning_content(e.g.photonic-waveguide-routinghit 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 helperprune_messages_to_fit(...)invoked only whenraw_tokens > max_ctx - min_reply(normal turns are 100% untouched):reasoning_contentand<think>...</think>(including open-think...</think>intool_calls_replayedturns) 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.tooloutputs (UTF-8 boundary safe) at the same deterministic 32-message cut while preservingsystemandusermessages verbatim.ContextWindowExceededError.server/src/server/http_server.cpp: hooksprune_messages_to_fitright afterrender_and_tokenize_requestfor 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