Files
magpie/internal/gateway/cache_unknown_test.go
T
yetone 436bcc946d routing: a request whose vendor counts no cache tokens shows no hit rate, not 0% (zeewell on X)
zeewell on X: every Kiro request in a routing group showed cache 0%, for
claude-sonnet-5.5 and claude-opus-5.5 from Claude Code, with 148k to
182k tokens and consecutive calls.

The cause, from real Kiro calls on the owner's account (read-only, from
a sandbox): Kiro does cache. A repeated 900-line prefix cost 0.0912
credits and then 0.0484, with or without cachePoints, and with a fixed
conversationId too. But Kiro's reply holds only assistantResponseEvent,
metadataEvent {stopReason}, contextUsageEvent (a percent) and
meteringEvent (credits). There are no token counts at all, and
kiro-cli 2.32's own trace shows the same. The plugin wrote
cache_read_input_tokens: 0, which magpie showed as 0%.

opencode-kiro-auth 0.1.16 (plugins 9f6c4e8) now leaves the cache fields
out and says `magpie_cache_unknown: true`. This commit reads that field:
- aUsage reads it into Usage.cacheUnknown, ORed in Usage.add.
- routeUsage sets RouteUsage.CacheUnknown (cache_unknown, omitempty) on
  a try that counted no cache read or write.
- The Routing page's promptOf leaves such a try out of the hit rate. The
  row and its session then show no Cache metric, as for older history.

Clients are never told the field. Usage.anthropic() leaves it out, and
a passthrough forwards the plugin's bytes as they came. The gateway
already relays cache_control to an Anthropic-protocol plugin as Claude
Code sent it, so nothing was lost on the way to Kiro.

Left alone: the usage ledger. usage.Record has no such flag, so the
Usage page's aggregate hit rate still counts a Kiro prompt as a miss.
Filed as #3464.

Run at this head (rebased on origin/main 628e18987):
- gofmt -l internal/gateway internal/provider: clean.
- go vet ./internal/gateway ./internal/provider: clean on darwin, with
  GOOS=linux and with GOOS=windows.
- go test -timeout 45m ./internal/gateway ./internal/provider: ok, ok
  (465s, 126s).
- go test ./internal/gui -run Budget: ok.
- GUI: routing-request-metrics.test.cjs, chromium and webkit, en and zh:
  4 of 4 pass.
- Every routing-*.test.cjs, one base back, at load 130 to 150: the only
  reds were routing-intent-entry, routing-keys-fold and routing-manual.
  Run alone, those three files also go red on a fresh origin/main
  628e18987 worktree (8 reds there, 5 on this branch). They are already
  filed: #3408, #1612 and #3409. This change touches only promptOf's
  cache_unknown rows, which none of their fixtures have.

Broken by hand:
- With aUsage.usage() not carrying the field, TestCacheUnknownReachesTheRoute
  fails in its four Kiro cases (Claude Code whole and streamed, translated
  whole and streamed). The counted-miss case still passes, at 0%.
- With promptOf's skip removed, the GUI test fails in chromium for en and
  zh: "a vendor that counts no cache tokens has no hit rate, not 0%".

The test fixtures are the plugin's real reply bytes from Kiro, captured
10-24.

Not tried: a magpie build running the 0.1.16 plugin against Kiro from the
GUI. The plugin's own end-to-end run against Kiro gave
{"input_tokens":0,"output_tokens":19,"magpie_cache_unknown":true}.
2026-10-24 18:16:17 +08:00

86 lines
4.1 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}}`
)
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])
}
})
}
}
// 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")
}
}