Skip to content

fix(cheapmodel): raise max_tokens above thinking.budget_tokens on prefix asks - #406

Merged
amiddavid merged 5 commits into
mainfrom
feat/prefixask-thinking-budget
Oct 7, 2026
Merged

amiddavid merged 5 commits into
mainfrom
feat/prefixask-thinking-budget

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Fixes #405.

Summary

CompletePrefixed (the Anthropic Messages leg of a prefix ask — used by
extract_llm_sweep and cache_aware_async's cache_aware_summarizer)
overwrote the stored request body's max_tokens with the fixed
PrefixAskMaxTokens (16000) without checking 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 (live evidence and
full repro in #405).

  • Added thinkingAdjustedMaxTokens(body, reply) in internal/cheapmodel/anthropic.go:
    with thinking.type == "enabled", the outbound max_tokens becomes
    budget_tokens + reply (strictly above the budget for any reply > 0,
    with room left for the actual answer). adaptive, disabled, and no
    thinking block at all pass through unchanged — only "enabled" ties
    max_tokens to a number this call doesn't otherwise know.
  • The thinking block itself is never touched. Per Anthropic's prompt-caching
    docs (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 own
    request already paid to write. proxy/keepalive.go:665-669 already relies
    on the same fact to justify refusing to ping a thinking-enabled session
    rather than editing its thinking block.
  • reply is billed as additional output only if the model actually produces
    that many tokens, same accounting PrefixAskMaxTokens's own doc comment
    already 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 Responses
    API'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_tokens in contradiction of. Left a comment at
    the call site explaining why, instead of a silent no-op.
  • extract_sweep.go and fix(offload): imply block_fallback under debug logging, WARN on ask failure #401 reference cheapmodel.PrefixAskMaxTokens by
    name everywhere, never the literal 16000, so this change doesn't affect
    either.

Test plan

  • TestCompletePrefixedRaisesMaxTokensAboveTheThinkingBudget: reproduces the
    exact failing shape (max_tokens: 32000, thinking.budget_tokens: 31999)
    offline against an httptest server, asserts the outbound max_tokens now
    clears the budget, the thinking block is byte-identical, and the rest of
    the body (model, messages, the appended ask, stream deleted) is
    untouched.
  • TestCompletePrefixedLeavesAdaptiveThinkingUnaffected and
    TestCompletePrefixedLeavesNoThinkingUnaffected: pin the ordinary cases
    (no budget to read) at the unadjusted PrefixAskMaxTokens.
  • TestThinkingAdjustedMaxTokens: unit-level table test on the arithmetic
    itself.
  • Ran on the shared eval box (laptop has no Go toolchain):
    • go build ./... — ok
    • go vet ./internal/cheapmodel/... ./components/offload/... — ok
    • gofmt -l on the changed/added .go files — empty
    • CGO_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)

…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]>
@amiddavid

amiddavid commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Review (updated after running tests and live traffic)

The diagnosis is right. Reading the budget without touching the thinking block is the correct constraint, and live traffic confirms the fix works for Claude Code's default shape. There is one remaining bug, found live: the fix can push max_tokens over the model's output cap, which is a new 400.

What I ran

Tests on the eval box (PR head): go build ./..., go vet, gofmt -l, the new tests with -v (all four ran and passed), and go test -race ./internal/cheapmodel/... ./components/offload/..., all OK. The full go test ./... has two failures, TestInstallRefusesAnUnverifiedDownload and TestInstallReportsPATHFromTheSourceFallbackToo. Both also fail on unmodified main on the same box, because the box has a stale root-owned /usr/local/bin/context-guru-proxy. They are not this PR's.

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, thinking.type: enabled), then calls the real Anthropic.CompletePrefixed over that exact body. I ran it on PR head and on main as the control.

shape (max_tokens / budget_tokens) model main PR head
32000 / 31999 (Claude Code default) claude-haiku-4-5 ask failed (gateway hung for 5 min, no answer) OK, reply YES, cache_read=16230, cache_write=0
32000 / 31999 aws/claude-sonnet-5 ask failed (same hang) OK, cache_read=23436, cache_write=0
64000 / 63999 claude-haiku-4-5 400 max_tokens must be greater than thinking.budget_tokens 400 max_tokens: 79999 > 64000, which is the maximum allowed number of output tokens

cache_write=0 with a full cache_read confirms the property the PR is protecting: changing only max_tokens keeps the agent's cache line. The asks on main hung at the gateway instead of returning the 400 promptly, so they are failures in either case. (sonnet-4-5 and opus-4-6 gave gateway errors on the seed call itself, so they were not exercised.)

1. budget_tokens + reply has no ceiling, so a large thinking budget gets a new 400 (blocking, reproduced live)

thinkingAdjustedMaxTokens returns budget + reply with no upper bound. A session that raises the thinking budget toward the model's limit, such as CLAUDE_CODE_MAX_OUTPUT_TOKENS=64000 with MAX_THINKING_TOKENS=63999 on Haiku 4.5, gets max_tokens: 79999, which the provider rejects (last row above). Every prefix ask on such a session still fails, just with a different message.

The agent's own request already carries a max_tokens that the provider accepted for this model and that already clears the budget. Use it as the ceiling:

	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 // the agent's own value: proven valid for this model, and > budget
	}
	return want

I applied this on top of the PR on the box. Unit tests pass under -race, and the 32000/31999 Haiku shape stays live-OK (cache_read=16230, cache_write=0, reply YES). The live run of the 64000/63999 shape on this patch did not get through: the gateway started timing out even on the seed calls. In that case the patch sends max_tokens: 64000, which is exactly the value the provider accepted on that shape's seed call above. The trade-off is that the reply only gets whatever the thinking leaves of the agent's own max_tokens. Please add a table case with max_tokens in the body, for 64000/63999, asserting a result ≤ 64000 and > 63999.

2. The new function was inserted inside CompletePrefixed's doc comment (should fix)

thinkingAdjustedMaxTokens and its comment sit between the end of CompletePrefixed's long doc block ("…stream is the one exception…") and func (a Anthropic) CompletePrefixed, with no blank line between them. godoc therefore attaches all of the CompletePrefixed documentation (the tool_choice table, the cache-key findings) to the helper, and CompletePrefixed ends up with no doc comment. Move the helper above that doc block, or below the method.

Minor

  • The openai_prefixed.go comment reads like a changelog ("Checked when fixing the Anthropic path's … defect"). A single line saying Responses has no token budget for max_output_tokens to contradict is enough.
  • type: "enabled" with budget_tokens missing falls through as 0 + reply. That's fine; the API would reject such a body anyway.

…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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

What changed

I 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 want

I checked internal/modelinfo first, as asked. It resolves the input
window only (Window/Exact). It has no output-cap field. CompletePrefixed
also takes no components.Ctx, so there is no path to one even if
modelinfo grew one. Adding that is a bigger change, so I used your rule as
the only ceiling for now.

I added the doc comment's trade-off in plain terms: on the capped branch, the
reply allowance shrinks to whatever thinking leaves of the body's own
max_tokens. In the worst case that is close to zero. I did not find a way
to detect a truncated reply (stop_reason: max_tokens) and route it through
a fail-open path in this PR's scope — that would touch the callers
(extract_llm_sweep, cache_aware_summarizer), which is a separate change.
I can open a follow-up issue for it if you want one tracked.

2. Test added

TestCompletePrefixedCapsAtTheBodysOwnMaxTokensWhenWantWouldExceedTheModelsCap
uses your exact shape: max_tokens: 64000, thinking.budget_tokens: 63999.
It asserts the result is <= 64000 and > 63999, and that the thinking
block stays byte-identical. I also added two edge cases to the unit table
test: orig == budget and orig < budget must both fall through to the
uncapped want, since neither is a value the provider has proven valid.

3. Doc comment moved

thinkingAdjustedMaxTokens now sits below CompletePrefixed, with a blank
line before its own comment. CompletePrefixed's doc comment now ends right
above its func line again.

4. Responses comment shortened

One line now: Responses' reasoning control is a qualitative effort level, not
a token budget, so there is no field for max_output_tokens to contradict.

Test results (eval box)

  • go build ./... — ok
  • go vet ./internal/cheapmodel/... ./components/offload/... — ok
  • gofmt -l on the changed files — empty
  • go test ./internal/cheapmodel/... ./components/offload/... — ok
  • go test -race -count=1 ./internal/cheapmodel/... ./components/offload/... — ok (1.805s / 148.489s)

Pushed as 9b1e53a on feat/prefixask-thinking-budget.

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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Result

I added the three items you asked for. All tests pass, including -race.

What changed

  • Truncated reply now fails. The ceiling can leave a reply almost no
    room. If the model still runs out, the provider sets
    stop_reason: "max_tokens". CompletePrefixed now turns that into an
    error. The caller takes its normal failure path: sweep_ask_failed, the
    WARN from fix(offload): imply block_fallback under debug logging, WARN on ask failure #401, then fallback or decline. Usage is still billed, since
    the tokens were spent either way.
  • One more test case. thinking.type: "enabled" with budget_tokens
    missing computes 0 + reply. The API would reject that body on its own.
    The case just states the choice.
  • Model-max-output cap: skipped, as agreed. internal/modelinfo
    resolves the input window only. CompletePrefixed has no path to a
    per-model output cap without new plumbing. Your rule stays the only
    ceiling. The trade-off is in the doc comment.

One more result from your own numbers

On main, the 32000/31999 asks did not return a 400. They hung at the
gateway for 5 minutes. The fix removes that hang too, for that shape: your
table shows it answering in time, with a full cache read and no cache
write.

Test results (eval box)

  • go build ./... — ok
  • go vet — ok
  • gofmt -l on the changed files — empty
  • go test ./internal/cheapmodel/... ./components/offload/... — ok
  • go test -race -count=1 ./internal/cheapmodel/... ./components/offload/... — ok (1.812s / 149.521s)

Pushed as 0c93fe3 on feat/prefixask-thinking-budget.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Follow-up review: commits 9b1e53a and 0c93fe3

Summary: 9b1e53a is good. 0c93fe3 adds a cost regression. I recommend that you revert it. The fault is partly mine: the first version of my comment said a cut-off reply "should be a counted outcome, not a silent one". The sweep already counts it, so no code change was necessary.

What I ran (eval box, PR head 0c93fe3)

  1. go build, go vet, gofmt -l: OK.
  2. New tests with -v: all 6 Anthropic tests pass.
  3. go test -race on internal/cheapmodel, components/offload, internal/extract, proxy: OK.
  4. Live, plain gateway, claude-haiku-4-5, shape 32000 / 31999: OK. Reply YES, cache_read=16230, cache_write=0.
  5. A check of the premise of 0c93fe3 against the real extract.ParseVerdicts (results below).

9b1e53a: ceiling, doc comment, OpenAI comment

  • The ceiling matches the suggestion and its tests cover the edge cases. Good.
  • The doc comment is now in the correct place. Good.
  • One correction to the text. The commit message, the doc comment, and the test comment say that live testing showed max_tokens: 64000 "worked where 79999 did not". That is more than I measured:
    • I measured that the provider accepted max_tokens: 64000 on the agent's own seed call.
    • My live run of the prefix ask with the ceiling at 64000 / 63999 timed out at the gateway. It did not give a result.
    • Please change the text to "64000 is the value the provider accepted on the seed call".

0c93fe3: a cut-off reply is now an error. This is a regression

What we found: a cut-off reply does not parse as a clean verdict. The sweep already detects it and counts it.

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):

  1. Before: a cut-off reply fails to parse → gate sweep_reply_truncated → the sweep declines. No extra cost.
  2. After: CompletePrefixed returns an error → gate sweep_ask_failed → by default runFallback() runs. That is a second, full-price call, with the outputs copied into the prompt.
  3. 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.
  4. The sweep_reply_truncated counter 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.
  5. The new test checks CompletePrefixed alone. 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 unmodified main. 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.

amiddavid added a commit that referenced this pull request Oct 7, 2026
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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Result

I reverted the error path from 0c93fe3. I kept its one useful test
case. I fixed the wording you flagged. I added a small DEBUG signal, no
change to the failure path.

What changed

  • Reverted the truncation error. CompletePrefixed returns the
    clipped reply again, same as before 0c93fe3. The sweep already
    catches a cut-off reply for free: it fails extract.ParseVerdicts,
    which reports ReplyWasTruncated=true, and the sweep declines under
    sweep_reply_truncated with no extra call. The error path routed this
    through sweep_ask_failed instead, which runs a second, full-price
    fallback by default — on every truncated ask, not only the ceiling
    case.
  • Removed TestCompletePrefixedFailsOnATruncatedReply. Kept the
    table case for thinking.type: "enabled" with budget_tokens missing.
    It is unrelated to the reverted behavior.
  • Fixed the wording. The doc comment and the test comment said live
    testing showed max_tokens: 64000 "worked where 79999 did not". That
    claimed more than what you measured. Both now say "64000 is the value
    the provider accepted on the agent's own seed call".
  • Added a DEBUG-only signal. thinkingAdjustedMaxTokens now also
    returns capped bool. CompletePrefixed logs
    cg.cheapmodel.prefixed_ceiling_applied at DEBUG when it fires. No
    change to control flow or the failure path — it is a log line, nothing
    else.

Test results (eval box)

  • go build ./... — ok
  • go vet on internal/cheapmodel, components/offload,
    internal/extract, proxy — ok
  • gofmt -l on the changed files — empty
  • go test on the same four packages — ok
  • go test -race -count=1 on the same four packages — ok
    (1.898s / 155.811s / 2.061s / 359.787s)

Pushed as 739e284 on feat/prefixask-thinking-budget.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Re-review: commit 739e284

Summary: the revert is correct, and the ceiling now works live on 64000 / 63999. I approve, with two small cleanups (not blocking).

What I ran (eval box, PR head 739e284)

  1. go build, go vet, gofmt -l: OK.
  2. go test -race on internal/cheapmodel, components/offload, internal/extract, proxy: OK.
  3. Pass-through check (an extra test, not in the PR): a mocked reply with stop_reason: "max_tokens" and text [{"i":0 comes back as that text, with no error. The sweep then declines it under sweep_reply_truncated, at no extra cost.
  4. Live, plain gateway, claude-haiku-4-5, through the real CompletePrefixed:
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)

  1. A test comment claims coverage that does not exist. The comment in anthropic_prefixed_test.go (where TestCompletePrefixedFailsOnATruncatedReply was) says that the pass-through "is pinned ... in TestCompletePrefixedCapsAtTheBodysOwnMaxTokens…". That test never sends a cut-off reply. So no test stops the 0c93fe3 regression from coming back. Proposal: replace the comment with a positive test. Mock stop_reason: "max_tokens" and assert err == nil and 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.
  2. 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_applied does not change control flow. logging.From falls back to slog.Default(), so a context without a logger is safe.
  • The capped return 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Result

Both cleanups are done. Pushed as 40339d8.

What changed

  • Added TestCompletePrefixedReturnsATruncatedReplyRatherThanAnError. A
    stop_reason: "max_tokens" reply, checked directly: err == nil, the
    clipped text comes back unchanged, usage still billed.
  • Shortened the CompletePrefixed comment to two lines. Replaced the
    matching comment in the test file with the new test above.
  • Updated the three places that said 64000 was "the value the provider
    accepted on the seed call" — the actual live run is now in: OK, reply
    "YES", cache_read=16230, cache_write=0.

Test results (eval box)

  • go build ./... — ok
  • go vet — ok
  • gofmt -l on the changed files — empty
  • go test ./internal/cheapmodel/... ./components/offload/... — ok
  • go test -race -count=1 ./internal/cheapmodel/... ./components/offload/... — ok (1.845s / 148.181s)

@amiddavid
amiddavid merged commit df37564 into main Oct 7, 2026
4 checks passed
amiddavid added a commit that referenced this pull request Oct 7, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 7, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
@amiddavid
amiddavid deleted the feat/prefixask-thinking-budget branch October 8, 2026 11:13
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 11, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

extract_llm_sweep / cache_aware_summarizer prefix ask 400s when thinking.budget_tokens exceeds PrefixAskMaxTokens

1 participant