Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6334 fix(usage): bill cache reads in daily and weekly cost charts (#7134)
Bohan Jiang5620b7e22d62
diff --git a/packages/views/dashboard/utils.test.ts b/packages/views/dashboard/utils.test.tsindex 0124be42a4..123bc34f60 100644--- a/packages/views/dashboard/utils.test.ts+++ b/packages/views/dashboard/utils.test.ts@@ -58,6 +58,29 @@ describe("aggregateDailyCost", () => {expect(result[1]).toMatchObject({ input: 3, output: 7.5, cacheWrite: 0, total: 10.5 });});+ it("bills cache reads into the stack and its total (MUL-6334)", () => {+ // The dashboard feeds the same DailyCostChart the runtime page does, so it+ // has to bill the same categories. Before the fix this aggregator summed+ // input + output + cacheWrite only, hiding cache-read spend from the bar,+ // the tooltip Total and the card's headline.+ const result = aggregateDailyCost([+ {+ date: "2026-05-10",+ provider: "claude",+ model: "claude-sonnet-4-6",+ input_tokens: 1_000_000,+ output_tokens: 0,+ cache_read_tokens: 20_000_000,+ cache_write_tokens: 1_000_000,+ task_count: 2,+ },+ ]);+ // claude-sonnet-4-6: input $3/M, cacheRead $0.30/M, cacheWrite $3.75/M.+ // $3 + $6 + $3.75 = $12.75.+ expect(result[0]).toMatchObject({ input: 3, cacheRead: 6, cacheWrite: 3.75 });+ expect(result[0]?.total).toBeCloseTo(12.75, 2);+ });+it("treats unmapped models as zero-cost", () => {const result = aggregateDailyCost([{diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.tsindex 82185d3526..9915aa614e 100644--- a/packages/views/dashboard/utils.ts+++ b/packages/views/dashboard/utils.ts@@ -43,11 +43,15 @@ import type {// side.// ---------------------------------------------------------------------------+// Mirrors `DailyCostStackData` in the runtimes utils, including its cache-read+// segment — the dashboard feeds the very same DailyCostChart, so a category+// missing here is a category missing from the chart's total (MUL-6334).export interface DailyCostStack {date: string;label: string;input: number;output: number;+ cacheRead: number;cacheWrite: number;total: number;}@@ -61,16 +65,25 @@ function formatDateLabel(d: string): string {return `${date.getMonth() + 1}/${date.getDate()}`;}-// Per-(date, model) rows → 1 row per date with cost broken into the three+// Per-(date, model) rows → 1 row per date with cost broken into the four// segments the stacked bar chart consumes. Stable sort by date asc so the// chart x-axis is left-to-right oldest-to-newest.export function aggregateDailyCost(usage: DashboardUsageDaily[]): DailyCostStack[] {- const map = new Map<string, { input: number; output: number; cacheWrite: number }>();+ const map = new Map<+ string,+ { input: number; output: number; cacheRead: number; cacheWrite: number }+ >();for (const u of usage) {const b = estimateCostBreakdown(u);- const entry = map.get(u.date) ?? { input: 0, output: 0, cacheWrite: 0 };+ const entry = map.get(u.date) ?? {+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ };entry.input += b.input;entry.output += b.output;+ entry.cacheRead += b.cacheRead;entry.cacheWrite += b.cacheWrite;map.set(u.date, entry);}@@ -80,14 +93,16 @@ export function aggregateDailyCost(usage: DashboardUsageDaily[]): DailyCostStack.map(([date, s]) => {const input = round(s.input);const output = round(s.output);+ const cacheRead = round(s.cacheRead);const cacheWrite = round(s.cacheWrite);return {date,label: formatDateLabel(date),input,output,+ cacheRead,cacheWrite,- total: round(input + output + cacheWrite),+ total: round(input + output + cacheRead + cacheWrite),};});}diff --git a/packages/views/runtimes/components/charts/daily-cost-chart.tsx b/packages/views/runtimes/components/charts/daily-cost-chart.tsxindex d8aba4b41a..3762a89c81 100644--- a/packages/views/runtimes/components/charts/daily-cost-chart.tsx+++ b/packages/views/runtimes/components/charts/daily-cost-chart.tsx@@ -14,18 +14,20 @@ import {import type { DailyCostStackData } from "../../utils";import { useT } from "../../../i18n";-// Three-segment stack (input / output / cache write) — keeps the user's-// attention on what's actually driving spend. Cache reads are excluded-// because their per-token rate is two orders of magnitude smaller and-// would be visually invisible in a stack; we surface their *savings*-// separately as a KPI.+// Four-segment stack (input / output / cache read / cache write) — every+// category `estimateCost` bills for, so the bars add up to the same money the+// Cost KPI reports. The tooltip derives Total by summing the segments it can+// see, so a category left out of this config is a category left out of the+// user's total (MUL-6334: cache read alone was >50% of some buckets).//-// Series → CSS chart token: stack reads bottom-up as chart-1 (deepest brand-// blue, "input") → chart-2 (mid) → chart-3 (lightest, "cache write"), so the-// visual depth maps directly to "primary cost driver → secondary".+// Series → CSS chart token: input/output/cache-write keep chart-1/2/3, and+// cache read takes chart-4 in the output→cache-write slot — the same colour+// and position DailyTokensChart gives it, so the cost and token views of the+// same day read as one chart at two scales.export const costStackConfig = {input: { label: "Input", color: "var(--chart-1)" },output: { label: "Output", color: "var(--chart-2)" },+ cacheRead: { label: "Cache read", color: "var(--chart-4)" },cacheWrite: { label: "Cache write", color: "var(--chart-3)" },} satisfies ChartConfig;@@ -94,6 +96,12 @@ export function DailyCostChart({ data }: { data: DailyCostStackData[] }) {fill="var(--color-output)"radius={[0, 0, 0, 0]}/>+ <Bar+ dataKey="cacheRead"+ stackId="cost"+ fill="var(--color-cacheRead)"+ radius={[0, 0, 0, 0]}+ /><BardataKey="cacheWrite"stackId="cost"diff --git a/packages/views/runtimes/components/charts/weekly-cost-chart.tsx b/packages/views/runtimes/components/charts/weekly-cost-chart.tsxindex 73ef7ad3f4..9e28e5bbbc 100644--- a/packages/views/runtimes/components/charts/weekly-cost-chart.tsx+++ b/packages/views/runtimes/components/charts/weekly-cost-chart.tsx@@ -15,13 +15,14 @@ import {import type { WeeklyCostStackData } from "../../utils";import { useT } from "../../../i18n";-// Same three-segment stack as DailyCostChart — keeping series, colours, and+// Same four-segment stack as DailyCostChart — keeping series, colours, and// ordering identical so the user reads "Weekly" as a coarser cut of the same// chart, not a different chart. Partial-week bars render at half-opacity so// "this week is in progress" is visually obvious without a separate legend.export const weeklyCostStackConfig = {input: { label: "Input", color: "var(--chart-1)" },output: { label: "Output", color: "var(--chart-2)" },+ cacheRead: { label: "Cache read", color: "var(--chart-4)" },cacheWrite: { label: "Cache write", color: "var(--chart-3)" },} satisfies ChartConfig;@@ -92,6 +93,11 @@ export function WeeklyCostChart({ data }: { data: WeeklyCostStackData[] }) {<Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />))}</Bar>+ <Bar dataKey="cacheRead" stackId="cost" fill="var(--color-cacheRead)">+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar><BardataKey="cacheWrite"stackId="cost"diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsxindex bb1e4c783d..0c2ac6bd2f 100644--- a/packages/views/runtimes/components/usage-section.tsx+++ b/packages/views/runtimes/components/usage-section.tsx@@ -366,7 +366,10 @@ function WhenChart({);const metricToggleVisible = !showHeatmap;- const legendIncludesCacheRead = !showHeatmap && chartMetric === "tokens";+ // Both metrics carry a cache-read segment now: the token stack always did,+ // and the cost stack gained one when it stopped dropping cache-read spend+ // from its total (MUL-6334).+ const legendIncludesCacheRead = !showHeatmap;return (<div className="rounded-lg border bg-card p-4">@@ -608,15 +611,15 @@ function CustomPricingBar({ usage }: { usage: RuntimeUsage[] }) {}// ----------------------------------------------------------------------------// Chart legend — three coloured dots + labels, rendered in WhenChart's-// header so the chart body keeps its full vertical real estate.+// Chart legend — one coloured dot + label per stack segment, rendered in+// WhenChart's header so the chart body keeps its full vertical real estate.// ---------------------------------------------------------------------------function ChartLegend({ includeCacheRead = false }: { includeCacheRead?: boolean }) {const { t } = useT("runtimes");- // Token-stack mode adds a cache-read pip between output and cache-write to- // match the four-segment stack of DailyTokensChart. The cost chart drops- // cache-read because at typical pricing it'd be ~0 px tall in the stack.+ // The cache-read pip sits between output and cache-write, matching the+ // segment order both the token and the cost stacks draw. Only the heatmap,+ // which has no stack at all, leaves it out.const items = [{ label: t(($) => $.usage.legend_input), color: "var(--color-chart-1)" },{ label: t(($) => $.usage.legend_output), color: "var(--color-chart-2)" },diff --git a/packages/views/runtimes/utils.test.ts b/packages/views/runtimes/utils.test.tsindex a43daeb890..277cf7c1d6 100644--- a/packages/views/runtimes/utils.test.ts+++ b/packages/views/runtimes/utils.test.ts@@ -4,6 +4,7 @@ import type { AgentRuntime, RuntimeUsage } from "@multica/core/types";import {addDaysIso,+ aggregateByDate,aggregateByWeek,aggregateCostByModel,collectUnmappedModels,@@ -1095,6 +1096,109 @@ describe("sliceWindow (timezone-aware)", () => {});});+describe("aggregateByDate", () => {+ // MUL-6334: the daily cost stack computed `estimateCostBreakdown` and then+ // summed only three of its four components, silently dropping cache-read+ // spend from every bar and from the tooltip Total that sums them.+ function makeUsage(+ date: string,+ tokens: Partial<{+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+ }>,+ model = "gpt-5.6-sol",+ ): RuntimeUsage {+ return {+ runtime_id: "r",+ date,+ provider: "openai",+ model,+ input_tokens: tokens.input ?? 0,+ output_tokens: tokens.output ?? 0,+ cache_read_tokens: tokens.cacheRead ?? 0,+ cache_write_tokens: tokens.cacheWrite ?? 0,+ };+ }++ it("bills cache reads in the daily stack and its total", () => {+ // gpt-5.6-sol: input $5/M, output $30/M, cacheRead $0.50/M.+ const rows = [+ makeUsage("2026-05-11", { input: 1_000_000, cacheRead: 10_000_000 }),+ ];+ const { dailyCostStack } = aggregateByDate(rows);+ const day = dailyCostStack[0];+ expect(day?.cacheRead).toBeCloseTo(5, 2);+ expect(day?.total).toBeCloseTo(10, 2);+ });++ it("keeps every daily bucket's total equal to the sum of estimateCost", () => {+ // The invariant the reporter asked for. A cache-read-dominated workload is+ // the only shape that catches the regression: with zero cache reads the+ // broken and fixed totals are identical.+ const rows = [+ makeUsage("2026-05-11", {+ input: 4_300_000,+ output: 456_400,+ cacheRead: 79_300_000,+ }),+ makeUsage("2026-05-11", { input: 1_000, output: 500 }),+ makeUsage("2026-05-12", { cacheRead: 50_000_000 }),+ // Anthropic rows exercise the cache-write segment too.+ makeUsage(+ "2026-05-12",+ { input: 200_000, output: 20_000, cacheRead: 8_000_000, cacheWrite: 400_000 },+ "claude-sonnet-4-6",+ ),+ ];+ const { dailyCostStack } = aggregateByDate(rows);+ expect(dailyCostStack).toHaveLength(2);+ for (const day of dailyCostStack) {+ const expected = rows+ .filter((r) => r.date === day.date)+ .reduce((sum, r) => sum + estimateCost(r), 0);+ // Each of the four segments is rounded to cents before being summed —+ // that is what keeps the tooltip footer equal to the bars above it — so+ // the bucket can sit up to half a cent per segment off the exact figure.+ // The tolerance is the rounding, not slack for a dropped category: a+ // missing segment shows up as dollars, not cents.+ expect(Math.abs(day.total - expected)).toBeLessThanOrEqual(0.02);+ // Total is what the tooltip footer prints; the segments are what it+ // sums to get there. They have to be exactly the same number.+ expect(day.input + day.output + day.cacheRead + day.cacheWrite).toBeCloseTo(+ day.total,+ 10,+ );+ }+ });++ it("reproduces the reported gpt-5.6-sol undercount", () => {+ // The exact workload from the bug report: the chart showed $35.19 against+ // a true $74.84, hiding $39.65 (53%) of spend.+ const rows = [+ makeUsage("2026-05-11", {+ input: 4_300_000,+ output: 456_400,+ cacheRead: 79_300_000,+ }),+ ];+ const { dailyCostStack, dailyCost } = aggregateByDate(rows);+ expect(dailyCostStack[0]?.total).toBeCloseTo(74.84, 2);+ // The non-stacked series always included cache reads; the stack now agrees+ // with it, which is what makes the chart agree with the Cost KPI.+ expect(dailyCostStack[0]?.total).toBeCloseTo(dailyCost[0]?.cost ?? 0, 2);+ });++ it("still reports a non-zero total when spend is entirely cache reads", () => {+ // `total` gates the chart's empty state, which blames an unmapped model+ // when it reads 0. A cache-read-only bucket used to trip that.+ const rows = [makeUsage("2026-05-11", { cacheRead: 20_000_000 })];+ const { dailyCostStack } = aggregateByDate(rows);+ expect(dailyCostStack[0]?.total).toBeCloseTo(10, 2);+ });+});+describe("aggregateByWeek", () => {beforeEach(() => {vi.useFakeTimers();@@ -1107,6 +1211,8 @@ describe("aggregateByWeek", () => {date: string,input: number,output: number,+ cacheRead = 0,+ cacheWrite = 0,): RuntimeUsage {return {runtime_id: "r",@@ -1115,8 +1221,8 @@ describe("aggregateByWeek", () => {model: "claude-sonnet-4-6",input_tokens: input,output_tokens: output,- cache_read_tokens: 0,- cache_write_tokens: 0,+ cache_read_tokens: cacheRead,+ cache_write_tokens: cacheWrite,};}@@ -1179,6 +1285,24 @@ describe("aggregateByWeek", () => {expect(weeklyCostStack[0]?.total).toBeCloseTo(36, 2);});+ it("bills cache reads in the weekly stack and its total (MUL-6334)", () => {+ vi.setSystemTime(new Date("2026-05-17T12:00:00Z"));+ // claude-sonnet-4-6: input $3/M, output $15/M, cacheRead $0.30/M,+ // cacheWrite $3.75/M. Row: $3 + $15 + $6 (20M cache reads) + $3.75 = $27.75.+ const rows = [+ makeUsage("2026-05-11", 1_000_000, 1_000_000, 20_000_000, 1_000_000),+ ];+ const { weeklyCostStack } = aggregateByWeek(rows, "UTC", 1);+ const week = weeklyCostStack[0];+ expect(week?.cacheRead).toBeCloseTo(6, 2);+ expect(week?.total).toBeCloseTo(27.75, 2);+ // Same invariant the daily stack holds: bucket total === sum of estimateCost.+ expect(week?.total).toBeCloseTo(+ rows.reduce((sum, r) => sum + estimateCost(r), 0),+ 2,+ );+ });+it("emits trailing calendar weeks pinned to today, dropping older populated weeks", () => {// Regression for MUL-2382 weekly window scoping:// before the fix, aggregateByWeek built buckets only for weeks that haddiff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.tsindex f01e1d43b0..5cb5a5a96e 100644--- a/packages/views/runtimes/utils.ts+++ b/packages/views/runtimes/utils.ts@@ -776,14 +776,25 @@ export interface DailyCostData {cost: number;}-// Stacked variant — splits the daily $ figure into the three components that-// drive billing (cache reads excluded; their cost is tracked separately as-// "savings" since they're typically dominated by the cached-input discount).+// Stacked variant — splits the daily $ figure into the four components that+// drive billing. Every component `estimateCost` charges for has to be here:+// `total` is what the tooltip and the empty-state check read, so a component+// missing from the stack is money missing from the user's cost figure.+//+// Cache reads were once excluded on the theory that their rate was too small+// to see. It isn't: across the current rate table cached input is ~10x cheaper+// than uncached, not ~100x, and agent sessions routinely read tens of times+// more cached tokens than uncached ones — so cache read is often the LARGEST+// segment, and dropping it understated some buckets by >50% (MUL-6334).+//+// Cache *savings* — a reconstruction of what the discount avoided — is a+// separate KPI and deliberately not part of this stack; savings is not spend.export interface DailyCostStackData {date: string;label: string;input: number;output: number;+ cacheRead: number;cacheWrite: number;total: number;}@@ -821,6 +832,7 @@ export interface WeeklyCostStackData {daysCovered: number;input: number;output: number;+ cacheRead: number;cacheWrite: number;total: number;}@@ -835,7 +847,7 @@ export function aggregateByDate(usage: RuntimeUsage[]): {const costMap = new Map<string, number>();const stackMap = new Map<string,- { input: number; output: number; cacheWrite: number }+ { input: number; output: number; cacheRead: number; cacheWrite: number }>();const modelMap = new Map<string, { tokens: number; cost: number }>();@@ -860,10 +872,12 @@ export function aggregateByDate(usage: RuntimeUsage[]): {const stack = stackMap.get(u.date) ?? {input: 0,output: 0,+ cacheRead: 0,cacheWrite: 0,};stack.input += breakdown.input;stack.output += breakdown.output;+ stack.cacheRead += breakdown.cacheRead;stack.cacheWrite += breakdown.cacheWrite;stackMap.set(u.date, stack);@@ -898,14 +912,19 @@ export function aggregateByDate(usage: RuntimeUsage[]): {const round = (n: number) => Math.round(n * 100) / 100;const input = round(s.input);const output = round(s.output);+ const cacheRead = round(s.cacheRead);const cacheWrite = round(s.cacheWrite);return {date,label: formatLabel(date),input,output,+ cacheRead,cacheWrite,- total: round(input + output + cacheWrite),+ // Rounded components, not round(sum) — the tooltip's Total is the sum+ // of the segments it draws, so totalling the rounded parts is what+ // keeps the footer agreeing with the bars it sits under.+ total: round(input + output + cacheRead + cacheWrite),};});@@ -958,7 +977,10 @@ export function aggregateByWeek(type TokenAgg = Omit<WeeklyTokenData, "label" | "rangeLabel" | "partial" | "daysCovered" | "weekEnd">;const tokenMap = new Map<string, TokenAgg>();- const stackMap = new Map<string, { input: number; output: number; cacheWrite: number }>();+ const stackMap = new Map<+ string,+ { input: number; output: number; cacheRead: number; cacheWrite: number }+ >();// Pre-seed every trailing calendar week in the window so sparse / empty// weeks still render as zero bars instead of being dropped.@@ -971,7 +993,7 @@ export function aggregateByWeek(cacheRead: 0,cacheWrite: 0,});- stackMap.set(wkStart, { input: 0, output: 0, cacheWrite: 0 });+ stackMap.set(wkStart, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });}for (const u of usage) {@@ -989,6 +1011,7 @@ export function aggregateByWeek(if (!stack) continue;stack.input += breakdown.input;stack.output += breakdown.output;+ stack.cacheRead += breakdown.cacheRead;stack.cacheWrite += breakdown.cacheWrite;}@@ -1025,13 +1048,15 @@ export function aggregateByWeek(const round = (n: number) => Math.round(n * 100) / 100;const input = round(s.input);const output = round(s.output);+ const cacheRead = round(s.cacheRead);const cacheWrite = round(s.cacheWrite);return {...decorate(weekStart),input,output,+ cacheRead,cacheWrite,- total: round(input + output + cacheWrite),+ total: round(input + output + cacheRead + cacheWrite),};});