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 = [
159 'rec-none',
160 'rec-docs',
161 'rec-corrupt',
162 'rec-clears',
163 'rec-storm',
164 ]
165 await db.insert(providers).values(
166 ids.map((id) => ({
167 id,
168 displayName: id,
169 specSourceUrl: 'https://example.com/spec.json',
170 })),
171 )
172 const docsFailing = {
173 since: NOW - 1800,
174 polls: 3,
175 lastAt: NOW,
176 failed: 2,
177 skipped: 1,
178 sources: ['https://example.com/docs/a', 'https://example.com/docs/b'],
179 error: 'page changed shape',
180 }
181 const priceClearsRefused = {
182 since: NOW - 900,
183 polls: 2,
184 lastAt: NOW,
185 refused: 6,
186 priced: 8,
187 }
188 const updateStorm = {
189 since: NOW - 60,
190 polls: 1,
191 lastAt: NOW,
192 updated: 21,
193 live: 30,
194 }
195 const row = (key: string, lastError: string | null) => ({
196 key,
197 fetchedAt: NOW,
198 staleTime: 0,
199 lastError,
200 })
201 await db.insert(cacheMeta).values([
202 row('docs-failing:rec-docs', JSON.stringify(docsFailing)),
203 row(
204 'price-clears-refused:rec-clears',
205 JSON.stringify(priceClearsRefused),
206 ),
207 row('update-storm:rec-storm', JSON.stringify(updateStorm)),
208 // Not JSON, JSON of the wrong shape, and no body at all.
209 row('docs-failing:rec-corrupt', '{not json'),
210 row('price-clears-refused:rec-corrupt', '"a string"'),
211 row('docs-failing:rec-none', null),
212 // Another cache_meta row is not a record.
213 row('schema:rec-none', JSON.stringify(docsFailing)),
214 ])
215
216 const status = await getServiceStatus(db, NOW)
217 const [none, docs, corrupt, clears, storm] = ids.map((id) =>
218 status.providers.find((p) => p.id === id),
219 )
220 expect(docs?.docsFailing).toEqual(docsFailing)
221 expect(docs).not.toHaveProperty('priceClearsRefused')
222 expect(docs).not.toHaveProperty('updateStorm')
223 expect(clears?.priceClearsRefused).toEqual(priceClearsRefused)
224 expect(clears).not.toHaveProperty('docsFailing')
225 expect(storm?.updateStorm).toEqual(updateStorm)
226 expect(storm).not.toHaveProperty('docsFailing')
227 for (const healthy of [none, corrupt]) {
228 expect(healthy).toMatchObject({ status: 'active' })
229 expect(healthy).not.toHaveProperty('docsFailing')
230 expect(healthy).not.toHaveProperty('priceClearsRefused')
231 expect(healthy).not.toHaveProperty('updateStorm')
232 }
233 // Neither record moves `status`.
234 expect(docs?.status).toBe('active')
235 expect(clears?.status).toBe('active')
236 })
237
238 const provider = (id: string) => ({
239 id,
240 displayName: id,
241 specSourceUrl: 'https://example.com/spec.json',
242 })
243 const model = (
244 providerId: string,
245 rawId: string,
246 facts: Partial<typeof models.$inferInsert> = {},
247 ) => ({
248 id: `${providerId}-${rawId}`,
249 providerId,
250 // Unique across providers, so no row needs an origin link by accident.
251 rawId: `${providerId}:${rawId}`,
252 activity: 'chat' as const,
253 firstSeenAt: NOW,
254 lastSeenAt: NOW,
255 ...facts,
256 })
257 const card = {
258 inputs: {},
259 tables: { rate: { base: { input_tokens: 1e-6, output_tokens: 2e-6 } } },
260 price: 1,
261 examples: [],
262 source: {
263 url: 'https://docs.example.com/pricing',
264 hash: 'a'.repeat(64),
265 extractedAt: '2026-01-01T00:00:00.000Z',
266 },
267 }
268
269 it('counts live rows only, and deprecated rows apart', async () => {
270 const db = getDb(env)
271 await db.insert(providers).values([provider('gone'), provider('part')])
272 const retired = { deprecatedAt: NOW - 10, pricing: card }
273 await db
274 .insert(models)
275 .values([
276 model('gone', 'a', retired),
277 model('gone', 'b', { ...retired, reasoning: { mode: 'toggle' } }),
278 model('part', 'old', retired),
279 model('part', 'live', { pricing: card }),
280 model('part', 'image', { activity: 'image' }),
281 ])
282
283 await recordCompleteness(db, NOW)
284 const status = await getServiceStatus(db, NOW)
285 const gone = status.providers.find((p) => p.id === 'gone')
286 const part = status.providers.find((p) => p.id === 'part')
287 // Every row retired: what `/v1/models?provider=gone` lists is nothing.
288 expect(gone?.counts).toMatchObject({
289 models: 0,
290 priced: 0,
291 reasoning: 0,
292 chat: 0,
293 deprecated: 2,
294 })
295 expect(gone?.completeness).toMatchObject({ score: null, rows: 0 })
296 expect(part?.counts).toMatchObject({
297 models: 2,
298 priced: 1,
299 reasoning: 0,
300 chat: 1,
301 deprecated: 1,
302 })
303 expect(part?.completeness.rows).toBe(2)
304 expect((await listModelsCatalog(db, { provider: 'part' })).count).toBe(
305 part?.counts.models,
306 )
307 })
308
309 it('scores completeness as the gap report does', async () => {
310 const db = getDb(env)
311 const ids = ['no-chat', 'all-silent', 'mixed']
312 await db.insert(providers).values(ids.map(provider))
313 await db.insert(models).values([
314 model('no-chat', 'image', { activity: 'image', pricing: card }),
315 model('all-silent', 'bare'),
316 model('mixed', 'full', {
317 contextWindow: 200_000,
318 maxOutput: 64_000,
319 modalities: { input: ['text'], output: ['text'] },
320 pricing: card,
321 capabilities: { reasoning: true, tools: true },
322 reasoning: { mode: 'effort', efforts: ['low', 'high'] },
323 requestMap: {
324 maxTokensField: 'max_tokens',
325 replayReasoningContent: false,
326 },
327 schemaEndpointId: 'v1/chat/completions',
328 }),
329 // Claims reasoning and stores none; a card that does not parse is
330 // served as null, so it is no price here either.
331 model('mixed', 'thin', {
332 contextWindow: 8000,
333 capabilities: { reasoning: true },
334 pricing: { tables: card.tables },
335 }),
336 // A models.dev price does not count.
337 model('mixed', 'borrowed', {
338 pricing: {
339 ...card,
340 source: { ...card.source, url: 'https://models.dev/api.json' },
341 },
342 }),
343 // Retired and of another activity: neither is scored.
344 model('mixed', 'retired', { deprecatedAt: NOW, contextWindow: 1 }),
345 model('mixed', 'image', { activity: 'image' }),
346 ])
347 const ledger: Ledger = new Map([
348 ['all-silent', new Set(FACT_KEYS)],
349 ['mixed', new Set(['cacheRead'] as const)],
350 ])
351
352 // Nothing scored yet (no record, whatever an earlier test stored): no
353 // score anywhere, and the request still answers.
354 await db.delete(cacheMeta)
355 const before = await getServiceStatus(db, NOW)
356 expect(before.completenessComputedAt).toBeNull()
357 expect(before.providers.every((p) => p.completeness.score === null)).toBe(
358 true,
359 )
360
361 expect(await recordCompleteness(db, NOW - 60, ledger)).toBe(true)
362 const status = await getServiceStatus(db, NOW)
363 expect(status.completenessComputedAt).toBe(NOW - 60)
364 const [noChat, allSilent, mixed] = ids.map(
365 (id) => status.providers.find((p) => p.id === id)?.completeness,
366 )
367 // An image row is scored on its own facts: priced only.
368 expect(noChat).toEqual({
369 score: 1 / 4,
370 rows: 1,
371 filled: 1,
372 needed: 4,
373 silent: [],
374 activities: { image: { rows: 1, score: 1 / 4, filled: 1, needed: 4 } },
375 originLink: { have: 0, need: 0 },
376 })
377 // Chat rows with every fact on the ledger have nothing left to fill.
378 expect(allSilent).toEqual({
379 score: 1,
380 rows: 1,
381 filled: 0,
382 needed: 0,
383 silent: [...FACT_KEYS],
384 activities: { chat: { rows: 1, score: 1, filled: 0, needed: 0 } },
385 originLink: { have: 0, need: 0 },
386 })
387 // full: 10 of 10. thin: contextWindow and capabilities of 7 (no
388 // OpenAI-compat route, so requestMap and replay are not scored).
389 // borrowed: 0 of 6. image: 0 of 4.
390 expect(mixed).toEqual({
391 score: 12 / 27,
392 rows: 4,
393 filled: 12,
394 needed: 27,
395 silent: ['cacheRead'],
396 activities: {
397 chat: { rows: 3, score: 12 / 23, filled: 12, needed: 23 },
398 image: { rows: 1, score: 0, filled: 0, needed: 4 },
399 },
400 originLink: { have: 0, need: 0 },
401 })
402
403 // The same rows as `pnpm run gap:report` reads them, off the API.
404 const served = await listModelsCatalog(db, { pricing: true })
405 const report = buildReport(served.models as Array<ModelRow>, ledger)
406 for (const id of ['all-silent', 'mixed']) {
407 const scored = report.providers.find((p) => p.provider === id)
408 const listed = status.providers.find((p) => p.id === id)
409 expect(listed?.completeness.score).toBe(scored?.score)
410 expect(listed?.completeness.rows).toBe(scored?.rows)
411 }
412 })
413
414 const KEY = 'status:completeness:v3'
415 const scoreOf = async (db: ReturnType<typeof getDb>, id: string) => {
416 const status = await getServiceStatus(db, NOW)
417 return {
418 computedAt: status.completenessComputedAt,
419 ...status.providers.find((p) => p.id === id)?.completeness,
420 }
421 }
422
423 it('serves the stored score only while it matches the live rows', async () => {
424 const db = getDb(env)
425 await db.insert(providers).values(provider('stored'))
426 await db.insert(models).values(model('stored', 'a'))
427 await recordCompleteness(db, NOW)
428 expect(await scoreOf(db, 'stored')).toMatchObject({
429 computedAt: NOW,
430 score: 0,
431 rows: 1,
432 needed: 7,
433 })
434
435 // A row the record never scored: no number over a different set.
436 await db.insert(models).values(model('stored', 'b'))
437 expect(await scoreOf(db, 'stored')).toMatchObject({
438 computedAt: NOW,
439 score: null,
440 rows: 0,
441 })
442 // The next poll's record scores both, and says when.
443 await recordCompleteness(db, NOW + 900)
444 expect(await scoreOf(db, 'stored')).toMatchObject({
445 computedAt: NOW + 900,
446 score: 0,
447 rows: 2,
448 })
449 // No live row left: null at once, before any rescore.
450 await db.update(models).set({ deprecatedAt: NOW })
451 expect(await scoreOf(db, 'stored')).toMatchObject({ score: null, rows: 0 })
452 })
453
454 it('answers with null scores when the record cannot be used', async () => {
455 const db = getDb(env)
456 await db.insert(providers).values(provider('broken'))
457 await db.insert(models).values(model('broken', 'a'))
458 await recordCompleteness(db, NOW)
459 expect(await scoreOf(db, 'broken')).toMatchObject({ score: 0 })
460 const none = { computedAt: null, score: null, rows: 0 }
461 const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
462
463 // Corrupt JSON, JSON of the wrong shape, an entry of the wrong shape.
464 for (const lastError of ['{not json', '"a string"', 'null']) {
465 await db
466 .update(cacheMeta)
467 .set({ lastError })
468 .where(eq(cacheMeta.key, KEY))
469 expect(await scoreOf(db, 'broken')).toMatchObject(none)
470 }
471 // Entries that are not a whole `Completeness`, though the row count
472 // matches the live one: never served, and no usable record at all.
473 const whole = {
474 score: 0,
475 rows: 1,
476 filled: 0,
477 needed: 8,
478 silent: [],
479 activities: {},
480 originLink: { have: 0, need: 0 },
481 }
482 for (const entry of [
483 7,
484 { rows: 1 },
485 { ...whole, score: 'high', silent: 'x' },
486 { ...whole, silent: [1] },
487 { ...whole, activities: { chat: { rows: 1 } } },
488 { ...whole, originLink: null },
489 // The chat-only shape stored before per-activity scores.
490 { score: 0, chat: 1, filled: 0, needed: 8, silent: [] },
491 ]) {
492 await db
493 .update(cacheMeta)
494 .set({ lastError: JSON.stringify({ broken: entry }) })
495 .where(eq(cacheMeta.key, KEY))
496 expect(await scoreOf(db, 'broken')).toEqual({
497 computedAt: null,
498 score: null,
499 rows: 0,
500 filled: 0,
501 needed: 0,
502 silent: [],
503 activities: {},
504 originLink: { have: 0, need: 0 },
505 })
506 }
507 // An array is not a record. One bad entry does not cost the good ones.
508 await db
509 .update(cacheMeta)
510 .set({ lastError: '[{"rows":1}]' })
511 .where(eq(cacheMeta.key, KEY))
512 expect(await scoreOf(db, 'broken')).toMatchObject(none)
513 const good = {
514 ...whole,
515 score: 0.5,
516 filled: 4,
517 activities: { chat: { rows: 1, score: 0.5, filled: 4, needed: 8 } },
518 }
519 await db
520 .update(cacheMeta)
521 .set({ lastError: JSON.stringify({ broken: good, other: { rows: 1 } }) })
522 .where(eq(cacheMeta.key, KEY))
523 expect(await scoreOf(db, 'broken')).toEqual({ computedAt: NOW, ...good })
524
525 // Deleted.
526 await db.delete(cacheMeta).where(eq(cacheMeta.key, KEY))
527 expect(await scoreOf(db, 'broken')).toMatchObject(none)
528
529 // The read itself throws: the rest of the status is still served.
530 await recordCompleteness(db, NOW)
531 vi.spyOn(db.query.cacheMeta, 'findFirst').mockImplementation(() => {
532 throw new Error('D1 down')
533 })
534 const status = await getServiceStatus(db, NOW)
535 expect(status.completenessComputedAt).toBeNull()
536 expect(status.providers.find((p) => p.id === 'broken')).toMatchObject({
537 counts: { models: 1, chat: 1 },
538 completeness: { score: null },
539 })
540 expect(errors).toHaveBeenCalled()
541 vi.restoreAllMocks()
542 })
543
544 it('keeps the previous record when scoring fails', async () => {
545 const db = getDb(env)
546 await db.insert(providers).values(provider('kept'))
547 await db.insert(models).values(model('kept', 'a'))
548 await recordCompleteness(db, NOW)
549 const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
550 const throwing = {
551 get: () => {
552 throw new Error('scorer broke')
553 },
554 } as unknown as Ledger
555 // Never throws: the cron that calls it goes on to its next step.
556 expect(await recordCompleteness(db, NOW + 900, throwing)).toBe(false)
557 expect(errors).toHaveBeenCalledWith(
558 JSON.stringify({ job: 'completeness', error: 'scorer broke' }),
559 )
560 vi.restoreAllMocks()
561 expect(await scoreOf(db, 'kept')).toMatchObject({
562 computedAt: NOW,
563 score: 0,
564 rows: 1,
565 })
566 })
567})
568
569it('scores only the exact raw model covered by a scoped silence entry', async () => {
570 const db = getDb(env)
571 await db.insert(providers).values({
572 id: 'scoped-status',
573 displayName: 'Scoped status',
574 specSourceUrl: 'https://example.com/docs',
575 })
576 await db.insert(models).values([
577 {
578 id: 'scoped-status-exact',
579 providerId: 'scoped-status',
580 rawId: 'maker/model:variant',
581 activity: 'chat',
582 firstSeenAt: NOW,
583 lastSeenAt: NOW,
584 },
585 {
586 id: 'scoped-status-sibling',
587 providerId: 'scoped-status',
588 rawId: 'maker/model:variant-snapshot',
589 activity: 'chat',
590 firstSeenAt: NOW,
591 lastSeenAt: NOW,
592 },
593 ])
594 const ledger: Ledger = new Map([
595 ['scoped-status/maker/model:variant', new Set(['maxOutput'])],
596 ])
597 await recordCompleteness(db, NOW, ledger)
598 const result = (await getServiceStatus(db, NOW)).providers.find(
599 (entry) => entry.id === 'scoped-status',
600 )?.completeness
601 expect(result?.filled).toBe(0)
602 expect(result?.needed).toBe(13)
603 const served = await listModelsCatalog(db, {
604 provider: 'scoped-status',
605 pricing: true,
606 })
607 const report = buildReport(served.models as Array<ModelRow>, ledger)
608 .providers[0]!
609 expect(report.activities.chat?.modelSilent).toEqual({ maxOutput: 1 })
610 expect(result?.score).toBe(report.score)
611})