Files
magpie/internal/gateway/cache_unknown_test.go
T
yetone 2987f5e2b7 gateway: a Chat usage's magpie_cache_unknown is read, as an Anthropic one's (#3991, #3979)
Trae CN users see cache read 0 / write 0 on every call. Trae's chat
token_usage stopped naming any cache count around 10-28 (modeyang's 786
trae-cn calls on 10-29 all at 0; plugins#434). opencode-trae-auth 0.2.26
now says magpie_cache_unknown on such a usage, as the Kiro plugin does,
but only aUsage read that flag: cUsage, which a Chat plugin's usage goes
through, dropped it, so the zero still counted as a 0% miss.

cUsage now reads magpie_cache_unknown into Usage.cacheUnknown, so the
route and the usage ledger mark the call's cache as unknown instead of a
miss. A counted 0 (prompt_tokens_details.cached_tokens: 0) stays a miss.
The flag is read, never told by chat(); a same-protocol reply is passed
through as it came, as Kiro's is on /v1/messages.

Test: TestChatCacheUnknownReachesTheRoute, with the plugin's Chat output
for chansee97's real token_usage (plugins#455): pi whole, pi streamed,
translated for Claude Code, and a counted miss.

Run (mote):
- go test -run 'CacheUnknown|CacheCounted' ./internal/gateway: ok
- broken by hand: the old chat.go fails 3 of 4 subtests (the counted
  miss stays green)
- go vet ./internal/gateway on darwin, GOOS=linux, GOOS=windows: ok
- gofmt -l internal/gateway: clean
- go test -timeout 45m ./internal/gateway: ok (641s), at base d6e111638 plus this change;
  rebased on d9845432f (4 commits, none in internal/gateway), where
  -run 'CacheUnknown|CacheCounted|Usage' ./internal/gateway: ok

Not tried: a real Trae CN account (none available), so whether Trae now
omits the cache fields or sends 0 is not confirmed; if it sends 0, the
call stays a 0% miss. Not run: the full ./... suite (the change is one
struct field in internal/gateway).
2026-10-31 20:35:12 +08:00

144 lines
7.6 KiB
Go

package gateway
import (
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// The Kiro plugin's real replies (opencode-kiro-auth 0.1.16 against
// Kiro, 10-24): Kiro caches but counts no tokens, cache included, so the
// plugin says magpie_cache_unknown and the Routing page shows no hit rate
// where it showed 0% (zeewell on X).
const (
kiroStream = "event: message_start\n" +
`data: {"type":"message_start","message":{"id":"msg_6eb0d1cc14c9126db4218f61","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}` + "\n\n" +
"event: content_block_start\n" +
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" +
"event: content_block_delta\n" +
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"OK"}}` + "\n\n" +
"event: content_block_stop\n" +
`data: {"type":"content_block_stop","index":0}` + "\n\n" +
"event: message_delta\n" +
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":19,"magpie_cache_unknown":true}}` + "\n\n" +
"event: message_stop\n" +
`data: {"type":"message_stop"}` + "\n\n"
kiroJSON = `{"id":"msg_e6ad400ac6ed0f3febe5125d","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[{"type":"text","text":"OK."}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":1,"magpie_cache_unknown":true}}`
// a vendor that counts its cache and read none of it: a real 0%
missJSON = `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"OK."}],"stop_reason":"end_turn","usage":{"input_tokens":1200,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}`
)
// TestCacheUnknownReachesTheRoute: the flag reaches the route and the
// ledger's record.
func TestCacheUnknownReachesTheRoute(t *testing.T) {
messages := `{"model":"fake/m1","max_tokens":20,"messages":[{"role":"user","content":"Say just OK."}]}`
streamed := `{"model":"fake/m1","max_tokens":20,"stream":true,"messages":[{"role":"user","content":"Say just OK."}]}`
chat := `{"model":"fake/m1","messages":[{"role":"user","content":"Say just OK."}]}`
for _, c := range []struct {
name, ctype, reply, path, request string
unknown bool
}{
{"Claude Code, whole", "application/json", kiroJSON, "/v1/messages", messages, true},
{"Claude Code, streamed", "", kiroStream, "/v1/messages", streamed, true},
// a translated request is always streamed from the vendor
{"translated for a Chat client", "", kiroStream, "/v1/chat/completions", chat, true},
{"translated, streamed", "", kiroStream, "/v1/chat/completions", strings.Replace(chat, `"messages"`, `"stream":true,"messages"`, 1), true},
{"a counted miss stays 0%", "application/json", missJSON, "/v1/messages", messages, false},
} {
t.Run(c.name, func(t *testing.T) {
setup(t, provider.Anthropic, &fake{ctype: c.ctype, reply: c.reply})
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", c.path, strings.NewReader(c.request)))
if rec.Code != 200 {
t.Fatalf("gateway: %d %s", rec.Code, rec.Body)
}
r := lastRoute(s)
if len(r.Usage) != 1 {
t.Fatalf("route usage %+v", r.Usage)
}
if got := r.Usage[0].CacheUnknown; got != c.unknown {
t.Fatalf("cache unknown %v, want %v: %+v", got, c.unknown, r.Usage[0])
}
// and the usage ledger, whose hit rates leave it out (#3464)
if got := lastRecord(t); got.CacheUnknown != c.unknown {
t.Fatalf("ledger cache unknown %v, want %v: %+v", got.CacheUnknown, c.unknown, got)
}
})
}
}
// a try whose vendor did count cache tokens is known, whatever another
// part of the reply said
func TestCacheCountedIsNotUnknown(t *testing.T) {
var u Usage
u.add(aUsage{OutputTokens: 1, CacheUnknown: true}.usage())
u.add(aUsage{InputTokens: 10, OutputTokens: 2, CacheReadInputTokens: 90}.usage())
if rs := routeUsage("p", "m", u); len(rs) != 1 || rs[0].CacheUnknown {
t.Fatalf("%+v", rs)
}
}
// what Claude Code is told is Anthropic's usage: magpie never adds the
// field to a reply it writes itself
func TestCacheUnknownNotTold(t *testing.T) {
u := aUsage{InputTokens: 5, OutputTokens: 1, CacheUnknown: true}.usage()
if u.anthropic().CacheUnknown {
t.Fatal("told")
}
}
// The Trae plugin's replies (opencode-trae-auth 0.2.26) to a token_usage
// naming no cache field, chansee97's real one in plugins#455
// ({"prompt_tokens":1717,"completion_tokens":2,"total_tokens":1719}): a
// Chat usage saying magpie_cache_unknown, which magpie read as a counted
// 0% miss on every Trae CN call (yetone/magpie#3991, #3979).
const (
traeStream = `data: {"id":"chatcmpl-1","object":"chat.completion.chunk","model":"deepseek-v3.1","choices":[{"index":0,"delta":{"role":"assistant","content":"OK"},"finish_reason":null}]}` + "\n\n" +
`data: {"id":"chatcmpl-1","object":"chat.completion.chunk","model":"deepseek-v3.1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}` + "\n\n" +
`data: {"id":"chatcmpl-1","object":"chat.completion.chunk","model":"deepseek-v3.1","choices":[],"usage":{"prompt_tokens":1717,"completion_tokens":2,"total_tokens":1719,"magpie_cache_unknown":true}}` + "\n\n" +
"data: [DONE]\n\n"
traeJSON = `{"id":"chatcmpl-1","object":"chat.completion","model":"deepseek-v3.1","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1717,"completion_tokens":2,"total_tokens":1719,"magpie_cache_unknown":true}}`
// a Chat vendor that counts its cache and read none of it: a real 0%
chatMissJSON = `{"id":"chatcmpl-2","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1717,"completion_tokens":2,"total_tokens":1719,"prompt_tokens_details":{"cached_tokens":0}}}`
)
// TestChatCacheUnknownReachesTheRoute: a Chat vendor's (a plugin's)
// magpie_cache_unknown reaches the route and the ledger, as Kiro's does.
func TestChatCacheUnknownReachesTheRoute(t *testing.T) {
chat := `{"model":"fake/m1","messages":[{"role":"user","content":"Say just OK."}]}`
streamed := strings.Replace(chat, `"messages"`, `"stream":true,"messages"`, 1)
messages := `{"model":"fake/m1","max_tokens":20,"messages":[{"role":"user","content":"Say just OK."}]}`
for _, c := range []struct {
name, ctype, reply, path, request string
unknown bool
}{
{"pi, whole", "application/json", traeJSON, "/v1/chat/completions", chat, true},
{"pi, streamed", "", traeStream, "/v1/chat/completions", streamed, true},
{"translated for Claude Code", "", traeStream, "/v1/messages", messages, true},
{"a counted miss stays 0%", "application/json", chatMissJSON, "/v1/chat/completions", chat, false},
} {
t.Run(c.name, func(t *testing.T) {
setup(t, provider.Chat, &fake{ctype: c.ctype, reply: c.reply})
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", c.path, strings.NewReader(c.request)))
if rec.Code != 200 {
t.Fatalf("gateway: %d %s", rec.Code, rec.Body)
}
r := lastRoute(s)
if len(r.Usage) != 1 {
t.Fatalf("route usage %+v", r.Usage)
}
if got := r.Usage[0].CacheUnknown; got != c.unknown {
t.Fatalf("cache unknown %v, want %v: %+v", got, c.unknown, r.Usage[0])
}
if got := lastRecord(t); got.CacheUnknown != c.unknown {
t.Fatalf("ledger cache unknown %v, want %v: %+v", got.CacheUnknown, c.unknown, got)
}
})
}
}