Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { env } from 'cloudflare:test'
3import { eq } from 'drizzle-orm'
4
5import { getDb } from '../db/index.ts'
6import {
7 cacheMeta,
8 endpoints,
9 models,
10 providers,
11 schemaVersions,
12} from '../db/schema.ts'
13import { FACT_KEYS, buildReport } from '../lib/completeness.ts'
14import type { Ledger, ModelRow } from '../lib/completeness.ts'
15import { providerRegistry } from '../server/providers/index.ts'
16import { listModelsCatalog } from './catalog.ts'
17import { getServiceStatus, recordCompleteness } from './status.ts'
18
19const NOW = 1_781_150_000
20
21describe('getServiceStatus', () => {
22 it('reports per-provider sync state and counts', async () => {
23 const db = getDb(env)
24 await db.insert(providers).values([
25 {
26 id: 'status-a',
27 displayName: 'Status A',
28 specSourceUrl: 'https://example.com/a.json',
29 lastPolledAt: NOW,
30 lastSyncedAt: NOW - 100,
31 },
32 {
33 id: 'status-b',
34 displayName: 'Status B',
35 specSourceUrl: 'https://example.com/b.json',
36 status: 'degraded',
37 },
38 ])
39 await db.insert(models).values([
40 {
41 id: 'status-a-model',
42 providerId: 'status-a',
43 rawId: 'model',
44 firstSeenAt: NOW,
45 lastSeenAt: NOW,
46 },
47 {
48 // A stored card counts as priced; a null column does not.
49 id: 'status-a-priced',
50 providerId: 'status-a',
51 rawId: 'priced',
52 pricing: { inputs: {}, tables: {}, price: 1, examples: [] },
53 firstSeenAt: NOW,
54 lastSeenAt: NOW,
55 },
56 {
57 // Chat without reasoning metadata: denominator only.
58 id: 'status-a-chat',
59 providerId: 'status-a',
60 rawId: 'chat',
61 activity: 'chat',
62 firstSeenAt: NOW,
63 lastSeenAt: NOW,
64 },
65 {
66 id: 'status-a-reasoner',
67 providerId: 'status-a',
68 rawId: 'reasoner',
69 activity: 'chat',
70 reasoning: { mode: 'effort', mandatory: false },
71 firstSeenAt: NOW,
72 lastSeenAt: NOW,
73 },
74 ])
75 await db.insert(endpoints).values({
76 id: 'status-a/v1/things',
77 providerId: 'status-a',
78 activity: 'chat',
79 method: 'POST',
80 path: '/v1/things',
81 })
82 await db.insert(schemaVersions).values([
83 {
84 id: 'status-a/v1/things:input:current',
85 endpointId: 'status-a/v1/things',
86 kind: 'input',
87 contentHash: 'c'.repeat(64),
88 schema: '{}',
89 createdAt: NOW,
90 },
91 {
92 // Superseded version must not count.
93 id: 'status-a/v1/things:input:old',
94 endpointId: 'status-a/v1/things',
95 kind: 'input',
96 contentHash: 'd'.repeat(64),
97 schema: '{}',
98 createdAt: NOW - 10,
99 supersededAt: NOW,
100 },
101 ])
102
103 const status = await getServiceStatus(db, NOW)
104 expect(status.service).toBe('modelschemas')
105 const a = status.providers.find((p) => p.id === 'status-a')
106 const b = status.providers.find((p) => p.id === 'status-b')
107 expect(a).toMatchObject({
108 status: 'active',
109 lastPolledAt: NOW,
110 lastSyncedAt: NOW - 100,
111 counts: {
112 models: 4,
113 priced: 1,
114 reasoning: 1,
115 chat: 2,
116 endpoints: 1,
117 schemas: 1,
118 },
119 })
120 expect(b).toMatchObject({
121 status: 'degraded',
122 lastPolledAt: null,
123 counts: {
124 models: 0,
125 priced: 0,
126 reasoning: 0,
127 chat: 0,
128 endpoints: 0,
129 schemas: 0,
130 },
131 })
132 })
133
134 it('lists every registered provider even before its first sync', async () => {
135 const db = getDb(env)
136 const status = await getServiceStatus(db, NOW)
137 // Nothing is seeded in the test DB, so every registry provider must
138 // surface as pending — the full roster is always visible.
139 for (const config of providerRegistry) {
140 const listed = status.providers.find((p) => p.id === config.id)
141 expect(listed).toMatchObject({
142 displayName: config.displayName,
143 status: 'pending',
144 counts: {
145 models: 0,
146 priced: 0,
147 reasoning: 0,
148 chat: 0,
149 endpoints: 0,
150 schemas: 0,
151 },
152 })
153 }
154 })
155
156 it('carries docs-failing and refused-clears records, and only those', async () => {
157 const db = getDb(env)
158 const ids = ['rec-none', 'rec-docs', 'rec-corrupt', 'rec-clears']
159 await db.insert(providers).values(
160 ids.map((id) => ({
161 id,
162 displayName: id,
163 specSourceUrl: 'https://example.com/spec.json',
164 })),
165 )
166 const docsFailing = {
167 since: NOW - 1800,
168 polls: 3,
169 lastAt: NOW,
170 failed: 2,
171 skipped: 1,
172 sources: ['https://example.com/docs/a', 'https://example.com/docs/b'],
173 error: 'page changed shape',
174 }
175 const priceClearsRefused = {
176 since: NOW - 900,
177 polls: 2,
178 lastAt: NOW,
179 refused: 6,
180 priced: 8,
181 }
182 const row = (key: string, lastError: string | null) => ({
183 key,
184 fetchedAt: NOW,
185 staleTime: 0,
186 lastError,
187 })
188 await db.insert(cacheMeta).values([
189 row('docs-failing:rec-docs', JSON.stringify(docsFailing)),
190 row(
191 'price-clears-refused:rec-clears',
192 JSON.stringify(priceClearsRefused),
193 ),
194 // Not JSON, JSON of the wrong shape, and no body at all.
195 row('docs-failing:rec-corrupt', '{not json'),
196 row('price-clears-refused:rec-corrupt', '"a string"'),
197 row('docs-failing:rec-none', null),
198 // Another cache_meta row is not a record.
199 row('schema:rec-none', JSON.stringify(docsFailing)),
200 ])
201
202 const status = await getServiceStatus(db, NOW)
203 const [none, docs, corrupt, clears] = ids.map((id) =>
204 status.providers.find((p) => p.id === id),
205 )
206 expect(docs?.docsFailing).toEqual(docsFailing)
207 expect(docs).not.toHaveProperty('priceClearsRefused')
208 expect(clears?.priceClearsRefused).toEqual(priceClearsRefused)
209 expect(clears).not.toHaveProperty('docsFailing')
210 for (const healthy of [none, corrupt]) {
211 expect(healthy).toMatchObject({ status: 'active' })
212 expect(healthy).not.toHaveProperty('docsFailing')
213 expect(healthy).not.toHaveProperty('priceClearsRefused')
214 }
215 // Neither record moves `status`.
216 expect(docs?.status).toBe('active')
217 expect(clears?.status).toBe('active')
218 })
219
220 const provider = (id: string) => ({
221 id,
222 displayName: id,
223 specSourceUrl: 'https://example.com/spec.json',
224 })
225 const model = (
226 providerId: string,
227 rawId: string,
228 facts: Partial<typeof models.$inferInsert> = {},
229 ) => ({
230 id: `${providerId}-${rawId}`,
231 providerId,
232 rawId,
233 activity: 'chat' as const,
234 firstSeenAt: NOW,
235 lastSeenAt: NOW,
236 ...facts,
237 })
238 const card = {
239 inputs: {},
240 tables: { rate: { base: { input_tokens: 1e-6, output_tokens: 2e-6 } } },
241 price: 1,
242 examples: [],
243 source: {
244 url: 'https://docs.example.com/pricing',
245 hash: 'a'.repeat(64),
246 extractedAt: '2026-01-01T00:00:00.000Z',
247 },
248 }
249
250 it('counts live rows only, and deprecated rows apart', async () => {
251 const db = getDb(env)
252 await db.insert(providers).values([provider('gone'), provider('part')])
253 const retired = { deprecatedAt: NOW - 10, pricing: card }
254 await db
255 .insert(models)
256 .values([
257 model('gone', 'a', retired),
258 model('gone', 'b', { ...retired, reasoning: { mode: 'toggle' } }),
259 model('part', 'old', retired),
260 model('part', 'live', { pricing: card }),
261 model('part', 'image', { activity: 'image' }),
262 ])
263
264 await recordCompleteness(db, NOW)
265 const status = await getServiceStatus(db, NOW)
266 const gone = status.providers.find((p) => p.id === 'gone')
267 const part = status.providers.find((p) => p.id === 'part')
268 // Every row retired: what `/v1/models?provider=gone` lists is nothing.
269 expect(gone?.counts).toMatchObject({
270 models: 0,
271 priced: 0,
272 reasoning: 0,
273 chat: 0,
274 deprecated: 2,
275 })
276 expect(gone?.completeness).toMatchObject({ score: null, chat: 0 })
277 expect(part?.counts).toMatchObject({
278 models: 2,
279 priced: 1,
280 reasoning: 0,
281 chat: 1,
282 deprecated: 1,
283 })
284 expect(part?.completeness.chat).toBe(1)
285 expect((await listModelsCatalog(db, { provider: 'part' })).count).toBe(
286 part?.counts.models,
287 )
288 })
289
290 it('scores completeness as the gap report does', async () => {
291 const db = getDb(env)
292 const ids = ['no-chat', 'all-silent', 'mixed']
293 await db.insert(providers).values(ids.map(provider))
294 await db.insert(models).values([
295 model('no-chat', 'image', { activity: 'image', pricing: card }),
296 model('all-silent', 'bare'),
297 model('mixed', 'full', {
298 contextWindow: 200_000,
299 maxOutput: 64_000,
300 modalities: { input: ['text'], output: ['text'] },
301 pricing: card,
302 capabilities: { reasoning: true, tools: true },
303 reasoning: { mode: 'effort', efforts: ['low', 'high'] },
304 requestMap: {
305 maxTokensField: 'max_tokens',
306 replayReasoningContent: false,
307 },
308 schemaEndpointId: 'v1/chat/completions',
309 }),
310 // Claims reasoning and stores none; a card that does not parse is
311 // served as null, so it is no price here either.
312 model('mixed', 'thin', {
313 contextWindow: 8000,
314 capabilities: { reasoning: true },
315 pricing: { tables: card.tables },
316 }),
317 // A models.dev price does not count.
318 model('mixed', 'borrowed', {
319 pricing: {
320 ...card,
321 source: { ...card.source, url: 'https://models.dev/api.json' },
322 },
323 }),
324 // Retired and of another activity: neither is scored.
325 model('mixed', 'retired', { deprecatedAt: NOW, contextWindow: 1 }),
326 model('mixed', 'image', { activity: 'image' }),
327 ])
328 const ledger: Ledger = new Map([
329 ['all-silent', new Set(FACT_KEYS)],
330 ['mixed', new Set(['cacheRead'] as const)],
331 ])
332
333 // Nothing scored yet (no record, whatever an earlier test stored): no
334 // score anywhere, and the request still answers.
335 await db.delete(cacheMeta)
336 const before = await getServiceStatus(db, NOW)
337 expect(before.completenessComputedAt).toBeNull()
338 expect(before.providers.every((p) => p.completeness.score === null)).toBe(
339 true,
340 )
341
342 expect(await recordCompleteness(db, NOW - 60, ledger)).toBe(true)
343 const status = await getServiceStatus(db, NOW)
344 expect(status.completenessComputedAt).toBe(NOW - 60)
345 const [noChat, allSilent, mixed] = ids.map(
346 (id) => status.providers.find((p) => p.id === id)?.completeness,
347 )
348 // Nothing to score is not a score of zero.
349 expect(noChat).toEqual({
350 score: null,
351 chat: 0,
352 filled: 0,
353 needed: 0,
354 silent: [],
355 })
356 // Chat rows with every fact on the ledger have nothing left to fill.
357 expect(allSilent).toEqual({
358 score: 1,
359 chat: 1,
360 filled: 0,
361 needed: 0,
362 silent: [...FACT_KEYS],
363 })
364 // full: 10 of 10. thin: contextWindow, capabilities of 9. borrowed: 0 of 7.
365 expect(mixed).toEqual({
366 score: 12 / 26,
367 chat: 3,
368 filled: 12,
369 needed: 26,
370 silent: ['cacheRead'],
371 })
372
373 // The same rows as `bun run gap:report` reads them, off the API.
374 const served = await listModelsCatalog(db, { pricing: true })
375 const report = buildReport(served.models as Array<ModelRow>, ledger)
376 for (const id of ['all-silent', 'mixed']) {
377 const scored = report.providers.find((p) => p.provider === id)
378 const listed = status.providers.find((p) => p.id === id)
379 expect(listed?.completeness.score).toBe(scored?.score)
380 expect(listed?.completeness.chat).toBe(scored?.chat)
381 }
382 })
383
384 const KEY = 'status:completeness:v1'
385 const scoreOf = async (db: ReturnType<typeof getDb>, id: string) => {
386 const status = await getServiceStatus(db, NOW)
387 return {
388 computedAt: status.completenessComputedAt,
389 ...status.providers.find((p) => p.id === id)?.completeness,
390 }
391 }
392
393 it('serves the stored score only while it matches the live chat rows', async () => {
394 const db = getDb(env)
395 await db.insert(providers).values(provider('stored'))
396 await db.insert(models).values(model('stored', 'a'))
397 await recordCompleteness(db, NOW)
398 expect(await scoreOf(db, 'stored')).toMatchObject({
399 computedAt: NOW,
400 score: 0,
401 chat: 1,
402 needed: 8,
403 })
404
405 // A chat row the record never scored: no number over a different set.
406 await db.insert(models).values(model('stored', 'b'))
407 expect(await scoreOf(db, 'stored')).toMatchObject({
408 computedAt: NOW,
409 score: null,
410 chat: 0,
411 })
412 // The next poll's record scores both, and says when.
413 await recordCompleteness(db, NOW + 900)
414 expect(await scoreOf(db, 'stored')).toMatchObject({
415 computedAt: NOW + 900,
416 score: 0,
417 chat: 2,
418 })
419 // No live chat row left: null at once, before any rescore.
420 await db.update(models).set({ deprecatedAt: NOW })
421 expect(await scoreOf(db, 'stored')).toMatchObject({ score: null, chat: 0 })
422 })
423
424 it('answers with null scores when the record cannot be used', async () => {
425 const db = getDb(env)
426 await db.insert(providers).values(provider('broken'))
427 await db.insert(models).values(model('broken', 'a'))
428 await recordCompleteness(db, NOW)
429 expect(await scoreOf(db, 'broken')).toMatchObject({ score: 0 })
430 const none = { computedAt: null, score: null, chat: 0 }
431 const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
432
433 // Corrupt JSON, JSON of the wrong shape, an entry of the wrong shape.
434 for (const lastError of ['{not json', '"a string"', 'null']) {
435 await db
436 .update(cacheMeta)
437 .set({ lastError })
438 .where(eq(cacheMeta.key, KEY))
439 expect(await scoreOf(db, 'broken')).toMatchObject(none)
440 }
441 // Entries that are not a whole `Completeness`, though the chat count
442 // matches the live one: never served, and no usable record at all.
443 for (const entry of [
444 7,
445 { chat: 1 },
446 { score: 'high', chat: 1, filled: 0, needed: 8, silent: 'x' },
447 { score: 0, chat: 1, filled: 0, needed: 8, silent: [1] },
448 ]) {
449 await db
450 .update(cacheMeta)
451 .set({ lastError: JSON.stringify({ broken: entry }) })
452 .where(eq(cacheMeta.key, KEY))
453 expect(await scoreOf(db, 'broken')).toEqual({
454 computedAt: null,
455 score: null,
456 chat: 0,
457 filled: 0,
458 needed: 0,
459 silent: [],
460 })
461 }
462 // An array is not a record. One bad entry does not cost the good ones.
463 await db
464 .update(cacheMeta)
465 .set({ lastError: '[{"chat":1}]' })
466 .where(eq(cacheMeta.key, KEY))
467 expect(await scoreOf(db, 'broken')).toMatchObject(none)
468 const good = { score: 0.5, chat: 1, filled: 4, needed: 8, silent: [] }
469 await db
470 .update(cacheMeta)
471 .set({ lastError: JSON.stringify({ broken: good, other: { chat: 1 } }) })
472 .where(eq(cacheMeta.key, KEY))
473 expect(await scoreOf(db, 'broken')).toEqual({ computedAt: NOW, ...good })
474
475 // Deleted.
476 await db.delete(cacheMeta).where(eq(cacheMeta.key, KEY))
477 expect(await scoreOf(db, 'broken')).toMatchObject(none)
478
479 // The read itself throws: the rest of the status is still served.
480 await recordCompleteness(db, NOW)
481 vi.spyOn(db.query.cacheMeta, 'findFirst').mockImplementation(() => {
482 throw new Error('D1 down')
483 })
484 const status = await getServiceStatus(db, NOW)
485 expect(status.completenessComputedAt).toBeNull()
486 expect(status.providers.find((p) => p.id === 'broken')).toMatchObject({
487 counts: { models: 1, chat: 1 },
488 completeness: { score: null },
489 })
490 expect(errors).toHaveBeenCalled()
491 vi.restoreAllMocks()
492 })
493
494 it('keeps the previous record when scoring fails', async () => {
495 const db = getDb(env)
496 await db.insert(providers).values(provider('kept'))
497 await db.insert(models).values(model('kept', 'a'))
498 await recordCompleteness(db, NOW)
499 const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
500 const throwing = {
501 get: () => {
502 throw new Error('scorer broke')
503 },
504 } as unknown as Ledger
505 // Never throws: the cron that calls it goes on to its next step.
506 expect(await recordCompleteness(db, NOW + 900, throwing)).toBe(false)
507 expect(errors).toHaveBeenCalledWith(
508 JSON.stringify({ job: 'completeness', error: 'scorer broke' }),
509 )
510 vi.restoreAllMocks()
511 expect(await scoreOf(db, 'kept')).toMatchObject({
512 computedAt: NOW,
513 score: 0,
514 chat: 1,
515 })
516 })
517})
518
519it('scores only the exact raw model covered by a scoped silence entry', async () => {
520 const db = getDb(env)
521 await db.insert(providers).values({
522 id: 'scoped-status',
523 displayName: 'Scoped status',
524 specSourceUrl: 'https://example.com/docs',
525 })
526 await db.insert(models).values([
527 {
528 id: 'scoped-status-exact',
529 providerId: 'scoped-status',
530 rawId: 'maker/model:variant',
531 activity: 'chat',
532 firstSeenAt: NOW,
533 lastSeenAt: NOW,
534 },
535 {
536 id: 'scoped-status-sibling',
537 providerId: 'scoped-status',
538 rawId: 'maker/model:variant-snapshot',
539 activity: 'chat',
540 firstSeenAt: NOW,
541 lastSeenAt: NOW,
542 },
543 ])
544 const ledger: Ledger = new Map([
545 ['scoped-status/maker/model:variant', new Set(['maxOutput'])],
546 ])
547 await recordCompleteness(db, NOW, ledger)
548 const result = (await getServiceStatus(db, NOW)).providers.find(
549 (entry) => entry.id === 'scoped-status',
550 )?.completeness
551 expect(result?.filled).toBe(0)
552 expect(result?.needed).toBe(15)
553 const served = await listModelsCatalog(db, {
554 provider: 'scoped-status',
555 pricing: true,
556 })
557 const report = buildReport(served.models as Array<ModelRow>, ledger)
558 .providers[0]!
559 expect(report.modelSilent).toEqual({ maxOutput: 1 })
560 expect(result?.score).toBe(report.score)
561})