Skip to content

Estimate count_tokens locally; resend without reasoning sealed by another account - #238

Merged
fylorn merged 1 commit into
mainfrom
feat/count-tokens-and-reasoning-retry
Sep 29, 2026
Merged

fylorn merged 1 commit into
mainfrom
feat/count-tokens-and-reasoning-retry

Conversation

@fylorn

@fylorn fylorn commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Local token-count estimate

Claude Code calls /v1/messages/count_tokens every turn. Routed to an upstream of another format it used to fail with gw.route.protocol_mismatch, and admission refused it outright when the model was only offered by non-Anthropic upstreams.

  • count_tokens and Gemini :countTokens routed to an upstream of another format are now answered by the gateway with an estimate — nothing is sent to that upstream. A same-format upstream that answers 404/405 (relays that only implement generation) is estimated for as well.
  • New tw_gateway::count: estimates system, messages, tool calls/results and tool definitions (serialized schema); images and files count a fixed 1600 tokens; ASCII counts 4 bytes a token, other characters one token each (so Chinese is not underestimated). Answers {"input_tokens": N} / {"totalTokens": N}, with x-thinkwatch-local: 1.
  • A count never fails over to an upstream of another format nor to a different (rewritten) model; after a 5xx/429 it only moves on to same-format upstreams asking for the same model.
  • Anthropic counting on Bedrock keeps the 501 not_supported Claude Code knows (it then counts precisely itself). gw.count_tokens.bedrock_model is removed: admission now lets counts through for any format, and the per-upstream 501 covers it.
  • Recording: the attempt chain gets a new outcome estimated (with the upstream's 404/405 as status when it was asked); the row is local, cost 0, billing free, so it stays out of the aggregates and token stats. The estimate bypasses relay, so no latency/auth/proxy/quota state is recorded for an upstream that never answered. CONTROL_API_VERSION 29 → 30.

Reasoning sealed by another account

  • New tw_gateway::seal: when an upstream answers 400 refusing sealed reasoning (Responses invalid_encrypted_content / "encrypted content … could not be verified"; Anthropic "Invalid signature in thinking block"), the gateway strips encrypted reasoning items / signed thinking and redacted_thinking blocks and sends to the same upstream once more. Other 400s are passed through untouched.
  • The refused seals (hashes) are remembered per (conversation, upstream) — the same conversation identity affinity uses — in a bounded in-memory map and left out up front on later turns; reasoning the upstream sealed itself still goes along.
  • Anthropic: if stripping leaves the final tool-calling assistant message without its leading thinking block, thinking is dropped for that request (the API requires it otherwise); assistant messages left empty are dropped.
  • Not handled: a refusal that only arrives inside a 200 stream (response.failed). OpenAI rejects it with a 400 before streaming; seal::refusal can be reused if start-of-stream failover wants to cover it.

Tests

  • count / seal unit tests; recorder test for estimated rows.
  • New tests/fallbacks.rs: estimate for another format, for a 404 relay, pass-through when the upstream counts, no failover to another format, Gemini shape, Responses resend + up-front strip on the next turn, unrelated 400 untouched, Anthropic signature resend.
  • Updated conversion.rs and bedrock.rs expectations.

cargo fmt --all, cargo clippy --workspace --all-targets -- -D warnings and cargo test --workspace pass locally.

🤖 Generated with Claude Code

…ther account

Token counting:
- /v1/messages/count_tokens and Gemini :countTokens routed to an upstream
  of another format are answered by the gateway with a local estimate
  (nothing is sent to that upstream); so is a same-format upstream that
  answers 404/405 (relays that only implement generation).
- The estimate covers system, messages, tool calls/results, tool
  definitions; images and files count a fixed 1600 tokens; ASCII counts
  four bytes a token, other characters one token each.
- A count never fails over to an upstream of another format or to a
  different model. Anthropic counting on Bedrock keeps the 501
  not_supported Claude Code knows.
- Model admission lets count_tokens through for any upstream format;
  gw.count_tokens.bedrock_model is gone (the per-upstream 501 covers it).
- The attempt chain gets a new outcome, `estimated`; the row is recorded
  as local, free, and out of the aggregates. CONTROL_API_VERSION 30.

Sealed reasoning:
- When an upstream answers 400 refusing encrypted reasoning another
  account sealed (Responses `invalid_encrypted_content`, Anthropic
  "Invalid `signature` in `thinking` block"), the gateway strips the
  sealed reasoning and sends to the same upstream once more.
- The refused seals are remembered per (conversation, upstream) in a
  bounded in-memory map and left out up front on later turns; reasoning
  the upstream sealed itself still goes along.
- If stripping leaves the final tool-calling assistant turn without its
  leading thinking block, thinking is turned off for that request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fylorn
fylorn force-pushed the feat/count-tokens-and-reasoning-retry branch from 23dbd34 to 4c0b27f Compare September 29, 2026 15:31
@fylorn
fylorn merged commit 2ffb8b3 into main Sep 29, 2026
4 checks passed
@fylorn
fylorn deleted the feat/count-tokens-and-reasoning-retry branch September 29, 2026 15:44
fylorn added a commit that referenced this pull request Sep 29, 2026
- Bump the workspace version to 0.56.0
- release-notes/0.56.0.md

Includes #237 (conversation affinity, route held per turn), #238 (local
token counts, resend without sealed reasoning) and #239 (fail over at the
start of a stream, pause upstreams by the reason they give).

The control-plane protocol goes from 28 to 30; the request store schema
(22) is unchanged. groups[].session_affinity is removed.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant