Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

usage: a call whose vendor counts no cache is left out of every hit rate (#3464)

yetone3a47e377e0d6
diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md
index 8f1430fcb..e826f10bf 100644
--- a/docs/subsystems/provider-plugins.md
+++ b/docs/subsystems/provider-plugins.md
@@ -40,7 +40,7 @@ The gateway parses the field into `Usage.Deferred` ([`cUsage`](../../internal/ga
## Cache a vendor doesn't count
-A plugin whose vendor counts no cache tokens says so with `usage.magpie_cache_unknown: true` in its Anthropic usage, and leaves the cache fields out. Kiro does this: it caches on its side (a repeated prompt costs about half the credits), but its replies carry credits and a context share, never tokens (opencode-kiro-auth 0.1.16, zeewell on X). The gateway reads the field in [`aUsage`](../../internal/gateway/anthropic.go) into `Usage.cacheUnknown`, ORed across a reply's usage events. [`routeUsage`](../../internal/gateway/trace.go) then sets `RouteUsage.CacheUnknown` on a try that counted no cache read or write. The Routing page's `promptOf` (`plugins/routing/client.js`) leaves such a try out of the hit rate, so the request shows none, not 0%. The field is never told to a client: `Usage.anthropic()` leaves it out, and a passthrough forwards the plugin's bytes as they are. The usage ledger doesn't carry it yet ([#3464](https://github.com/yetone/magpie/issues/3464)). [`cache_unknown_test.go`](../../internal/gateway/cache_unknown_test.go) covers the passthrough and translated replies, both whole and streamed.
+A plugin whose vendor counts no cache tokens says so with `usage.magpie_cache_unknown: true` in its Anthropic usage, and leaves the cache fields out. Kiro does this: it caches on its side (a repeated prompt costs about half the credits), but its replies carry credits and a context share, never tokens (opencode-kiro-auth 0.1.16, zeewell on X). The gateway reads the field in [`aUsage`](../../internal/gateway/anthropic.go) into `Usage.cacheUnknown`, ORed across a reply's usage events. [`routeUsage`](../../internal/gateway/trace.go) then sets `RouteUsage.CacheUnknown` on a try that counted no cache read or write. The Routing page's `promptOf` (`plugins/routing/client.js`) leaves such a try out of the hit rate, so the request shows none, not 0%. The field is never told to a client: `Usage.anthropic()` leaves it out, and a passthrough forwards the plugin's bytes as they are. The usage ledger carries it too ([#3464](https://github.com/yetone/magpie/issues/3464)): the gateway records `usage.Record.CacheUnknown` on a call that counted no cache (`Usage.cacheNotCounted`), the ledger keeps it as row flag 8192 (`rowCacheUnknown`), and `usage.Totals` sums such calls' prompt into `cache_unknown` and their count into `cache_unknown_calls`. Every hit rate leaves that prompt out of its denominator: `Totals.HitRate`, and `cacheHitOf` in app.js, used by the tray panel's card, the Usage page's agent rows and cache tile, the requests' Cache hit rate card (which says how many it left out, `cacheLeftOut`) and each ranking row. One of only such calls shows no rate. A request row's cache cells show "—" and its details say the vendor doesn't count the cache. Calls kept before Kiro's plugin said so carry no flag, so a Kiro call (`kiro` or `kiro-plugin`) with no cache counted is read as one (`usage.CountsNoCache`): in the ledger's `rowChunk.row`, in `Totals.countCache`, and for Routing's history in `pricedRoutes` (`cacheCounted`, `internal/gui/trace.go`). The context view (`internal/gui/context.go`, `context.js`) shows no cache for such a call and doesn't score it as a miss. Not covered: hit rates read from agents' own session files (`sessions.Tokens`: the TUI and CLI session lists, the Sessions tab's totals), which carry Kiro's 0 as a miss. [`cache_unknown_test.go`](../../internal/gateway/cache_unknown_test.go) covers the passthrough and translated replies, both whole and streamed.
## A plugin's daily check-in
diff --git a/internal/gateway/cache_unknown_test.go b/internal/gateway/cache_unknown_test.go
index 6f5ef8f13..4d3799e6c 100644
--- a/internal/gateway/cache_unknown_test.go
+++ b/internal/gateway/cache_unknown_test.go
@@ -30,6 +30,8 @@ const (
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."}]}`
@@ -60,6 +62,10 @@ func TestCacheUnknownReachesTheRoute(t *testing.T) {
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)
+ }
})
}
}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index b605dd956..3bedcde12 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -3046,7 +3046,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream,
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
- CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status,
+ CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, CacheUnknown: call.Usage.billed().cacheNotCounted(), Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status,
TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier,
TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true}
@@ -3090,7 +3090,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
Requested: call.Model, Served: call.Usage.Served,
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
- CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status,
+ CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, CacheUnknown: call.Usage.billed().cacheNotCounted(), Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status,
TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier,
TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true}
@@ -3701,7 +3701,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream,
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
- CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: call.Millis, Status: call.Status,
+ CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, CacheUnknown: call.Usage.billed().cacheNotCounted(), Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: call.Millis, Status: call.Status,
TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier,
TTFT: call.TTFT, FirstText: call.FirstText, FirstReasoning: call.FirstReasoning, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Sent: sentMs, Own: ownMs, Retried: retriedMs, Queued: queuedMs, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
RequestID: call.Usage.RequestID, ResponseID: call.Usage.ResponseID, Endpoint: endpointOf(r, from, call.To, lastTried, model), Stop: call.Usage.Stop, Archive: call.archiveName()}
diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go
index 722818edf..3124d7bf7 100644
--- a/internal/gateway/ir.go
+++ b/internal/gateway/ir.go
@@ -402,6 +402,13 @@ type Usage struct {
// billed is what the request is billed for: its own count, and what it
// counted of earlier ones (Deferred).
+// cacheNotCounted is whether the vendor counted no cache for this usage:
+// it said so (cacheUnknown) and no try of it reported a cache token. The
+// Routing page and the ledger leave such a prompt out of a hit rate (#3464).
+func (u Usage) cacheNotCounted() bool {
+ return u.cacheUnknown && u.CacheRead+u.CacheWrite == 0
+}
+
func (u Usage) billed() Usage {
if d := u.Deferred; d != nil {
u.Input += d.Input
diff --git a/internal/gateway/observe.go b/internal/gateway/observe.go
index 6b77ce740..eb762cf28 100644
--- a/internal/gateway/observe.go
+++ b/internal/gateway/observe.go
@@ -77,7 +77,7 @@ func (o *observed) attempt(call Call, attempt Try, providerID, effort string, he
u := call.Usage.billed()
rec := usage.Record{RouteID: o.routeID, Time: attempt.Start, Agent: call.Agent,
Provider: providerID, Model: attempt.Model, Requested: call.Model, Served: u.Served, Effort: effort,
- Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning,
+ Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, CacheUnknown: u.cacheNotCounted(), Reasoning: u.Reasoning,
Millis: time.Since(attempt.Start).Milliseconds(), Status: attempt.Status, TTFT: attempt.TTFT, FirstText: attempt.FirstText, FirstReasoning: attempt.FirstReasoning, ReasoningHidden: attempt.ReasoningHidden}
if wanted := usage.ObservedBodies(); wanted != usage.NoBodies {
reply, cut := capture.body.text(), capture.body.truncated
diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go
index 30fa86d21..5abc2d074 100644
--- a/internal/gateway/trace.go
+++ b/internal/gateway/trace.go
@@ -893,5 +893,5 @@ func routeUsage(id, model string, u Usage) []RouteUsage {
}
return append(out, RouteUsage{Provider: id, Model: model, Input: u.Input, Output: u.Output,
CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning,
- CacheUnknown: u.cacheUnknown && u.CacheRead+u.CacheWrite == 0})
+ CacheUnknown: u.cacheNotCounted()})
}
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index 8b2b17a0b..bcc2396ea 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -16989,7 +16989,7 @@ function renderPanelUse() {
none.append(el("b", "", t(panelUseProvider || panelUsePeriod !== "today" ? "No requests here" : "No requests today")), t("Every request an agent sends to magpie, and every call the agents' own session files record, is counted here."));
out.push(none);
} else {
- const prompt = l.input + l.cache_write + l.cache_read;
+ const hitRate = cacheHitOf(l);
const tot = el("div", "pu-tot");
const blk = (label, value, sub, cls, subCls) => {
const b = el("div", "blk");
@@ -17007,7 +17007,7 @@ function renderPanelUse() {
blk("Requests", ledNum(l.calls), [l.errors ? t("{n} failed", { n: ledNum(l.errors) }) : t("none failed"), l.retried ? t("{n} answered on a retry", { n: ledNum(l.retried) }) : ""].filter(Boolean).join(" · "), "", l.errors ? "bad" : "");
const c = fmtCost(l);
blk("Cost", c ? "≈" + c : "—", l.unpriced ? t("{n} unpriced", { n: l.unpriced }) : t("effective prices"), c ? "cost" : "");
- blk("Cache hit rate", prompt ? Math.round((100 * l.cache_read) / prompt) + "%" : "—", t("of the prompt"));
+ blk("Cache hit rate", hitRate === null ? "—" : Math.round(100 * hitRate) + "%", cacheLeftOut(l) || t("of the prompt"));
const card = el("div", "pu-card");
const head = el("div", "led-bar");
const met = el("div", "segs");
@@ -18408,6 +18408,16 @@ function ledMoney(v) {
const LED_METRICS = [["tokens", "Tokens"], ["cost", "Cost"], ["calls", "Requests"]];
const LED_SHOWN = 7; // told apart in a chart; the rest are "Other"
const allTokens = (x) => x.input + x.output + x.cache_read + x.cache_write;
+// a total's cache hit rate, leaving out cache_unknown (calls whose vendor
+// counts no cache); null when nothing is left (#3464)
+const cacheHitOf = (x) => {
+ const prompt = (x.input || 0) + (x.cache_read || 0) + (x.cache_write || 0) - (x.cache_unknown || 0);
+ return prompt > 0 ? (x.cache_read || 0) / prompt : null;
+};
+// what a hit rate leaves out, when it leaves anything out
+const cacheLeftOut = (x) => x.cache_unknown_calls
+ ? t(x.cache_unknown_calls === 1 ? "{n} request left out: its vendor doesn't count the cache" : "{n} requests left out: their vendor doesn't count the cache", { n: ledNum(x.cache_unknown_calls) })
+ : "";
// how fast the timed replies of a point, a share or a part wrote, in tokens
// a second after their first (usage.Totals.Speed): 0 for none timed
const ledSpeed = (x) => x?.decode_ms > 0 ? (1000 * x.decode_out) / x.decode_ms : 0;
@@ -18699,8 +18709,8 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
// how fast its replies came, beside what they cost (#860)
if (metric !== "speed" && gs) more.push(Object.assign(el("span", "rk-speed", gs.text), { title: gs.title }));
if (ledTTFT(x)) more.push(t("TTFT {ms}", { ms: ledTook(ledTTFT(x)) }));
- const prompt = x.input + x.cache_write + x.cache_read;
- if (prompt && !compact) more.push(t("hit rate {p}", { p: Math.round((100 * x.cache_read) / prompt) + "%" }));
+ const hit = cacheHitOf(x);
+ if (hit !== null && !compact) more.push(t("hit rate {p}", { p: Math.round(100 * hit) + "%" }));
// a speed is no one's share of all
if (metric !== "speed") more.push(Math.round((100 * v) / sum) + "%");
const l2 = el("div", "rk-b");
@@ -18717,7 +18727,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
for (const x of top) box.append(one(x, x.color));
if (rest.length) {
const tot = rest.reduce((acc, x) => {
- for (const k of ["calls", "errors", "loops", "input", "output", "cache_read", "cache_write", "cost", "credits", "credited", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]) acc[k] = (acc[k] || 0) + (x[k] || 0);
+ for (const k of ["calls", "errors", "loops", "input", "output", "cache_read", "cache_write", "cache_unknown", "cache_unknown_calls", "cost", "credits", "credited", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]) acc[k] = (acc[k] || 0) + (x[k] || 0);
return acc;
}, { id: "\0other", name: t("Other ({n})", { n: rest.length }) });
box.append(one(tot, "var(--faint)", true));
diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js
index 4ed66c668..c5eb4b5c7 100644
--- a/internal/gui/assets/context.js
+++ b/internal/gui/assets/context.js
@@ -77,7 +77,8 @@
// the cache a route's vendor read: its last answer's usage
function cacheOf(r) {
const u = r.usage?.[r.usage.length - 1];
- if (!u) return null;
+ // a vendor that counts no cache has none to show, not 0% (#3464)
+ if (!u || u.cache_unknown) return null;
const total = (u.in || 0) + (u.cache_read || 0) + (u.cache_write || 0);
if (!total) return null;
return { read: u.cache_read || 0, total };
@@ -1216,7 +1217,7 @@
if (open && s.latest) {
const last = s.points[s.points.length - 1];
const r = { id: s.latestId, time: s.last, done: true, agent: s.agent, model: s.model, prompt: s.latest };
- const cache = last && s.latest.counted && last.tokens ? { read: last.cache || 0, total: last.tokens } : null;
+ const cache = last && s.latest.counted && last.tokens && !last.cache_unknown ? { read: last.cache || 0, total: last.tokens } : null;
box.append(ctxCard(r, {
still: true, cache, place: "session",
series: s.points,
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 4b4313cbf..256695f08 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -2689,6 +2689,9 @@ const I18N = {
"… {n} more characters not shown": "……还有 {n} 个字符未显示",
"Read from the agent's session file; magpie keeps no copy": "读自 Agent 的会话文件,magpie 不保存副本",
"Cache hit rate": "缓存命中率",
+ "{n} request left out: its vendor doesn't count the cache": "{n} 个请求未计入:其服务商不统计缓存",
+ "{n} requests left out: their vendor doesn't count the cache": "{n} 个请求未计入:其服务商不统计缓存",
+ "The vendor doesn't count the cache": "服务商不统计缓存",
"Metrics": "指标",
"Usage trend": "使用趋势",
"Split by": "拆分维度",
@@ -6627,6 +6630,9 @@ const I18N = {
"… {n} more characters not shown": "……還有 {n} 個字元未顯示",
"Read from the agent's session file; magpie keeps no copy": "讀自 Agent 的會話檔案,magpie 不儲存副本",
"Cache hit rate": "快取命中率",
+ "{n} request left out: its vendor doesn't count the cache": "{n} 個請求未計入:其服務商不統計快取",
+ "{n} requests left out: their vendor doesn't count the cache": "{n} 個請求未計入:其服務商不統計快取",
+ "The vendor doesn't count the cache": "服務商不統計快取",
"Metrics": "指標",
"Usage trend": "使用趨勢",
"Split by": "拆分維度",
@@ -10567,6 +10573,9 @@ const I18N = {
"… {n} more characters not shown": "… ほか {n} 文字は表示されていません",
"Read from the agent's session file; magpie keeps no copy": "エージェントのセッションファイルから読み取り。magpie はコピーを保存しません",
"Cache hit rate": "キャッシュヒット率",
+ "{n} request left out: its vendor doesn't count the cache": "{n} 件のリクエストを除外:提供元がキャッシュを数えません",
+ "{n} requests left out: their vendor doesn't count the cache": "{n} 件のリクエストを除外:提供元がキャッシュを数えません",
+ "The vendor doesn't count the cache": "提供元はキャッシュを数えません",
"Metrics": "指標",
"Usage trend": "使用量の推移",
"Split by": "分割",
@@ -14517,6 +14526,9 @@ const I18N = {
"… {n} more characters not shown": "… {n} weitere Zeichen nicht angezeigt",
"Read from the agent's session file; magpie keeps no copy": "Aus der Sitzungsdatei des Agenten gelesen; magpie behält keine Kopie",
"Cache hit rate": "Cache-Trefferquote",
+ "{n} request left out: its vendor doesn't count the cache": "{n} Anfrage nicht gezählt: ihr Anbieter zählt den Cache nicht",
+ "{n} requests left out: their vendor doesn't count the cache": "{n} Anfragen nicht gezählt: ihr Anbieter zählt den Cache nicht",
+ "The vendor doesn't count the cache": "Der Anbieter zählt den Cache nicht",
"Metrics": "Kennzahlen",
"Usage trend": "Nutzungsverlauf",
"Split by": "Aufteilen nach",
diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js
index 28ee2a875..da85aaea3 100644
--- a/internal/gui/assets/plugins/usage/page.js
+++ b/internal/gui/assets/plugins/usage/page.js
@@ -473,8 +473,9 @@ function renderUsage() {
// them), so what was written counts in the prompt too: left out, a prompt
// written to the cache again at every turn showed a rate near 100%. The
// written count is secondary and only fits in the tooltip.
- const promptTokens = u.input + u.cache_read + u.cache_write;
- const hit = u.cache_read && promptTokens ? t("hit rate {p}", { p: Math.round(100 * u.cache_read / promptTokens) + "%" }) : "";
+ // a vendor that counts no cache (cache_unknown) is left out (#3464)
+ const hitRate = cacheHitOf(u);
+ const hit = u.cache_read && hitRate !== null ? t("hit rate {p}", { p: Math.round(100 * hitRate) + "%" }) : "";
tile(fmtN(u.cache_read), t("cache read"), hit, u.cache_write ? t("{n} written", { n: fmtN(u.cache_write) }) + cacheTTLs(u, fmtN) : "");
tile(fmtN(u.reasoning), t("reasoning"), t("inside output"));
tile(String(u.calls), t(u.calls === 1 ? "call" : "calls"), [u.errors ? t("{n} failed", { n: u.errors }) : "", u.retried ? t("{n} answered on a retry", { n: u.retried }) : "", u.unpriced ? t("{n} unpriced", { n: u.unpriced }) : ""].filter(Boolean).join(" · "), u.unpriced ? unpricedCallsWhy(u.unpriced) : "");
@@ -547,8 +548,8 @@ function renderUsage() {
const num = el("div", "num");
// how much of its prompt came from the cache, counted as the cache
// read tile counts it (#925)
- const prompt = g.input + g.cache_read + (g.cache_write || 0);
- const hit = g.cache_read && prompt ? " · " + t("hit rate {p}", { p: Math.round(100 * g.cache_read / prompt) + "%" }) : "";
+ const hitRate = cacheHitOf(g);
+ const hit = g.cache_read && hitRate !== null ? " · " + t("hit rate {p}", { p: Math.round(100 * hitRate) + "%" }) : "";
num.append(el("b", "", fmtN(usageTokens(g))), el("small", "", t("{a} in · {b} out", { a: fmtN(g.input), b: fmtN(g.output) }) + (g.cache_read ? " · " + t("{n} cached", { n: fmtN(g.cache_read) }) : "") + hit));
r.append(num);
r.append(el("div", "cost", fmtCost(g) ? "≈" + fmtCost(g) : ""));
@@ -938,7 +939,7 @@ function ledDetail(r, cols) {
// whole of it, where the row's cache columns are out of sight (#1839).
// In leaves the cache out, as Anthropic counts it.
if (r.in || r.out || r.cache_read || r.cache_write || !ledFailed_(r)) {
- add("Tokens", t("{i} in · {o} out · {r} cache read · {w} cache creation", { i: ledNum(r.in || 0), o: ledNum(r.out || 0), r: ledNum(r.cache_read || 0), w: ledNum(r.cache_write || 0) }) + cacheTTLs(r, ledNum), "led-tokens");
+ add("Tokens", t("{i} in · {o} out · {r} cache read · {w} cache creation", { i: ledNum(r.in || 0), o: ledNum(r.out || 0), r: ledNum(r.cache_read || 0), w: ledNum(r.cache_write || 0) }) + cacheTTLs(r, ledNum) + (r.cache_unknown ? " · " + t("The vendor doesn't count the cache") : ""), "led-tokens");
}
if (ledRowSpeed(r)) add("Speed", t("{n} tok/s", { n: ledNum(Math.round(ledRowSpeed(r))) }));
else if (ledFloorSpeed(r)) add("Speed", "≥" + t("{n} tok/s", { n: ledNum(Math.round(ledFloorSpeed(r))) }));
@@ -1123,8 +1124,8 @@ function renderLedgerDash(l) {
dash.hidden = !l.total && !l.day;
if (dash.hidden) return;
const total = allTokens(l);
- const prompt = l.input + l.cache_write + l.cache_read;
- const rate = prompt ? l.cache_read / prompt : 0;
+ // of the calls whose vendor counted the cache: none when no call's was (#3464)
+ const rate = cacheHitOf(l);
const strip = $("#ledKpi");
strip.replaceChildren();
const block = (label, value, sub, cls, title) => {
@@ -1165,9 +1166,9 @@ function renderLedgerDash(l) {
if (l.retried) strip.lastChild.append(jumps(jump(t("{n} answered on a retry", { n: ledNum(l.retried) }), "retried", t("Show only the requests answered on a retry"))));
const c = fmtCost(l);
block("Cost", c ? "≈" + c : "—", line(l.unpriced ? t(l.unpriced === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: l.unpriced }) : t("effective prices")), c ? "cost" : "");
- const hit = block("Cache hit rate", (100 * rate).toFixed(1) + "%", null, "", t("The share of the prompt read from the cache"));
+ const hit = block("Cache hit rate", rate === null ? "—" : (100 * rate).toFixed(1) + "%", cacheLeftOut(l) ? line(cacheLeftOut(l)) : null, "", t("The share of the prompt read from the cache"));
const meter = el("div", "meter"), fill = el("i");
- fill.style.width = (100 * rate).toFixed(1) + "%";
+ fill.style.width = (100 * (rate || 0)).toFixed(1) + "%";
meter.append(fill);
hit.append(meter);
// how fast the streamed replies wrote, and how long they took to begin (#860):
@@ -1771,7 +1772,7 @@ function renderLedger() {
// are the rows the filter keeps, so with one source picked the total cell
// would read that one's figures under the whole period's count
const all = {};
- for (const k of ["calls", "errors", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out"]) {
+ for (const k of ["calls", "errors", "input", "output", "cache_read", "cache_write", "cache_unknown", "cache_unknown_calls", "cost", "timed", "ttft_ms", "decode_ms", "decode_out"]) {
all[k] = (thru[k] || 0) + (dir[k] || 0) + (rep[k] || 0);
}
const tile = (b, label, calls, tot, pick) => {
@@ -1932,8 +1933,12 @@ function renderLedger() {
td(r.effort || "—", r.effort ? "" : "faint");
td(ledNum(r.in), "n");
td(ledNum(r.out), "n", r.reasoning ? t("{n} reasoning, inside output", { n: ledNum(r.reasoning) }) : "");
- td(ledNum(r.cache_write), "n" + (r.cache_write ? "" : " faint"), cacheTTLs(r, ledNum).replace(/^ · /, ""));
- td(ledNum(r.cache_read), "n" + (r.cache_read ? "" : " faint"));
+ // a vendor that counts no cache wrote and read none we know of, not 0 (#3464)
+ if (r.cache_unknown) for (let i = 0; i < 2; i++) td("—", "n faint", t("The vendor doesn't count the cache"));
+ else {
+ td(ledNum(r.cache_write), "n" + (r.cache_write ? "" : " faint"), cacheTTLs(r, ledNum).replace(/^ · /, ""));
+ td(ledNum(r.cache_read), "n" + (r.cache_read ? "" : " faint"));
+ }
const cost = td(r.priced ? "≈" + fmtCost({ cost: r.cost, unpriced: 0 }) : "—", "n cost" + (r.priced ? "" : " faint"), r.priced ? (r.pricing_model ? t("API price reference") + ": " + r.pricing_model : "") : t("No known price for this model"));
if (r.priced && r.pricing_model) {
const reference = el("div", "price-reference", t("Price reference: {model}", { model: r.pricing_model }));
diff --git a/internal/gui/cache_unknown_test.go b/internal/gui/cache_unknown_test.go
new file mode 100644
index 000000000..715d3b008
--- /dev/null
+++ b/internal/gui/cache_unknown_test.go
@@ -0,0 +1,64 @@
+package gui
+
+import (
+ "slices"
+ "testing"
+
+ "github.com/yetone/magpie/internal/gateway"
+)
+
+// A Kiro request's prompt is counted as Kiro counts it, prompt tokens but
+// no cache, so the Context page scores its agent neither up nor down for
+// the cache and doesn't call it cache-misses, and each point says its cache
+// is unknown (#3464): the plugin said so (CacheUnknown), or it was kept
+// before the plugin did and Kiro never counts it.
+func TestContextKiroCacheNotAMiss(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ u gateway.RouteUsage
+ }{
+ {"said so", gateway.RouteUsage{Provider: "kiro", Input: 9000, CacheUnknown: true}},
+ {"kept before", gateway.RouteUsage{Provider: "kiro", Input: 9000}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ var routes []gateway.Route
+ for i := range 6 {
+ r := ctxRoute(int64(i+1), "claude", "s1", 8000, 1000*i, 1000000, 0)
+ r.Usage = []gateway.RouteUsage{c.u}
+ routes = append(routes, r)
+ }
+ out := contextOf(routes, 1)
+ a := out.Agents[0]
+ if a.Scores[0].Key != "cache" || a.Scores[0].Points != 18 || a.Cache != 0 {
+ t.Fatalf("cache %v, score %+v", a.Cache, a.Scores[0])
+ }
+ if slices.Contains(tagKeys(a), "cache-misses") {
+ t.Fatalf("tags %v", tagKeys(a))
+ }
+ for _, p := range out.Sessions[0].Points {
+ if !p.CacheUnknown {
+ t.Fatalf("point %+v", p)
+ }
+ }
+ })
+ }
+}
+
+// The Routing page is sent a Kiro try kept before its plugin said Kiro
+// counts no cache as one that doesn't, so it shows no hit rate rather than
+// 0% (zeewell on X, #3464). A vendor that counts its cache keeps its 0%,
+// and the route read is left as it was.
+func TestRoutingKiroCacheKeptBefore(t *testing.T) {
+ kept := []gateway.RouteUsage{{Provider: "kiro", Input: 148000, Output: 19}, {Provider: "anthropic", Input: 1200, Output: 1}}
+ got := cacheCounted(kept)
+ if !got[0].CacheUnknown || got[1].CacheUnknown {
+ t.Fatalf("%+v", got)
+ }
+ if kept[0].CacheUnknown {
+ t.Fatal("the route read was changed")
+ }
+ routes := pricedRoutes([]gateway.Route{{ID: 1, Agent: "claude", Provider: "kiro", Model: "claude-sonnet-4.5", Done: true, Status: 200, Usage: kept[:1]}})
+ if len(routes) != 1 || !routes[0].Usage[0].CacheUnknown {
+ t.Fatalf("%+v", routes)
+ }
+}
diff --git a/internal/gui/context.go b/internal/gui/context.go
index 4b46ae35a..413293ef4 100644
--- a/internal/gui/context.go
+++ b/internal/gui/context.go
@@ -29,6 +29,9 @@ type ctxPoint struct {
Tokens int `json:"tokens"`
Window int `json:"window,omitempty"`
Cache int `json:"cache,omitempty"` // of Tokens, read from the vendor's cache
+ // CacheUnknown: the vendor counted no cache for it, so Cache's 0 is
+ // not a miss (#3464)
+ CacheUnknown bool `json:"cache_unknown,omitempty"`
}
type ctxSession struct {
@@ -150,6 +153,13 @@ func cacheOf(r gateway.Route) int {
return r.Usage[len(r.Usage)-1].CacheRead
}
+// cacheKnown is whether the vendor counted the cache of r's answering try:
+// one that counts none (Kiro) is left out of a hit rate rather than read as
+// a miss (#3464).
+func cacheKnown(r gateway.Route) bool {
+ return len(r.Usage) == 0 || !cacheNotCounted(r.Usage[len(r.Usage)-1])
+}
+
// sessionOfRoute is the conversation a route is part of.
func sessionOfRoute(r gateway.Route) string {
switch {
@@ -289,7 +299,7 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
for _, x := range p.Parts {
acc.parts[x.Kind] += x.Tokens
}
- if p.Counted {
+ if p.Counted && cacheKnown(r) {
acc.counted += p.Tokens
acc.cached += min(cacheOf(r), p.Tokens)
}
@@ -321,7 +331,7 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
acc.growths = append(acc.growths, d)
}
}
- s.Points = append(s.Points, ctxPoint{ID: r.ID, Time: r.Time, Tokens: p.Tokens, Window: p.Window, Cache: cacheOf(r)})
+ s.Points = append(s.Points, ctxPoint{ID: r.ID, Time: r.Time, Tokens: p.Tokens, Window: p.Window, Cache: cacheOf(r), CacheUnknown: !cacheKnown(r)})
s.Requests++
s.Last, s.Latest, s.LatestID, s.Model = r.Time, p, r.ID, r.Model
s.Peak = max(s.Peak, p.Tokens)
diff --git a/internal/gui/tests/ledger-cache-unknown.test.cjs b/internal/gui/tests/ledger-cache-unknown.test.cjs
new file mode 100644
index 000000000..d94965f05
--- /dev/null
+++ b/internal/gui/tests/ledger-cache-unknown.test.cjs
@@ -0,0 +1,148 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// #3464 (zeewell on X): Kiro caches but tells only credits, so its calls
+// carry no cache tokens, and every hit rate read their 0 as a miss: "缓存
+// 0%" on each Kiro call, and a mixed total pulled toward 0. The ledger now
+// keeps such a call's cache as not counted (cache_unknown), and every hit
+// rate leaves it out: the Usage page's agent rows and cache tile, the
+// requests' Cache hit rate card (with how many were left out), each Kiro
+// request's cache cells and details, and the tray panel's card. In
+// Chromium and WebKit, in every language; the API is faked.
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const path = require("node:path");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+
+const assets = path.resolve(__dirname, "../assets");
+const now = Date.now();
+
+// a counted call, 9000 of its 10000 prompt from the cache, and a Kiro one
+// whose 148000 prompt no one counted: 90%, where reading Kiro's 0 as a miss
+// said 9000 / 158000, 6%
+const counted = { input: 500, cache_read: 9000, cache_write: 500 };
+const kiro = { input: 148000, cache_read: 0, cache_write: 0, cache_unknown: 148000, cache_unknown_calls: 1 };
+const plus = (...xs) => xs.reduce((a, x) => { for (const [k, v] of Object.entries(x)) a[k] = (a[k] || 0) + v; return a; }, {});
+const agentRow = (name, x) => ({ name, icon: "", calls: 10, errors: 0, output: 1000, reasoning: 0, cost: 0, unpriced: 0, cache_unknown: 0, ...x });
+const agents = [agentRow("Claude Code", plus(counted, kiro)), agentRow("Kiro only", kiro)];
+const usage = { calls: 20, errors: 0, output: 2000, reasoning: 0, cost: 0, unpriced: 0, path: "/test/usage.jsonl", bucket: "day", agents, models: [], series: [], ...plus(counted, kiro, kiro) };
+
+const req = (i, x) => ({
+ t: new Date(now - (i + 1) * 60e3).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color",
+ providerAccount: "[email protected]", req: "claude-sonnet-4.5", model: "claude-sonnet-4.5", served: "claude-sonnet-4.5",
+ ms: 3000, status: 200, rid: "r-" + i, ep: "/v1/messages", cost: 0.01, priced: true, out: 19, ...x,
+});
+const ROWS = [
+ req(0, { provider: "anthropic", providerName: "Anthropic", in: 500, cache_read: 9000, cache_write: 500 }),
+ req(1, { provider: "kiro", providerName: "Kiro", in: 148000, cache_read: 0, cache_write: 0, cache_unknown: true }),
+];
+const page = (q) => ({ period: q.get("period"), rows: ROWS, offset: 0, total: ROWS.length, calls: 2, errors: 0, output: 38, reasoning: 0, cost: 0.02, unpriced: 0,
+ ...plus(counted, kiro), bucket: "day", series: [], by: { provider: [], agent: [], model: [] }, agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }] });
+
+function serve(lang) {
+ return async (route) => {
+ const url = new URL(route.request().url());
+ const json = (data) => route.fulfill({ json: data });
+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
+ if (url.pathname === "/api/gateway/trace") {
+ if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));
+ return json({ mine: true, now: new Date(now).toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
+ }
+ if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
+ if (url.pathname === "/api/groups") return json({ groups: [], pools: [], models: [] });
+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, calls: [], groups: [] } });
+ if (url.pathname === "/api/plugins") return json({ plugins: [] });
+ if (url.pathname === "/api/usage/requests") return json(page(url.searchParams));
+ if (url.pathname === "/api/usage/requests/content") return json({ found: false, why: "read" });
+ if (url.pathname === "/api/usage/quotas") return json([]);
+ if (url.pathname === "/api/usage") return json(usage);
+ if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
+ if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
+ if (url.pathname.startsWith("/api/window/")) return route.fulfill({ status: 204 });
+ if (url.pathname.startsWith("/api/")) return json({});
+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
+ try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404 }); }
+ };
+}
+
+const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
+const LEFT_OUT = "{n} request left out: its vendor doesn't count the cache";
+const NOT_COUNTED = "The vendor doesn't count the cache";
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ test(`${engine}: a hit rate leaves out the calls whose vendor counts no cache`, async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(() => browser.close());
+ for (const lang of LANGS) {
+ await t.test(lang, async () => {
+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" });
+ const errors = [];
+ const open = async (url) => {
+ const p = await context.newPage();
+ p.setDefaultTimeout(5000);
+ p.on("pageerror", (e) => errors.push(e.message));
+ await p.route("**/*", serve(lang));
+ await p.goto(url);
+ return p;
+ };
+ try {
+ const p = await open("http://magpie.test/?view=usage");
+ const say = (s, v) => p.evaluate(([s, v]) => t(s, v), [s, v]);
+ const n1 = await p.evaluate(() => ledNum(1));
+ const leftOut = await say(LEFT_OUT, { n: n1 }), notCounted = await say(NOT_COUNTED);
+ if (lang !== "en") assert.notEqual(notCounted, NOT_COUNTED, "translated");
+ const rate = (p90) => say("hit rate {p}", { p: p90 });
+
+ // the Usage page: the mixed agent's row and the cache read tile
+ // say 90%, the Kiro-only row none
+ await p.locator("#usageAgents .row.stat").nth(1).waitFor();
+ const notes = await p.locator("#usageAgents .row.stat .num small").allTextContents();
+ assert.equal(notes.length, 2, notes.join(" | "));
+ assert(notes[0].includes(await rate("90%")), notes[0]);
+ const hitWord = (await rate("")).trim();
+ assert(!notes[1].includes(hitWord), notes[1]);
+ const r90 = await rate("90%");
+ const tiles = await p.locator(".kpi").allTextContents();
+ assert(tiles.some((x) => x.includes(r90)), tiles.join(" | "));
+
+ // the requests: 90.0% with one left out, and the Kiro call's cache
+ // cells say nothing counted rather than 0
+ await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
+ const rows = p.locator(".led tbody tr.led-row");
+ await rows.nth(ROWS.length - 1).waitFor({ timeout: 15000 });
+ const card = await p.locator("#ledKpi .blk").evaluateAll((bs, label) => {
+ const b = bs.find((x) => x.querySelector(".k")?.textContent === label);
+ return b && { v: b.querySelector(".v").textContent, sub: b.querySelector(".sub")?.textContent || "" };
+ }, await say("Cache hit rate"));
+ assert(card, "a Cache hit rate card");
+ assert.equal(card.v, "90.0%");
+ assert.equal(card.sub, leftOut);
+ const cells = await p.locator(".led").evaluate((tb, [w, r]) => {
+ const heads = [...tb.tHead.rows[0].cells].map((c) => c.textContent);
+ const at = [heads.indexOf(w), heads.indexOf(r)];
+ return [...tb.tBodies[0].rows].filter((x) => x.classList.contains("led-row")).map((x) => at.map((i) => ({ text: x.cells[i].textContent, title: x.cells[i].title })));
+ }, [await say("Cache write"), await say("Cache read")]);
+ assert.deepEqual(cells[0].map((c) => c.text), [await p.evaluate(() => ledNum(500)), await p.evaluate(() => ledNum(9000))]);
+ assert.deepEqual(cells[1], [{ text: "—", title: notCounted }, { text: "—", title: notCounted }]);
+ // its details say so beside its tokens
+ await rows.nth(1).click();
+ const tokens = await p.locator(".led-detail").last().evaluate((b) => b.querySelector(".led-tokens")?.textContent || b.textContent);
+ assert(tokens.includes(notCounted), tokens);
+ assert(await p.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "the page scrolls sideways");
+
+ // the tray panel's card
+ const panel = await open("http://magpie.test/?mode=panel");
+ await panel.locator('[data-ptab="stats"]').click();
+ await panel.locator("#panelUsage .pu-tot").waitFor();
+ const blk = await panel.locator("#panelUsage .pu-tot .blk").evaluateAll((bs) => bs.map((b) => b.textContent));
+ assert(blk.some((x) => x.includes("90%") && x.includes(leftOut)), blk.join(" | "));
+ assert.deepEqual(errors, []);
+ } finally {
+ await context.close();
+ }
+ });
+ }
+ });
+}
diff --git a/internal/gui/trace.go b/internal/gui/trace.go
index f38f445dd..6b385f489 100644
--- a/internal/gui/trace.go
+++ b/internal/gui/trace.go
@@ -99,6 +99,7 @@ func pricedRoutes(routes []gateway.Route) []routeJSON {
pub := publicRefs()
for _, r := range routes {
r = publicRoute(r, pub)
+ r.Usage = cacheCounted(r.Usage)
recs := make([]usage.Record, len(r.Usage))
for i, u := range r.Usage {
recs[i] = u.PricingRecord()
@@ -119,6 +120,32 @@ func pricedRoutes(routes []gateway.Route) []routeJSON {
return out
}
+// cacheCounted marks the usage of a vendor that counts no cache as such,
+// kept before its plugin said so (usage.CountsNoCache): its hit rate is
+// none rather than 0% (#3464). us is copied before it is changed.
+func cacheCounted(us []gateway.RouteUsage) []gateway.RouteUsage {
+ var out []gateway.RouteUsage
+ for i, u := range us {
+ if u.CacheUnknown || !cacheNotCounted(u) {
+ continue
+ }
+ if out == nil {
+ out = slices.Clone(us)
+ }
+ out[i].CacheUnknown = true
+ }
+ if out == nil {
+ return us
+ }
+ return out
+}
+
+// cacheNotCounted is whether u's vendor counted no cache for it: it said
+// so, or it never does and none was recorded.
+func cacheNotCounted(u gateway.RouteUsage) bool {
+ return u.CacheUnknown || u.CacheRead+u.CacheWrite == 0 && usage.CountsNoCache(u.Provider)
+}
+
// publicRefs is provider.PublicRef, each ref looked up once: a page of
// routes names a few models many times over.
func publicRefs() func(string) string {
diff --git a/internal/usage/cache_unknown_test.go b/internal/usage/cache_unknown_test.go
new file mode 100644
index 000000000..4e03b4a19
--- /dev/null
+++ b/internal/usage/cache_unknown_test.go
@@ -0,0 +1,89 @@
+package usage
+
+import (
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/catalog"
+)
+
+// readBack is r as the ledger reads it back: from a chunk as written, priced
+// into a block, and packed to its archive and out again.
+func readBack(t *testing.T, r Record) []Row {
+ t.Helper()
+ made := func() *rowChunk {
+ var chunk rowChunk
+ for i := 0; i < 80; i++ {
+ chunk.add(Row{Record: r}, "", int64(i), false)
+ }
+ return &chunk
+ }
+ b := newBlockPricer(nil, nil, func(Record) *catalog.Price { return nil })
+ defer b.release()
+ raw := made()
+ return []Row{raw.row(0), b.block(raw).row(0), b.block(made().pack()).row(0)}
+}
+
+// A call whose vendor counted no cache (a plugin's magpie_cache_unknown:
+// Kiro tells only credits) is read back from the ledger as one, so its
+// CacheRead of 0 is never read as a miss (#3464). A vendor that counted a
+// miss stays one, and a Kiro call kept before its plugin said so is read
+// as uncounted: Kiro never counted its cache.
+func TestCacheUnknownKeptInTheLedger(t *testing.T) {
+ at := time.Now()
+ for _, c := range []struct {
+ name string
+ r Record
+ want bool
+ }{
+ {"said so", Record{Time: at, Provider: "zcode", Model: "glm-5", Input: 148000, Output: 19, CacheUnknown: true, Status: 200}, true},
+ {"a counted miss", Record{Time: at, Provider: "anthropic", Model: "claude-sonnet-4-5", Input: 148000, Output: 19, Status: 200}, false},
+ {"Kiro, kept before", Record{Time: at, Provider: "kiro", Model: "claude-sonnet-4.5", Input: 148000, Output: 19, Status: 200}, true},
+ {"Kiro's plugin id, kept before", Record{Time: at, Provider: "kiro-plugin", Model: "claude-sonnet-4.5", Input: 148000, Output: 19, Status: 200}, true},
+ {"Kiro with cache counted", Record{Time: at, Provider: "kiro", Model: "claude-sonnet-4.5", Input: 1000, CacheRead: 9000, Output: 19, Status: 200}, false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ for i, row := range readBack(t, c.r) {
+ if row.CacheUnknown != c.want {
+ t.Fatalf("read %d: cache unknown %v, want %v", i, row.CacheUnknown, c.want)
+ }
+ }
+ })
+ }
+}
+
+// A hit rate leaves out the prompt of calls whose vendor counted no cache:
+// a mixed ledger isn't diluted by them, and one of only those has none,
+// where it read 0% (zeewell on X, #3464).
+func TestHitRateLeavesUncountedOut(t *testing.T) {
+ at := time.Now()
+ counted := Record{Time: at, Provider: "anthropic", Model: "claude-sonnet-4-5", Input: 500, CacheRead: 9000, CacheWrite: 500, Output: 10, Status: 200}
+ kiro := Record{Time: at, Provider: "kiro", Model: "claude-sonnet-4.5", Input: 148000, Output: 19, CacheUnknown: true, Status: 200}
+ // kept before the plugin said so: Kiro never counts its cache
+ kiroBefore := Record{Time: at, Provider: "kiro-plugin", Model: "claude-sonnet-4.5", Input: 90000, Output: 19, Status: 200}
+ for _, c := range []struct {
+ name string
+ rs []Record
+ rate float64
+ known bool
+ calls int
+ }{
+ {"mixed", []Record{counted, kiro, kiro, kiroBefore}, 0.9, true, 3},
+ {"only uncounted", []Record{kiro, kiroBefore}, 0, false, 2},
+ {"only counted", []Record{counted}, 0.9, true, 0},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ var byRecord, byRow Totals
+ for _, r := range c.rs {
+ byRecord.add(r, nil)
+ byRow.addRow(Row{Record: r})
+ }
+ for _, tot := range []Totals{byRecord, byRow} {
+ rate, known := tot.HitRate()
+ if known != c.known || rate != c.rate || tot.CacheUnknownCalls != c.calls {
+ t.Fatalf("hit rate %v (%v), %d left out; want %v (%v), %d: %+v", rate, known, tot.CacheUnknownCalls, c.rate, c.known, c.calls, tot)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go
index 69f18c07d..3266c120a 100644
--- a/internal/usage/ledger.go
+++ b/internal/usage/ledger.go
@@ -748,6 +748,7 @@ func (t *Totals) addRow(r Row) {
t.CacheRead += r.CacheRead
t.CacheWrite += r.CacheWrite
t.CacheWrite1h += r.CacheWrite1h
+ t.countCache(r.Record)
t.Reasoning += r.Reasoning
switch {
case r.Priced:
diff --git a/internal/usage/reasoning_stream_speed_test.go b/internal/usage/reasoning_stream_speed_test.go
index c95d1a4e1..2c4505825 100644
--- a/internal/usage/reasoning_stream_speed_test.go
+++ b/internal/usage/reasoning_stream_speed_test.go
@@ -149,7 +149,7 @@ func TestRowFlagsApart(t *testing.T) {
}
})
}
- bits := []uint16{1, 2, 4, 8, 16, 32, swapKnown, rowHandedOn, rowReasoningHidden, rowOwnCost, rowCompactionKnown, rowCompaction, rowCredits}
+ bits := []uint16{1, 2, 4, 8, 16, 32, swapKnown, rowHandedOn, rowReasoningHidden, rowOwnCost, rowCompactionKnown, rowCompaction, rowCredits, rowCacheUnknown}
var all uint16
for _, b := range bits {
if all&b != 0 {
diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go
index fae008806..ca017502e 100644
--- a/internal/usage/request_page.go
+++ b/internal/usage/request_page.go
@@ -96,6 +96,10 @@ const rowOwnCost = 256
// Record.Credits again.
const rowCredits = 4096
+// rowCacheUnknown is the Flags bit of Record.CacheUnknown: its vendor
+// counted no cache (#3464).
+const rowCacheUnknown = 8192
+
type rowChunk struct {
Archive []byte
Locations []*time.Location
@@ -237,6 +241,9 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
if r.Routed {
p.Flags |= 32
}
+ if r.CacheUnknown {
+ p.Flags |= rowCacheUnknown
+ }
if failed {
p.Flags |= 16
}
@@ -276,7 +283,7 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
}
func (c *rowChunk) row(i int) Row {
p := &c.Rows[i]
- r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time, Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: p.Millis, TTFT: p.TTFT, FirstText: p.FirstText, FirstReasoning: p.FirstReasoning, ReasoningHidden: p.Flags&rowReasoningHidden != 0, Sent: p.Sent, Flow: p.Flow, Own: p.Own, Retried: p.Retried, Queued: p.Queued, Status: int(p.Status), Tries: int(p.Tries), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
+ r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time, Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: p.Millis, TTFT: p.TTFT, FirstText: p.FirstText, FirstReasoning: p.FirstReasoning, ReasoningHidden: p.Flags&rowReasoningHidden != 0, CacheUnknown: p.Flags&rowCacheUnknown != 0, Sent: p.Sent, Flow: p.Flow, Own: p.Own, Retried: p.Retried, Queued: p.Queued, Status: int(p.Status), Tries: int(p.Tries), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
if p.Flags&rowCredits != 0 {
credits := p.Credits
r.Credits = &credits
@@ -300,6 +307,9 @@ func (c *rowChunk) row(i int) Row {
if r.Swapped && p.Flags&swapKnown == 0 && (SameSpelled(r.Model, r.Served) || ServingName(r.Model, r.Served) || RelayRenamed(r.Model, r.Served)) {
r.Swapped = false // kept before a name spelled otherwise, a vendor's serving name or a relay's rename was the same
}
+ if r.cacheNotCounted() {
+ r.CacheUnknown = true // kept before its plugin said its vendor counts no cache
+ }
if r.Source == SourceReported {
r.Record.Source = SourceReported
if p.Flags&rowOwnCost != 0 {
diff --git a/internal/usage/usage.go b/internal/usage/usage.go
index b90d771be..164a52e70 100644
--- a/internal/usage/usage.go
+++ b/internal/usage/usage.go
@@ -74,7 +74,13 @@ type Record struct {
// kept has none: all its writes are counted as 5-minute ones, as they
// were.
CacheWrite1h int `json:"cache_write_1h,omitempty"`
- Reasoning int `json:"reasoning,omitempty"`
+ // CacheUnknown: the vendor counted no cache tokens for this call (a
+ // plugin's magpie_cache_unknown: Kiro caches but tells only credits),
+ // so its CacheRead of 0 is not a miss. A hit rate leaves its prompt
+ // out (Totals.CacheUnknown, #3464). A record from before it was kept
+ // has none: its 0 still reads as a miss.
+ CacheUnknown bool `json:"cache_unknown,omitempty"`
+ Reasoning int `json:"reasoning,omitempty"`
// Effort is the reasoning the model was asked for — a routing group's
// pick for the turn, or the agent's own — as it takes it; "" for none
Effort string `json:"effort,omitempty"`
@@ -394,10 +400,17 @@ type Totals struct {
CacheRead int `json:"cache_read"`
CacheWrite int `json:"cache_write"`
// CacheWrite1h is how many of CacheWrite were 1-hour writes
- CacheWrite1h int `json:"cache_write_1h,omitempty"`
- Reasoning int `json:"reasoning"`
- Cost float64 `json:"cost"` // USD at the effective price, for the priced calls
- Unpriced int `json:"unpriced"` // calls with tokens but no known price
+ CacheWrite1h int `json:"cache_write_1h,omitempty"`
+ // CacheUnknown is how many of the prompt's tokens (Input, CacheRead
+ // and CacheWrite) were of calls whose vendor counted no cache
+ // (Record.CacheUnknown), CacheUnknownCalls how many calls they were:
+ // a hit rate is CacheRead over the prompt less CacheUnknown, and none
+ // when nothing is left (#3464)
+ CacheUnknown int `json:"cache_unknown,omitempty"`
+ CacheUnknownCalls int `json:"cache_unknown_calls,omitempty"`
+ Reasoning int `json:"reasoning"`
+ Cost float64 `json:"cost"` // USD at the effective price, for the priced calls
+ Unpriced int `json:"unpriced"` // calls with tokens but no known price
// Credits are what the vendors said Credited of the calls cost in
// their plans' own credits (Record.Credits): the rest said nothing
Credits float64 `json:"credits,omitempty"`
@@ -594,6 +607,49 @@ func FormatCost(amountUSD float64, currency string, rate float64) string {
}
}
+// countCache counts r's prompt as one whose cache wasn't counted when its
+// vendor said so, or never counts it (a record kept before it said so).
+func (t *Totals) countCache(r Record) {
+ if r.cacheNotCounted() {
+ t.CacheUnknown += r.cacheUnknownIn()
+ t.CacheUnknownCalls++
+ }
+}
+
+// CountsNoCache is whether a provider's vendor never counts cache tokens,
+// so a call of it with none recorded was not a miss: Kiro caches but tells
+// only credits. Calls kept before its plugin said so (opencode-kiro-auth
+// 0.1.16's magpie_cache_unknown) carry no CacheUnknown, and are read as
+// having it (#3464). The provider is the built-in's id, or the plugin's
+// own when it is signed in under that.
+func CountsNoCache(provider string) bool {
+ return provider == "kiro" || provider == "kiro-plugin"
+}
+
+// cacheNotCounted is whether r's vendor counted no cache for it: it said
+// so, or it never counts any and r has none (kept before it said so).
+func (r Record) cacheNotCounted() bool {
+ return r.CacheUnknown || r.CacheRead+r.CacheWrite == 0 && CountsNoCache(r.Provider)
+}
+
+// cacheUnknownIn is r's prompt when its vendor counted no cache, else 0.
+func (r Record) cacheUnknownIn() int {
+ if !r.cacheNotCounted() {
+ return 0
+ }
+ return r.Input + r.CacheRead + r.CacheWrite
+}
+
+// HitRate is the share of the prompt read from the cache, of the calls
+// whose vendor counted it; false when none did (#3464).
+func (t Totals) HitRate() (float64, bool) {
+ p := t.Input + t.CacheRead + t.CacheWrite - t.CacheUnknown
+ if p <= 0 {
+ return 0, false
+ }
+ return float64(t.CacheRead) / float64(p), true
+}
+
func (t *Totals) add(r Record, price *catalog.Price) { t.addFrom(Row{Record: r}, price) }
// addFrom is add for a ledger row, whose speed is told as Row.Decode tells
@@ -606,6 +662,7 @@ func (t *Totals) addFrom(row Row, price *catalog.Price) {
t.CacheRead += r.CacheRead
t.CacheWrite += r.CacheWrite
t.CacheWrite1h += r.CacheWrite1h
+ t.countCache(r)
t.Reasoning += r.Reasoning
if r.TTFT > 0 && !r.Failed() {
t.Timed++