gateway: preserve cache splits and known 1h writes across updates (#1717)

Keep reported Anthropic cache_creation splits, including pure-5m replies,
through API and subscription parsing and client output. Only positive
counters replace known usage. Completed sums retain all counters and
split presence.

Across continuation tries, search rounds and internal bridge messages,
partial updates add earlier total writes only with a positive total. A
split with counts and zero 1h keeps the current message's known 1h before
adding earlier messages' usage. A zero-filled or absent split keeps the
per-counter rule. Omit a zero-filled partial split with a positive total
from output; retain a reported zero-total split. Split presence and the
parsed update's own count evidence remain separate.

Yetone's zero-filled bridge probe and matching continuation/search probes
failed at 0c9298d with 10 instead of 15 1h writes. Fable's partial-5m and
pure-5m cases failed at e1de9bc7 in bridge, continuation and both search
modes with the same loss. All pass after the repair. The 12-case matrix
matches main's client totals and 1h counts and continuation/search ledger
counts. A renderer test rejects a fabricated 50/0 split on a sparse delta.

Verified under sandbox HOME, pinned Go caches and nogui: focused race,
Darwin vet ./..., Linux/Windows gateway vet, gofmt and diff checks. Archive
mutations removing current-message carry, bypassing each of three callers,
and restoring the fabricated split each fail behavior assertions. Restored
archive passes. Earlier zero-total, unreported-split and pure-5m cases stay
green. No live-provider check in this repair.

Review (yetone's session, landed from the PR's head c4cf224 and 90cdb2f):
the partial-cache probes go red when carryUpdate is reverted by hand,
and the 12-case matrix gives the same client totals and 1h counts as
main a15e57656. Rebased on 8b84dc902; gofmt clean; GOOS=darwin/linux/windows
go vet -tags nogui ./... clean.
Full suite: set -o pipefail; go test -timeout 45m ./... at the rebased head -> 65 packages ok, internal/gui red only on TestPanelJoinsFullScreenSpaces ("the panel shown doesn't take the keyboard"), red the same without this change, filed as #2450.
This commit is contained in:
deephbz
2026-10-16 15:14:48 +08:00
committed by yetone
parent d9e87eb328
commit e72b6a3327
11 changed files with 632 additions and 31 deletions
+4 -2
View File
@@ -1277,6 +1277,8 @@ type aCacheCreation struct {
func (u aUsage) usage() Usage {
out := Usage{Input: u.InputTokens, Output: u.OutputTokens, CacheRead: u.CacheReadInputTokens, CacheWrite: u.CacheCreationInputTokens}
if c := u.CacheCreation; c != nil {
out.cacheCreationReported = true
out.cacheCreationHasCounts = c.Ephemeral5m+c.Ephemeral1h > 0
out.CacheWrite = max(out.CacheWrite, c.Ephemeral5m+c.Ephemeral1h)
out.CacheWrite1h = c.Ephemeral1h
}
@@ -1284,10 +1286,10 @@ func (u aUsage) usage() Usage {
}
// anthropic is the usage as Anthropic says it, the cache writes split by
// how long they are kept where some were for an hour.
// how long they are kept when upstream reported TTLs or some were for an hour.
func (u Usage) anthropic() aUsage {
out := aUsage{InputTokens: u.Input, OutputTokens: u.Output, CacheReadInputTokens: u.CacheRead, CacheCreationInputTokens: u.CacheWrite}
if h := min(u.CacheWrite1h, u.CacheWrite); h > 0 {
if h := min(u.CacheWrite1h, u.CacheWrite); u.cacheCreationReported || h > 0 {
out.CacheCreation = &aCacheCreation{Ephemeral5m: u.CacheWrite - h, Ephemeral1h: h}
}
return out
+47 -24
View File
@@ -358,42 +358,65 @@ func TestClaudeClientCacheUsage(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("a shell script stands in for Claude Code")
}
dir := t.TempDir()
testenv.Program(t, filepath.Join(dir, "claude"), `#!/bin/sh
for _, tc := range []struct {
name string
write, hour int
split string
}{
{"mixed", 40, 29, `,"cache_creation":{"ephemeral_5m_input_tokens":11,"ephemeral_1h_input_tokens":29}`},
// The pure-5m counts come from the live omitted-TTL probe.
{"pure5m", 1894, 0, `,"cache_creation":{"ephemeral_5m_input_tokens":1894,"ephemeral_1h_input_tokens":0}`},
{"reportedZero", 0, 0, `,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`},
{"unreported", 40, 0, ""},
} {
for _, stream := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/stream_%t", tc.name, stream), func(t *testing.T) {
dir := t.TempDir()
u := fmt.Sprintf(`{"input_tokens":12,"cache_read_input_tokens":300,"cache_creation_input_tokens":%d%s,"output_tokens":1}`, tc.write, tc.split)
testenv.Program(t, filepath.Join(dir, "claude"), `#!/bin/sh
while read -r line; do
case $line in *'"type":"control_request"'*)
id=$(printf '%s' "$line" | sed 's/.*"request_id":"\([^"]*\)".*/\1/')
echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}'
continue ;;
esac
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":12,"cache_read_input_tokens":300,"cache_creation_input_tokens":40,"cache_creation":{"ephemeral_5m_input_tokens":11,"ephemeral_1h_input_tokens":29},"output_tokens":1}}}}'
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":`+u+`}}}'
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}}'
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}}'
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
done
`)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
runsEndWithTest(t, dir)
s := New()
t.Cleanup(s.subscription.abortAll)
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
for _, stream := range []bool{false, true} {
body := fmt.Sprintf(`{"model":"claude-sonnet-5","max_tokens":100,"stream":%t,"cache_control":{"type":"ephemeral"},"messages":[{"role":"user","content":"hi"}]}`, stream)
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
r.Header.Set("X-Magpie-Cache-Marks", "client")
w := httptest.NewRecorder()
var usage Usage
if code, msg := s.serveClaudeSubscription(w, r, provider.Anthropic, p, "claude-sonnet-5", []byte(body), &usage); code != 200 {
t.Fatalf("%d %s", code, msg)
}
if usage.CacheWrite != 40 || usage.CacheWrite1h != 29 || usage.CacheRead != 300 {
t.Fatalf("cache usage changed: %+v", usage)
}
for _, want := range []string{`"ephemeral_5m_input_tokens":11`, `"ephemeral_1h_input_tokens":29`} {
if !strings.Contains(w.Body.String(), want) {
t.Fatalf("stream=%t: missing %s from %s", stream, want, w.Body)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
runsEndWithTest(t, dir)
s := New()
t.Cleanup(s.subscription.abortAll)
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
body := fmt.Sprintf(`{"model":"claude-sonnet-5","max_tokens":100,"stream":%t,"cache_control":{"type":"ephemeral"},"messages":[{"role":"user","content":"hi"}]}`, stream)
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
r.Header.Set("X-Magpie-Cache-Marks", "client")
w := httptest.NewRecorder()
var usage Usage
if code, msg := s.serveClaudeSubscription(w, r, provider.Anthropic, p, "claude-sonnet-5", []byte(body), &usage); code != 200 {
t.Fatalf("%d %s", code, msg)
}
if usage.CacheWrite != tc.write || usage.CacheWrite1h != tc.hour || usage.CacheRead != 300 {
t.Fatalf("cache usage changed: %+v", usage)
}
if tc.split == "" {
if strings.Contains(w.Body.String(), `"cache_creation":`) {
t.Fatalf("invented TTL split: %s", w.Body)
}
} else {
want := strings.TrimPrefix(tc.split, ",")
if !strings.Contains(w.Body.String(), want) {
t.Fatalf("missing %s from %s", want, w.Body)
}
if stream && strings.Count(w.Body.String(), want) != 2 {
t.Fatalf("TTL split must survive to message_delta: %s", w.Body)
}
}
})
}
}
}
+26 -2
View File
@@ -2030,7 +2030,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
usage := func(u cliUsage) Usage {
v := u.gateway()
this.add(v)
return v.plus(before, true)
return v.carryUpdate(this, before)
}
// A stream Anthropic cut short (a dropped connection, a stall) Claude
// Code ends with a message_stop of its own and no message_delta, and
@@ -2494,18 +2494,42 @@ func claudeLimits(raw json.RawMessage) []provider.ClaudeLimit {
return out
}
// carryUpdate keeps this message's known 1h writes when a partial split
// reports only 5m counts, then adds usage from earlier messages.
func (u Usage) carryUpdate(this, before Usage) Usage {
if u.CacheWrite1h == 0 && u.cacheCreationHasCounts {
u.CacheWrite1h = this.CacheWrite1h
}
return u.plus(before, true)
}
func (u Usage) plus(v Usage, only bool) Usage {
for _, f := range []struct{ a, b *int }{{&u.Input, &v.Input}, {&u.Output, &v.Output}, {&u.CacheRead, &v.CacheRead}, {&u.CacheWrite, &v.CacheWrite}, {&u.CacheWrite1h, &v.CacheWrite1h}, {&u.Reasoning, &v.Reasoning}} {
if only && u.CacheWrite > 0 && !u.cacheCreationHasCounts && u.CacheWrite1h == 0 {
u.cacheCreationReported = false
}
for _, f := range []struct{ a, b *int }{{&u.Input, &v.Input}, {&u.Output, &v.Output}, {&u.CacheRead, &v.CacheRead}, {&u.Reasoning, &v.Reasoning}} {
if *f.a > 0 || !only {
*f.a += *f.b
}
}
writes := u.CacheWrite > 0
if writes || !only {
u.CacheWrite += v.CacheWrite
}
if u.CacheWrite1h > 0 || u.cacheCreationHasCounts || !only {
u.CacheWrite1h += v.CacheWrite1h
}
if !only {
u.cacheCreationReported = u.cacheCreationReported || v.cacheCreationReported
}
return u
}
func (u cliUsage) gateway() Usage {
out := Usage{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.OutputDetails.Thinking}
if c := u.CacheCreation; c != nil {
out.cacheCreationReported = true
out.cacheCreationHasCounts = c.Ephemeral5m+c.Ephemeral1h > 0
out.CacheWrite = max(out.CacheWrite, c.Ephemeral5m+c.Ephemeral1h)
out.CacheWrite1h = c.Ephemeral1h
}
+1 -1
View File
@@ -431,7 +431,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
u.add(Usage{Served: ev.Model}) // the model the vendor says answered
case KUsage:
this.add(ev.Usage)
ev.Usage = ev.Usage.plus(before, true)
ev.Usage = ev.Usage.carryUpdate(this, before)
u.add(ev.Usage)
case KStop:
stop = ev.Stop
+9 -1
View File
@@ -332,7 +332,14 @@ type Usage struct {
// 5-minute write is 1.25×, when its usage says so (cache_creation's
// ephemeral_1h_input_tokens)
CacheWrite1h int `json:"cache_write_1h,omitempty"`
Reasoning int `json:"reasoning"`
// cacheCreationReported distinguishes a reported zero or pure-5m split
// from usage that did not report TTLs. It is wire evidence, not a counter.
cacheCreationReported bool
// cacheCreationHasCounts describes the parsed update's own split.
// It is never accumulated from earlier usage.
cacheCreationHasCounts bool
Reasoning int `json:"reasoning"`
// Served: the model the vendor's reply says answered, when it named
// one — which may not be the one it was asked for
Served string `json:"served,omitempty"`
@@ -397,6 +404,7 @@ func (u *Usage) add(v Usage) {
if v.CacheWrite1h > 0 {
u.CacheWrite1h = v.CacheWrite1h
}
u.cacheCreationReported = u.cacheCreationReported || v.cacheCreationReported
if v.Reasoning > 0 {
u.Reasoning = v.Reasoning
}
+1 -1
View File
@@ -956,7 +956,7 @@ func (s *Server) searchRounds(ctx context.Context, q *Request, tool string, in <
started = true
case KUsage:
this.add(ev.Usage)
ev.Usage = ev.Usage.plus(before, true)
ev.Usage = ev.Usage.carryUpdate(this, before)
case KText:
if gap && ev.Text != "" {
// what it says after a search goes on from what it
+61
View File
@@ -239,6 +239,67 @@ func TestWebSearchForAModelThatCannot(t *testing.T) {
}
}
func TestSearchZeroCacheSplitKeepsWrites(t *testing.T) {
fresh(t)
apis := newSearchAPIs(t)
if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var asked []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
asked = append(asked, string(b))
n := len(asked)
mu.Unlock()
if n == 1 {
writeStream(w, []string{
anthCacheStart(30, false),
`{"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{
anthCacheStart(20, true), anthText("Go 1.27.1 is out."),
`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":4,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}}`,
`{"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 || textOf(w.Body.String()) != "Go 1.27.1 is out." {
t.Fatalf("search reply = %d %s", w.Code, w.Body)
}
mu.Lock()
defer mu.Unlock()
if len(asked) != 2 || !strings.Contains(asked[1], `"tool_result"`) || !strings.Contains(asked[1], "https://go.dev/dl/") {
t.Fatalf("model did not receive search results in a second round: %v", asked)
}
apis.mu.Lock()
searched := strings.Join(apis.asked, "|")
apis.mu.Unlock()
if searched != "tavily: latest go" {
t.Fatalf("search API calls = %q", searched)
}
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)
}
}
func TestWebSearchAskedOfEachAPI(t *testing.T) {
for _, c := range []struct {
proto provider.Protocol
@@ -0,0 +1,89 @@
package gateway
import (
"strings"
"testing"
)
func TestCachePartialUpdateMatrix(t *testing.T) {
for _, tc := range []struct {
name, fields string
hour int
}{
{"A_zeroFilled", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 15},
{"B_partial5m", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":0}`, 15},
{"C_partialBoth", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":2}`, 12},
{"D_partial1h", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2}`, 12},
{"E_pure5m", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":0}`, 15},
{"F_pure1h", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20}`, 30},
{"G_unreported", `"cache_creation_input_tokens":20`, 15},
{"H_zeroTotal", `"cache_creation_input_tokens":0`, 15},
{"I_zeroTotalSplit", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 15},
{"J_noCache", `"output_tokens":7`, 15},
{"K_splitOnly", `"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":5}`, 15},
{"L_consistent", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":5}`, 15},
} {
t.Run(tc.name, func(t *testing.T) {
delta := `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{` + tc.fields + `}}`
t.Run("bridge", func(t *testing.T) { checkCacheBridge(t, delta, tc.hour) })
t.Run("continuation", func(t *testing.T) { checkCacheContinuation(t, delta, tc.hour) })
t.Run("search", func(t *testing.T) { checkCacheSearch(t, delta, tc.hour) })
})
}
}
func checkCacheBridge(t *testing.T, delta string, hour int) {
t.Helper()
ev := func(e string) string { return `{"type":"stream_event","event":` + e + `}` }
lines := []string{
ev(cacheSplitRoundStart(zeroSplitBefore)),
ev(`{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"WebSearch"}}`),
ev(`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}`),
ev(`{"type":"message_stop"}`),
`{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"results"}]}}`,
ev(cacheSplitRoundStart(zeroSplitStart)),
ev(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"answer"}}`),
ev(delta),
ev(`{"type":"message_stop"}`),
}
run := &subscriptionRun{}
seg := run.attach()
done := make(chan struct{})
go func() {
defer close(done)
run.readOutput(strings.NewReader(strings.Join(lines, "\n") + "\n"))
}()
var client Usage
for e := range seg {
if e.Kind == KStart || e.Kind == KUsage {
client.add(e.Usage)
}
}
<-done
if client.CacheWrite != 50 || client.CacheWrite1h != hour {
t.Errorf("client writes: %d/hour%d, want50/hour%d", client.CacheWrite, client.CacheWrite1h, hour)
}
}
func TestCacheZeroFilledPartialUpdateOmitsSplit(t *testing.T) {
before := Usage{CacheWrite: 30, CacheWrite1h: 10}
for _, tc := range []struct {
name string
total int
}{
{"positiveTotal", 20},
{"zeroTotal", 0},
} {
t.Run(tc.name, func(t *testing.T) {
u := aUsage{CacheCreationInputTokens: tc.total, CacheCreation: &aCacheCreation{}}.usage().plus(before, true)
got := u.anthropic().CacheCreation
if tc.total > 0 {
if got != nil {
t.Fatalf("zero-filled partial update rendered split %+v, want none", got)
}
} else if got == nil || *got != (aCacheCreation{}) {
t.Fatalf("zero-total split = %+v, want reported zero split", got)
}
})
}
}
+102
View File
@@ -0,0 +1,102 @@
package gateway
import (
"fmt"
"strings"
"testing"
)
// anthCacheStart reports the writes billed for one Anthropic round.
func anthCacheStart(writes int, split bool) string {
usage := fmt.Sprintf(`"cache_creation_input_tokens":%d`, writes)
if split {
usage += fmt.Sprintf(`,"cache_creation":{"ephemeral_5m_input_tokens":%d,"ephemeral_1h_input_tokens":0}`, writes)
}
return `{"type":"message_start","message":{"id":"m1","type":"message","role":"assistant","model":"m","content":[],"usage":{` + usage + `}}}`
}
func TestStreamCutZeroCacheSplitKeepsWrites(t *testing.T) {
f := &cutAnthropic{
cuts: map[int][]string{0: {anthCacheStart(30, false), anthText("hel")}},
whole: []string{
anthCacheStart(20, true), anthText("lo"),
`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":4,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}}`,
`{"type":"message_stop"}`,
},
}
body := continuationChatServer(t, "m", f)
if f.calls() != 2 {
t.Fatalf("calls = %d, want 2", f.calls())
}
if prefill, ok := f.lastAssistantText(t, 1); !ok || prefill != "hel" {
t.Fatalf("second try did not continue the cut reply: %q, %v", prefill, ok)
}
if got := chatTextOf(body); got != "hello" {
t.Fatalf("client's text = %q, want hello", got)
}
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)
}
}
func TestClaudeInternalMessagesKeepCacheWrites(t *testing.T) {
for _, tc := range []struct {
name, before, start, delta string
hour 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},
{"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},
} {
t.Run(tc.name, func(t *testing.T) {
ev := func(e string) string { return `{"type":"stream_event","event":` + e + `}` }
lines := []string{
ev(`{"type":"message_start","message":{"id":"m1","model":"x","usage":{` + tc.before + `}}}`),
ev(`{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"WebSearch"}}`),
ev(`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}`),
ev(`{"type":"message_stop"}`),
`{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"results"}]}}`,
ev(`{"type":"message_start","message":{"id":"m2","model":"x","usage":{` + tc.start + `}}}`),
ev(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"answer"}}`),
ev(`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7,` + tc.delta + `}}`),
ev(`{"type":"message_stop"}`),
}
run := &subscriptionRun{}
seg := run.attach()
done := make(chan struct{})
go func() {
defer close(done)
run.readOutput(strings.NewReader(strings.Join(lines, "\n") + "\n"))
}()
var client Usage
var starts, stops int
var text string
for e := range seg {
switch e.Kind {
case KStart:
starts++
client.add(e.Usage)
case KUsage:
client.add(e.Usage)
case KStop:
stops++
case KText:
text += e.Text
}
}
<-done
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)
}
wantUsageSplit(t, client, &aCacheCreation{Ephemeral5m: 50 - tc.hour, Ephemeral1h: tc.hour})
})
}
}
+135
View File
@@ -0,0 +1,135 @@
package gateway
import (
"encoding/json"
"testing"
"github.com/yetone/magpie/internal/provider"
)
func splitUsage(t *testing.T, raw string) Usage {
t.Helper()
var a aUsage
if err := json.Unmarshal([]byte(raw), &a); err != nil {
t.Fatal(err)
}
return a.usage()
}
func wantUsageSplit(t *testing.T, u Usage, want *aCacheCreation) {
t.Helper()
got := u.anthropic().CacheCreation
if (got == nil) != (want == nil) || got != nil && *got != *want {
t.Fatalf("cache_creation = %+v, want %+v", got, want)
}
}
func TestAnthropicCacheSplitPresence(t *testing.T) {
for _, tc := range []struct {
name, raw string
want *aCacheCreation
}{
{"pure5m", `{"cache_creation_input_tokens":1894,"cache_creation":{"ephemeral_5m_input_tokens":1894,"ephemeral_1h_input_tokens":0}}`, &aCacheCreation{Ephemeral5m: 1894}},
{"reportedZero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}`, &aCacheCreation{}},
{"totalFromSplit", `{"cache_creation":{"ephemeral_5m_input_tokens":40,"ephemeral_1h_input_tokens":0}}`, &aCacheCreation{Ephemeral5m: 40}},
{"unreported", `{"cache_creation_input_tokens":40}`, nil},
{"null", `{"cache_creation_input_tokens":40,"cache_creation":null}`, nil},
} {
t.Run(tc.name, func(t *testing.T) {
u := splitUsage(t, tc.raw)
wantUsageSplit(t, u, tc.want)
// A later output-only event must not erase an earlier split or
// manufacture one when the upstream never reported it.
u.add(splitUsage(t, `{"output_tokens":7}`))
wantUsageSplit(t, u, tc.want)
})
}
}
func TestAnthropicCacheSplitUpdatesAndTotals(t *testing.T) {
hour := splitUsage(t, `{"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20}}`)
short := splitUsage(t, `{"cache_creation_input_tokens":30,"cache_creation":{"ephemeral_5m_input_tokens":30,"ephemeral_1h_input_tokens":0}}`)
zero := splitUsage(t, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}`)
u := hour
u.add(short)
wantUsageSplit(t, u, &aCacheCreation{Ephemeral5m: 10, Ephemeral1h: 20})
u.add(zero)
wantUsageSplit(t, u, &aCacheCreation{Ephemeral5m: 10, Ephemeral1h: 20})
for _, only := range []bool{false, true} {
wantUsageSplit(t, short.plus(hour, only), &aCacheCreation{Ephemeral5m: 30, Ephemeral1h: 20})
}
wantUsageSplit(t, zero.plus(hour, false), &aCacheCreation{Ephemeral1h: 20})
wantUsageSplit(t, zero.plus(hour, true), &aCacheCreation{})
// Summing a completed reply retains the split. A sparse output update
// carries no new cache counters, so it must not reset the previous ones.
wantUsageSplit(t, Usage{}.plus(short, false), &aCacheCreation{Ephemeral5m: 30})
update := (Usage{Output: 7}).plus(hour, true)
wantUsageSplit(t, update, nil)
u = short
u.add(update)
wantUsageSplit(t, u, &aCacheCreation{Ephemeral5m: 30})
// Existing explicit 1h accounting still emits a split even without
// presence evidence, including its cap to the total writes.
wantUsageSplit(t, Usage{CacheWrite: 40, CacheWrite1h: 60}, &aCacheCreation{Ephemeral1h: 40})
}
func TestAnthropicCacheSplitUnreportedDeltaKeepsHour(t *testing.T) {
before := splitUsage(t, `{"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20}}`)
start := splitUsage(t, `{"cache_creation_input_tokens":40,"cache_creation":{"ephemeral_5m_input_tokens":25,"ephemeral_1h_input_tokens":15}}`)
delta := splitUsage(t, `{"cache_creation_input_tokens":40}`)
var client Usage
client.add(start.plus(before, false))
client.add(delta.plus(before, true))
if client.CacheWrite != 60 || client.CacheWrite1h != 35 {
t.Fatalf("delta without a split changed known writes: got %d/%d, want 60/35", client.CacheWrite, client.CacheWrite1h)
}
wantUsageSplit(t, client, &aCacheCreation{Ephemeral5m: 25, Ephemeral1h: 35})
}
func TestAnthropicCacheSplitZeroDeltaKeepsWrites(t *testing.T) {
s := newSniffer(provider.Anthropic, "text/event-stream")
s.parse([]byte(`{"type":"message_start","message":{"usage":{"cache_creation_input_tokens":30}}}`))
s.parse([]byte(`{"type":"message_delta","usage":{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}}`))
if s.u.CacheWrite != 30 {
t.Fatalf("zero delta erased cache writes: got %d, want 30", s.u.CacheWrite)
}
wantUsageSplit(t, s.u, &aCacheCreation{Ephemeral5m: 30})
}
func TestAnthropicCacheSplitZeroDeltaKeepsEarlierRound(t *testing.T) {
before := Usage{CacheWrite: 30}
start := aUsage{CacheCreationInputTokens: 20, CacheCreation: &aCacheCreation{Ephemeral5m: 20}}.usage()
delta := aUsage{CacheCreation: &aCacheCreation{}}.usage()
var client Usage
client.add(start.plus(before, false))
if client.CacheWrite != 50 {
t.Fatalf("message_start cache writes = %d, want 50", client.CacheWrite)
}
client.add(delta.plus(before, true))
if client.CacheWrite != 50 {
t.Fatalf("zero delta after earlier round reduced cache writes: got %d, want 50", client.CacheWrite)
}
}
func TestOtherUsageDoesNotInventAnthropicSplit(t *testing.T) {
var chat cUsage
if err := json.Unmarshal([]byte(`{"prompt_tokens":100,"completion_tokens":7,"prompt_tokens_details":{"cache_write_tokens":40}}`), &chat); err != nil {
t.Fatal(err)
}
var responses rUsage
if err := json.Unmarshal([]byte(`{"input_tokens":100,"output_tokens":7,"input_tokens_details":{"cache_write_tokens":40}}`), &responses); err != nil {
t.Fatal(err)
}
for _, u := range []Usage{chat.usage(), responses.usage()} {
if u.CacheWrite != 40 {
t.Fatalf("fixture has no cache writes: %+v", u)
}
wantUsageSplit(t, u, nil)
var total Usage
total.add(u)
wantUsageSplit(t, total, nil)
wantUsageSplit(t, total.plus(u, false), nil)
}
}
@@ -0,0 +1,157 @@
package gateway
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
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}}}`
)
func cacheSplitRoundStart(fields string) string {
return `{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"m","content":[],"usage":{` + fields + `}}}`
}
func wantCacheLedger(t *testing.T, hour int) {
t.Helper()
records := usage.Load(time.Time{})
if len(records) != 1 {
t.Fatalf("ledger records = %d, want 1", len(records))
}
if u := records[0]; u.CacheWrite != 50 || u.CacheWrite1h != hour {
t.Errorf("ledger writes: %d/hour%d, want 50/hour%d", u.CacheWrite, u.CacheWrite1h, hour)
}
}
func TestProbe1717ContinuationTotalZeroSplit(t *testing.T) {
checkCacheContinuation(t, zeroSplitDelta, 15)
}
func checkCacheContinuation(t *testing.T, delta string, hour int) {
t.Helper()
f := &cutAnthropic{
cuts: map[int][]string{0: {cacheSplitRoundStart(zeroSplitBefore), anthText("hel")}},
whole: []string{cacheSplitRoundStart(zeroSplitStart), anthText("lo"), delta, `{"type":"message_stop"}`},
}
body := continuationChatServer(t, "m", f)
if f.calls() != 2 || chatTextOf(body) != "hello" {
t.Fatalf("continuation failed: calls%d body%s", f.calls(), body)
}
if prefill, ok := f.lastAssistantText(t, 1); !ok || prefill != "hel" {
t.Fatalf("retry did not continue cut reply: %q %t", prefill, ok)
}
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"])
}
wantCacheLedger(t, hour)
}
func TestProbe1717SearchTotalZeroSplit(t *testing.T) {
checkCacheSearch(t, zeroSplitDelta, 15)
}
func checkCacheSearch(t *testing.T, delta string, hour int) {
t.Helper()
for _, stream := range []bool{true, false} {
t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) {
fresh(t)
apis := newSearchAPIs(t)
if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var asked []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
asked = append(asked, string(b))
n := len(asked)
mu.Unlock()
if n == 1 {
writeStream(w, []string{
cacheSplitRoundStart(zeroSplitBefore),
`{"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":5}}`,
`{"type":"message_stop"}`,
}, false, "")
return
}
writeStream(w, []string{cacheSplitRoundStart(zeroSplitStart), anthText("answer"), delta, `{"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)
}
body := fmt.Sprintf(`{"model":"up/m","max_tokens":100,"stream":%t,"messages":[{"role":"user","content":"latest go"}],"tools":[{"type":"web_search_20250305","name":"web_search"}]}`, stream)
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
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 {
t.Fatalf("search reply=%d %s", w.Code, w.Body)
}
mu.Lock()
secondRound := len(asked) == 2 && strings.Contains(asked[1], `"tool_result"`) && strings.Contains(asked[1], "https://go.dev/dl/")
mu.Unlock()
if !secondRound {
t.Fatal("model did not receive search results in a second round")
}
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)
}
wantCacheLedger(t, hour)
})
}
}
func TestProbe1717BridgeTotalZeroSplit(t *testing.T) {
ev := func(e string) string { return `{"type":"stream_event","event":` + e + `}` }
before := `"cache_creation_input_tokens":30,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":10}`
start := `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":5}`
delta := `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`
lines := []string{
ev(`{"type":"message_start","message":{"id":"m1","model":"x","usage":{` + before + `}}}`),
ev(`{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"WebSearch"}}`),
ev(`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}`),
ev(`{"type":"message_stop"}`),
`{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"results"}]}}`,
ev(`{"type":"message_start","message":{"id":"m2","model":"x","usage":{` + start + `}}}`),
ev(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"answer"}}`),
ev(`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7,` + delta + `}}`),
ev(`{"type":"message_stop"}`),
}
run := &subscriptionRun{}
seg := run.attach()
done := make(chan struct{})
go func() { defer close(done); run.readOutput(strings.NewReader(strings.Join(lines, "\n") + "\n")) }()
var client Usage
for e := range seg {
if e.Kind == KStart || e.Kind == KUsage {
client.add(e.Usage)
}
}
<-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)
}
}