test(mock): enforce backend series metric rules

Port seriesValidMetric and the usage/series query checks into the mock so it
returns the backend 400 for an invalid scope, metric and window combination.
This commit is contained in:
2026-11-25 12:38:58 +00:00
parent fd9dc53241
commit b48ec65f94
4 changed files with 190 additions and 30 deletions
+6 -1
View File
@@ -1,5 +1,6 @@
import { matchFixture, nearestFixture, normaliseQuery, type Fixture } from './match.ts'
import { applyScenarios, errorEnvelope, hotUserIds, scenarioDelayMs } from './scenarios.ts'
import { seriesQueryError } from './series-rules.ts'
import { fitSeriesScopes, synthesise } from './synth.ts'
import { CAPTURE_AT, shiftTimestamps } from './time-shift.ts'
@@ -23,7 +24,7 @@ export interface MockResponse {
const SERIES = '/admin/api/usage/series'
const MODELS = '/admin/api/usage/models'
const SERIES_SCOPE = /^(model|provider|group|user):.+$|^total$/
const SERIES_SCOPE = /^(model|provider|provmodel|group|user):.+$|^total$/
const WINDOWS = ['hour', 'day', 'month']
const JITTER = 0.15
const RANGE_TOO_LARGE = 'range too large; narrow span or filter'
@@ -56,6 +57,10 @@ function limitRows(path: string, query: URLSearchParams, body: Obj): Obj {
function resolveBase(i: RespondInput): { status: number; body: unknown } {
const { manifest, path, query, now } = i
if (!manifest.some((f) => f.path === path)) return notFound(`unknown admin route ${path}`)
if (path === SERIES) {
const invalid = seriesQueryError(query)
if (invalid) return { status: 400, body: errorEnvelope(400, 'invalid_request_error', invalid) }
}
const bad = validQuery(path, query)
if (bad) return notFound(bad)
+78
View File
@@ -0,0 +1,78 @@
// Mirror of the backend's GET /admin/api/usage/series validation (stats_read.go, admin.go). Keep case-for-case in sync.
export const SERIES_MAX_SCOPES = 100
const HISTORY_MAX_SPAN: Record<string, number> = { hour: 48, day: 35, month: 13 }
const HISTORY_METRICS = ['req', 'tokin', 'tokout', 'cost']
const KNOWN_STATS_METRICS = ['rej', 'attempt', 'fail', 'timeout', 'fover', 'r402', 'chit', 'cmiss', 'csave']
export type SeriesScopeKind = 'user' | 'group' | 'total' | 'model' | 'prov' | 'provmodel'
/** parseSeriesScope: the scope kind a `scope` param names, or null when the backend would list it as unknown. */
export function parseSeriesScope(raw: string): SeriesScopeKind | null {
if (raw === 'total') return 'total'
const at = raw.indexOf(':')
if (at < 0 || at === raw.length - 1) return null
switch (raw.slice(0, at)) {
case 'user':
case 'group':
case 'model':
case 'provmodel':
return raw.slice(0, at) as SeriesScopeKind
case 'provider':
return 'prov'
default:
return null
}
}
/** seriesValidMetric: stats_read.go's metric x scope-kind x window matrix. */
export function seriesValidMetric(scopeKind: SeriesScopeKind, metric: string, window: string): boolean {
const hourOrDay = window === 'hour' || window === 'day'
switch (scopeKind) {
case 'user':
case 'group':
case 'total':
if (['req', 'tokin', 'tokout', 'cost'].includes(metric)) return true
if (metric === 'rej') return hourOrDay
if (scopeKind === 'total' && ['chit', 'cmiss', 'csave', 'r402'].includes(metric)) return hourOrDay
return false
case 'model':
if (['req', 'tokin', 'tokout', 'cost'].includes(metric)) return true
if (['chit', 'csave', 'r402'].includes(metric)) return window === 'day'
return false
case 'prov':
return ['attempt', 'fail', 'timeout', 'fover'].includes(metric) && hourOrDay
case 'provmodel':
return ['attempt', 'fail'].includes(metric) && hourOrDay
}
}
const isInt = (raw: string): boolean => /^[+-]?\d+$/.test(raw)
/** seriesQueryError: the 400 message serveAdminUsageSeries returns for this query, or null when the backend accepts it. Same check order as the Go handler. */
export function seriesQueryError(query: URLSearchParams): string | null {
const scopes = query.getAll('scope')
if (scopes.length === 0) return 'at least one scope is required'
if (scopes.length > SERIES_MAX_SCOPES) return 'too many scopes'
const window = query.get('window') ?? ''
const max = HISTORY_MAX_SPAN[window]
if (max === undefined) return 'unknown window'
const metric = query.get('metric') ?? ''
if (!HISTORY_METRICS.includes(metric) && !KNOWN_STATS_METRICS.includes(metric)) return 'unknown metric'
const rawSpan = query.get('span') ?? ''
let span = max
if (rawSpan !== '') {
span = Number(rawSpan)
if (!isInt(rawSpan) || span < 1 || span > max) return 'invalid span'
}
const rawOffset = query.get('offset') ?? ''
if (rawOffset !== '') {
const offset = Number(rawOffset)
if (!isInt(rawOffset) || offset < 0 || offset > max - span) return 'invalid offset'
}
for (const raw of scopes) {
const kind = parseSeriesScope(raw)
if (kind !== null && !seriesValidMetric(kind, metric, window)) return 'unknown metric for scope kind'
}
return null
}
+101
View File
@@ -0,0 +1,101 @@
import { describe, expect, it } from 'vitest'
import manifestJson from '../../mock/manifest.json'
import type { Fixture } from '../../mock/match'
import { respond } from '../../mock/respond'
import { parseSeriesScope, seriesQueryError, seriesValidMetric, type SeriesScopeKind } from '../../mock/series-rules'
import { CAPTURE_AT } from '../../mock/time-shift'
const ALL_METRICS = ['req', 'tokin', 'tokout', 'cost', 'rej', 'attempt', 'fail', 'timeout', 'fover', 'r402', 'chit', 'cmiss', 'csave']
const WINDOWS = ['hour', 'day', 'month']
const BASE = ['req', 'tokin', 'tokout', 'cost']
// Valid metrics per scope kind and window, transcribed from stats_read.go's seriesValidMetric switch.
const VALID: Record<SeriesScopeKind, Record<string, string[]>> = {
user: { hour: [...BASE, 'rej'], day: [...BASE, 'rej'], month: BASE },
group: { hour: [...BASE, 'rej'], day: [...BASE, 'rej'], month: BASE },
total: {
hour: [...BASE, 'rej', 'chit', 'cmiss', 'csave', 'r402'],
day: [...BASE, 'rej', 'chit', 'cmiss', 'csave', 'r402'],
month: BASE,
},
model: { hour: BASE, day: [...BASE, 'chit', 'csave', 'r402'], month: BASE },
prov: { hour: ['attempt', 'fail', 'timeout', 'fover'], day: ['attempt', 'fail', 'timeout', 'fover'], month: [] },
provmodel: { hour: ['attempt', 'fail'], day: ['attempt', 'fail'], month: [] },
}
describe('seriesValidMetric', () => {
for (const [kind, byWindow] of Object.entries(VALID) as [SeriesScopeKind, Record<string, string[]>][]) {
for (const window of WINDOWS) {
it(`${kind} @ ${window} accepts exactly ${(byWindow[window] ?? []).join(',') || 'nothing'}`, () => {
for (const metric of ALL_METRICS) {
expect(seriesValidMetric(kind, metric, window), `${kind}/${metric}/${window}`).toBe((byWindow[window] ?? []).includes(metric))
}
})
}
}
it('rejects a metric the backend does not know', () => {
expect(seriesValidMetric('total', 'bogus', 'day')).toBe(false)
})
})
describe('parseSeriesScope', () => {
it.each([
['total', 'total'],
['user:alice', 'user'],
['group:friends', 'group'],
['model:openai/gpt-5', 'model'],
['provider:openai', 'prov'],
['provmodel:openai/gpt-5', 'provmodel'],
['user:', null],
['bogus:x', null],
['alice', null],
])('%s -> %s', (raw, kind) => expect(parseSeriesScope(raw)).toBe(kind))
})
describe('seriesQueryError', () => {
const q = (s: string) => new URLSearchParams(s)
it.each([
['metric=req&window=day', 'at least one scope is required'],
['scope=total&metric=req', 'unknown window'],
['scope=total&metric=req&window=min', 'unknown window'],
['scope=total&metric=nope&window=day', 'unknown metric'],
['scope=total&metric=req&window=hour&span=49', 'invalid span'],
['scope=total&metric=req&window=day&span=36', 'invalid span'],
['scope=total&metric=req&window=month&span=14', 'invalid span'],
['scope=total&metric=req&window=day&span=0', 'invalid span'],
['scope=total&metric=req&window=day&span=x', 'invalid span'],
['scope=total&metric=req&window=day&span=7&offset=29', 'invalid offset'],
['scope=total&metric=req&window=day&span=7&offset=-1', 'invalid offset'],
['scope=provider:openai&metric=req&window=day&span=7', 'unknown metric for scope kind'],
['scope=provider:openai&metric=attempt&window=month&span=3', 'unknown metric for scope kind'],
['scope=total&scope=provider:openai&metric=req&window=day&span=7', 'unknown metric for scope kind'],
])('%s -> %s', (query, message) => expect(seriesQueryError(q(query))).toBe(message))
it.each([
'scope=provider:openai&metric=attempt&window=day&span=30',
'scope=total&metric=req&window=month&span=13',
'scope=total&metric=req&window=day&span=7&offset=28',
'scope=total&metric=req&window=day',
'scope=bogus:x&metric=req&window=day',
])('accepts %s', (query) => expect(seriesQueryError(q(query))).toBeNull())
it('rejects more than 100 scopes', () => {
const p = new URLSearchParams('metric=req&window=day&span=1')
for (let i = 0; i < 101; i++) p.append('scope', `user:u${i}`)
expect(seriesQueryError(p)).toBe('too many scopes')
})
})
describe('mock usage/series handler', () => {
const manifest = manifestJson as Fixture[]
const get = (query: string) =>
respond({ manifest, readFixture: () => ({}), path: '/admin/api/usage/series', query: new URLSearchParams(query), scenarios: [], now: CAPTURE_AT, rng: () => 0.5 })
it('answers an invalid scope/metric combination with the backend 400 body', () => {
const r = get('scope=provider:openai&metric=req&window=day&span=7')
expect(r.status).toBe(400)
expect(r.body).toEqual({ error: { message: 'unknown metric for scope kind', type: 'invalid_request_error', code: '400' } })
})
})
+5 -29
View File
@@ -381,34 +381,10 @@ describe('huge scenario consistency', () => {
})
it('serves series for the tripled provider and model scopes', () => {
const b = hugeGet('/admin/api/usage/series', 'scope=provider:alibaba-2&scope=model:alibaba-3/deepseek-v4-flash-0731-v2&metric=req&window=day&span=7')
expect(b.series.map((s: Any) => s.scope)).toEqual(['provider:alibaba-2', 'model:alibaba-3/deepseek-v4-flash-0731-v2'])
for (const s of b.series) expect(s.points).toHaveLength(7)
})
})
describe('month boundaries', () => {
const NEW_YEAR_EVE = Date.parse('2026-12-31T23:59:00Z')
const NEW_YEAR = Date.parse('2027-01-01T00:30:00Z')
it('bucketsFor rolls day, hour and month labels over the year end', () => {
expect(bucketsFor('day', 2, 0, NEW_YEAR_EVE)).toEqual(['20261230', '20261231'])
expect(bucketsFor('day', 2, 0, NEW_YEAR)).toEqual(['20261231', '20270101'])
expect(bucketsFor('hour', 2, 0, NEW_YEAR_EVE)).toEqual(['2026123122', '2026123123'])
expect(bucketsFor('hour', 2, 0, NEW_YEAR)).toEqual(['2026123123', '2027010100'])
expect(bucketsFor('month', 2, 0, NEW_YEAR_EVE)).toEqual(['202611', '202612'])
expect(bucketsFor('month', 2, 0, NEW_YEAR)).toEqual(['202612', '202701'])
expect(bucketsFor('month', 2, 1, NEW_YEAR)).toEqual(['202611', '202612'])
})
it('shiftTimestamps lands the newest bucket on now across the year end', () => {
const body = { buckets: ['20261124', '20261125'], points: [{ id: '20261125' }], hours: { buckets: ['2026112500', '2026112501'] }, months: { buckets: ['202610', '202611'] } }
for (const now of [NEW_YEAR_EVE, NEW_YEAR]) {
const out = shiftTimestamps(body, CAPTURE_AT, now) as Any
expect(out.buckets).toEqual(bucketsFor('day', 2, 0, now))
expect(out.points[0].id).toBe(out.buckets[1])
expect(out.hours.buckets).toEqual(bucketsFor('hour', 2, 0, now))
expect(out.months.buckets).toEqual(bucketsFor('month', 2, 0, now))
}
const prov = hugeGet('/admin/api/usage/series', 'scope=provider:alibaba-2&metric=attempt&window=day&span=7')
const model = hugeGet('/admin/api/usage/series', 'scope=model:alibaba-3/deepseek-v4-flash-0731-v2&metric=req&window=day&span=7')
expect(prov.series.map((s: Any) => s.scope)).toEqual(['provider:alibaba-2'])
expect(model.series.map((s: Any) => s.scope)).toEqual(['model:alibaba-3/deepseek-v4-flash-0731-v2'])
for (const s of [...prov.series, ...model.series]) expect(s.points).toHaveLength(7)
})
})