What: pi.js wrote message_start with usageOf() and no argument, so every
field was 0 until message_delta. Claude Code's context meter reads the
usage the assistant message has so far, and a turn interrupted before
message_delta was stored with 0. message_start now carries the vendor's
prompt (input, cache read, cache write) and the output pi's start named
(startUsage): from pi's start event's partial.usage, as the issue
describes, or, as pi-ai's anthropic-messages pushes start before it reads
the vendor's message_start (start's usage is still 0 then), from the
partial message the events after it share. That message is pi's own,
still being written (by the time magpie reads it pi may have pushed the
whole turn), so only its prompt is taken from it, never its output.
message_delta is unchanged: the whole turn's cumulative usage from done.
Siblings, the gateway's translators to Anthropic's stream:
- Gemini / Code Assist (codeassist.go): usageMetadata rides on the first
chunk, but KStart was emitted before reading it. KStart now carries the
prompt (input, cached); output stays 0 there.
- Chat Completions (chat.go): most streams count only at their end, so
nothing to tell; a stream that counts on its first chunk now has its
prompt on KStart.
- Responses: response.created has no usage. Anthropic-to-Anthropic and the
Claude subscription already carry it. Cursor, Kiro, Devin, Qoder,
Command Code send KStart before any usage is known.
Ledger: no double count. The usage sniffer and the collector both take
each field's latest non-zero value (Usage.add replaces, it doesn't sum),
and continuation/search take a try's KStart usage as its own (this =
ev.Usage) and KUsage replaces it. message_delta's input equals
message_start's, which Anthropic's clients also take as the same count.
Run (Go 1.26.8, darwin):
- TestPiPackage with a fake pi stream as the issue's (start with
partial.usage input 11, cache 3/2, output 0, text, done with output 7):
message_start 11/3/2/0, message_delta 11/3/2/7; and pi-ai's order
("late": start with zero usage, then the shared message counted):
message_start 11/3/2/0. Red with message_start back on usageOf(), and
the late case red when only start's usage is read.
- TestPromptUsageOnMessageStart (Gemini, chat counting per chunk, chat
counting at the end): red with codeassist.go and chat.go stashed.
- go test ./internal/plugin and ./internal/gateway in full (-timeout 28m;
the default 10m timed out under load average ~20). The disk filled
during the run (3.7G free, not this change's): every failure was
ENOSPC, and each of them (37 gateway, TestFakePlugin) passed on rerun.
- gofmt -l; go vet for darwin, linux and windows on both packages.
Not tried against a real pi vendor or Claude Code's meter.
Reported-by: guoqchen1001
112 lines
4.0 KiB
Go
112 lines
4.0 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/json"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// toAnthropic runs a stream's chunks through a decoder and the Anthropic
|
|
// encoder: what Claude Code is answered.
|
|
func toAnthropic(t *testing.T, decode func(string, func(Event)) error, chunks ...string) []map[string]any {
|
|
t.Helper()
|
|
rec := httptest.NewRecorder()
|
|
enc := &anthropicEncoder{w: newSSEWriter(rec), model: "m"}
|
|
for _, c := range chunks {
|
|
if err := decode(c, enc.event); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
enc.finish()
|
|
var out []map[string]any
|
|
sc := bufio.NewScanner(strings.NewReader(rec.Body.String()))
|
|
for sc.Scan() {
|
|
if data, ok := strings.CutPrefix(sc.Text(), "data: "); ok {
|
|
var m map[string]any
|
|
if json.Unmarshal([]byte(data), &m) == nil {
|
|
out = append(out, m)
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// usageOfType is the usage the stream's first event of that type told.
|
|
func usageOfType(t *testing.T, out []map[string]any, typ string) map[string]any {
|
|
t.Helper()
|
|
for _, ev := range out {
|
|
if ev["type"] != typ {
|
|
continue
|
|
}
|
|
if typ == "message_start" {
|
|
return ev["message"].(map[string]any)["usage"].(map[string]any)
|
|
}
|
|
return ev["usage"].(map[string]any)
|
|
}
|
|
t.Fatalf("no %s in %v", typ, out)
|
|
return nil
|
|
}
|
|
|
|
// A stream that counts the prompt on its first chunk tells it on
|
|
// message_start, which Claude Code's context meter reads while the turn
|
|
// is still being written (#1887); message_delta still tells the whole
|
|
// turn, the prompt counted once.
|
|
func TestPromptUsageOnMessageStart(t *testing.T) {
|
|
for _, c := range []struct {
|
|
name string
|
|
decode func(string, func(Event)) error
|
|
chunks []string
|
|
start map[string]float64
|
|
end map[string]float64
|
|
}{
|
|
{
|
|
name: "gemini",
|
|
decode: (&codeAssistDecoder{}).decode,
|
|
chunks: []string{
|
|
`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Read"}]}}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":1,"cachedContentTokenCount":40}}}`,
|
|
`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ing."}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":10,"cachedContentTokenCount":40}}}`,
|
|
},
|
|
start: map[string]float64{"input_tokens": 60, "cache_read_input_tokens": 40, "output_tokens": 0},
|
|
end: map[string]float64{"input_tokens": 60, "cache_read_input_tokens": 40, "output_tokens": 10},
|
|
},
|
|
{
|
|
name: "chat counting on every chunk",
|
|
decode: (&chatDecoder{}).decode,
|
|
chunks: []string{
|
|
`{"id":"x","choices":[{"index":0,"delta":{"content":"Read"}}],"usage":{"prompt_tokens":100,"completion_tokens":1,"prompt_tokens_details":{"cached_tokens":40}}}`,
|
|
`{"id":"x","choices":[{"index":0,"delta":{"content":"ing."},"finish_reason":"stop"}],"usage":{"prompt_tokens":100,"completion_tokens":10,"prompt_tokens_details":{"cached_tokens":40}}}`,
|
|
},
|
|
start: map[string]float64{"input_tokens": 60, "cache_read_input_tokens": 40, "output_tokens": 0},
|
|
end: map[string]float64{"input_tokens": 60, "cache_read_input_tokens": 40, "output_tokens": 10},
|
|
},
|
|
{
|
|
// most chat streams count only at their end: nothing to tell
|
|
// at the start
|
|
name: "chat counting at the end",
|
|
decode: (&chatDecoder{}).decode,
|
|
chunks: []string{
|
|
`{"id":"x","choices":[{"index":0,"delta":{"content":"Reading."}}]}`,
|
|
`{"id":"x","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`,
|
|
`{"id":"x","choices":[],"usage":{"prompt_tokens":100,"completion_tokens":10,"prompt_tokens_details":{"cached_tokens":40}}}`,
|
|
},
|
|
start: map[string]float64{"input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0},
|
|
end: map[string]float64{"input_tokens": 60, "cache_read_input_tokens": 40, "output_tokens": 10},
|
|
},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
out := toAnthropic(t, c.decode, c.chunks...)
|
|
for typ, want := range map[string]map[string]float64{"message_start": c.start, "message_delta": c.end} {
|
|
u := usageOfType(t, out, typ)
|
|
for k, v := range want {
|
|
if u[k] != v {
|
|
t.Errorf("%s usage = %v, want %v", typ, u, want)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|