mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
fix(webui): usage CSV, detail flags, burn-down labels
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { thinLabels } from './chart-labels'
|
||||
|
||||
const nums = (n: number) => Array.from({ length: n }, (_, i) => String(i))
|
||||
|
||||
describe('thinLabels', () => {
|
||||
it('keeps every label when within max', () => {
|
||||
expect(thinLabels(nums(6))).toEqual(nums(6))
|
||||
})
|
||||
|
||||
it('keeps every Nth label and blanks the rest', () => {
|
||||
// 10 labels, max 6 -> N = 2
|
||||
expect(thinLabels(nums(10))).toEqual(['0', '', '2', '', '4', '', '6', '', '8', '9'])
|
||||
})
|
||||
|
||||
it('always keeps the last label', () => {
|
||||
const out = thinLabels(nums(25), 6)
|
||||
expect(out.at(-1)).toBe('24')
|
||||
expect(out).toHaveLength(25)
|
||||
})
|
||||
|
||||
it('keeps the output length and handles empty input', () => {
|
||||
expect(thinLabels([])).toEqual([])
|
||||
expect(thinLabels(['a'])).toEqual(['a'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
/** thinLabels blanks every label except every Nth (N = ceil(len / max)), always keeping the last, so long axes stay legible. */
|
||||
export function thinLabels(labels: string[], max = 6): string[] {
|
||||
const step = Math.max(1, Math.ceil(labels.length / Math.max(1, max)))
|
||||
const last = labels.length - 1
|
||||
return labels.map((label, i) => (i % step === 0 || i === last ? label : ''))
|
||||
}
|
||||
@@ -78,6 +78,7 @@ export function comparison(range: RangeKey): ComparisonResult {
|
||||
/** Spans from which GET /usage/models?detail=1 answers 400 "range too large" (observed on the live API: 48h and 30d fail, 24h and 14d pass). */
|
||||
const DETAIL_REJECTED_FROM_SPAN: Partial<Record<HistoryWindow, number>> = { hour: 48, day: 30 }
|
||||
|
||||
/** Pre-flight optimisation only (avoids a failed request); the retry-on-400 in stores/spend.ts fetchModelsRanking is the real guard for any range the backend rejects. */
|
||||
/** modelDetailSupported is false for ranges where asking for per-model detail is known to fail, so callers skip the doomed request. */
|
||||
export function modelDetailSupported(window: HistoryWindow, span: number): boolean {
|
||||
const limit = DETAIL_REJECTED_FROM_SPAN[window]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { usageCsv } from './usage-csv'
|
||||
import { breakdownCsv, usageCsv } from './usage-csv'
|
||||
import type { AdminUsageEntryView } from '@/types/api'
|
||||
|
||||
function testEntry(overrides: Partial<AdminUsageEntryView> = {}): AdminUsageEntryView {
|
||||
@@ -93,3 +93,14 @@ describe('usageCsv', () => {
|
||||
// modelRankingCsv/modelDetailCsv (and their own describe blocks here)
|
||||
// were removed with the functions themselves (P3 item 25, dead code) —
|
||||
// see usage-csv.ts's own doc comment.
|
||||
|
||||
describe('breakdownCsv', () => {
|
||||
it('exports id, selected metric and share', () => {
|
||||
const csv = breakdownCsv('user', 'req', [{ id: 'alice', value: 9, share: 0.75 }, { id: 'bob', value: 3, share: null }])
|
||||
expect(csv.trim().split(/\r?\n/)).toEqual(['user,req,share', 'alice,9,0.75', 'bob,3,'])
|
||||
})
|
||||
|
||||
it('labels the cost column with its unit', () => {
|
||||
expect(breakdownCsv('group', 'cost', []).split(/\r?\n/)[0]).toBe('group,cost (micro-USD),share')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -125,3 +125,15 @@ export function usageCsv(
|
||||
// redesigned shell — grep confirms only this file and its own now-deleted
|
||||
// spec section ever referenced them. The redesigned Models page
|
||||
// (ModelCatalogTable.vue) has no CSV export of its own.
|
||||
|
||||
export interface BreakdownCsvRow {
|
||||
id: string
|
||||
value: number
|
||||
share: number | null
|
||||
}
|
||||
|
||||
/** breakdownCsv exports exactly what a Usage breakdown table shows: id, the range-selected metric (raw; cost stays micro-USD) and its share. */
|
||||
export function breakdownCsv(idHeader: string, metric: string, rows: BreakdownCsvRow[]): string {
|
||||
const metricHeader = metric === 'cost' ? 'cost (micro-USD)' : metric
|
||||
return toCsv([idHeader, metricHeader, 'share'], rows.map((r) => [r.id, r.value, r.share === null ? '' : r.share]))
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useEntityLinks } from '@/composables/useEntityLinks'
|
||||
import { useNow } from '@/composables/useNow'
|
||||
import { budgetLineVisible, cumulative, runOutDate } from '@/lib/burndown'
|
||||
import { cacheSavingsStatus } from '@/lib/cache-savings'
|
||||
import { toCsv } from '@/lib/csv'
|
||||
import { thinLabels } from '@/lib/chart-labels'
|
||||
import { costAvoidedMicros, freeRows, pickReferenceModel } from '@/lib/cost-avoided'
|
||||
import { downloadText } from '@/lib/download'
|
||||
import type { DownloadOutcome } from '@/lib/download'
|
||||
@@ -22,7 +22,7 @@ import { deltaOf, sumPoints } from '@/lib/overview-metrics'
|
||||
import type { ChartLine } from '@/lib/overview-metrics'
|
||||
import { parseScope, scopeBudgetLimits, scopeId, scopeMtdMicros } from '@/lib/scope'
|
||||
import { seriesToStacked } from '@/lib/series'
|
||||
import { usageCsv } from '@/lib/usage-csv'
|
||||
import { breakdownCsv } from '@/lib/usage-csv'
|
||||
import { wbColumns } from '@/lib/wb-columns'
|
||||
import { useCatalogStore } from '@/stores/catalog'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
@@ -32,6 +32,7 @@ import { isSpendMetric, SPEND_METRIC_LABEL, SPEND_METRICS, useSpendStore } from
|
||||
import { USERS_RANGE_TOO_LARGE, useUsageUsersStore } from '@/stores/usage-users'
|
||||
import type { HistoryMetric } from '@/types/api'
|
||||
import ModelName from '@/widgets/ModelName.vue'
|
||||
import ShareCell from '@/widgets/ShareCell.vue'
|
||||
import StateView from '@/widgets/StateView.vue'
|
||||
import type { ViewState } from '@/widgets/StateView.vue'
|
||||
import WbTable from '@/widgets/WbTable.vue'
|
||||
@@ -163,6 +164,8 @@ interface BreakdownRow {
|
||||
name: string
|
||||
value: number
|
||||
share: number | null
|
||||
/** Set for a zero-valued model row with detail: what to show instead of a zero cost. */
|
||||
zeroText: string | null
|
||||
}
|
||||
|
||||
const columns = computed(() =>
|
||||
@@ -173,17 +176,22 @@ const columns = computed(() =>
|
||||
]),
|
||||
)
|
||||
|
||||
const sourceRows = computed<{ id: string; value: number }[]>(() => {
|
||||
if (by.value === 'model') return spend.modelRanking.map((m) => ({ id: m.id, value: m.value }))
|
||||
const sourceRows = computed<{ id: string; value: number; free?: boolean }[]>(() => {
|
||||
if (by.value === 'model') return spend.modelRanking.map((m) => ({ id: m.id, value: m.value, free: m.free }))
|
||||
if (by.value === 'group') return spend.drilldownRows.map((r) => ({ id: r.id, value: r.values[metric.value] ?? 0 }))
|
||||
return users.rows
|
||||
})
|
||||
|
||||
function zeroText(r: { value: number; free?: boolean }): string | null {
|
||||
if (by.value !== 'model' || !spend.detailAvailable || r.value !== 0) return null
|
||||
return r.free && metric.value === 'cost' ? 'free' : '—'
|
||||
}
|
||||
|
||||
const tableRows = computed<BreakdownRow[]>(() => {
|
||||
const rows = sourceRows.value.filter((r) => r.value > 0 || by.value === 'model').sort((a, b) => b.value - a.value)
|
||||
const sum = rows.reduce((acc, r) => acc + r.value, 0)
|
||||
const total = filters.scope === 'all' && totalInRange.value > 0 ? totalInRange.value : sum
|
||||
return rows.map((r) => ({ id: r.id, name: r.id, value: r.value, share: total > 0 ? Math.min(1, r.value / total) : null }))
|
||||
return rows.map((r) => ({ id: r.id, name: r.id, value: r.value, share: total > 0 ? Math.min(1, r.value / total) : null, zeroText: zeroText(r) }))
|
||||
})
|
||||
|
||||
const tablePage = ref(1)
|
||||
@@ -221,7 +229,7 @@ const limits = computed(() => scopeBudgetLimits(filters.scope, dashboard.overvie
|
||||
const projected = computed(() => projectMonthEnd(mtdMicros.value, monthProgress(now.value)))
|
||||
const room = computed(() => headroom(projected.value, limits.value?.costPerMonthUSD))
|
||||
|
||||
const burnLabels = computed(() => spend.burndownBuckets.map((b) => formatBucketLabel(b, 'day')))
|
||||
const burnLabels = computed(() => thinLabels(spend.burndownBuckets.map((b) => formatBucketLabel(b, 'day'))))
|
||||
const burnSpent = computed(() => cumulative(spend.burndownPoints))
|
||||
const burnTotal = computed(() => burnSpent.value.at(-1) ?? 0)
|
||||
const burnLines = computed<ChartLine[]>(() => {
|
||||
@@ -275,7 +283,7 @@ const healthColumns = computed(() =>
|
||||
{ key: 'id', header: 'Model', kind: 'text', sortable: false },
|
||||
{ key: 'priceSource', header: 'Source', kind: 'status', sortable: false },
|
||||
{ key: 'inputPerMTokUsd', header: 'Price in / out per MTok', kind: 'text', sortable: false },
|
||||
...(spend.detailAvailable
|
||||
...(spend.pricingDetailAvailable
|
||||
? [
|
||||
{ key: 'requests', header: 'Requests', kind: 'number' as const, sortable: false },
|
||||
{ key: 'costMicroUsd', header: 'Cost', kind: 'number' as const, sortable: false },
|
||||
@@ -311,14 +319,8 @@ const feedback = ref<DownloadOutcome | null>(null)
|
||||
const FEEDBACK_LABEL: Record<DownloadOutcome, string> = { downloaded: 'Downloaded', copied: 'Copied', selected: 'Selected', failed: 'Export failed' }
|
||||
let feedbackTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function groupMemberCount(id: string): string {
|
||||
return String((dashboard.usage?.users ?? []).filter((u) => (u.groups ?? (u.groupName === undefined ? [] : [u.groupName])).includes(id)).length)
|
||||
}
|
||||
|
||||
function buildCsv(): string {
|
||||
if (by.value === 'group') return usageCsv(dashboard.usage?.groups ?? [], 'groups', (e) => groupMemberCount(e.id), now.value)
|
||||
if (by.value === 'user') return usageCsv(dashboard.usage?.users ?? [], 'users', (e) => (e.groups ?? (e.groupName === undefined ? [] : [e.groupName])).join(', '), now.value)
|
||||
return toCsv(['model', metric.value, 'share'], tableRows.value.map((r) => [r.id, r.value, r.share ?? '']))
|
||||
return breakdownCsv(by.value, metric.value, tableRows.value)
|
||||
}
|
||||
|
||||
async function exportCsv(): Promise<void> {
|
||||
@@ -428,7 +430,11 @@ const money = (micros: number | null): string | null => (micros === null ? null
|
||||
<ModelName v-if="by === 'model'" :id="value as string" />
|
||||
<template v-else>{{ value }}</template>
|
||||
</template>
|
||||
<template #cell-value="{ value }">{{ fmtValue(value) }}</template>
|
||||
<template #cell-value="{ value, row }">{{ (row as BreakdownRow).zeroText ?? fmtValue(value) }}</template>
|
||||
<template #cell-share="{ value, row }">
|
||||
<ShareCell v-if="!(row as BreakdownRow).zeroText" :value="value as number" />
|
||||
<span v-else aria-hidden="true" />
|
||||
</template>
|
||||
</WbTable>
|
||||
<div v-if="tableRows.length > TABLE_PAGE_SIZE" class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground text-xs">{{ tableRows.length.toLocaleString('en-US') }} rows</span>
|
||||
@@ -506,7 +512,7 @@ const money = (micros: number | null): string | null => (micros === null ? null
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-2">
|
||||
<StateView :state="healthState" empty-title="No served models in this range" :error-message="healthError" @retry="retryHealth">
|
||||
<p v-if="!spend.detailAvailable" class="text-muted-foreground m-0 text-xs">{{ DETAIL_NOTICE }}</p>
|
||||
<p v-if="!spend.pricingDetailAvailable" class="text-muted-foreground m-0 text-xs">{{ DETAIL_NOTICE }}</p>
|
||||
<WbTable
|
||||
:columns="healthColumns"
|
||||
:rows="healthPaged"
|
||||
@@ -520,7 +526,7 @@ const money = (micros: number | null): string | null => (micros === null ? null
|
||||
</template>
|
||||
<template #cell-inputPerMTokUsd="{ row }"><span class="font-mono text-xs">{{ priceText(row as PricingHealthRow) }}</span></template>
|
||||
<template #cell-requests="{ value }">{{ formatCompactCount(value as number) }}</template>
|
||||
<template #cell-costMicroUsd="{ value }">{{ formatCostDisplay(value as number) }}</template>
|
||||
<template #cell-costMicroUsd="{ value, row }">{{ (row as PricingHealthRow).priceSource === 'unpriced' ? '—' : formatCostDisplay(value as number) }}</template>
|
||||
</WbTable>
|
||||
<div v-if="healthRows.length > HEALTH_PAGE_SIZE" class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground text-xs">{{ healthRows.length.toLocaleString('en-US') }} models</span>
|
||||
|
||||
@@ -752,6 +752,33 @@ describe('useSpendStore detail fallback', () => {
|
||||
expect(spend.rankingError).toBe('')
|
||||
})
|
||||
|
||||
it('falls back on a 400 for a range not on the known-rejected list (day/14)', async () => {
|
||||
const urls: string[] = []
|
||||
mockedAdminFetch.mockImplementation((async (path: string) => {
|
||||
urls.push(path)
|
||||
if (path.includes('detail=1')) throw tooLarge()
|
||||
return { ...rankingWith(['a/one']), detail: false, models: [{ id: 'a/one', value: 5 }] }
|
||||
}) as typeof adminFetch)
|
||||
useFiltersStore().setFilters({ range: '14d' })
|
||||
const spend = useSpendStore()
|
||||
await spend.fetchModelRanking()
|
||||
expect(urls).toHaveLength(2)
|
||||
expect(spend.detailAvailable).toBe(false)
|
||||
expect(spend.rankingError).toBe('')
|
||||
})
|
||||
|
||||
it('keeps the two ranking flags independent', async () => {
|
||||
mockedAdminFetch.mockImplementation((async (path: string) => {
|
||||
if (path.includes('metric=req') && path.includes('detail=1')) throw tooLarge()
|
||||
return { ...rankingWith(['a/one']), models: [{ id: 'a/one', value: 5 }] }
|
||||
}) as typeof adminFetch)
|
||||
const spend = useSpendStore()
|
||||
await spend.fetchModelRanking()
|
||||
await spend.fetchPricingHealthRanking()
|
||||
expect(spend.pricingDetailAvailable).toBe(false)
|
||||
expect(spend.detailAvailable).toBe(true)
|
||||
})
|
||||
|
||||
it('does the same for the pricing-health ranking', async () => {
|
||||
mockedAdminFetch.mockImplementation((async (path: string) => {
|
||||
if (path.includes('detail=1')) throw tooLarge()
|
||||
@@ -761,7 +788,7 @@ describe('useSpendStore detail fallback', () => {
|
||||
await spend.fetchPricingHealthRanking()
|
||||
expect(spend.pricingHealthRanking).toHaveLength(1)
|
||||
expect(spend.pricingHealthError).toBe('')
|
||||
expect(spend.detailAvailable).toBe(false)
|
||||
expect(spend.pricingDetailAvailable).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps surfacing non-400 failures', async () => {
|
||||
|
||||
@@ -130,8 +130,10 @@ export const useSpendStore = defineStore('spend', {
|
||||
* longer discards a row specifically BECAUSE it is unpriced.
|
||||
*/
|
||||
pricingHealthRanking: [] as AdminUsageModelsResponse['models'],
|
||||
/** False when the server refused `detail=1` for this range (400 range too large) and the rankings fell back to value-only rows, so per-model tokens, cost and free flags are absent. */
|
||||
/** False when the server refused `detail=1` for this range (400 range too large) and the model ranking fell back to value-only rows, so per-model tokens, cost and free flags are absent. */
|
||||
detailAvailable: true,
|
||||
/** Same as detailAvailable, for the pricing-health ranking. */
|
||||
pricingDetailAvailable: true,
|
||||
|
||||
// --- burn-down (BurnDownChart) ---
|
||||
burndownBuckets: [] as string[],
|
||||
@@ -348,7 +350,7 @@ export const useSpendStore = defineStore('spend', {
|
||||
const { res, detail } = await fetchModelsRanking('req', filters.window, filters.span)
|
||||
if (requestId !== this.pricingHealthReqId) return
|
||||
this.pricingHealthRanking = res.models
|
||||
this.detailAvailable = detail
|
||||
this.pricingDetailAvailable = detail
|
||||
this.pricingHealthError = ''
|
||||
this.pricingHealthLoaded = true
|
||||
} catch (err) {
|
||||
|
||||
Reference in New Issue
Block a user