fix(webui): mock live token meters and consistent huge scenario

Add tokensPerMinute to the live and limits-hot scenarios. Make the huge scenario agree across overview, catalog, performance and usage endpoints. Derive hot users from the friends group.
This commit is contained in:
2026-11-25 11:52:35 +00:00
parent 853a66dcb7
commit af3628d13d
3 changed files with 174 additions and 26 deletions
+18 -5
View File
@@ -1,5 +1,5 @@
import { matchFixture, nearestFixture, normaliseQuery, type Fixture } from './match.ts'
import { applyScenarios, errorEnvelope, scenarioDelayMs } from './scenarios.ts'
import { applyScenarios, errorEnvelope, hotUserIds, scenarioDelayMs } from './scenarios.ts'
import { fitSeriesScopes, synthesise } from './synth.ts'
import { CAPTURE_AT, shiftTimestamps } from './time-shift.ts'
@@ -97,17 +97,30 @@ export function jitterMeters(path: string, body: unknown, rng: () => number): un
p.failuresMinute = Math.min(wobble(p.failuresMinute, rng), p.attemptsMinute)
}
} else {
for (const u of b.users ?? []) u.requestsPerMinute = wobble(u.requestsPerMinute, rng, u.limits?.requestsPerMinute || undefined)
for (const g of b.groups ?? []) g.requestsPerMinute = wobble(g.requestsPerMinute, rng)
if (b.total) b.total.requestsPerMinute = wobble(b.total.requestsPerMinute, rng)
for (const u of b.users ?? []) {
u.requestsPerMinute = wobble(u.requestsPerMinute, rng, u.limits?.requestsPerMinute || undefined)
if (u.tokensPerMinute > 0) u.tokensPerMinute = wobble(u.tokensPerMinute, rng, u.limits?.tokensPerMinute || undefined)
}
for (const o of [...(b.groups ?? []), b.total ?? {}]) {
o.requestsPerMinute = wobble(o.requestsPerMinute, rng)
if (o.tokensPerMinute > 0) o.tokensPerMinute = wobble(o.tokensPerMinute, rng)
}
}
return b
}
const EVENTS = '/admin/api/events'
function usageBody(i: RespondInput): Obj {
const f = i.manifest.find((m) => m.path === '/admin/api/usage')
return f ? (i.readFixture(f.file) as Obj) : { users: [] }
}
/** One mock admin API response: fixture or synthesis, then scenarios, then meter jitter. */
export function respond(i: RespondInput): MockResponse {
const base = resolveBase(i)
const out = applyScenarios(i.scenarios, i.path, base.body, base.status, { now: i.now, rng: i.rng })
const hotUsers = i.scenarios.includes('limits-hot') && i.path === EVENTS ? hotUserIds(usageBody(i)) : undefined
const out = applyScenarios(i.scenarios, i.path, base.body, base.status, { now: i.now, rng: i.rng, hotUsers })
const body = out.status === 200 ? jitterMeters(i.path, out.body, i.rng) : out.body
return { status: out.status, body, delayMs: scenarioDelayMs(i.scenarios) }
}
+54 -17
View File
@@ -23,8 +23,10 @@ export const SLOW_DELAY_MS = 1500
const API = '/admin/api/'
const HISTORY_PATHS = ['/admin/api/usage/series', '/admin/api/usage/totals', '/admin/api/usage/models']
const LATENCY_KEYS = ['p50Ms', 'p95Ms', 'p99Ms', 'ttfbP50Ms', 'ttfbP95Ms']
const HOT_USER_IDS = ['user-01', 'user-02', 'user-03']
const HOT_USERS = 3
const HOT_GROUP = 'friends'
const LIVE_TPM_MIN_FRACTION = 0.01
const LIVE_TPM_SPREAD_FRACTION = 0.03
const HOT_MINUTE_FRACTION = 0.93
const HOT_DAY_FRACTION = 0.9
const BREAKER_OPEN_MS = 90_000
@@ -33,6 +35,8 @@ const HUGE_FACTOR = 3
export interface ScenarioContext {
now: number
rng: () => number
/** Users limits-hot targets on the events path; usage derives them itself, see hotUserIds. */
hotUsers?: string[]
}
export interface ScenarioResult {
@@ -201,19 +205,37 @@ function empty(path: string, body: Obj) {
}
}
/** The first HOT_USERS members of the friends group that have a per-minute request limit. */
export function hotUserIds(usage: Obj): string[] {
return (usage.users as Obj[])
.filter((u) => (u.groups ?? [u.groupName]).includes(HOT_GROUP) && (u.limits?.requestsPerMinute ?? 0) > 0)
.map((u) => u.id as string)
.sort()
.slice(0, HOT_USERS)
}
function addToGroupAndTotal(body: Obj, groupName: string | undefined, field: string, delta: number) {
for (const g of body.groups ?? []) if (g.id === groupName) g[field] = (g[field] ?? 0) + delta
if (body.total) body.total[field] = (body.total[field] ?? 0) + delta
}
function limitsHot(path: string, body: Obj, ctx: ScenarioContext) {
if (path === '/admin/api/usage') {
const hot = (body.users as Obj[]).filter((u) => HOT_USER_IDS.includes(u.id) && (u.limits?.requestsPerMinute ?? 0) > 0)
for (const u of hot) {
u.requestsPerMinute = Math.floor(u.limits.requestsPerMinute * HOT_MINUTE_FRACTION)
const ids = hotUserIds(body)
for (const u of (body.users as Obj[]).filter((x) => ids.includes(x.id))) {
const rpm = Math.floor(u.limits.requestsPerMinute * HOT_MINUTE_FRACTION)
addToGroupAndTotal(body, HOT_GROUP, 'requestsPerMinute', rpm - u.requestsPerMinute)
u.requestsPerMinute = rpm
if (u.limits.tokensPerMinute > 0) {
const tpm = Math.floor(u.limits.tokensPerMinute * HOT_MINUTE_FRACTION)
addToGroupAndTotal(body, HOT_GROUP, 'tokensPerMinute', tpm - (u.tokensPerMinute ?? 0))
u.tokensPerMinute = tpm
}
if (u.limits.requestsPerDay > 0) u.requestsPerDay = Math.floor(u.limits.requestsPerDay * HOT_DAY_FRACTION)
u.rejectionsPerDay = Math.max(u.rejectionsPerDay ?? 0, 9)
}
const added = hot.reduce((s: number, u: Obj) => s + u.requestsPerMinute, 0)
for (const g of body.groups ?? []) if (g.id === HOT_GROUP) g.requestsPerMinute += added
if (body.total) body.total.requestsPerMinute += added
} else if (path === '/admin/api/events') {
const fresh = HOT_USER_IDS.flatMap((user, i) => [
const fresh = (ctx.hotUsers ?? []).flatMap((user, i) => [
limitEvent(user, 'rate_limit', ctx.now - (i * 2 + 1) * 4000, 'requests per minute limit reached; request rejected', 429),
limitEvent(user, 'paced', ctx.now - (i * 2 + 2) * 4000, `request delayed ${(1.5 + i * 0.7).toFixed(1)}s by pacing`),
])
@@ -227,6 +249,17 @@ function limitEvent(user: string, kind: string, at: number, message: string, sta
const copies = <T>(factor: number, make: (n: number) => T): T[] => Array.from({ length: factor }, (_, n) => make(n))
const suffix = (id: string, n: number) => (n === 0 ? id : `${id}-v${n + 1}`)
const hugeProvider = (name: string, n: number) => (n === 0 ? name : `${name}-${n + 1}`)
/** Every "provider/model" id the huge overview and catalog list for one captured id. */
function hugeModelIds(id: string): string[] {
const slash = id.indexOf('/')
const provider = slash < 0 ? '' : id.slice(0, slash)
const model = id.slice(slash + 1)
return copies(HUGE_FACTOR, (n) => copies(HUGE_FACTOR, (r) => `${provider ? `${hugeProvider(provider, n)}/` : ''}${suffix(model, r)}`)).flat()
}
const expandRows = (rows: Obj[], ids: (id: string) => string[]): Obj[] => rows.flatMap((r) => ids(r.id).map((id) => ({ ...r, id })))
function huge(path: string, body: Obj) {
if (path === '/admin/api/overview') {
@@ -234,28 +267,26 @@ function huge(path: string, body: Obj) {
copies(HUGE_FACTOR, (n) => {
const models = (p.models as string[]).flatMap((m) => copies(HUGE_FACTOR, (r) => suffix(m, r)))
const grow = (src: Obj) => Object.fromEntries(Object.entries(src ?? {}).flatMap(([m, v]) => copies(HUGE_FACTOR, (r) => [suffix(m, r), v])))
return { ...p, name: n === 0 ? p.name : `${p.name}-${n + 1}`, models, modelCount: models.length, modelMeta: grow(p.modelMeta), modelRates: grow(p.modelRates) }
return { ...p, name: hugeProvider(p.name, n), models, modelCount: models.length, modelMeta: grow(p.modelMeta), modelRates: grow(p.modelRates) }
}),
)
} else if (path === '/admin/api/catalog') {
body.providers = (body.providers as Obj[]).flatMap((p) =>
copies(HUGE_FACTOR, (n) => {
const name = n === 0 ? p.name : `${p.name}-${n + 1}`
const name = hugeProvider(p.name, n)
const models = (p.models as Obj[]).flatMap((m) => copies(HUGE_FACTOR, (r) => ({ ...m, model: suffix(m.model, r), id: `${name}/${suffix(m.model, r)}` })))
return { ...p, name, models }
}),
)
} else if (path === '/admin/api/usage/models' && Array.isArray(body.models)) {
body.models = tripleRows(body.models)
} else if (path === '/admin/api/performance' && Array.isArray(body.rows) && body.kind === 'model') {
body.rows = tripleRows(body.rows)
body.models = expandRows(body.models, hugeModelIds)
} else if (path === '/admin/api/performance' && Array.isArray(body.rows)) {
body.rows = expandRows(body.rows, body.kind === 'provider' ? (id) => copies(HUGE_FACTOR, (n) => hugeProvider(id, n)) : hugeModelIds)
} else if (path === '/admin/api/usage/totals' && body.kind === 'usermodel') {
body.rows = expandRows(body.rows, hugeModelIds)
}
}
function tripleRows(rows: Obj[]): Obj[] {
return rows.flatMap((r) => copies(HUGE_FACTOR, (n) => ({ ...r, id: suffix(r.id, n) })))
}
function live(path: string, body: Obj, ctx: ScenarioContext) {
if (path === '/admin/api/events') {
const kinds = ['upstream', 'capacity', 'unpriced']
@@ -264,6 +295,12 @@ function live(path: string, body: Obj, ctx: ScenarioContext) {
} else if (path === '/admin/api/usage') {
for (const u of body.users ?? []) if (u.requestsPerDay > 0) u.requestsPerMinute = Math.max(u.requestsPerMinute, 3)
body.total.requestsPerMinute = Math.max(body.total.requestsPerMinute, 24)
for (const u of body.users ?? []) {
const limit = u.limits?.tokensPerMinute ?? 0
if (limit <= 0 || !(u.requestsPerDay > 0)) continue
u.tokensPerMinute = Math.round(limit * (LIVE_TPM_MIN_FRACTION + ctx.rng() * LIVE_TPM_SPREAD_FRACTION))
addToGroupAndTotal(body, u.groupName, 'tokensPerMinute', u.tokensPerMinute)
}
} else if (path === '/admin/api/overview') {
for (const p of body.providers ?? []) if (p.attemptsDay > 0) p.attemptsMinute = Math.max(p.attemptsMinute, 4)
}
+102 -4
View File
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import manifestJson from '../../mock/manifest.json'
import { matchFixture, type Fixture } from '../../mock/match'
import { respond } from '../../mock/respond'
import { applyScenarios, SCENARIOS, scenarioDelayMs, parseScenarios } from '../../mock/scenarios'
import { applyScenarios, hotUserIds, SCENARIOS, scenarioDelayMs, parseScenarios } from '../../mock/scenarios'
import { bucketsFor, CAPTURE_AT, shiftTimestamps } from '../../mock/time-shift'
const manifest = manifestJson as Fixture[]
@@ -156,7 +156,7 @@ describe('respond', () => {
it('jitters live minute meters between calls', () => {
let n = 0
const rng = () => (n++ % 2 ? 0.9 : 0.1)
const rng = () => (n++ * 0.37) % 1
const call = () => respond({ manifest, readFixture, path: '/admin/api/usage', query: q(''), scenarios: ['live'], now: NOW, rng }).body as Any
expect(call().total.requestsPerMinute).not.toBe(call().total.requestsPerMinute)
})
@@ -270,20 +270,58 @@ describe('scenarios', () => {
})
it('limits-hot sets requestsPerMinute near limit for 3 friends users and adds rate_limit/paced events', () => {
const u = apply(['limits-hot'], '/admin/api/usage', readFixture('usage.json')).body as Any
const usage = readFixture('usage.json') as Any
const u = apply(['limits-hot'], '/admin/api/usage', usage).body as Any
const hot = u.users.filter((x: Any) => x.limits?.requestsPerMinute > 0 && x.requestsPerMinute >= x.limits.requestsPerMinute * 0.8)
expect(hot).toHaveLength(3)
expect(hot.map((h: Any) => h.id).sort()).toEqual(hotUserIds(usage))
for (const h of hot) {
expect(h.groupName).toBe('friends')
expect(h.requestsPerMinute).toBeLessThanOrEqual(h.limits.requestsPerMinute)
}
const e = apply(['limits-hot'], '/admin/api/events', readFixture('events__limit-200.json')).body as Any
const e = applyScenarios(['limits-hot'], '/admin/api/events', readFixture('events__limit-200.json'), 200, { ...NOWS, hotUsers: hotUserIds(usage) }).body as Any
const kinds = new Set(e.events.map((x: Any) => x.kind))
expect(kinds.has('rate_limit')).toBe(true)
expect(kinds.has('paced')).toBe(true)
expect(e.events.filter((x: Any) => hot.some((h: Any) => h.id === x.user)).length).toBeGreaterThan(0)
})
it('derives the hot users from the friends group members', () => {
const usage = { users: [
{ id: 'b', groupName: 'home', groups: ['home'], limits: { requestsPerMinute: 5 } },
{ id: 'z', groupName: 'friends', groups: ['friends'], limits: { requestsPerMinute: 5 } },
{ id: 'c', groupName: 'friends', groups: ['friends'], limits: { requestsPerMinute: 5 } },
{ id: 'n', groupName: 'friends', groups: ['friends'], limits: {} },
{ id: 'a', groupName: 'friends', groups: ['friends'], limits: { requestsPerMinute: 5 } },
{ id: 'd', groupName: 'friends', groups: ['friends'], limits: { requestsPerMinute: 5 } },
] }
expect(hotUserIds(usage)).toEqual(['a', 'c', 'd'])
})
it('limits-hot sets live tokensPerMinute near the limit and sums it into group and total', () => {
const usage = readFixture('usage.json') as Any
const u = apply(['limits-hot'], '/admin/api/usage', usage).body as Any
const hot = u.users.filter((x: Any) => hotUserIds(usage).includes(x.id))
for (const h of hot) {
expect(h.tokensPerMinute).toBe(Math.floor(h.limits.tokensPerMinute * 0.93))
expect(h.tokensPerMinute).toBeLessThanOrEqual(h.limits.tokensPerMinute)
}
const sum = hot.reduce((n: number, h: Any) => n + h.tokensPerMinute, 0)
expect(u.groups.find((g: Any) => g.id === 'friends').tokensPerMinute).toBe(sum)
expect(u.total.tokensPerMinute).toBe(sum)
})
it('live gives users with a tokensPerMinute limit a small value and others none', () => {
const u = apply(['live'], '/admin/api/usage', readFixture('usage.json')).body as Any
const active = u.users.filter((x: Any) => x.limits?.tokensPerMinute > 0 && x.requestsPerDay > 0)
expect(active.length).toBeGreaterThan(0)
for (const x of active) {
expect(x.tokensPerMinute).toBeGreaterThan(0)
expect(x.tokensPerMinute).toBeLessThan(x.limits.tokensPerMinute * 0.05)
}
for (const x of u.users.filter((y: Any) => !(y.limits?.tokensPerMinute > 0))) expect(x.tokensPerMinute).toBeUndefined()
})
it('huge triples providers and models with unique ids', () => {
const base = overview()
const o = apply(['huge'], '/admin/api/overview', base).body as Any
@@ -306,3 +344,63 @@ describe('scenarios', () => {
expect(apply(['live'], '/admin/api/config', body).body).toEqual(body)
})
})
describe('huge scenario consistency', () => {
const hugeGet = (path: string, query: string) => get(path, query, ['huge']).body as Any
it('lists the same provider ids in overview and performance kind=provider', () => {
const overview = hugeGet('/admin/api/overview', '')
const perf = hugeGet('/admin/api/performance', 'kind=provider&window=day&span=14')
const names = overview.providers.map((p: Any) => p.name).sort()
expect(perf.rows.map((r: Any) => r.id).sort()).toEqual(names)
expect(names).toHaveLength(57)
})
it('lists model ids that overview and catalog also list', () => {
const overview = hugeGet('/admin/api/overview', '')
const fromOverview = overview.providers.flatMap((p: Any) => p.models.map((m: string) => `${p.name}/${m}`))
const catalog = hugeGet('/admin/api/catalog', '')
const known = new Set<string>(catalog.providers.flatMap((p: Any) => p.models.map((m: Any) => m.id)))
for (const id of fromOverview) expect(known.has(id), id).toBe(true)
const perf = hugeGet('/admin/api/performance', 'kind=model&window=day&span=14')
const models = hugeGet('/admin/api/usage/models', 'metric=req&window=day&span=7&limit=100&detail=1')
const totals = hugeGet('/admin/api/usage/totals', 'kind=usermodel&window=day&span=14&user=admin')
for (const rows of [perf.rows, models.models, totals.rows]) {
expect(rows.length).toBeGreaterThan(0)
expect(new Set(rows.map((r: Any) => r.id)).size).toBe(rows.length)
for (const r of rows) expect(known.has(r.id), r.id).toBe(true)
}
})
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))
}
})
})