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
+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)
})
})