Repository navigation
feat(server): prune stale thinking and oversized tool outputs on context overflow #1126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dusterbloom
wants to merge
7
commits into
Luce-Org:main
Choose a base branch
from
dusterbloom:feat/server-overflow-context-prune
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
239a469
feat(server): prune stale thinking and oversized tool outputs on cont…
dusterbloom 799a8bc
fix(server): keep reasoning_sent set on stripped turns so TurnMemory …
dusterbloom ae51545
perf(server): make overflow thinking prune prefix-invariant and widen…
dusterbloom a2ec9b5
fix(server): skip oversized agent-turn replay after context prune to …
dusterbloom 38a6811
fix(server): anchor think stripping, suppress TurnMemory echo, and sn…
dusterbloom b795ab6
fix(server): skip PFlash after context prune and preserve Gemma/Qwen3…
dusterbloom 5f2d6f4
fix(server): handle context_pruned in admission and upstream proxy fo…
dusterbloom File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,265 @@ | ||
| // Overflow-only context pruning for multi-turn agent loops. | ||
| // | ||
| // Normal requests (prompt_tokens <= max_prompt_tokens) are untouched, keeping | ||
| // native interleaved thinking (`preserve_thinking=true`) and full prefix cache | ||
| // hit rates. Only when a request would otherwise starve the reply or fail with | ||
| // ContextWindowExceededError do we: | ||
| // 1. Strip stale assistant thinking (`reasoning_content` and `<think>...</think>` | ||
| // blocks inside replayed tool-memory turns) from all historical turns [0, n). | ||
| // Because this is an element-wise prefix homomorphism, [0, prev_n) stays | ||
| // bit-for-bit identical on every subsequent turn (1 transition, 0 jumps). | ||
| // 2. If still over budget, middle-truncate oversized `tool` outputs (UTF-8 safe) | ||
| // at coarse monotonic epochs (up to 128-message / 64-turn stride) while | ||
| // preserving `system` and `user` messages verbatim. | ||
| // | ||
| // Header-only so unit tests compile without a model, backend, or GPU. | ||
| #pragma once | ||
|
|
||
| #include "server/chat_template.h" | ||
|
|
||
| #include <algorithm> | ||
| #include <cstddef> | ||
| #include <functional> | ||
| #include <string> | ||
| #include <vector> | ||
|
|
||
| namespace luce::common { | ||
|
|
||
| struct ContextPruneStats { | ||
| bool pruned = false; | ||
| int thinking_stripped = 0; | ||
| int tools_truncated = 0; | ||
| int raw_tokens = 0; | ||
| int pruned_tokens = 0; | ||
| int cut = 0; | ||
| }; | ||
|
|
||
| namespace context_prune_detail { | ||
|
|
||
| // Deterministic cut boundary snapped downward to multiples of `step` while | ||
| // leaving at least `keep_recent` trailing messages untouched. | ||
| inline int snapped_cut(int n_msgs, int keep_recent, int step = 32) { | ||
| if (n_msgs <= keep_recent || step <= 0) return 0; | ||
| return ((n_msgs - keep_recent) / step) * step; | ||
| } | ||
|
|
||
| // Monotonic coarse stride for Stage 2A tool truncation: 32 -> 64 -> 128 msgs | ||
| // (64 turns per epoch on long sessions) so prefix-cache snapshots stay valid | ||
| // across dozens of turns without skipping Stage 2A on shorter giant-tool runs. | ||
| inline int coarse_tool_cut(int n_msgs, int keep_recent = 8) { | ||
| const int avail = n_msgs - keep_recent; | ||
| if (avail < 32) return 0; | ||
| const int step = avail >= 128 ? 128 : (avail >= 64 ? 64 : 32); | ||
| return snapped_cut(n_msgs, keep_recent, step); | ||
| } | ||
|
|
||
| // Strip `reasoning_content` and any leading `<think>...</think>` (or open-think | ||
| // `...</think>` from replayed tool-memory turns) from an assistant message. | ||
| // Always sets `reasoning_sent = true` so TurnMemory::lookup cannot re-inject | ||
| // remembered reasoning when the client echoed content without reasoning_content. | ||
| inline bool strip_assistant_thinking(ChatMessage & m) { | ||
| if (m.role != "assistant") return false; | ||
| const bool was_reasoning_sent = m.reasoning_sent; | ||
| bool changed = false; | ||
| if (!m.reasoning_content.empty()) { | ||
| // Keep reasoning_sent = true: an empty-but-sent reasoning field makes | ||
| // TurnMemory::lookup miss so the chat codec renders the stripped turn | ||
| // instead of replaying the remembered turn with its original <think>. | ||
| m.reasoning_content.clear(); | ||
| m.reasoning_sent = true; | ||
| changed = true; | ||
| } | ||
| // Strip inline `<think>...</think>` only when the client did not already | ||
| // supply a separate reasoning field (or on raw ToolMemory replay), so a | ||
| // literal `<think>...</think>` example inside visible content is preserved. | ||
| size_t strip_after = std::string::npos; | ||
| if (!was_reasoning_sent || m.tool_calls_replayed) { | ||
| size_t lead = 0; | ||
| while (lead < m.content.size() && | ||
| (m.content[lead] == ' ' || m.content[lead] == '\t' || | ||
| m.content[lead] == '\n' || m.content[lead] == '\r')) { | ||
| ++lead; | ||
| } | ||
| if (m.content.compare(lead, 7, "<think>") == 0) { | ||
| const size_t close = m.content.find("</think>", lead + 7); | ||
| if (close != std::string::npos) strip_after = close + 8; | ||
| } else if (m.tool_calls_replayed) { | ||
| // Open-think raw replay: generation started inside <think>, so the | ||
| // closing tag must appear before any serialized tool call markup. | ||
| const size_t close = m.content.find("</think>"); | ||
| if (close != std::string::npos) { | ||
| const size_t call = std::min({ | ||
| m.content.find("<tool_call>"), | ||
| m.content.find("<|tool_call>"), | ||
| m.content.find("<|call:") | ||
| }); | ||
| if (call == std::string::npos || close < call) { | ||
| strip_after = close + 8; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if (strip_after != std::string::npos) { | ||
| while (strip_after < m.content.size() && | ||
| (m.content[strip_after] == '\n' || m.content[strip_after] == '\r')) { | ||
| ++strip_after; | ||
| } | ||
| m.content.erase(0, strip_after); | ||
| m.reasoning_sent = true; | ||
| changed = true; | ||
| } else if (!m.reasoning_sent && m.content.find("</think>") == std::string::npos) { | ||
| // Client omitted reasoning_content; mark sent-empty so TurnMemory misses | ||
| // if a remembered turn carried non-empty reasoning. Leave reasoning_sent | ||
| // false when content still contains an unstripped `</think>` so Qwen | ||
| // 3.5/3.6's inline `OLD_REASONING</think>VISIBLE` split stays active. | ||
| m.reasoning_sent = true; | ||
| changed = true; | ||
| } | ||
| return changed; | ||
| } | ||
|
|
||
| // Middle-truncate a UTF-8 string longer than `max_chars` to head + marker + tail, | ||
| // never splitting a multi-byte UTF-8 code point. | ||
| inline bool middle_truncate_tool(ChatMessage & m, size_t max_chars, | ||
| size_t head_chars, size_t tail_chars) { | ||
| if (m.role != "tool" || m.content.size() <= max_chars) return false; | ||
| if (head_chars + tail_chars >= m.content.size()) return false; | ||
| size_t head = head_chars; | ||
| while (head > 0 && ((unsigned char)m.content[head] & 0xC0) == 0x80) --head; | ||
| size_t tail_start = m.content.size() - tail_chars; | ||
| while (tail_start < m.content.size() && | ||
| ((unsigned char)m.content[tail_start] & 0xC0) == 0x80) { | ||
| ++tail_start; | ||
| } | ||
| if (tail_start <= head) return false; | ||
| const size_t omitted = tail_start - head; | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| const std::string marker = | ||
| "\n... [" + std::to_string(omitted) + " bytes omitted for context limit] ...\n"; | ||
| if (head + marker.size() + (m.content.size() - tail_start) >= m.content.size()) { | ||
| return false; | ||
| } | ||
| std::string out; | ||
| out.reserve(head + marker.size() + (m.content.size() - tail_start)); | ||
| out.append(m.content, 0, head); | ||
| out.append(marker); | ||
| out.append(m.content, tail_start, m.content.size() - tail_start); | ||
| m.content = std::move(out); | ||
| return true; | ||
| } | ||
|
|
||
| } // namespace context_prune_detail | ||
|
|
||
| // Prune `messages` in place until `render_and_count(messages) <= max_prompt_tokens`, | ||
| // returning stats with `pruned=true` on success. Never modifies `system` or `user` | ||
| // messages; if the prompt still exceeds `max_prompt_tokens`, returns `pruned=false`. | ||
| inline ContextPruneStats prune_messages_to_fit( | ||
| std::vector<ChatMessage> & messages, | ||
| int raw_tokens, | ||
| int max_prompt_tokens, | ||
| const std::function<int(const std::vector<ChatMessage> &)> & render_and_count) { | ||
| ContextPruneStats stats; | ||
| stats.raw_tokens = raw_tokens; | ||
| stats.pruned_tokens = raw_tokens; | ||
| const int n = (int)messages.size(); | ||
| if (raw_tokens <= max_prompt_tokens || max_prompt_tokens <= 0 || n < 2) { | ||
| return stats; | ||
| } | ||
|
|
||
| auto try_fit = [&](int cut) -> bool { | ||
| const int tok = render_and_count(messages); | ||
| if (tok < 0) return false; | ||
| stats.pruned_tokens = tok; | ||
| stats.cut = cut; | ||
| if (tok <= max_prompt_tokens) { | ||
| stats.pruned = true; | ||
| return true; | ||
| } | ||
| return false; | ||
| }; | ||
|
|
||
| // Stage 1: strip stale assistant thinking from all historical messages [0, n). | ||
| // Stripping every completed assistant turn is an element-wise prefix | ||
| // homomorphism: once raw_tokens > max_prompt_tokens, [0, prev_n) renders | ||
| // identically on every subsequent turn, avoiding periodic stride re-prefills | ||
| // and Stage-1A/1B backwards oscillation. | ||
| { | ||
| int stripped = 0; | ||
| for (int i = 0; i < n; ++i) { | ||
| if (context_prune_detail::strip_assistant_thinking(messages[(size_t)i])) { | ||
| ++stripped; | ||
| } | ||
| } | ||
| stats.thinking_stripped += stripped; | ||
| if (stripped > 0 && try_fit(n)) return stats; | ||
| } | ||
|
|
||
| // Snapshot post-Stage-1 messages before Stage 2A mutates tool outputs so | ||
| // Stage 2B always computes its omitted-byte markers from original tool | ||
| // lengths rather than double-truncating Stage 2A's 3 KB outputs across | ||
| // epoch boundaries. | ||
| const std::vector<ChatMessage> after_stage1 = messages; | ||
|
|
||
| // Stage 2A: middle-truncate oversized old `tool` outputs before a coarse | ||
| // deterministic cut (up to 128-message / 64-turn epochs), preserving system, | ||
| // user, and the most recent 8+ messages verbatim. | ||
| const int tool_cut = context_prune_detail::coarse_tool_cut(n, /*keep_recent=*/8); | ||
| if (tool_cut > 0) { | ||
| int trunc = 0; | ||
| for (int i = 0; i < tool_cut; ++i) { | ||
| if (context_prune_detail::middle_truncate_tool(messages[(size_t)i], 4096, 1536, 1536)) { | ||
| ++trunc; | ||
| } | ||
| } | ||
| stats.tools_truncated += trunc; | ||
| if (trunc > 0 && try_fit(tool_cut)) return stats; | ||
| } | ||
|
|
||
| // Stage 2A-fine: if oversized tools accumulated inside the current coarse | ||
| // epoch still overflow, extend the same 4096-byte cap to the 32-message | ||
| // boundary before tightening all older tools to 1024 bytes in Stage 2B. | ||
| // Still monotonic when `coarse_tool_cut` advances (next multiple >= fine_cut). | ||
| const int fine_tool_cut = context_prune_detail::snapped_cut(n, /*keep_recent=*/8, /*step=*/32); | ||
| if (fine_tool_cut > tool_cut) { | ||
| int trunc = 0; | ||
| for (int i = tool_cut; i < fine_tool_cut; ++i) { | ||
| if (context_prune_detail::middle_truncate_tool(messages[(size_t)i], 4096, 1536, 1536)) { | ||
| ++trunc; | ||
| } | ||
| } | ||
| stats.tools_truncated += trunc; | ||
| if (trunc > 0 && try_fit(fine_tool_cut)) return stats; | ||
| } | ||
|
|
||
| // Stage 2B: tighter cap on all non-final tool outputs (keep the very last turn's tool intact). | ||
| // Reset to `after_stage1` so omitted-byte markers reflect original tool sizes | ||
| // and stay invariant across Stage 2A epoch boundaries. | ||
| { | ||
| messages = after_stage1; | ||
| stats.tools_truncated = 0; | ||
| const int lim = std::max(0, n - 2); | ||
| int trunc = 0; | ||
| for (int i = 0; i < lim; ++i) { | ||
| if (context_prune_detail::middle_truncate_tool(messages[(size_t)i], 1024, 448, 448)) { | ||
| ++trunc; | ||
| } | ||
| } | ||
| stats.tools_truncated = trunc; | ||
| if (trunc > 0 && try_fit(lim)) return stats; | ||
| } | ||
|
|
||
| // Stage 2C: last resort for a single huge recent tool output (e.g., accidental giant dump). | ||
| { | ||
| int trunc = 0; | ||
| for (int i = std::max(0, n - 2); i < n; ++i) { | ||
| if (context_prune_detail::middle_truncate_tool(messages[(size_t)i], 8192, 3072, 3072)) { | ||
| ++trunc; | ||
| } | ||
| } | ||
| stats.tools_truncated += trunc; | ||
| if (trunc > 0 && try_fit(n)) return stats; | ||
| } | ||
|
|
||
| return stats; | ||
| } | ||
|
|
||
| } // namespace luce::common | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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_thinkingclearsreasoning_contentand setsreasoning_sent = false(line 53). The pruning candidate is then re-rendered throughHttpServer::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 withinput.memory = &turn_memory_(http_server.cpp:3381) and consultsTurnMemory::lookupfor 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 == falsemakes the reasoning compare a wildcard. Withreasoning_sentforced 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_fitfails, 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 = truewith now-emptyreasoning_contentrequires 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 whenreasoning_contentwas 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
TurnMemorycontract and call sites but not the surrounding replay logic. If every hit path re-renders reasoning from the current message rather than from the rememberedTurn, this would be harmless; theshows_thinkinggate at line 498 (independent of the message'sreasoning_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) replaysgenerated.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.