usage: a cache hit rate reads 100% only when all of the prompt was cached (ZhangXiaof48473 on X)
Routing's request list showed "缓存 100%" for Codex requests of 77.5K
tokens that read 77,200 of them from the cache (99.6%), beside rows at
99%, and the route line said "请求缓存命中率 99%". Every hit rate was
Math.round(100 * h) + "%", so anything from 99.5% up read 100%.
One formatter now says every hit rate: hitPct(h, d) in app.js, whole
percents (d decimals) unless rounding would say 100% or 0% of a prompt
not all or none cached, then one or two decimals (99.6%, 99.95%; never
past 99.99% or under 0.01%). Its callers: Routing's request rows, their
route line and a session's Avg. cache (plugins/routing/client.js); the
tray panel's Cache hit rate and the ranking rows' hit rate (app.js); the
Usage page's tiles, agent rows, Requests table, request detail and its
KPI strip, which keeps its one decimal (plugins/usage/page.js); the
context card's Prompt cache and the session traits Cache-friendly,
Cache misses and Cache hit (context.js). The TUI's and CLI's sessions
line, which floored the integer, use usage.HitPct, the same rule in Go;
it rounds now, so the TUI test's 67% (25.2K of 37.3K, 67.6%) reads 68%.
No new strings; app.js pays its bytes with six ledger comments cut, so
the core scripts are 15 bytes smaller than at its parent, no raise. Main
is over the core budget already (1,534,476 > 1,533,802 at the parent,
#5918); this commit doesn't add to it.
Run on mote:
- new internal/gui/tests/cache-hit-pct.test.cjs (Routing rows 99.6% /
100% / 99%, the route line, hitPct at its edges) in chromium and
webkit, en and zh: green; with the escalation line removed by hand,
red (99.99% where 99.6% is wanted).
- cache-hit-pct, panel-usage, context-window, i18n-keys, usage-ledger,
tray-totals, ctx-route, ledger-cache-hit, usage-hit-rate,
routing-request-metrics (both engines; ledger-cache-unknown and
ledger-cache-tokens in an earlier run): 186 pass, 6 red, all in
usage-ledger's 'newest live route needs no return-to-live button',
red the same on origin/main 00e8242e8 (#5048, #4078).
- go test ./internal/usage ./internal/cli ./internal/tui: ok, with
TestHitPctNeverRoundsToAllOrNone and a 99.6% case in
TestHitRateCountsCacheWrites (red on the old floor: 99%).
- go test ./internal/gui at the first base: TestCoreScriptBudget ok; one red,
TestGatewayModeStatsNameTheGatewaySessions, run at 00:25 local (#5690,
the first hour of a local day).
- gofmt; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
At the pushed head (rebased, comments cut): cache-hit-pct and
routing-request-metrics again, both engines, 8 of 8.
Not tried: the real app's window, or GUI files beyond those above (a
65-file run waited on mote's suite lock behind four full suites).
This commit is contained in:
@@ -499,7 +499,7 @@ func rollupCost(c float64, unpriced []string) string {
|
||||
// leaves out both).
|
||||
func hitRate(t sessions.Tokens) string {
|
||||
if p := t.Input + t.CacheRead + t.CacheWrite; t.CacheRead > 0 && p > 0 {
|
||||
return muted.Render(fmt.Sprintf(" (%d%% hit)", 100*t.CacheRead/p))
|
||||
return muted.Render(" (" + stats.HitPct(float64(t.CacheRead)/float64(p)) + " hit)")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -190,4 +190,8 @@ func TestHitRateCountsCacheWrites(t *testing.T) {
|
||||
if got := hitRate(sessions.Tokens{Input: 10, CacheRead: 20, CacheWrite: 70}); !strings.Contains(got, "(20% hit)") {
|
||||
t.Errorf("hitRate = %q, want 20%%", got)
|
||||
}
|
||||
// nearly all of it read is not all of it (ZhangXiaof48473 on X)
|
||||
if got := hitRate(sessions.Tokens{Input: 300, CacheRead: 77200}); !strings.Contains(got, "(99.6% hit)") {
|
||||
t.Errorf("hitRate = %q, want 99.6%%", got)
|
||||
}
|
||||
}
|
||||
|
||||
+12
-10
@@ -17433,7 +17433,7 @@ function renderPanelUse() {
|
||||
const c = fmtCost(l);
|
||||
const u = l.unpriced, one = u === 1;
|
||||
blk("Cost", c ? "≈" + c : "—", u ? t(one ? "{n} call unpriced" : "{n} calls unpriced", { n: u }) : t("effective prices"), c ? "cost" : "", "", u ? t(one ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: u }) : "");
|
||||
blk("Cache hit rate", hitRate === null ? "—" : Math.round(100 * hitRate) + "%", cacheLeftOut(l) || t("of the prompt"));
|
||||
blk("Cache hit rate", hitRate === null ? "—" : hitPct(hitRate), cacheLeftOut(l) || t("of the prompt"));
|
||||
const card = el("div", "pu-card");
|
||||
const head = el("div", "led-bar");
|
||||
const met = el("div", "segs");
|
||||
@@ -18799,8 +18799,7 @@ function computerOpts(cs) {
|
||||
let ledFmt, ledFmtLang;
|
||||
const ledNum = (n) => { const l = intlLang(); return typeof (n ||= 0) != "number" ? n.toLocaleString(l)
|
||||
: (l == ledFmtLang ? ledFmt : (ledFmtLang = l, ledFmt = new Intl.NumberFormat(l))).format(n); };
|
||||
// what x's credited requests cost in their plan's credits, as the replies
|
||||
// said (WorkBuddy's usage.credit, #2512): nothing when none said
|
||||
// x's requests' plan credits, as replies said (#2512)
|
||||
function ledCredits(x) {
|
||||
if (!x?.credited) return null;
|
||||
const n = x.credits || 0;
|
||||
@@ -18822,21 +18821,24 @@ 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)
|
||||
// a total's hit rate without cache_unknown; null for none (#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;
|
||||
};
|
||||
// a hit rate, more decimals where d would round it to 100% or 0%
|
||||
const hitPct = (h, d = 0) => {
|
||||
let s = (100 * h).toFixed(d);
|
||||
while (d < 2 && h > 0 && h < 1 && (+s >= 100 || +s <= 0)) s = (100 * h).toFixed(++d);
|
||||
return (h < 1 && +s >= 100 ? "99.99" : h > 0 && +s <= 0 ? "0.01" : s) + "%";
|
||||
};
|
||||
// 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
|
||||
// timed replies' tokens a second after their first (usage.Totals.Speed)
|
||||
const ledSpeed = (x) => x?.decode_ms > 0 ? (1000 * x.decode_out) / x.decode_ms : 0;
|
||||
// the least the replies of a group that has no first token wrote at
|
||||
// (usage.Totals.Floor, ledFloorSpeed's for each): 0 for none
|
||||
// the least untimed replies wrote at (usage.Totals.Floor)
|
||||
const ledFloor = (x) => x?.floor_ms > 0 ? (1000 * x.floor_out) / x.floor_ms : 0;
|
||||
// a group's speed by one rule (Fallmonkey): timed replies "125 tok/s · 1
|
||||
// timed reply", session-file floors "≥100 tok/s · 30 replies", both with
|
||||
@@ -19123,7 +19125,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
|
||||
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 hit = cacheHitOf(x);
|
||||
if (hit !== null && !compact) more.push(t("hit rate {p}", { p: Math.round(100 * hit) + "%" }));
|
||||
if (hit !== null && !compact) more.push(t("hit rate {p}", { p: hitPct(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");
|
||||
|
||||
@@ -838,7 +838,7 @@
|
||||
const c = el("div", "ctx-stat ctx-cache" + (!known && shown ? " was" : shown ? "" : " none"));
|
||||
c.append(el("div", "ctx-k", t("Prompt cache")));
|
||||
const cb = el("div", "ctx-big");
|
||||
cb.append(el("b", "", shown ? pct(shown.read / shown.total) : "—"), el("span", "", t("hit")));
|
||||
cb.append(el("b", "", shown ? hitPct(shown.read / shown.total) : "—"), el("span", "", t("hit")));
|
||||
const bar = el("div", "ctx-bar");
|
||||
const fillBar = el("i");
|
||||
fillBar.style.width = (shown ? (shown.read / shown.total) * 100 : 0).toFixed(1) + "%";
|
||||
@@ -998,8 +998,8 @@
|
||||
reliable: "Its requests that didn't fail: none at 20% failing",
|
||||
};
|
||||
const TAGS = {
|
||||
"cache-friendly": ["Cache-friendly", (v) => t("{pct} of its prompts were read from the vendor's cache", { pct: pct(v) })],
|
||||
"cache-misses": ["Cache misses", (v) => t("Only {pct} of its prompts were read from the cache: each request pays for most of its prompt again", { pct: pct(v) })],
|
||||
"cache-friendly": ["Cache-friendly", (v) => t("{pct} of its prompts were read from the vendor's cache", { pct: hitPct(v) })],
|
||||
"cache-misses": ["Cache misses", (v) => t("Only {pct} of its prompts were read from the cache: each request pays for most of its prompt again", { pct: hitPct(v) })],
|
||||
lean: ["Lean start", (v) => t("Every request starts with {tokens} of system prompt, tools and memory", { tokens: fmtK(v) })],
|
||||
"heavy-start": ["Heavy start", (v) => t("Every request starts with {tokens} of system prompt, tools and memory, before a word of yours", { tokens: fmtK(v) })],
|
||||
"mcp-heavy": ["MCP-heavy", (v) => t("MCP servers' tool definitions take {tokens} of every request", { tokens: fmtK(v) })],
|
||||
@@ -1086,7 +1086,7 @@
|
||||
fact("Largest", fmtK(a.p90), "90% of its requests' prompts are this size or smaller");
|
||||
fact("Starts with", fmtK(a.baseline), "System prompt, tools and memory: what every request carries before the conversation");
|
||||
fact("Grows by", a.growth ? "+" + fmtK(a.growth) : "—", "How much a request's prompt adds to the one before it, the median");
|
||||
fact("Cache hit", a.scores?.find((s) => s.key === "cache") && a.cache ? pct(a.cache) : "—", "Of its prompts, what the vendor read from its cache");
|
||||
fact("Cache hit", a.scores?.find((s) => s.key === "cache") && a.cache ? hitPct(a.cache) : "—", "Of its prompts, what the vendor read from its cache");
|
||||
fact("Window size", a.window ? fmtK(a.window) : "—", "The largest context window of the models it used");
|
||||
|
||||
const mix = el("div", "ctx-mix");
|
||||
|
||||
@@ -562,7 +562,7 @@ function routingPage(part) {
|
||||
duration: ["duration", "Duration", r.done && r.ms ? took(r.ms) : "—", ""],
|
||||
ttft: ["ttft", "First token", r.done && r.ttft ? took(r.ttft) : "—", t("First token")],
|
||||
tokens: ["tokens", "Tokens", r.tokens ? tokens(r.tokens) : "—", tokenBreakdown([r])],
|
||||
cache: ["cache-hit", "Cache", prompt ? pct(100 * read / prompt) : "—",
|
||||
cache: ["cache-hit", "Cache", prompt ? hitPct(read / prompt) : "—",
|
||||
t("Cache hit rate") + ": " + t("The share of the prompt read from the cache")],
|
||||
speed: ["speed", "Speed", speed ? speed.text : "—", speed?.title ||
|
||||
t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed")],
|
||||
@@ -584,7 +584,7 @@ function routingPage(part) {
|
||||
const v = speedOf(r, tr.ms, tr.ttft, tr.firstText, tr.flow, tr.firstReasoning || 0, tr.reasoningHidden || false);
|
||||
if (v) s += " · " + t("{n} tok/s", { n: Math.round(v) });
|
||||
const { prompt, read } = promptOf(r);
|
||||
if (prompt) s += " · " + t("request cache hit rate {p}", { p: pct(100 * read / prompt) });
|
||||
if (prompt) s += " · " + t("request cache hit rate {p}", { p: hitPct(read / prompt) });
|
||||
return s;
|
||||
}
|
||||
// a count short (fmtN: 12.3K, 1.2 万), exact on hover when they differ
|
||||
@@ -4140,7 +4140,7 @@ function routingPage(part) {
|
||||
if (total.running) count.append(" · " + bits[bits.length - 1]);
|
||||
const meta = [count];
|
||||
const coverage = (n) => t("Based on {n} of {total} completed requests", { n, total: total.completed });
|
||||
if (g.key && visibleMetrics.includes("cache") && total.prompt) meta.push(metricElement(["cache-hit", "Avg. cache", pct(100 * total.read / total.prompt),
|
||||
if (g.key && visibleMetrics.includes("cache") && total.prompt) meta.push(metricElement(["cache-hit", "Avg. cache", hitPct(total.read / total.prompt),
|
||||
t("Total cache reads divided by total prompt tokens; larger prompts carry more weight") + "\n" + coverage(total.cached)]));
|
||||
if (g.key && visibleMetrics.includes("speed") && total.decodeMs) meta.push(metricElement(["speed", "Avg. speed", t("{n} tok/s", { n: Math.round(total.decodeOut * 1000 / total.decodeMs) }),
|
||||
t("Total output tokens divided by total decode time; excludes waiting and replies without usable timing") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed") + "\n" + coverage(total.timed)]));
|
||||
|
||||
@@ -775,7 +775,7 @@ function renderUsage() {
|
||||
// written count is secondary and only fits in the tooltip.
|
||||
// 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) + "%" }) : "";
|
||||
const hit = u.cache_read && hitRate !== null ? t("hit rate {p}", { p: hitPct(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.credited ? ledCredits(u).textContent : "", u.errors ? t("{n} failed", { n: u.errors }) : "", u.retried ? t("{n} answered on a retry", { n: u.retried }) : "", u.canceled ? t("{n} canceled", { n: u.canceled }) : "", u.unpriced ? unpricedCalls(u.unpriced) : ""].filter(Boolean).join(" · "), u.unpriced ? unpricedCallsWhy(u.unpriced) : "");
|
||||
@@ -854,7 +854,7 @@ function renderUsage() {
|
||||
// how much of its prompt came from the cache, counted as the cache
|
||||
// read tile counts it (#925)
|
||||
const hitRate = cacheHitOf(g);
|
||||
const hit = g.cache_read && hitRate !== null ? " · " + t("hit rate {p}", { p: Math.round(100 * hitRate) + "%" }) : "";
|
||||
const hit = g.cache_read && hitRate !== null ? " · " + t("hit rate {p}", { p: hitPct(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) : ""));
|
||||
@@ -1869,7 +1869,7 @@ function renderLedgerDash(l) {
|
||||
// the count in the words the quick panel uses too, the whole sentence on
|
||||
// hover (tenacious_eagle on Discord)
|
||||
block("Cost", c ? "≈" + c : "—", line(l.unpriced ? unpricedCalls(l.unpriced) : t("effective prices")), c ? "cost" : "", l.unpriced ? unpricedCallsWhy(l.unpriced) : "");
|
||||
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 hit = block("Cache hit rate", rate === null ? "—" : hitPct(rate, 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 || 0)).toFixed(1) + "%";
|
||||
meter.append(fill);
|
||||
@@ -2360,7 +2360,7 @@ new ResizeObserver(() => {
|
||||
// prompt, writes included; null for a vendor that counts no cache
|
||||
// (#3464) or a request with no prompt counted
|
||||
const ledCacheHit = (r) => r.cache_unknown ? null : cacheHitOf({ input: r.in, cache_read: r.cache_read, cache_write: r.cache_write });
|
||||
const ledHitText = (h) => h === null ? "" : Math.round(100 * h) + "%";
|
||||
const ledHitText = (h) => h === null ? "" : hitPct(h);
|
||||
const LED_COLS = [
|
||||
["Time"], ["Agent"], ["Requested"], ["Provider · account"], ["Sent", "", true], ["Served"], ["Effort", "", true],
|
||||
["In", "n"], ["Out", "n"], ["Cache write", "n", true], ["Cache read", "n", true], ["Cache hit rate", "n", 2, "The share of the prompt read from the cache"], ["Cost", "n"], ["TTFT", "n", 2, "Time to first token"], ["Duration", "n"], ["Speed", "n"], ["Status"],
|
||||
@@ -3676,7 +3676,7 @@ function renderSessions() {
|
||||
tile(c ? "≈" + c : "—", t("cost"), unpricedModels || t("at effective prices"), unpricedNote);
|
||||
// input leaves out what was read from the cache and written to it
|
||||
const prompt = tot.input + tot.cache_read + tot.cache_write;
|
||||
tile(fmtN(tot.cache_read), t("cache read"), tot.cache_read && prompt ? t("hit rate {p}", { p: Math.round(100 * tot.cache_read / prompt) + "%" }) : "", tot.cache_write ? t("{n} written", { n: fmtN(tot.cache_write) }) : "");
|
||||
tile(fmtN(tot.cache_read), t("cache read"), tot.cache_read && prompt ? t("hit rate {p}", { p: hitPct(tot.cache_read / prompt) }) : "", tot.cache_write ? t("{n} written", { n: fmtN(tot.cache_write) }) : "");
|
||||
tile(active == null ? "—" : fmtDur(active), t("active"), active == null ? t("not kept by model") : t(days === 1 ? "on {n} day" : "on {n} days", { n: days }),
|
||||
t("The time the sessions were at work: the pauses between one message and the next, each under five minutes"), "dur");
|
||||
// how many folders, and how much of it the first took
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// A cache hit rate never reads 100% unless every prompt token came from the
|
||||
// cache (ZhangXiaof48473 on X: Codex gpt-6.1-sol requests of 77.5K tokens
|
||||
// read "缓存 100%" on Routing's request list beside "缓存 99%"). Where
|
||||
// rounding to a whole percent would say 100% or 0% of a prompt not all or
|
||||
// none cached, the rate shows a decimal or two: 99.6%. One formatter
|
||||
// (hitPct) says every hit rate. No backend: the API is faked here.
|
||||
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 = new Date();
|
||||
const seat = { id: "codex", provider: "codex", name: "Codex", who: "test@example.com", kind: "account", model: "gpt-6.1-sol" };
|
||||
function req(id, input, read) {
|
||||
const time = new Date(now.getTime() - (20 - id) * 60e3).toISOString();
|
||||
return { id, seq: id, time, agent: "codex", session: "cache-pct", model: "codex/gpt-6.1-sol", provider: "codex",
|
||||
order: [seat], tries: [{ id: seat.id, model: seat.model, start: time, done: true, status: 200, ms: 11000, ttft: 7000 }],
|
||||
done: true, status: 200, ms: 11000, ttft: 7000, tokens: input + read + 400, out: 400,
|
||||
usage: [{ provider: seat.provider, model: seat.model, in: input, out: 400, cache_read: read, cache_write: 0 }], priced: true, cost: 0.01 };
|
||||
}
|
||||
// newest first: 77,200 of 77,500 read (99.6%), all read, 77,035 of 77,500 (99.4%)
|
||||
const fixtures = [req(3, 300, 77200), req(2, 0, 77500), req(1, 465, 77035)];
|
||||
|
||||
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", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.has("wait")) return new Promise(() => {});
|
||||
return json({ mine: true, now: now.toISOString(), seq: 3, totals: { requests: fixtures.length, rerouted: 0, errors: 0 }, routes: fixtures });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } });
|
||||
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 }); }
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh"]) {
|
||||
test(`${engine} ${lang}: a cache hit rate reads 100% only when all of the prompt was cached`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" });
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang));
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
const rows = page.locator(".rt-req");
|
||||
await rows.nth(fixtures.length - 1).waitFor();
|
||||
assert.deepEqual(await rows.locator(".cache-hit .v").allTextContents(), ["99.6%", "100%", "99%"]);
|
||||
await rows.nth(0).click();
|
||||
assert.match(await page.locator(".rt-steps").textContent(), lang === "zh" ? /请求缓存命中率 99\.6%/ : /request cache hit rate 99\.6%/);
|
||||
// every caller's shared formatter, at its edges
|
||||
const got = await page.evaluate(() => [[1], [0], [0.6], [0.994], [0.9995], [0.99999], [0.003], [0.0004], [1e-7], [0.873, 1], [0.99996, 1], [1, 1]]
|
||||
.map(([h, d]) => hitPct(h, d)));
|
||||
assert.deepEqual(got, ["100%", "0%", "60%", "99%", "99.95%", "99.99%", "0.3%", "0.04%", "0.01%", "87.3%", "99.99%", "100.0%"]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,7 @@ func sessLines(st sessions.Stats, rng int, model, folder string, byCost bool, wi
|
||||
// of all the prompts came to: Input leaves out what was read from the
|
||||
// cache and what was written to it
|
||||
if p := r.Input + r.CacheRead + r.CacheWrite; r.CacheRead > 0 && p > 0 {
|
||||
hit = sMuted.Render(fmt.Sprintf(" (%d%% hit)", 100*r.CacheRead/p))
|
||||
hit = sMuted.Render(" (" + usage.HitPct(float64(r.CacheRead)/float64(p)) + " hit)")
|
||||
}
|
||||
active := sessions.Duration(r.Active)
|
||||
if r.Active >= 0 {
|
||||
|
||||
@@ -55,7 +55,7 @@ func TestSessionsPage(t *testing.T) {
|
||||
t.Fatalf("page %d, range %d", m.page, m.srange)
|
||||
}
|
||||
v := m.View()
|
||||
for _, want := range []string{"5 sessions", " all ", "all models", "all folders", "11.9K tokens", "cache read 25.2K (67% hit)", "active 7m on 2 days",
|
||||
for _, want := range []string{"5 sessions", " all ", "all models", "all folders", "11.9K tokens", "cache read 25.2K (68% hit)", "active 7m on 2 days",
|
||||
"█", "Sep 20", "tokens · a day", "models", "gpt-6-astra", "claude-opus-5-5", "folders", "/work/app", "/work/it's", "M model", "f folder"} {
|
||||
if !strings.Contains(v, want) {
|
||||
t.Errorf("missing %q in\n%s", want, v)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package usage
|
||||
|
||||
import "testing"
|
||||
|
||||
// A hit rate never reads 100% unless every prompt token was cached, nor 0%
|
||||
// when any was: rounding that would hide the difference shows a decimal or
|
||||
// two instead (ZhangXiaof48473 on X: Codex requests read "缓存 100%").
|
||||
func TestHitPctNeverRoundsToAllOrNone(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
h float64
|
||||
want string
|
||||
}{
|
||||
{1, "100%"}, {0, "0%"}, {0.6, "60%"}, {0.994, "99%"},
|
||||
{77200.0 / 77500, "99.6%"}, {0.9995, "99.95%"}, {0.99999, "99.99%"},
|
||||
{0.003, "0.3%"}, {0.0004, "0.04%"}, {0.0000001, "0.01%"},
|
||||
} {
|
||||
if got := HitPct(c.h); got != c.want {
|
||||
t.Errorf("HitPct(%v) = %q, want %q", c.h, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -844,6 +844,26 @@ func (t Totals) HitRate() (float64, bool) {
|
||||
return float64(t.CacheRead) / float64(p), true
|
||||
}
|
||||
|
||||
// HitPct is a hit rate (0 to 1) as a percent, whole unless rounding would
|
||||
// say 100% or 0% of a prompt not all or none cached, then to one or two
|
||||
// decimals (ZhangXiaof48473 on X); the GUI's hitPct says it the same way.
|
||||
func HitPct(h float64) string {
|
||||
s, v := "", 0.0
|
||||
for d := 0; d <= 2; d++ {
|
||||
s = strconv.FormatFloat(100*h, 'f', d, 64)
|
||||
if v, _ = strconv.ParseFloat(s, 64); h <= 0 || h >= 1 || (v > 0 && v < 100) {
|
||||
break
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case h < 1 && v >= 100:
|
||||
s = "99.99"
|
||||
case h > 0 && v <= 0:
|
||||
s = "0.01"
|
||||
}
|
||||
return s + "%"
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user