Repository navigation
fix(cheapmodel): raise max_tokens above thinking.budget_tokens on prefix asks - #406
Conversation
…fix asks CompletePrefixed (the Anthropic Messages leg of a prefix ask) overwrote the stored request body's max_tokens with the fixed PrefixAskMaxTokens (16000) without looking at thinking.budget_tokens already on that body. Claude Code sends max_tokens=32000 with thinking.budget_tokens=31999, so every prefix ask on such a session 400'd: "max_tokens must be greater than thinking.budget_tokens". This broke cache_aware_summarizer on the Anthropic route and is very likely the unrecorded cause of two prior sweep_ask_failed fires, since extract_llm_sweep's adjudication call goes through the same path. The thinking block itself must stay byte-identical: per Anthropic's prompt-caching docs, changing thinking parameters (including the budget) invalidates the cached message prefix, which would defeat the entire point of a prefix ask (proxy/keepalive.go already relies on the same fact to justify refusing to ping a thinking-enabled session). So the fix reads the existing budget rather than editing it: with thinking.type == "enabled", the outbound max_tokens becomes budget_tokens + the existing reply allowance, which clears the invariant while leaving room for the actual answer. "adaptive", "disabled", and no thinking block at all are unaffected, since only "enabled" ties max_tokens to a budget this call doesn't otherwise know. Checked openai_prefixed.go (the Responses leg): the Responses API's reasoning control is a qualitative effort level, not a token budget, so no equivalent fix applies there -- documented why in a comment at the call site. Also checked that extract_llm_sweep and #401 reference PrefixAskMaxTokens by name rather than its literal value, so this change does not affect them. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Review (updated after running tests and live traffic)The diagnosis is right. Reading the budget without touching the What I ranTests on the eval box (PR head): Live traffic went to the plain litellm gateway, not Context Guru. The harness is a build-tagged test that seeds the agent's own request (a cached system block of about 16k tokens,
1.
|
…limit The reviewer found a live bug in the previous commit. budget_tokens + reply has no ceiling. A large thinking budget pushes max_tokens past the model's own output cap. Example: Claude Code with CLAUDE_CODE_MAX_OUTPUT_TOKENS=64000 and MAX_THINKING_TOKENS=63999 on claude-haiku-4-5 computed want=79999. The provider rejected it: "max_tokens: 79999 > 64000, which is the maximum allowed number of output tokens". Same failure class, new message. Fix: when the computed want exceeds the body's own max_tokens, and that max_tokens already clears the thinking budget, use it instead. It is the value the provider already accepted for this exact model on this exact request (the agent's own seed call succeeded with it). The reviewer measured this live: max_tokens: 64000 worked where 79999 did not. Trade-off, now stated in the function's doc comment: on that fallback branch the reply allowance shrinks to whatever thinking leaves of the agent's own max_tokens, as little as ~1 token in the worst case. The alternative is to learn the model's real output cap and use that as the ceiling instead, but nothing in this codebase resolves one reachable from CompletePrefixed: internal/modelinfo resolves the input window, never an output cap, and this method takes no components.Ctx to carry one even if modelinfo grew one. Plumbing that through is future work, not blocking this fix. Also: - Moved thinkingAdjustedMaxTokens below CompletePrefixed, with a blank line separating the two doc comments. It previously sat between the end of CompletePrefixed's doc block and its func line, so godoc attached the whole block to the wrong function and left CompletePrefixed undocumented. - Shortened the openai_prefixed.go comment to one line, per review. - Added a test for the exact 64000/63999 shape (both at the CompletePrefixed level and as a thinkingAdjustedMaxTokens unit case), plus two edge cases: an orig max_tokens equal to or below the budget must not be used as a ceiling. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
What changedI fixed the ceiling bug. I moved the doc comment. I shortened the Responses comment. 1. The ceiling bug (blocking)I used your rule. The code now reads: budget := int(gjson.GetBytes(body, "thinking.budget_tokens").Int())
want := budget + reply
if orig := int(gjson.GetBytes(body, "max_tokens").Int()); orig > budget && orig < want {
return orig
}
return wantI checked I added the doc comment's trade-off in plain terms: on the capped branch, the 2. Test added
3. Doc comment moved
4. Responses comment shortenedOne line now: Responses' reasoning control is a qualitative effort level, not Test results (eval box)
Pushed as |
A prefix ask can still run out of its reply budget on the capped branch added for the ceiling bug. The provider marks this with stop_reason: "max_tokens", not a 400. CompletePrefixed now treats that as an error. A clipped JSON array must not parse as a clean "nothing was spent" verdict. The failure takes the normal path: sweep_ask_failed, the WARN added in #401, then fallback or decline. Usage is still billed, since the tokens were spent either way. Added one more table case: thinking.type "enabled" with budget_tokens missing computes 0 + reply. The API would reject such a body on its own, so this just states the choice instead of leaving it unexplained. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
ResultI added the three items you asked for. All tests pass, including -race. What changed
One more result from your own numbersOn Test results (eval box)
Pushed as |
Follow-up review: commits
|
| reply (cut off) | ParseVerdicts ok |
ReplyWasTruncated |
|---|---|---|
[{"i":0,…,"verdict":"drop"},{"i":1 |
false | true |
{"verdicts":[{"i":0 |
false | true |
Why it matters (components/offload/extract_sweep.go):
- Before: a cut-off reply fails to parse → gate
sweep_reply_truncated→ the sweep declines. No extra cost. - After:
CompletePrefixedreturns an error → gatesweep_ask_failed→ by defaultrunFallback()runs. That is a second, full-price call, with the outputs copied into the prompt. - The change applies to every prefix ask, not only the ceiling case. The sweep's own comment says that cut-off replies were once 70% of calls.
- The
sweep_reply_truncatedcounter no longer fires on this path. It is the counter that tells "raise the budget" apart from "fix the prompt". A cut-off reply now looks like a transport failure. - The new test checks
CompletePrefixedalone. No test covers what the sweep then does, so the extra fallback call is not visible.
Proposal: revert 0c93fe3, but keep its extra table case (enabled with budget_tokens missing). The small reply allowance on the ceiling branch is already counted by sweep_reply_truncated. If you want a signal for the ceiling branch alone, add a counter or a log field for "ceiling applied". Do not change the failure path.
Technical notes
- Box failures in
context-guru-plugin(TestInstallRefusesAnUnverifiedDownload,TestInstallReportsPATHFromTheSourceFallbackToo) also fail on unmodifiedmain. They come from the box's old/usr/local/bin/context-guru-proxy, not from this PR. - I did the live calls on the plain litellm gateway, not through Context Guru.
A model reply can stop early. The model's token budget or thinking budget can run out before the reply ends. The summarizer prompt asks the model to close its reply with a `</summary>` tag. A reply that stops early does not have this tag. Two existing functions hide this problem. sanitizeSummary removes the `</summary>` tag from every reply, because the tag is also a control string an untrusted reply must not forge. ensureSummaryTags then adds the tag back if it is missing. Together, these two steps turn a cut off reply into text that looks complete. The checkpoint built from this text would then replace real history with a fragment. This commit checks the reply for the `</summary>` tag before either of those two functions runs. A reply with no closing tag is now treated as a failed call. The call is counted (cache_aware_summarizer_truncated), logged as a warning, and no checkpoint is written. The turn still forwards the full transcript, exactly as any other failed call does. The check runs on both paths that can produce a checkpoint: the detached async path and the keep-alive substitute path. summarize's own prompt asks for the same tag, so the same risk exists there in theory. This commit does not change summarize. Many of summarize's own tests use reply text with no `</summary>` tag at all, on the strength of ensureSummaryTags' existing, accepted leniency. Adding the same strict check to summarize would break those tests and change a long-shipped contract. That is a separate decision for a separate change, not a shared-helper fix. Also discovered live: the Anthropic prefix-ask response can carry `stop_reason: max_tokens` and no readable reply at all when the model's thinking budget exceeds the ping's old 16000-token cap. #406 fixes that cap. This commit's check is the second, independent guard: even once #406 raises the cap, a reply can still stop early for other reasons, and this check catches that case too. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…style error Follow-up review on commit 0c93fe3 found a cost regression. Reverting the error path; keeping its one useful test case. 0c93fe3 made CompletePrefixed return an error when the provider cuts a reply off (stop_reason: max_tokens). That looked right, but the sweep already handles this for free: a cut-off reply fails to parse, extract.ParseVerdicts reports ReplyWasTruncated=true, and the sweep declines under the sweep_reply_truncated gate with no extra call. Turning it into an error instead routes it through sweep_ask_failed, which runs a second, full-price fallback call by default -- on every truncated ask, not only the ceiling case from 9b1e53a. This component's own comments note cut-off replies were once 70% of calls. The change also hid sweep_reply_truncated, the one counter that tells "raise the budget" apart from "fix the prompt", behind a reading that looks like a transport failure. CompletePrefixed now returns the clipped reply as before, unchanged by this revert. Removed the test that asserted the error path (TestCompletePrefixedFailsOnATruncatedReply); kept 9b1e53a's "enabled with budget_tokens missing" table case, which is unrelated to the reverted behavior. Also, per the same review: corrected the doc comment and test comment that said live testing showed max_tokens: 64000 "worked where 79999 did not". What was actually measured is narrower: the provider accepted 64000 on the agent's own seed call; the prefix ask itself timed out at the gateway before returning a result either way. Both now say "64000 is the value the provider accepted on the seed call". Added a DEBUG-only signal for when thinkingAdjustedMaxTokens's ceiling fires (cg.cheapmodel.prefixed_ceiling_applied), since the review noted there's currently no way to tell that branch apart from the ordinary one. It changes nothing about control flow or the failure path -- thinkingAdjustedMaxTokens now also reports whether it capped, purely so the caller can log it. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
ResultI reverted the error path from What changed
Test results (eval box)
Pushed as |
Re-review: commit
|
shape (max_tokens / budget_tokens) |
result | cache read | cache write |
|---|---|---|---|
| 32000 / 31999 | OK, reply YES |
16230 | 0 |
| 64000 / 63999 (ceiling applies) | OK, reply YES |
16230 | 0 |
This is new: the 64000 / 63999 case now works end to end. My earlier run of it timed out at the gateway. The comments can now say that the ceiling was measured live.
Cleanups (not blocking)
- A test comment claims coverage that does not exist. The comment in
anthropic_prefixed_test.go(whereTestCompletePrefixedFailsOnATruncatedReplywas) says that the pass-through "is pinned ... inTestCompletePrefixedCapsAtTheBodysOwnMaxTokens…". That test never sends a cut-off reply. So no test stops the0c93fe3regression from coming back. Proposal: replace the comment with a positive test. Mockstop_reason: "max_tokens"and asserterr == niland that the clipped text is returned. This is not "a test for the absence of code". It pins the contract that the sweep's free decline needs. My check in step 3 is about 15 lines and you can use it. - Two long comments tell the history of removed code. One is in
CompletePrefixed("A TRUNCATED REPLY IS NOT RETURNED AS AN ERROR HERE…", 14 lines). The other is the test-file comment above. The commit message already has this history. Proposal: keep two lines in the code, for example: "A cut-off reply (stop_reason: max_tokens) is returned as text, not as an error. The sweep detects it and declines at no cost (sweep_reply_truncated). An error here would start a full-price fallback."
Checked, no change needed
- The DEBUG log
cg.cheapmodel.prefixed_ceiling_applieddoes not change control flow.logging.Fromfalls back toslog.Default(), so a context without a logger is safe. - The
cappedreturn value is covered for every row of the table test.
… comments Follow-up review on 739e284. Two cleanups it asked for. Added a real test for the behavior the revert restored. TestCompletePrefixedReturnsATruncatedReplyRatherThanAnError sends a stop_reason: "max_tokens" reply and checks err == nil and the clipped text comes back unchanged. The old comment only pointed at a different test that does not cover this case. Shortened two comments that had grown into history lessons. The CompletePrefixed comment is now two lines. The removed test-file comment is replaced by the new test itself. Also updated three comments that said 64000 was "the value the provider accepted on the seed call". The reviewer has since run the actual prefix ask at 64000/63999 live: OK, reply "YES", cache_read=16230, cache_write=0. The comments now say that. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
ResultBoth cleanups are done. Pushed as What changed
Test results (eval box)
|
Fixes the cache-loss finding from review on #413. insertAskMessage's first version inserted the ask BEFORE a trailing role:"system" message, to satisfy Anthropic's rule that a system message away from index 0 must precede an assistant message or end the array. That fixed the 400, but review measured a worse cost live: Claude Code's own cache_control breakpoint sits ON that trailing system message, and inserting anything before it changes the bytes the provider hashes up to the breakpoint. Live, that version got read=0, write=21,652 -- a full cache write where the whole point of this method is a cheap read. Fixed: leave the system message exactly where it is. When the array's last message is role:"system", append one short synthetic assistant turn ("Understood.") and then the ask, both strictly after the existing array -- nothing before or at the breakpoint moves. Live, this version got read=21,644, write=0: the full entry, read rather than rewritten. Why a synthetic assistant turn: Anthropic's own rule needs the system message followed by an assistant message or ending the array. A second user message would not clear it; "Understood." is the reviewer's own live-tested text (2 of 2 runs). Open question, documented rather than silently assumed: for a thinking.type: "enabled" session (Claude Code's shape on haiku, which PR #406's thinkingAdjustedMaxTokens exists for), Anthropic's docs say "the final assistant turn of a thinking-enabled request" must begin with a thinking block in manual mode. The synthetic turn here carries none. Whether that rule reaches a turn not continuing an active tool-use loop is not settled by the docs text alone. Added a second gated live test for exactly this shape; I could not run it myself -- typing a real API token into a command on this machine is blocked as credential leakage, and the eval box has no credentials of its own either. Rewrote the live test per review: the first call is now a plain POST of the body exactly as the main agent would send it, not a second CompletePrefixed call. The previous version's two calls both went through CompletePrefixed, so the first call's own write WAS the bug under test, and the second call read that already-wrong entry back rather than a real main-agent entry -- a passing test proved nothing. Updated the two comments review named: the "still covers the identical byte prefix" claim at CompletePrefixed's own doc comment, and insertAskMessage's doc comment, now describe the append-after shape and cite the measured numbers for both versions. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
A model reply can stop early. The model's token budget or thinking budget can run out before the reply ends. The summarizer prompt asks the model to close its reply with a `</summary>` tag. A reply that stops early does not have this tag. Two existing functions hide this problem. sanitizeSummary removes the `</summary>` tag from every reply, because the tag is also a control string an untrusted reply must not forge. ensureSummaryTags then adds the tag back if it is missing. Together, these two steps turn a cut off reply into text that looks complete. The checkpoint built from this text would then replace real history with a fragment. This commit checks the reply for the `</summary>` tag before either of those two functions runs. A reply with no closing tag is now treated as a failed call. The call is counted (cache_aware_summarizer_truncated), logged as a warning, and no checkpoint is written. The turn still forwards the full transcript, exactly as any other failed call does. The check runs on both paths that can produce a checkpoint: the detached async path and the keep-alive substitute path. summarize's own prompt asks for the same tag, so the same risk exists there in theory. This commit does not change summarize. Many of summarize's own tests use reply text with no `</summary>` tag at all, on the strength of ensureSummaryTags' existing, accepted leniency. Adding the same strict check to summarize would break those tests and change a long-shipped contract. That is a separate decision for a separate change, not a shared-helper fix. Also discovered live: the Anthropic prefix-ask response can carry `stop_reason: max_tokens` and no readable reply at all when the model's thinking budget exceeds the ping's old 16000-token cap. #406 fixes that cap. This commit's check is the second, independent guard: even once #406 raises the cap, a reply can still stop early for other reasons, and this check catches that case too. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Fixes #405.
Summary
CompletePrefixed(the Anthropic Messages leg of a prefix ask — used byextract_llm_sweepandcache_aware_async'scache_aware_summarizer)overwrote the stored request body's
max_tokenswith the fixedPrefixAskMaxTokens(16000) without checkingthinking.budget_tokensalready on that body. Claude Code sends
max_tokens: 32000withthinking.budget_tokens: 31999, so every prefix ask on such a session 400'd:max_tokens must be greater than thinking.budget_tokens(live evidence andfull repro in #405).
thinkingAdjustedMaxTokens(body, reply)ininternal/cheapmodel/anthropic.go:with
thinking.type == "enabled", the outboundmax_tokensbecomesbudget_tokens + reply(strictly above the budget for anyreply > 0,with room left for the actual answer).
adaptive,disabled, and nothinkingblock at all pass through unchanged — only"enabled"tiesmax_tokensto a number this call doesn't otherwise know.thinkingblock itself is never touched. Per Anthropic's prompt-cachingdocs (https://platform.claude.com/docs/en/build-with-claude/prompt-caching,
"What invalidates the cache"), changing thinking parameters — including the
budget — invalidates the cached message prefix, which would defeat the
entire point of
CompletePrefixed: reading the cache entry the agent's ownrequest already paid to write.
proxy/keepalive.go:665-669already relieson the same fact to justify refusing to ping a thinking-enabled session
rather than editing its thinking block.
replyis billed as additional output only if the model actually producesthat many tokens, same accounting
PrefixAskMaxTokens's own doc commentalready relies on — so there's no cost to leaving it generous.
Scope checked, no change needed
internal/cheapmodel/openai_prefixed.go(the Responses leg): the ResponsesAPI's reasoning control is
reasoning.effort— a qualitative level(low/medium/high/xhigh/max), not a token budget — so there's no field this
call could set
max_output_tokensin contradiction of. Left a comment atthe call site explaining why, instead of a silent no-op.
extract_sweep.goand fix(offload): imply block_fallback under debug logging, WARN on ask failure #401 referencecheapmodel.PrefixAskMaxTokensbyname everywhere, never the literal
16000, so this change doesn't affecteither.
Test plan
TestCompletePrefixedRaisesMaxTokensAboveTheThinkingBudget: reproduces theexact failing shape (
max_tokens: 32000,thinking.budget_tokens: 31999)offline against an
httptestserver, asserts the outboundmax_tokensnowclears the budget, the
thinkingblock is byte-identical, and the rest ofthe body (model, messages, the appended ask,
streamdeleted) isuntouched.
TestCompletePrefixedLeavesAdaptiveThinkingUnaffectedandTestCompletePrefixedLeavesNoThinkingUnaffected: pin the ordinary cases(no budget to read) at the unadjusted
PrefixAskMaxTokens.TestThinkingAdjustedMaxTokens: unit-level table test on the arithmeticitself.
go build ./...— okgo vet ./internal/cheapmodel/... ./components/offload/...— okgofmt -lon the changed/added.gofiles — emptyCGO_ENABLED=1 go test ./internal/cheapmodel/... ./components/offload/...— ok (0.139s / 12.539s)CGO_ENABLED=1 go test -race -count=1 ./internal/cheapmodel/... ./components/offload/...— ok (1.814s / 148.259s)