feat(webui): compare cost avoided against MiniMax M3.1 Flash and latest Sonnet

This commit is contained in:
2026-11-25 12:47:28 +00:00
parent 8c9ec9e241
commit 81bf2e4ffe
4 changed files with 200 additions and 134 deletions
+57 -63
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { costAvoidedMicros, freeRows, pickReferenceModel } from './cost-avoided'
import { costAvoidedMicros, costComparisons, COST_REFERENCES, freeRows, latestSonnet } from './cost-avoided'
import type { AdminCatalogModel, AdminUsageModelEntry } from '@/types/api'
describe('freeRows', () => {
@@ -49,80 +49,74 @@ describe('costAvoidedMicros', () => {
})
})
describe('pickReferenceModel', () => {
const catalog = new Map<string, AdminCatalogModel>([
['a/paid-high', { id: 'a/paid-high', model: 'paid-high', priceSource: 'builtin' }],
['a/paid-low', { id: 'a/paid-low', model: 'paid-low', priceSource: 'override' }],
['a/free', { id: 'a/free', model: 'free', priceSource: 'free' }],
['a/unpriced', { id: 'a/unpriced', model: 'unpriced', priceSource: 'unpriced' }],
])
const model = (id: string, priceSource: AdminCatalogModel['priceSource'], inP?: number, outP?: number): [string, AdminCatalogModel] => [
id,
{ id, model: id.split('/')[1] ?? id, priceSource, inputPerMTokUsd: inP, outputPerMTokUsd: outP },
]
const SONNETS = [
model('anthropic/claude-sonnet-4-5-20250929', 'litellm', 3, 15),
model('anthropic/claude-sonnet-4-6', 'litellm', 3, 15),
model('anthropic/claude-sonnet-5', 'litellm', 2, 10),
model('anthropic/claude-sonnet-5-5', 'litellm', 2, 10),
]
const MINIMAX_ID = 'minimax/MiniMax-M3.1-Flash'
it('picks the most-requested model among genuinely priced catalog entries', () => {
const models: AdminUsageModelEntry[] = [
{ id: 'a/paid-low', value: 1, requests: 5 },
{ id: 'a/paid-high', value: 1, requests: 50 },
]
expect(pickReferenceModel(models, catalog)).toBe('a/paid-high')
describe('latestSonnet', () => {
it('picks 5-5 over 5, 4-6 and the dated 4-5', () => {
expect(latestSonnet(new Map(SONNETS))?.id).toBe('anthropic/claude-sonnet-5-5')
})
it('skips free and unpriced catalog entries even if most-requested', () => {
const models: AdminUsageModelEntry[] = [
{ id: 'a/free', value: 1, requests: 1000 },
{ id: 'a/paid-low', value: 1, requests: 1 },
]
expect(pickReferenceModel(models, catalog)).toBe('a/paid-low')
it('treats a date suffix as a tie-breaker, never a version', () => {
const catalog = new Map([model('anthropic/claude-sonnet-4-5-20250929', 'litellm', 3, 15), model('anthropic/claude-sonnet-4-6', 'litellm', 3, 15)])
expect(latestSonnet(catalog)?.id).toBe('anthropic/claude-sonnet-4-6')
const sameVersion = new Map([model('anthropic/claude-sonnet-4-5-20250101', 'litellm', 3, 15), model('anthropic/claude-sonnet-4-5-20250929', 'litellm', 3, 15)])
expect(latestSonnet(sameVersion)?.id).toBe('anthropic/claude-sonnet-4-5-20250929')
})
it('skips a served id missing from the catalog entirely', () => {
const models: AdminUsageModelEntry[] = [{ id: 'a/removed', value: 1, requests: 999 }]
expect(pickReferenceModel(models, catalog)).toBeNull()
it('skips unpriced and free Sonnets', () => {
const catalog = new Map([...SONNETS, model('anthropic/claude-sonnet-6', 'unpriced'), model('anthropic/claude-sonnet-7', 'free', 0, 0)])
expect(latestSonnet(catalog)?.id).toBe('anthropic/claude-sonnet-5-5')
})
it('skips a detail-less entry with no requests field', () => {
const models: AdminUsageModelEntry[] = [{ id: 'a/paid-high', value: 1 }]
expect(pickReferenceModel(models, catalog)).toBeNull()
})
it('returns null when nothing qualifies', () => {
const models: AdminUsageModelEntry[] = [{ id: 'a/free', value: 1, requests: 10 }]
expect(pickReferenceModel(models, catalog)).toBeNull()
})
it('returns null for an empty ranking', () => {
expect(pickReferenceModel([], catalog)).toBeNull()
it('returns null when no Sonnet is priced', () => {
expect(latestSonnet(new Map([model('anthropic/claude-sonnet-5', 'unpriced')]))).toBeNull()
expect(latestSonnet(new Map())).toBeNull()
})
})
/**
* N1 (verify-redesign-final.md): CostAvoidedCard.vue's own `avoidedMicros`
* computed is exactly `pickReferenceModel` feeding `costAvoidedMicros`
* with the picked model's `cat.inputPerMTokUsd`/`outputPerMTokUsd` — this
* end-to-end shape is what broke when the catalog reported `priceSource:
* 'override'` alongside undefined prices (admin_catalog.go's now-fixed
* bug). This exercises the same two-step flow directly against a fixed-
* shape catalog (billing price present for every priced source,
* including 'override' — the contract GET /admin/api/catalog now
* guarantees) so a regression back to undefined-but-priced catalog
* entries fails here, not just in a Go-only test.
*/
describe('pickReferenceModel + costAvoidedMicros end-to-end (N1 regression)', () => {
it('computes a non-null avoided-cost figure when the picked reference model is override-priced', () => {
const catalog = new Map<string, AdminCatalogModel>([
['a/override-priced', { id: 'a/override-priced', model: 'override-priced', priceSource: 'override', inputPerMTokUsd: 5, outputPerMTokUsd: 10 }],
])
const models: AdminUsageModelEntry[] = [
{ id: 'a/override-priced', value: 1, requests: 42, free: false },
{ id: 'a/free-model', value: 0, free: true, tokensIn: 1_000_000, tokensOut: 500_000 },
]
describe('costComparisons', () => {
const rows = [{ tokensIn: 1_000_000, tokensOut: 500_000 }]
const picked = pickReferenceModel(models, catalog)
expect(picked).toBe('a/override-priced')
it('returns MiniMax then the latest Sonnet', () => {
const out = costComparisons(rows, new Map(SONNETS))
expect(out.map((r) => r.id)).toEqual([COST_REFERENCES.minimax.id, 'anthropic/claude-sonnet-5-5'])
})
const cat = catalog.get(picked as string)
expect(cat?.inputPerMTokUsd).toBe(5)
expect(cat?.outputPerMTokUsd).toBe(10)
it('uses the reference rate when the catalog has MiniMax unpriced', () => {
const [mm] = costComparisons(rows, new Map([model(MINIMAX_ID, 'unpriced')]))
expect(mm).toMatchObject({ inPerMTok: 0.15, outPerMTok: 0.6, priceLabel: 'MiniMax list price, Nov 2026' })
expect(mm.avoidedMicros).toBe(Math.round(1_000_000 * 0.15 + 500_000 * 0.6))
})
const avoided = costAvoidedMicros(freeRows(models), cat?.inputPerMTokUsd as number, cat?.outputPerMTokUsd as number)
expect(avoided).toBe(1_000_000 * 5 + 500_000 * 10)
it('uses the catalog rate when the catalog has MiniMax priced', () => {
const [mm] = costComparisons(rows, new Map([model(MINIMAX_ID, 'litellm', 0.3, 1.2)]))
expect(mm).toMatchObject({ inPerMTok: 0.3, outPerMTok: 1.2, priceLabel: 'gateway price' })
expect(mm.avoidedMicros).toBe(1_000_000 * 0.3 + 500_000 * 1.2)
})
it('prices Sonnet from the catalog', () => {
const [, son] = costComparisons(rows, new Map(SONNETS))
expect(son).toMatchObject({ inPerMTok: 2, outPerMTok: 10, priceLabel: 'gateway price', avoidedMicros: 1_000_000 * 2 + 500_000 * 10 })
})
it('gives null avoided cost when no Sonnet is priced', () => {
const [, son] = costComparisons(rows, new Map())
expect(son.avoidedMicros).toBeNull()
expect(son.inPerMTok).toBeNull()
})
it('gives 0, never NaN, for zero free traffic', () => {
const out = costComparisons([], new Map(SONNETS))
expect(out.map((r) => r.avoidedMicros)).toEqual([0, 0])
})
})
+111 -25
View File
@@ -1,6 +1,6 @@
// Pure math behind CostAvoidedCard.vue (redesign-plan.md section 3.4): how
// much a fleet's FREE-tier traffic would have cost against a real, priced
// reference model, plus which model to default that reference to. Kept out
// reference models. Kept out
// of the component the same way lib/forecast.ts/lib/burndown.ts keep their
// own math out of theirs.
import type { AdminCatalogModel, AdminUsageModelEntry } from '@/types/api'
@@ -53,32 +53,118 @@ export function costAvoidedMicros(rows: FreeUsageRow[], refInputPerMTokUsd: numb
return Math.round(total)
}
/** REFERENCE_INELIGIBLE_SOURCES are the catalog priceSource values pickReferenceModel refuses to default to — a "what would this have cost at a real price" comparison is meaningless against another $0 model. */
const REFERENCE_INELIGIBLE_SOURCES = new Set(['free', 'unpriced'])
/** UNPRICED_SOURCES are the catalog priceSource values that carry no usable rate. */
const UNPRICED_SOURCES = new Set(['free', 'unpriced'])
/** GATEWAY_PRICE_LABEL labels a rate read from the live catalog rather than the reference table. */
const GATEWAY_PRICE_LABEL = 'gateway price'
const SONNET_PREFIX = 'anthropic/claude-sonnet-'
const DATE_SEGMENT = /^\d{8}$/
/**
* pickReferenceModel defaults the "compare free traffic against" model to
* the MOST-REQUESTED genuinely-priced model actually served in the current
* range (redesign-plan.md section 3.4: "reference model picker from priced
* catalog models, default most-requested paid model in range"). Ranked by
* `requests` specifically — NOT by whichever metric the Spend page's own
* breakdown happens to be sorted by — since a cost-ranked or token-ranked
* list would bias the default toward an expensive or verbose model rather
* than the one readers actually reach for most. A model missing from
* `catalog` (not currently in the live registry — a stale ranking entry
* for a since-removed model) or lacking a `requests` count (a detail-less
* entry) is skipped. Returns null when nothing in the range qualifies —
* every served model was itself free/unpriced, or usage/models was empty
* — the caller then falls back to an explicit picker with no preselection
* rather than a fabricated default.
* COST_REFERENCES holds list prices for models the gateway records as
* unpriced, used only by the Cost avoided card. `in`/`out` are USD per
* 1M tokens. A real catalog price for the same id wins over this table.
*/
export function pickReferenceModel(models: AdminUsageModelEntry[], catalog: Map<string, AdminCatalogModel>): string | null {
let best: AdminUsageModelEntry | null = null
for (const m of models) {
if (m.requests === undefined) continue
const cat = catalog.get(m.id)
if (!cat || REFERENCE_INELIGIBLE_SOURCES.has(cat.priceSource)) continue
if (best === null || m.requests > (best.requests ?? 0)) best = m
export const COST_REFERENCES = {
minimax: { id: 'minimax/MiniMax-M3.1-Flash', label: 'MiniMax M3.1 Flash', in: 0.15, out: 0.6, source: 'MiniMax list price', asOf: '2026-11' },
} as const
export interface CostComparison {
id: string
label: string
inPerMTok: number | null
outPerMTok: number | null
priceLabel: string
avoidedMicros: number | null
}
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
function asOfLabel(asOf: string): string {
const [year, month] = asOf.split('-')
return `${MONTHS[Number(month) - 1] ?? month} ${year}`
}
function isPriced(m: AdminCatalogModel): boolean {
return !UNPRICED_SOURCES.has(m.priceSource) && m.inputPerMTokUsd !== undefined && m.outputPerMTokUsd !== undefined
}
/** parseSonnet splits "claude-sonnet-4-5-20250929" into version [4, 5] and date 20250929 (0 when undated). */
function parseSonnet(id: string): { version: number[]; date: number } | null {
const parts = id.slice(SONNET_PREFIX.length).split('-')
const version: number[] = []
let date = 0
for (const p of parts) {
if (DATE_SEGMENT.test(p)) date = Number(p)
else if (/^\d+$/.test(p)) version.push(Number(p))
else return null
}
return best?.id ?? null
return version.length === 0 ? null : { version, date }
}
function compareSonnet(a: { version: number[]; date: number }, b: { version: number[]; date: number }): number {
const n = Math.max(a.version.length, b.version.length)
for (let i = 0; i < n; i++) {
const d = (a.version[i] ?? 0) - (b.version[i] ?? 0)
if (d !== 0) return d
}
return a.date - b.date
}
/**
* latestSonnet returns the highest-version priced `anthropic/claude-sonnet-*`
* in the catalog, or null. A date suffix only breaks ties between equal versions.
*/
export function latestSonnet(catalog: Map<string, AdminCatalogModel>): AdminCatalogModel | null {
let best: AdminCatalogModel | null = null
let bestKey: { version: number[]; date: number } | null = null
for (const m of catalog.values()) {
if (!m.id.startsWith(SONNET_PREFIX) || !isPriced(m)) continue
const key = parseSonnet(m.id)
if (key === null) continue
if (bestKey === null || compareSonnet(key, bestKey) > 0) {
best = m
bestKey = key
}
}
return best
}
/**
* costComparisons prices the free-tier rows against MiniMax M3.1 Flash, then
* the latest Sonnet. Entry `avoidedMicros` is null only when no rate exists.
*/
export function costComparisons(rows: FreeUsageRow[], catalog: Map<string, AdminCatalogModel>): CostComparison[] {
const ref = COST_REFERENCES.minimax
const mm = catalog.get(ref.id)
const mmCatalog = mm && isPriced(mm) ? mm : null
const minimax = mmCatalog
? { inP: mmCatalog.inputPerMTokUsd as number, outP: mmCatalog.outputPerMTokUsd as number, priceLabel: GATEWAY_PRICE_LABEL }
: { inP: ref.in as number, outP: ref.out as number, priceLabel: `${ref.source}, ${asOfLabel(ref.asOf)}` }
const out: CostComparison[] = [
{
id: ref.id,
label: ref.label,
inPerMTok: minimax.inP,
outPerMTok: minimax.outP,
priceLabel: minimax.priceLabel,
avoidedMicros: costAvoidedMicros(rows, minimax.inP, minimax.outP),
},
]
const sonnet = latestSonnet(catalog)
out.push(
sonnet
? {
id: sonnet.id,
label: sonnet.model,
inPerMTok: sonnet.inputPerMTokUsd as number,
outPerMTok: sonnet.outputPerMTokUsd as number,
priceLabel: GATEWAY_PRICE_LABEL,
avoidedMicros: costAvoidedMicros(rows, sonnet.inputPerMTokUsd as number, sonnet.outputPerMTokUsd as number),
}
: { id: `${SONNET_PREFIX}*`, label: 'Latest Claude Sonnet', inPerMTok: null, outPerMTok: null, priceLabel: 'no priced Sonnet in catalog', avoidedMicros: null },
)
return out
}
+31 -45
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Badge, Button, Card, CardAction, CardContent, CardHeader, CardTitle, KpiTile, LineChart, NativeSelect, Pagination, SegmentedControl, StatGroup } from '@perfect-design/ui'
import { Badge, Button, Card, CardAction, CardContent, CardHeader, CardTitle, KpiTile, LineChart, Pagination, SegmentedControl, StatGroup } from '@perfect-design/ui'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useEntityLinks } from '@/composables/useEntityLinks'
@@ -7,7 +7,7 @@ import { useNow } from '@/composables/useNow'
import { budgetLineVisible, cumulative, runOutDate } from '@/lib/burndown'
import { cacheSavingsStatus } from '@/lib/cache-savings'
import { thinLabels } from '@/lib/chart-labels'
import { costAvoidedMicros, freeRows, pickReferenceModel } from '@/lib/cost-avoided'
import { costComparisons, freeRows } from '@/lib/cost-avoided'
import { downloadText } from '@/lib/download'
import type { DownloadOutcome } from '@/lib/download'
import { headroom, monthProgress, NOT_ENOUGH_DATA, projectMonthEnd } from '@/lib/forecast'
@@ -57,18 +57,16 @@ const users = useUsageUsersStore()
const { openEntity } = useEntityLinks()
const { now, start: startClock, stop: stopClock } = useNow()
// --- Page params (hash): by, metric, ref ------------------------------------
// --- Page params (hash): by, metric ------------------------------------
const by = computed<Breakdown>(() => (BREAKDOWNS as readonly string[]).includes(nav.params.by ?? '') ? (nav.params.by as Breakdown) : 'model')
const metric = computed<HistoryMetric>(() => (nav.params.metric && isSpendMetric(nav.params.metric) ? nav.params.metric : 'cost'))
const refParam = computed(() => nav.params.ref ?? '')
function updateParams(next: Partial<{ by: Breakdown; metric: HistoryMetric; ref: string }>): void {
const merged = { by: next.by ?? by.value, metric: next.metric ?? metric.value, ref: next.ref ?? refParam.value }
function updateParams(next: Partial<{ by: Breakdown; metric: HistoryMetric }>): void {
const merged = { by: next.by ?? by.value, metric: next.metric ?? metric.value }
const params: Record<string, string> = {}
if (merged.by !== 'model') params.by = merged.by
if (merged.metric !== 'cost') params.metric = merged.metric
if (merged.ref !== '') params.ref = merged.ref
nav.goTo('usage', params)
}
@@ -249,28 +247,14 @@ const burnState = computed<ViewState>(() => {
const cacheSavings = computed(() => cacheSavingsStatus(filters.window))
const cacheEnabled = computed(() => dashboard.overview?.features.cacheStats ?? false)
const referenceOptions = computed(() =>
spend.modelRanking
.filter((m) => {
const c = catalog.modelsById.get(m.id)
return c && c.priceSource !== 'free' && c.priceSource !== 'unpriced'
})
.sort((a, b) => (b.requests ?? 0) - (a.requests ?? 0))
.slice(0, 100)
.map((m) => ({ value: m.id, label: m.id })),
)
const effectiveRef = computed(() => refParam.value || pickReferenceModel(spend.modelRanking, catalog.modelsById) || '')
const avoidedMicros = computed(() => {
const cat = effectiveRef.value ? catalog.modelsById.get(effectiveRef.value) : undefined
if (!cat || cat.inputPerMTokUsd === undefined || cat.outputPerMTokUsd === undefined) return null
return costAvoidedMicros(freeRows(spend.modelRanking), cat.inputPerMTokUsd, cat.outputPerMTokUsd)
})
const freeUsage = computed(() => freeRows(spend.modelRanking))
const freeTokens = computed(() => ({
in: freeUsage.value.reduce((acc, r) => acc + r.tokensIn, 0),
out: freeUsage.value.reduce((acc, r) => acc + r.tokensOut, 0),
}))
const comparisons = computed(() => costComparisons(freeUsage.value, catalog.modelsById))
const rateText = (inP: number | null, outP: number | null): string => (inP === null || outP === null ? 'n/a' : `$${inP} / $${outP} per 1M`)
const cacheSavedMicros = computed(() => spend.modelRanking.reduce((acc, m) => acc + (m.cacheSavedMicroUsd ?? 0), 0))
const avoidedHint = computed(() => {
if (!spend.detailAvailable) return 'needs per-model detail'
if (referenceOptions.value.length === 0) return 'no priced model served in range'
return avoidedMicros.value === null ? 'pick a reference model' : `at ${effectiveRef.value} rates`
})
const avoidedState = computed<ViewState>(() => {
if (spend.rankingError && spend.modelRanking.length === 0) return 'error'
return spend.modelRanking.length === 0 && spend.loading ? 'loading' : 'ready'
@@ -471,16 +455,26 @@ const money = (micros: number | null): string | null => (micros === null ? null
</CardHeader>
<CardContent class="flex flex-col gap-3">
<StateView :state="avoidedState" :error-message="spend.rankingError" @retry="spend.refresh()">
<StatGroup :columns="cacheEnabled ? 2 : 1" gap="sm" aria-label="Savings">
<div v-if="spend.detailAvailable" class="flex flex-col gap-1" data-wb-ignore-numeric>
<p class="text-muted-foreground m-0 text-xs">
Free-tier traffic: <span class="font-mono tabular-nums">{{ formatCompactCount(freeTokens.in) }}</span> in ·
<span class="font-mono tabular-nums">{{ formatCompactCount(freeTokens.out) }}</span> out. Cost at:
</p>
<ul class="m-0 flex list-none flex-col p-0" aria-label="Cost avoided by reference model">
<li
v-for="c in comparisons"
:key="c.id"
class="border-border grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-x-3 border-t py-2 first:border-t-0"
>
<span class="min-w-0 truncate text-sm"><ModelName :id="c.id" /></span>
<span class="text-right font-mono text-sm font-medium tabular-nums">{{ money(c.avoidedMicros) ?? 'n/a' }}</span>
<span class="text-muted-foreground text-xs" :title="c.priceLabel">{{ c.priceLabel }}</span>
<span class="text-muted-foreground text-right font-mono text-xs tabular-nums">{{ rateText(c.inPerMTok, c.outPerMTok) }}</span>
</li>
</ul>
</div>
<StatGroup v-if="cacheEnabled" :columns="1" gap="sm" aria-label="Savings">
<KpiTile
label="Free-tier traffic"
size="compact"
:value="spend.detailAvailable ? money(avoidedMicros) : null"
good-when="none"
:hint="avoidedHint"
/>
<KpiTile
v-if="cacheEnabled"
label="Cache savings"
size="compact"
:value="spend.detailAvailable && cacheSavings.available ? formatCostDisplay(cacheSavedMicros) : 'n/a'"
@@ -488,14 +482,6 @@ const money = (micros: number | null): string | null => (micros === null ? null
:hint="cacheSavings.note ?? rangeLabel"
/>
</StatGroup>
<NativeSelect
v-if="spend.detailAvailable && referenceOptions.length > 0"
:model-value="effectiveRef"
:options="referenceOptions"
size="sm"
aria-label="Reference model"
@update:model-value="(v: string) => updateParams({ ref: v })"
/>
<p v-if="!spend.detailAvailable" class="text-muted-foreground m-0 text-xs">{{ DETAIL_NOTICE }}</p>
</StateView>
</CardContent>
+1 -1
View File
@@ -828,7 +828,7 @@ export interface AdminPerfResponse {
* final.md): an earlier version filled the two price fields from that
* same display resolution instead, so a `pricing:` override with no
* separate modelMeta/discovery price reported `priceSource: 'override'`
* alongside undefined prices — CostAvoidedCard's pickReferenceModel
* alongside undefined prices — CostAvoidedCard's costComparisons
* (lib/cost-avoided.ts) and PricingHealthTable both read these fields
* assuming they agree with `priceSource`, and broke for exactly that
* model.