gateway: a reply of several requests tells the last one's prompt, bills them all

Claude Code reads a reply's input, cache_creation and cache_read as how
full its conversation is. A reply more than one upstream request made
summed all three across them. In the bridge: Claude Code's own
ToolSearch/WebSearch going on into the answering message, a TUI message
written after its call was told (lateUsage), a cut stream's retry
(b42ff722). Each later request re-sends what the earlier one had, so the
reporter's TaskStop reply after a ToolSearch said cache_read 1,154,857
(577,009 + 577,848) and cache_creation 829 (253 + 576) for a ~577k
conversation, and Claude Code compacted early. 12 of their 30 replies
after ToolSearch were about 2x.

The translated route summed the same way across its tries (#5115): the
empty reply asked again (#667), a loop's re-ask (#1359), a cut reply's
continuation (#853), and search.go's web search rounds. The Anthropic
passthrough has no in-reply fold; each try is its own call.

Usage.after (claude_subscription.go) replaces plus at these joins: the
client is told the last request's input, cache writes and cache reads,
and every request's output and reasoning (all of it was streamed). The
earlier requests' prompts go in Deferred, which the ledger bills
(billed()) and no encoder tells. Usage.restart makes a later request's
prompt counts replace the earlier's, a zero too, so a later request that
reads nothing from the cache isn't told, or billed again, the earlier's
reads. Cache writes are last-only for the client as well: the later
request reads what the earlier wrote, so summed they count it twice.
ggbdpq's #5115 analysis named the translated route's case; no code of
theirs was used.

Tests (usage_last_prompt_test.go), on the reporter's numbers:
- TestClaudeOwnCallReplyTellsLastPrompt: bridge, told 6/576/577848,
  billed 8/829/1154857; and a second request that missed the cache.
- TestClaudeTUILateMessagePromptNotTold: interactive mode's late message.
- TestRetriedReplyTellsLastPrompt: Gemini three reasoning-only replies
  then an answer, Chat and Anthropic clients; ledger has all four.
- TestLaterTryZeroCacheReadNotTold: a continuation and a search round
  whose later request reads 0 from the cache.
Tests that pinned the summed client numbers now pin the last request's
and check the billed sum (CachePartialUpdateMatrix, Probe1717 zero split,
cut stream retry, own WebSearch, search rounds, StreamCutUsage renamed
TestStreamCutUsageTellsLastTry).

Run (mote, Go 1.26.8, -tags nogui):
- The new tests on origin/main ca77a9ea8: red, the client told
  8/829/1154857 (the report's numbers), prompt_tokens 2,000,000 for
  four 500k tries.
- Broken by hand: restart dropped -> TestClaudeCutStreamGoesOnInRetry
  and the cache-missed case red (reads billed twice); after() put back
  to plus -> 12 tests red; restart on the translated tries dropped ->
  TestLaterTryZeroCacheReadNotTold red (cache reads 200 billed, 111
  told). The last one was green before that test was added.
- go test ./internal/gateway/ whole: ok except
  TestClaudeInternalMessagesKeepCacheWrites, which pinned the sum and
  was updated after; that test with the usage, cache, search,
  continuation and TUI tests then ok (61.8s).
- go vet ./internal/gateway for darwin, linux and windows; gofmt clean.
- The full suite runs after the push (mote's suite lock held 3h+ by
  another session).

Not tried: a real Claude Code account or the real TUI, the reporter's
session, a real Gemini/translated provider, Windows or Linux runs of
the package.

Reported-by: sleepy_shibe (Discord)
This commit is contained in:
yetone
2026-11-07 10:03:52 +08:00
parent e2f085fda2
commit 665b9aff12
13 changed files with 407 additions and 38 deletions
+17 -1
View File
@@ -272,11 +272,27 @@ reader (`run.onCall`). Not shown from the transcript within `callFirst`
it), the call is a reply of its own: a message with that one `tool_use`
(Claude Code makes its MCP calls one at a time, a message's parallel
calls too). The first message written after such a call is the one that
made it. Its rows are left out (`lateID`), and its usage is told with the
made it. Its rows are left out (`lateID`), and its usage is billed with the
next reply. A call in that message that wasn't made yet becomes its own
reply when it is made (`written`). A reply told this way has no words or
thinking: the model's text before its call is lost to the client.
A reply that more than one message makes (a late message, Claude Code's
own ToolSearch or WebSearch, a cut stream's retry) tells its client the
last message's input, cache writes and cache reads, and every message's
output (`Usage.after`). Claude Code reads the last reply's three as how
full the conversation is, and each message re-sent what the one before
it had: summed, a reply after a ToolSearch read 1,154,857 cached tokens
for a 577k conversation and Claude Code compacted early (sleepy_shibe on
Discord). The earlier messages' prompts go in `Usage.Deferred`, billed in
the ledger and never told. The translated route's tries (the empty reply
asked again, a loop's re-ask, a cut reply's continuation) and web search
rounds tell theirs the same way (#5115). A later message's prompt counts
replace the earlier's, a zero too (`Usage.restart`), so a field the later
one reads nothing in is not left at the earlier's (`TestClaudeOwnCallReplyTellsLastPrompt`,
`TestClaudeTUILateMessagePromptNotTold`, `TestRetriedReplyTellsLastPrompt`,
`TestLaterTryZeroCacheReadNotTold`).
The user's own `~/.claude.json` and `~/.claude` are never written by
magpie (Claude Code writes them, as when it records its onboarding done,
below). Claude
+3 -2
View File
@@ -111,8 +111,9 @@ func TestClaudeCutStreamGoesOnInRetry(t *testing.T) {
if text != "the answer" || stop != "end_turn" || ended != "stop" || !ok {
t.Fatalf("reply %q stop %q, run ended %q %v:\n%s", text, stop, ended, ok, raw)
}
// both attempts were made, and are counted
if out != 12005 || write != 467708 {
// both attempts' output was made, and is counted; the prompt told is
// the retry's, which read what the cut attempt wrote (sleepy_shibe)
if out != 12005 || write != 0 {
t.Fatalf("usage: %d out, %d written:\n%s", out, write, raw)
}
}
+41 -5
View File
@@ -3579,7 +3579,8 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
var refusedDetails []byte // its stop_details, told only if it stands
replyModel := "" // the model the reply began with
// what the messages before cost, as each message's usage counts only
// itself and the client keeps the last it is told
// itself and the client keeps the last it is told: their output is
// told with this one's, their prompt billed only (after)
var before, this Usage
var lateUsage cliUsage // a message left out as told by its call (onCall)
var reqID, errKind string // the last request's id, and how it failed
@@ -3714,7 +3715,10 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
before, this = before.plus(this, false), Usage{}
// Claude Code's fallback model answering: a reply told
// whole names it; a stream named its model as it began
// its prompt is the reply's, the messages before billed as
// its Deferred (after)
v := usage(u)
v.restart = true
if model == replyModel {
model = ""
}
@@ -4273,8 +4277,6 @@ type cliUsage struct {
} `json:"output_tokens_details"`
}
// plus adds v's counts to u's; only to those u has, when it only updates
// what the client was told.
// claudeLimits are the allowance windows a rate_limit_event's info tells:
// each of its unifiedWindows, and the one it is about, when that says how
// much is used or that it turned the request away.
@@ -4309,14 +4311,48 @@ func claudeLimits(raw json.RawMessage) []provider.ClaudeLimit {
}
// carryUpdate keeps this message's known 1h writes when a partial split
// reports only 5m counts, then adds usage from earlier messages.
// reports only 5m counts, then adds usage from earlier messages
// (after).
func (u Usage) carryUpdate(this, before Usage) Usage {
if u.CacheWrite1h == 0 && u.cacheCreationHasCounts {
u.CacheWrite1h = this.CacheWrite1h
}
return u.plus(before, true)
return u.after(before, true)
}
// after is u, the usage of the request answering now, as told the
// client of a reply that earlier requests began (before): another try,
// the message after Claude Code's own tool call, a search round. What
// they wrote out was streamed to the client as it came, so their output
// and reasoning are added to this one's. Their prompt (input, cache
// reads and writes) is billed as the reply's Deferred and never told as
// its own: a client reads the last reply's prompt back as how full its
// conversation is, and each later request re-sent what the earlier one
// had, so a reply told the sum read twice its size and Claude Code
// compacted early (sleepy_shibe on Discord; WorkBuddy, #5115). update
// is whether u only updates what the client was told (a message_delta),
// so only the counts it has are added to.
func (u Usage) after(before Usage, update bool) Usage {
b := before.billed()
u = u.plus(Usage{Output: b.Output, Reasoning: b.Reasoning}, update)
if b.Input+b.CacheRead+b.CacheWrite+b.CacheWrite1h == 0 {
return u
}
d := Usage{Input: b.Input, CacheRead: b.CacheRead, CacheWrite: b.CacheWrite, CacheWrite1h: b.CacheWrite1h}
if own := u.Deferred; own != nil {
d.Input += own.Input
d.Output += own.Output
d.CacheRead += own.CacheRead
d.CacheWrite += own.CacheWrite
d.CacheWrite1h += own.CacheWrite1h
d.Reasoning += own.Reasoning
}
u.Deferred = &d
return u
}
// plus adds v's counts to u's; only to those u has, when it only updates
// what the client was told.
func (u Usage) plus(v Usage, only bool) Usage {
if only && u.CacheWrite > 0 && !u.cacheCreationHasCounts && u.CacheWrite1h == 0 {
u.cacheCreationReported = false
+2 -1
View File
@@ -323,7 +323,8 @@ func TestClaudeOwnWebSearchStaysInside(t *testing.T) {
if s := strings.Join(got, "|"); s != "start:m1|text:Let me look. |text:Go 1.27.1|stop:stop" {
t.Fatalf("events: %s", s)
}
if usage.Input != 40 || usage.Output != 12 {
// the prompt told is the answering message's, both billed
if usage.Input != 30 || usage.Output != 12 || usage.billed().Input != 40 {
t.Fatalf("usage: %+v", usage)
}
}
+7 -3
View File
@@ -434,6 +434,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
said, stop := false, ""
var kept []Event // the reply's end, while nothing is said in it
var before, this Usage // what the tries before this one billed, and this try
tried := false // a try began: the next one's prompt is the reply's (restart)
// spoke: the reply has said something, a text or a call; relooped: this
// try's reasoning was found stuck in a loop before it had, and it is
// let go to ask again (loopReasks)
@@ -483,11 +484,14 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
}
errSent = true
case KStart:
// the tries are each billed, so their usages are summed into
// the reply's — the client's and the ledger's (a cut try's is
// the tries are each billed: the earlier ones' prompts as the
// reply's Deferred, their output with this one's (after); the
// client is told this try's prompt (a cut try's counts are
// only what it said before the cut)
this = ev.Usage
ev.Usage = ev.Usage.plus(before, false)
ev.Usage = ev.Usage.after(before, false)
ev.Usage.restart = tried
tried = true
u.add(ev.Usage)
u.add(Usage{Served: ev.Model}) // the model the vendor says answered
case KUsage:
+11 -5
View File
@@ -12,6 +12,7 @@ import (
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// cutChat is a Chat upstream that severs the reply mid-stream on the calls
@@ -649,9 +650,9 @@ func TestStreamCutPrefillRefusedEndsAsBefore(t *testing.T) {
}
}
// The tries are each billed, so the reply's usage — the client's and the
// ledger's — sums them: the cut try's prompt with the continuation's.
func TestStreamCutUsageSumsTries(t *testing.T) {
// The tries are each billed in the ledger, and the client is told the
// last try's prompt: the continuation re-sent the cut try's.
func TestStreamCutUsageTellsLastTry(t *testing.T) {
f := &cutAnthropic{
cuts: map[int][]string{0: {anthStart("m", 7), anthText("hel")}},
whole: []string{anthStart("m", 11), anthText("lo"), anthStop(4)},
@@ -661,8 +662,13 @@ func TestStreamCutUsageSumsTries(t *testing.T) {
if u == nil {
t.Fatalf("no usage in the stream: %s", body)
}
if u["prompt_tokens"] != 18.0 || u["completion_tokens"] != 4.0 {
t.Fatalf("usage = %v, want the tries summed: prompt 7+11=18, completion 4", u)
// the client is told the continuation's prompt, which holds the cut
// try's; both are billed (sleepy_shibe, #5115)
if u["prompt_tokens"] != 11.0 || u["completion_tokens"] != 4.0 {
t.Fatalf("usage = %v, want the last try's prompt 11, completion 4", u)
}
if r := usage.Load(time.Time{}); len(r) != 1 || r[0].Input != 18 {
t.Fatalf("ledger %+v, want both tries billed: 7+11=18", r)
}
}
+7
View File
@@ -483,6 +483,10 @@ type Usage struct {
// provider's own tool (searchTally), for the request log's Web search
// rows; told nowhere else
searches int
// restart: the usage of a request that goes on with a reply another
// began (after): its prompt counts are the reply's from now on, a
// zero too, as what the earlier one counted is the reply's Deferred
restart bool
Reasoning int `json:"reasoning"`
// Served: the model the vendor's reply says answered, when it named
@@ -545,6 +549,9 @@ func (u Usage) prompt() int {
}
func (u *Usage) add(v Usage) {
if v.restart {
u.Input, u.CacheRead, u.CacheWrite, u.CacheWrite1h = v.Input, v.CacheRead, v.CacheWrite, v.CacheWrite1h
}
if v.Input > 0 {
u.Input = v.Input
}
+4 -1
View File
@@ -1331,8 +1331,11 @@ func (s *Server) searchRounds(ctx context.Context, q *Request, tool string, in <
col.add(ev)
switch ev.Kind {
case KStart:
// a round's prompt is told, the rounds before billed as
// the reply's Deferred (after)
this = ev.Usage
ev.Usage = ev.Usage.plus(before, false)
ev.Usage = ev.Usage.after(before, false)
ev.Usage.restart = started
if started {
ev = Event{Kind: KUsage, Usage: ev.Usage}
}
+5 -3
View File
@@ -192,7 +192,7 @@ func TestWebSearchForAModelThatCannot(t *testing.T) {
if rec.Code != 200 || len(res.Choices) != 1 || res.Choices[0].Message.Content != "Let me check.\n\nGo 1.27.1 is out." || len(res.Choices[0].Message.ToolCalls) != 0 || res.Choices[0].FinishReason != "stop" {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
if res.Usage.Prompt != 40 || res.Usage.Completion != 12 {
if res.Usage.Prompt != 10 || res.Usage.Completion != 12 { // the last round's prompt, both rounds' output
t.Fatalf("usage %+v", res.Usage)
}
@@ -295,8 +295,10 @@ func TestSearchZeroCacheSplitKeepsWrites(t *testing.T) {
}
client := newSniffer(provider.Anthropic, "text/event-stream")
client.write(w.Body.Bytes())
if client.u.CacheWrite != 50 {
t.Fatalf("zero delta after search round reduced client cache writes: got %d, want 50", client.u.CacheWrite)
// the client is told the last round's writes, the first round's
// billed with them
if client.u.CacheWrite != 20 {
t.Fatalf("zero delta after search round reduced client cache writes: got %d, want the last round's 20", client.u.CacheWrite)
}
}
+5 -2
View File
@@ -60,8 +60,11 @@ func checkCacheBridge(t *testing.T, delta string, hour int) {
}
}
<-done
if client.CacheWrite != 50 || client.CacheWrite1h != hour {
t.Errorf("client writes: %d/hour%d, want50/hour%d", client.CacheWrite, client.CacheWrite1h, hour)
if client.CacheWrite != 20 || client.CacheWrite1h != hour-zeroSplitBefore1h {
t.Errorf("client writes: %d/hour%d, want the last message's 20/hour%d", client.CacheWrite, client.CacheWrite1h, hour-zeroSplitBefore1h)
}
if b := client.billed(); b.CacheWrite != 50 || b.CacheWrite1h != hour {
t.Errorf("billed writes: %d/hour%d, want50/hour%d", b.CacheWrite, b.CacheWrite1h, hour)
}
}
+19 -8
View File
@@ -4,6 +4,9 @@ import (
"fmt"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/usage"
)
// anthCacheStart reports the writes billed for one Anthropic round.
@@ -36,22 +39,26 @@ func TestStreamCutZeroCacheSplitKeepsWrites(t *testing.T) {
}
u := chatUsageOf(body)
details, _ := u["prompt_tokens_details"].(map[string]any)
if got := details["cache_write_tokens"]; got != 50.0 {
t.Fatalf("zero delta after cut try reduced client cache writes: got %v, want 50; usage %v", got, u)
// told the continuation's writes, billed both tries'
if got := details["cache_write_tokens"]; got != 20.0 {
t.Fatalf("zero delta after cut try reduced client cache writes: got %v, want the last try's 20; usage %v", got, u)
}
if r := usage.Load(time.Time{}); len(r) != 1 || r[0].CacheWrite != 50 {
t.Fatalf("ledger %+v, want both tries' writes billed: 50", r)
}
}
func TestClaudeInternalMessagesKeepCacheWrites(t *testing.T) {
for _, tc := range []struct {
name, before, start, delta string
hour int
hour, told int
}{
{"zeroDelta", `"cache_creation_input_tokens":30`,
`"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":0}`,
`"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 0},
`"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 0, 20},
{"pure5mAfterHour", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20}`,
`"cache_creation_input_tokens":30,"cache_creation":{"ephemeral_5m_input_tokens":30,"ephemeral_1h_input_tokens":0}`,
`"cache_creation_input_tokens":30,"cache_creation":{"ephemeral_5m_input_tokens":30,"ephemeral_1h_input_tokens":0}`, 20},
`"cache_creation_input_tokens":30,"cache_creation":{"ephemeral_5m_input_tokens":30,"ephemeral_1h_input_tokens":0}`, 20, 30},
} {
t.Run(tc.name, func(t *testing.T) {
ev := func(e string) string { return `{"type":"stream_event","event":` + e + `}` }
@@ -93,10 +100,14 @@ func TestClaudeInternalMessagesKeepCacheWrites(t *testing.T) {
if starts != 1 || stops != 1 || text != "answer" {
t.Fatalf("internal messages did not produce one reply: starts=%d stops=%d text=%q", starts, stops, text)
}
if client.CacheWrite != 50 || client.CacheWrite1h != tc.hour || client.Output != 12 {
t.Fatalf("internal-message usage = writes %d/%d, output %d; want 50/%d, 12", client.CacheWrite, client.CacheWrite1h, client.Output, tc.hour)
// told the answering message's writes, billed both messages'
if client.CacheWrite != tc.told || client.CacheWrite1h != 0 || client.Output != 12 {
t.Fatalf("internal-message usage = writes %d/%d, output %d; want the last message's %d/0, 12", client.CacheWrite, client.CacheWrite1h, client.Output, tc.told)
}
wantUsageSplit(t, client, &aCacheCreation{Ephemeral5m: 50 - tc.hour, Ephemeral1h: tc.hour})
if b := client.billed(); b.CacheWrite != 50 || b.CacheWrite1h != tc.hour {
t.Fatalf("billed writes %d/%d, want 50/%d", b.CacheWrite, b.CacheWrite1h, tc.hour)
}
wantUsageSplit(t, client, &aCacheCreation{Ephemeral5m: tc.told})
})
}
}
@@ -17,7 +17,9 @@ import (
const (
zeroSplitBefore = `"cache_creation_input_tokens":30,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":10}`
zeroSplitStart = `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":5}`
zeroSplitDelta = `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7,"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}}`
// zeroSplitBefore1h is the first request's 1h writes in zeroSplitBefore
zeroSplitBefore1h = 10
zeroSplitDelta = `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7,"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}}`
)
func cacheSplitRoundStart(fields string) string {
@@ -54,8 +56,9 @@ func checkCacheContinuation(t *testing.T, delta string, hour int) {
}
u := chatUsageOf(body)
details, _ := u["prompt_tokens_details"].(map[string]any)
if details["cache_write_tokens"] != 50.0 {
t.Errorf("client cache writes=%v, want50", details["cache_write_tokens"])
// the client is told the last try's writes, the ledger every try's
if details["cache_write_tokens"] != 20.0 {
t.Errorf("client cache writes=%v, want the last try's 20", details["cache_write_tokens"])
}
wantCacheLedger(t, hour)
}
@@ -116,8 +119,8 @@ func checkCacheSearch(t *testing.T, delta string, hour int) {
client := newSniffer(provider.Anthropic, w.Header().Get("Content-Type"))
client.write(w.Body.Bytes())
u := client.usage()
if u.CacheWrite != 50 || u.CacheWrite1h != hour {
t.Errorf("client writes: %d/hour%d, want50/hour%d", u.CacheWrite, u.CacheWrite1h, hour)
if u.CacheWrite != 20 || u.CacheWrite1h != hour-zeroSplitBefore1h {
t.Errorf("client writes: %d/hour%d, want the last round's 20/hour%d", u.CacheWrite, u.CacheWrite1h, hour-zeroSplitBefore1h)
}
wantCacheLedger(t, hour)
})
@@ -151,7 +154,9 @@ func TestProbe1717BridgeTotalZeroSplit(t *testing.T) {
}
}
<-done
if client.CacheWrite1h != 15 {
t.Errorf("1h writes = %d, want 15 (10 from the first message + 5 from the second's message_start)", client.CacheWrite1h)
// told the second message's, billed both: 10 from the first + 5 from
// the second's message_start
if client.CacheWrite1h != 5 || client.billed().CacheWrite1h != 15 {
t.Errorf("1h writes = %d told, %d billed; want 5 and 15", client.CacheWrite1h, client.billed().CacheWrite1h)
}
}
+274
View File
@@ -0,0 +1,274 @@
package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// A reply that more than one upstream request answered tells its client
// the last request's prompt (input, cache writes, cache reads): Claude
// Code reads the last reply's three as how full its conversation is, and
// each later request re-sent what the earlier one had. Summed, a reply
// after a ToolSearch read 1,154,857 cached tokens for a ~577k
// conversation and Claude Code compacted early (sleepy_shibe on
// Discord). Each request is still billed (Deferred, billed).
// anthUsageOf is what an Anthropic stream's client takes as the reply's
// usage: message_start's, each message_delta's counts laid over it.
func anthUsageOf(t *testing.T, raw string) map[string]float64 {
t.Helper()
out := map[string]float64{}
for _, l := range strings.Split(raw, "\n") {
data, ok := strings.CutPrefix(l, "data: ")
if !ok {
continue
}
var ev struct {
Type string `json:"type"`
Message struct {
Usage map[string]any `json:"usage"`
} `json:"message"`
Usage map[string]any `json:"usage"`
}
if json.Unmarshal([]byte(data), &ev) != nil {
continue
}
u := ev.Usage
if ev.Type == "message_start" {
u = ev.Message.Usage
}
for k, v := range u {
if n, ok := v.(float64); ok {
out[k] = n
}
}
}
return out
}
// relaySegment is what an Anthropic client is told of one reply's
// events, and the usage its call is billed for.
func relaySegment(t *testing.T, seg chan Event) (string, Usage) {
t.Helper()
done := make(chan struct{})
rec := httptest.NewRecorder()
var u Usage
go func() {
defer close(done)
relay(rec, httptest.NewRequest("POST", "/v1/messages", nil), provider.Anthropic, "Claude Code", &Request{Model: "claude-opus-5-5", Stream: true}, seg, &u,
func() {}, nil, func(string, string, bool) {})
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("the reply never ended")
}
return rec.Body.String(), u
}
func wantPrompt(t *testing.T, got map[string]float64, input, write, read float64) {
t.Helper()
if got["input_tokens"] != input || got["cache_creation_input_tokens"] != write || got["cache_read_input_tokens"] != read {
t.Errorf("client told input %v, cache writes %v, cache reads %v; want the last request's %v, %v, %v",
got["input_tokens"], got["cache_creation_input_tokens"], got["cache_read_input_tokens"], input, write, read)
}
}
func wantBilled(t *testing.T, u Usage, input, write, read int) {
t.Helper()
if b := u.billed(); b.Input != input || b.CacheWrite != write || b.CacheRead != read {
t.Errorf("billed input %d, cache writes %d, cache reads %d; want every request's: %d, %d, %d", b.Input, b.CacheWrite, b.CacheRead, input, write, read)
}
}
// The reporter's numbers, in the bridge: the message calling Claude
// Code's own ToolSearch goes on into the next, which answers, and the
// client hears one reply.
func TestClaudeOwnCallReplyTellsLastPrompt(t *testing.T) {
for _, c := range []struct {
name string
second string
input, write, read float64
billIn, billWrite, billRead int
}{
{"reporter", `"input_tokens":6,"cache_creation_input_tokens":576,"cache_read_input_tokens":577848`, 6, 576, 577848, 8, 829, 1154857},
// a second request that missed the cache: what the first read is
// not told as this one's, nor billed twice
{"cache missed", `"input_tokens":577854,"cache_creation_input_tokens":0,"cache_read_input_tokens":0`, 577854, 0, 0, 577856, 253, 577009},
} {
t.Run(c.name, func(t *testing.T) {
lines := []string{
se(`{"type":"message_start","message":{"id":"m1","model":"claude-opus-5-5","usage":{"input_tokens":2,"cache_creation_input_tokens":253,"cache_read_input_tokens":577009,"output_tokens":1}}}`),
se(`{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"ToolSearch"}}`),
se(`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"input_tokens":2,"cache_creation_input_tokens":253,"cache_read_input_tokens":577009,"output_tokens":221}}`),
se(`{"type":"message_stop"}`),
`{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"loaded"}]}}`,
se(`{"type":"message_start","message":{"id":"m2","model":"claude-opus-5-5","usage":{` + c.second + `,"output_tokens":1}}}`),
se(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`),
se(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"stopped"}}`),
se(`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{` + c.second + `,"output_tokens":124}}`),
se(`{"type":"message_stop"}`),
}
run := &subscriptionRun{}
seg := run.attach()
go run.readOutput(strings.NewReader(strings.Join(lines, "\n") + "\n"))
raw, u := relaySegment(t, seg)
got := anthUsageOf(t, raw)
wantPrompt(t, got, c.input, c.write, c.read)
if got["output_tokens"] != 345 {
t.Errorf("output %v, want both messages' 221+124, as both were streamed", got["output_tokens"])
}
wantBilled(t, u, c.billIn, c.billWrite, c.billRead)
if u.billed().Output != 345 {
t.Errorf("billed output %d, want 345", u.billed().Output)
}
})
}
}
// The interactive mode's message written after its call was told: its
// usage goes with the next reply, billed, but the next reply's prompt is
// its own.
func TestClaudeTUILateMessagePromptNotTold(t *testing.T) {
c := newTUICalls(t)
first := c.run.segment
c.call("toolu_a", `{"p":1}`)
if _, calls, _, _, raw := c.reply(first); len(calls) != 1 {
t.Fatalf("first reply: %s", raw)
}
seg := c.answer("toolu_a")
row := func(id, block, stop, u string) string {
return `{"type":"assistant","message":{"id":"` + id + `","model":"claude-opus-5-5","role":"assistant","content":[` + block + `],"stop_reason":"` + stop + `","usage":{` + u + `}}}`
}
c.write(
row("msg_late", tuiCall("toolu_a", 1), "tool_use", `"input_tokens":2,"cache_creation_input_tokens":253,"cache_read_input_tokens":577009,"output_tokens":221`),
row("msg_ans", `{"type":"text","text":"done"}`, "end_turn", `"input_tokens":6,"cache_creation_input_tokens":576,"cache_read_input_tokens":577848,"output_tokens":124`),
tuiDone,
)
raw, u := relaySegment(t, seg)
got := anthUsageOf(t, raw)
wantPrompt(t, got, 6, 576, 577848)
if got["output_tokens"] != 345 {
t.Errorf("output %v, want the late message's 221 and the answer's 124", got["output_tokens"])
}
wantBilled(t, u, 8, 829, 1154857)
}
// The translated route's tries (#5115): Gemini answering with only its
// reasoning, asked again three times, and a cut reply's continuation.
func TestRetriedReplyTellsLastPrompt(t *testing.T) {
gem := func(text string, thought bool) string {
return fmt.Sprintf(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":%q,"thought":%t}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":500000,"cachedContentTokenCount":380000,"candidatesTokenCount":10}}`+"\n\n", text, thought)
}
for _, a := range []struct{ name, path, body string }{
{"chat", "/v1/chat/completions", `{"model":"gem/gemini-3.8-flash","stream":true,"messages":[{"role":"user","content":"hi"}]}`},
{"anthropic", "/v1/messages", `{"model":"gem/gemini-3.8-flash","stream":true,"max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`},
} {
t.Run(a.name, func(t *testing.T) {
fresh(t)
calls := 0
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
calls++
w.Header().Set("Content-Type", "text/event-stream")
if calls <= 3 {
io.WriteString(w, gem("Let me see.", true))
return
}
io.WriteString(w, gem("hello", false))
}))
t.Cleanup(up.Close)
saveGem(t, up.URL, "gemini-3.8-flash")
code, body := post(t, a.path, a.body)
if code != 200 || calls != 4 || !strings.Contains(body, "hello") {
t.Fatalf("not asked past three empty replies: %d calls, %d %s", calls, code, body)
}
if a.name == "chat" {
if u := chatUsageOf(body); u["prompt_tokens"] != 500000.0 {
t.Errorf("client prompt_tokens %v, want the last try's 500000, not the four tries' sum", u["prompt_tokens"])
}
} else {
wantPrompt(t, anthUsageOf(t, body), 120000, 0, 380000)
}
records := usage.Load(time.Time{})
if len(records) != 1 || records[0].Input != 4*120000 || records[0].CacheRead != 4*380000 {
t.Errorf("ledger %+v, want each of the four tries billed", records)
}
})
}
}
// A later try or round whose prompt reads nothing from the cache tells its
// own zero, not the earlier request's reads, which are billed once.
func TestLaterTryZeroCacheReadNotTold(t *testing.T) {
start := func(input, read int) string {
return fmt.Sprintf(`{"type":"message_start","message":{"id":"m1","type":"message","role":"assistant","model":"m","content":[],"usage":{"input_tokens":%d,"cache_read_input_tokens":%d,"output_tokens":0}}}`, input, read)
}
t.Run("continuation", func(t *testing.T) {
f := &cutAnthropic{
cuts: map[int][]string{0: {start(7, 100), anthText("hel")}},
whole: []string{start(11, 0), anthText("lo"), anthStop(4)},
}
body := continuationChatServer(t, "m", f)
if f.calls() != 2 {
t.Fatalf("calls = %d, want 2", f.calls())
}
u := chatUsageOf(body)
details, _ := u["prompt_tokens_details"].(map[string]any)
if u["prompt_tokens"] != 11.0 || details["cached_tokens"] != 0.0 {
t.Errorf("client told %v, want the continuation's prompt 11 with nothing cached", u)
}
if r := usage.Load(time.Time{}); len(r) != 1 || r[0].Input != 18 || r[0].CacheRead != 100 {
t.Errorf("ledger %+v, want input 7+11, the cut try's 100 reads once", r)
}
})
t.Run("search", func(t *testing.T) {
fresh(t)
apis := newSearchAPIs(t)
if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil {
t.Fatal(err)
}
calls := 0
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
calls++
if calls == 1 {
writeStream(w, []string{
start(5, 100),
`{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_1","name":"web_search","input":{}}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"query\":\"latest go\"}"}}`,
`{"type":"content_block_stop","index":0}`,
`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":7}}`,
`{"type":"message_stop"}`,
}, false, "")
return
}
writeStream(w, []string{start(9, 0), anthText("Go 1.27.1 is out."), anthStop(4), `{"type":"message_stop"}`}, false, "")
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"m"}, Anthropic: up.URL}); err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"up/m","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"What is the latest Go?"}],"tools":[{"type":"web_search_20250305","name":"web_search"}]}`))
r.Header.Set("x-api-key", Token)
r.RemoteAddr = "127.0.0.1:12345"
w := httptest.NewRecorder()
lanGuard(New().Handler()).ServeHTTP(w, r)
if w.Code != 200 || calls != 2 {
t.Fatalf("search reply = %d after %d rounds: %s", w.Code, calls, w.Body)
}
wantPrompt(t, anthUsageOf(t, w.Body.String()), 9, 0, 0)
if r := usage.Load(time.Time{}); len(r) != 1 || r[0].Input != 14 || r[0].CacheRead != 100 {
t.Errorf("ledger %+v, want input 5+9, the first round's 100 reads once", r)
}
})
}