perf(webui): cut duplicate and serial admin requests

The Spend page fetched the detail model ranking twice, once by the chosen metric and once by requests.
One detail response carries every metric, so the second call now re-ranks the in-flight response.
It sends its own request when the response is cut at the limit, is not detail, or failed.
The Overview page now starts the model ranking beside the first series batch instead of after it.
The embedded assets are regenerated.
This commit is contained in:
2026-11-26 07:48:33 +00:00
parent f03c1090f6
commit f3af3a9879
5 changed files with 310 additions and 170 deletions
+28
View File
@@ -46,6 +46,34 @@ describe('useOverviewStore.refresh', () => {
expect(s.lastUpdated).not.toBeNull()
})
it('requests the model ranking before the first series batch has resolved', async () => {
const order: string[] = []
let releaseSeries: () => void = () => undefined
const gate = new Promise<void>((resolve) => (releaseSeries = resolve))
mocked.mockImplementation(async (url: string) => {
order.push(new URL(url, 'http://x').pathname)
if (url.includes('/usage/series')) await gate
return route(url) as never
})
const s = useOverviewStore()
const done = s.refresh()
await vi.waitFor(() => expect(order).toContain('/admin/api/usage/models'))
releaseSeries()
await done
expect(s.topModels.map((m) => m.id)).toEqual(['p/m1', 'p/m2'])
})
it('reports a failing series batch without an unhandled ranking rejection', async () => {
mocked.mockImplementation(async (url: string) => {
if (url.includes('/usage/models')) throw new Error('models 500')
if (url.includes('/usage/series')) throw new Error('series 500')
return route(url) as never
})
const s = useOverviewStore()
await s.refresh()
expect(s.error.traffic).toContain('series 500')
})
it('fetches the previous period only when compare is requested', async () => {
useFiltersStore().cmp = 'prev'
const s = useOverviewStore()
+4 -3
View File
@@ -73,11 +73,12 @@ export const useOverviewStore = defineStore('overview', {
const res = await this.series([TOTAL_SCOPE], metric, window, span, off)
return { buckets: res.buckets, points: res.series.find((s) => s.scope === TOTAL_SCOPE)?.points ?? [] }
}
// The ranking does not depend on the series, so it runs beside the first batch.
const rankingRequest = adminFetch<AdminUsageModelsResponse>(`/admin/api/usage/models?metric=req&window=${window}&span=${span}&limit=${TOP_N}`)
rankingRequest.catch(() => undefined) // a failing series batch never awaits it; the real error surfaces below
const current = await Promise.all(TOTAL_METRICS.map((m) => totalOf(m, 0)))
const prior = offset > 0 ? await Promise.all(COMPARED_METRICS.map((m) => totalOf(m, offset))) : null
const ranking = await adminFetch<AdminUsageModelsResponse>(
`/admin/api/usage/models?metric=req&window=${window}&span=${span}&limit=${TOP_N}`,
)
const ranking = await rankingRequest
const scopes = ranking.models.map((m) => `model:${m.id}`)
const top = scopes.length > 0 ? (await this.series(scopes, 'req', window, span, 0)).series : []
if (id !== this.reqId) return
+71 -3
View File
@@ -38,6 +38,10 @@ function rankingWith(ids: string[]): AdminUsageModelsResponse {
}
}
function truncatedRanking(): AdminUsageModelsResponse {
return rankingWith(Array.from({ length: 100 }, (_, i) => `a/m${i}`))
}
/** mockRoutes wires adminFetch's mock by matching the route prefix — the four concerns this store fetches (models ranking, series, totals, and again totals for drilldown) all hit different admin.go routes. */
function mockRoutes(handlers: { series?: (url: string) => AdminSeriesResponse; totals?: (url: string) => AdminTotalsResponse; models?: (url: string) => AdminUsageModelsResponse }): void {
mockedAdminFetch.mockImplementation((async (path: string) => {
@@ -147,6 +151,70 @@ describe('useSpendStore.fetchPricingHealthRanking', () => {
})
})
describe('useSpendStore: one detail fetch feeds both rankings', () => {
function entries(n: number): AdminUsageModelsResponse['models'] {
// cost ascending with index while req descends, so the two rankings order differently.
return Array.from({ length: n }, (_, i) => ({ id: `p/m${String(i).padStart(3, '0')}`, value: 0, requests: n - i, tokensIn: 1, tokensOut: 1, costMicroUsd: i + 1, free: false }))
}
function byCost(n: number): AdminUsageModelsResponse {
const models = entries(n)
.map((m) => ({ ...m, value: m.costMicroUsd! }))
.sort((a, b) => b.value - a.value)
return { metric: 'cost', window: 'day', span: 7, detail: true, offset: 0, models }
}
it('requests once and re-ranks the pricing-health ranking by req', async () => {
const urls: string[] = []
mockRoutes({
models: (url) => {
urls.push(url)
return byCost(3)
},
})
const spend = useSpendStore()
spend.$patch({ metric: 'cost' })
await Promise.all([spend.fetchModelRanking(), spend.fetchPricingHealthRanking()])
expect(urls).toHaveLength(1)
expect(spend.modelRanking.map((m) => m.id)).toEqual(['p/m002', 'p/m001', 'p/m000'])
expect(spend.pricingHealthRanking.map((m) => [m.id, m.value])).toEqual([
['p/m000', 3],
['p/m001', 2],
['p/m002', 1],
])
})
it('fetches again when the response is truncated at the limit', async () => {
const urls: string[] = []
mockRoutes({
models: (url) => {
urls.push(url)
return byCost(100)
},
})
const spend = useSpendStore()
spend.$patch({ metric: 'cost' })
await Promise.all([spend.fetchModelRanking(), spend.fetchPricingHealthRanking()])
expect(urls).toHaveLength(2)
})
it('fetches again when the shared request fails', async () => {
let calls = 0
mockRoutes({
models: () => {
calls++
if (calls === 1) throw new Error('boom')
return byCost(3)
},
})
const spend = useSpendStore()
spend.$patch({ metric: 'cost' })
await Promise.all([spend.fetchModelRanking(), spend.fetchPricingHealthRanking()])
expect(calls).toBe(2)
expect(spend.rankingError).toBe('boom')
expect(spend.pricingHealthRanking).toHaveLength(3)
})
})
describe('useSpendStore.fetchBreakdown: by=model, scope=all', () => {
it('fetches total + top-N model series and computes other = total - sum(top)', async () => {
mockRoutes({
@@ -524,7 +592,7 @@ describe('useSpendStore: per-request error fields', () => {
mockRoutes({
models: (url) => {
if (url.includes('metric=req')) throw new Error('pricing boom')
return rankingWith([])
return truncatedRanking() // at the limit, so the pricing leg cannot reuse it and sends its own request
},
})
const spend = useSpendStore()
@@ -555,7 +623,7 @@ describe('useSpendStore: per-request error fields', () => {
mockRoutes({
models: (url) => {
if (url.includes('metric=req')) throw new Error('pricing boom')
return rankingWith([])
return truncatedRanking() // at the limit, so the pricing leg cannot reuse it and sends its own request
},
})
const spend = useSpendStore()
@@ -572,7 +640,7 @@ describe('useSpendStore: per-request error fields', () => {
mockRoutes({
models: (url) => {
if (url.includes('metric=req')) throw new Error('pricing boom')
return rankingWith([])
return truncatedRanking() // at the limit, so the pricing leg cannot reuse it and sends its own request
},
})
const spend = useSpendStore()
+45 -2
View File
@@ -630,8 +630,51 @@ export const useSpendStore = defineStore('spend', {
},
})
/** fetchModelsRanking asks for `detail=1` except on ranges the server is known to refuse (48h, 30d); a 400 elsewhere retries once without detail. Reports which form it got. */
async function fetchModelsRanking(metric: string, window: HistoryWindow, span: number): Promise<{ res: AdminUsageModelsResponse; detail: boolean }> {
type ModelsRanking = { res: AdminUsageModelsResponse; detail: boolean }
/** The metric each detail row carries a total for, so one detail response can be re-ranked by any of them. */
const DETAIL_VALUE_FIELD = { req: 'requests', tokin: 'tokensIn', tokout: 'tokensOut', cost: 'costMicroUsd' } as const
/** Detail fetches in flight per window/span, so concurrent callers with another metric share one request instead of sending their own. */
const inflightDetailRankings = new Map<string, { metric: string; promise: Promise<ModelsRanking> }>()
/** rerankDetail returns `got` re-ranked by `metric` as the server would rank it, or null when it cannot: a non-detail or truncated response is missing rows the other ranking would include. */
function rerankDetail(got: ModelsRanking, metric: string): ModelsRanking | null {
const field = DETAIL_VALUE_FIELD[metric as keyof typeof DETAIL_VALUE_FIELD]
if (!got.detail || !field || got.res.models.length >= MODEL_RANKING_LIMIT) return null
if (got.res.models.some((m) => m[field] === undefined || m.requests === undefined)) return null
const models = got.res.models
.map((m) => ({ ...m, value: m[field]! }))
.sort((a, b) => b.value - a.value || b.requests! - a.requests! || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
return { res: { ...got.res, metric, models }, detail: true }
}
/** fetchModelsRanking asks for `detail=1` except on ranges the server is known to refuse (48h, 30d); a 400 elsewhere retries once without detail. Reports which form it got. A concurrent call for the same range with another metric re-ranks the in-flight detail response instead of fetching again. */
async function fetchModelsRanking(metric: string, window: HistoryWindow, span: number): Promise<ModelsRanking> {
if (!modelDetailSupported(window, span)) return fetchModelsRankingOnce(metric, window, span)
const key = `${window}|${span}`
const inflight = inflightDetailRankings.get(key)
if (inflight) {
if (inflight.metric === metric) return inflight.promise
try {
const derived = rerankDetail(await inflight.promise, metric)
if (derived) return derived
} catch {
// The shared fetch failed; this metric makes its own request below.
}
return fetchModelsRankingOnce(metric, window, span)
}
const promise = fetchModelsRankingOnce(metric, window, span)
const entry = { metric, promise }
inflightDetailRankings.set(key, entry)
const clear = () => {
if (inflightDetailRankings.get(key) === entry) inflightDetailRankings.delete(key)
}
promise.then(clear, clear)
return promise
}
async function fetchModelsRankingOnce(metric: string, window: HistoryWindow, span: number): Promise<ModelsRanking> {
const base = `/admin/api/usage/models?metric=${metric}&window=${window}&span=${span}&limit=${MODEL_RANKING_LIMIT}`
if (!modelDetailSupported(window, span)) return { res: await adminFetch<AdminUsageModelsResponse>(base), detail: false }
try {