Open History to see the last commit
1import { count, eq, isNull, sql } from 'drizzle-orm'
2
3import type { Db } from '#/db/index.ts'
4import {
5 cacheMeta,
6 endpoints,
7 models,
8 providers,
9 schemaVersions,
10} from '#/db/schema.ts'
11import { FACT_KEYS, buildReport, scoredFacts } from '#/lib/completeness.ts'
12import type { FactKey, Ledger, ModelRow } from '#/lib/completeness.ts'
13import { errorMessage } from '#/server/errors.ts'
14import { readIngestRecords } from '#/server/ingest/docs-failing.ts'
15import type {
16 DocsFailing,
17 PriceClearsRefused,
18 UpdateStorm,
19} from '#/server/ingest/docs-failing.ts'
20import { providerRegistry } from '#/server/providers/index.ts'
21import { staleProbeCount } from '#/server/providers/probes/index.ts'
22import { sourceSilentLedger } from '#/server/source-silent.ts'
23
24/** One activity's share of `Completeness`; `score` null = no fact set. */
25export interface ActivityCompleteness {
26 rows: number
27 score: number | null
28 filled: number
29 needed: number
30}
31
32/**
33 * The gap-report score (`#/lib/completeness.ts`) over the provider's live
34 * models: `filled / needed`, the same number `pnpm run gap:report` prints.
35 */
36export interface Completeness {
37 /**
38 * 0 to 1 over every scored activity and `originLink`. Null when nothing
39 * is scored (every row's activity has no fact set and no row needs a
40 * link), and when there is no current score: none computed yet, or the
41 * provider's live rows changed since the last poll scored them.
42 */
43 score: number | null
44 /** Live models scored. */
45 rows: number
46 /** Facts carried, summed over those models; `silent` facts left out. */
47 filled: number
48 /** Facts that apply, summed over those models; `silent` facts left out. */
49 needed: number
50 /** Facts the provider does not publish (`docs/source-silent`). */
51 silent: Array<FactKey>
52 /** By activity, plus `unclassified` for rows with a null activity. */
53 activities: Record<string, ActivityCompleteness>
54 /** Rows that need an upstream link (`need`) and rows that have one. */
55 originLink: { have: number; need: number }
56}
57
58export interface ProviderStatus {
59 id: string
60 displayName: string
61 /** `pending` = registered in code but not yet synced into the DB. */
62 status: 'active' | 'degraded' | 'disabled' | 'pending'
63 lastPolledAt: number | null
64 lastSyncedAt: number | null
65 /**
66 * Present while the provider's docs pages fail to load: polls go on and
67 * rows keep their stored docs-derived facts. Does not change `status`.
68 */
69 docsFailing?: DocsFailing
70 /**
71 * Present while polls refuse a mass price clear: the stored prices stay.
72 * Does not change `status`.
73 */
74 priceClearsRefused?: PriceClearsRefused
75 /**
76 * Probe records older than 90 days. The facts stay served. Present only
77 * when the count is above zero. Does not change `status`.
78 */
79 staleProbes?: number
80 /**
81 * Present while the latest poll wrote `model.updated` for more than half
82 * of the live rows, and at least 20. The updates are written; this only
83 * marks a catalog-wide rewrite. Does not change `status`.
84 */
85 updateStorm?: UpdateStorm
86 completeness: Completeness
87 /** Model tallies count live rows: what `GET /v1/models` lists by default. */
88 counts: {
89 models: number
90 /** Models with a stored rate card. */
91 priced: number
92 /** Models with stored reasoning metadata. */
93 reasoning: number
94 /** Models whose activity is `chat`. */
95 chat: number
96 /** Models no longer listed upstream; in none of the tallies above. */
97 deprecated: number
98 endpoints: number
99 schemas: number
100 }
101}
102
103export interface ServiceStatus {
104 service: 'modelschemas'
105 time: number
106 /**
107 * Epoch seconds the `completeness` scores were computed (the last models
108 * poll), or null when there is no record and every score is null.
109 */
110 completenessComputedAt: number | null
111 providers: Array<ProviderStatus>
112}
113
114/** A tally of live rows, optionally only those matching `where`. */
115const live = (where = sql`1`) =>
116 sql<number>`count(case when ${models.deprecatedAt} is null and ${where} then 1 end)`
117
118/**
119 * The `cache_meta` row holding every provider's score: `fetched_at` is when
120 * it was computed, `last_error` the JSON. Scoring reads every live row
121 * as `GET /v1/models?pricing=1` serves it, so the 15-minute poll
122 * computes it once (`recordCompleteness`) and requests only read the row.
123 * Bump the version when the scorer or the `Completeness` shape changes: the
124 * old row then reads as no record, and scores are null until the next poll.
125 */
126const COMPLETENESS_KEY = 'status:completeness:v3'
127
128/**
129 * Completeness of every provider with live rows: the rows `GET
130 * /v1/models?pricing=1` serves, so this and the CLI score the same thing.
131 * Origin links match across the whole catalog, so every row is read.
132 */
133async function scoreCompleteness(
134 db: Db,
135 ledger: Ledger,
136): Promise<Record<string, Completeness>> {
137 // Imported here: the catalog imports this module for its status rows.
138 const { listModelsCatalog } = await import('#/server/catalog.ts')
139 const { models: rows } = await listModelsCatalog(db, { pricing: true })
140 // JSON columns: the scorer checks what it reads of each.
141 const report = buildReport(rows as Array<ModelRow>, ledger)
142 return Object.fromEntries(
143 report.providers.map((provider) => {
144 const { have, need } = scoredFacts(provider)
145 const activities: Record<string, ActivityCompleteness> = {}
146 for (const [name, a] of Object.entries(provider.activities)) {
147 if (!a) continue
148 const { rows: n, score, filled, needed } = a
149 activities[name] = { rows: n, score, filled, needed }
150 }
151 return [
152 provider.provider,
153 {
154 score: provider.score,
155 rows: provider.rows,
156 filled: have,
157 needed: need,
158 silent: provider.silent,
159 activities,
160 originLink: {
161 have: provider.originLink.have,
162 need: provider.originLink.need,
163 },
164 },
165 ]
166 }),
167 )
168}
169
170const logCompleteness = (error: unknown) => {
171 console.error(
172 JSON.stringify({ job: 'completeness', error: errorMessage(error) }),
173 )
174}
175
176const isCount = (value: unknown) => typeof value === 'number'
177const isScore = (value: unknown) => value === null || isCount(value)
178
179/** A stored entry is served only if it is wholly a `Completeness`. */
180function isCompleteness(value: unknown): value is Completeness {
181 if (typeof value !== 'object' || value === null) return false
182 const entry = value as Partial<Record<keyof Completeness, unknown>>
183 const link = entry.originLink as Record<string, unknown> | null | undefined
184 return (
185 isScore(entry.score) &&
186 isCount(entry.rows) &&
187 isCount(entry.filled) &&
188 isCount(entry.needed) &&
189 Array.isArray(entry.silent) &&
190 entry.silent.every((fact) => typeof fact === 'string') &&
191 typeof entry.activities === 'object' &&
192 entry.activities !== null &&
193 Object.values(entry.activities).every((a: unknown) => {
194 const act = a as Record<string, unknown> | null
195 return (
196 typeof act === 'object' &&
197 act !== null &&
198 isCount(act.rows) &&
199 isScore(act.score) &&
200 isCount(act.filled) &&
201 isCount(act.needed)
202 )
203 }) &&
204 typeof link === 'object' &&
205 link !== null &&
206 isCount(link.have) &&
207 isCount(link.need)
208 )
209}
210
211/**
212 * Score every provider and store the result, after the models poll. Never
213 * throws: a failure is logged and the previous record stays. Returns
214 * whether a new record was written.
215 */
216export async function recordCompleteness(
217 db: Db,
218 now = Math.floor(Date.now() / 1000),
219 ledger: Ledger = sourceSilentLedger,
220): Promise<boolean> {
221 try {
222 const lastError = JSON.stringify(await scoreCompleteness(db, ledger))
223 await db
224 .insert(cacheMeta)
225 .values({
226 key: COMPLETENESS_KEY,
227 fetchedAt: now,
228 staleTime: 0,
229 lastError,
230 })
231 .onConflictDoUpdate({
232 target: cacheMeta.key,
233 set: { fetchedAt: now, lastError },
234 })
235 return true
236 } catch (error) {
237 logCompleteness(error)
238 return false
239 }
240}
241
242/**
243 * The stored scores. A missing, unreadable or misshapen record is no
244 * record: every score is then null and the request goes on.
245 */
246async function readCompleteness(db: Db): Promise<{
247 computedAt: number | null
248 scores: Partial<Record<string, Completeness>>
249}> {
250 try {
251 const row = await db.query.cacheMeta.findFirst({
252 where: eq(cacheMeta.key, COMPLETENESS_KEY),
253 })
254 if (row?.lastError) {
255 const stored: unknown = JSON.parse(row.lastError)
256 if (typeof stored === 'object' && stored !== null) {
257 const entries = Object.entries(stored)
258 const valid = entries.filter(([, entry]) => isCompleteness(entry))
259 // Entries and none of them usable is no record either.
260 if (
261 !Array.isArray(stored) &&
262 (valid.length > 0 || entries.length === 0)
263 ) {
264 return {
265 computedAt: row.fetchedAt,
266 scores: Object.fromEntries(valid),
267 }
268 }
269 }
270 }
271 } catch (error) {
272 logCompleteness(error)
273 }
274 return { computedAt: null, scores: {} }
275}
276
277/**
278 * Public per-provider sync status + row counts (GET /v1/status).
279 *
280 * The provider REGISTRY (code) is the source of truth for which providers
281 * exist; the DB carries runtime state. Registered providers whose first
282 * sync hasn't landed yet still appear — as `pending` with zero counts — so
283 * the listing is always the full roster, for humans and agents alike.
284 */
285function staleProbeField(
286 providerId: string,
287 nowSeconds: number,
288): { staleProbes?: number } {
289 const stale = staleProbeCount(providerId, new Date(nowSeconds * 1000))
290 return stale > 0 ? { staleProbes: stale } : {}
291}
292
293export async function getServiceStatus(
294 db: Db,
295 now = Math.floor(Date.now() / 1000),
296): Promise<ServiceStatus> {
297 const [
298 providerRows,
299 records,
300 { computedAt, scores },
301 modelCounts,
302 endpointCounts,
303 schemaCounts,
304 ] = await Promise.all([
305 db.select().from(providers),
306 // One statement for every provider's docs-failing, refused-clears, and update-storm row.
307 readIngestRecords(db),
308 readCompleteness(db),
309 // One pass yields every model tally. Deprecated rows are counted apart:
310 // the catalog hides them, and a provider's count must match its list.
311 db
312 .select({
313 providerId: models.providerId,
314 models: live(),
315 priced: live(sql`${models.pricing} is not null`),
316 reasoning: live(sql`${models.reasoning} is not null`),
317 chat: live(sql`${models.activity} = 'chat'`),
318 deprecated: count(models.deprecatedAt),
319 })
320 .from(models)
321 .groupBy(models.providerId),
322 db
323 .select({ providerId: endpoints.providerId, n: count() })
324 .from(endpoints)
325 .groupBy(endpoints.providerId),
326 // Current (non-superseded) schema versions per provider.
327 db
328 .select({ providerId: endpoints.providerId, n: count() })
329 .from(schemaVersions)
330 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
331 .where(isNull(schemaVersions.supersededAt))
332 .groupBy(endpoints.providerId),
333 ])
334
335 const toMap = (rows: Array<{ providerId: string; n: number }>) =>
336 new Map(rows.map((r) => [r.providerId, r.n]))
337 const modelsBy = new Map(modelCounts.map((r) => [r.providerId, r]))
338 const endpointsBy = toMap(endpointCounts)
339 const schemasBy = toMap(schemaCounts)
340 // The record is as old as the last poll. It is served only for a provider
341 // whose live row count still equals the count it scored, so a score never
342 // sits over a different row set; that also makes no rows a null, not a
343 // zero.
344 const completeness = (providerId: string): Completeness => {
345 const scored = scores[providerId]
346 const rows = modelsBy.get(providerId)?.models ?? 0
347 if (rows > 0 && scored?.rows === rows) return scored
348 return {
349 score: null,
350 rows: 0,
351 filled: 0,
352 needed: 0,
353 silent: FACT_KEYS.filter((key) =>
354 sourceSilentLedger.get(providerId)?.has(key),
355 ),
356 activities: {},
357 originLink: { have: 0, need: 0 },
358 }
359 }
360
361 const byId = new Map<string, ProviderStatus>()
362 for (const p of providerRows) {
363 byId.set(p.id, {
364 id: p.id,
365 displayName: p.displayName,
366 status: p.status,
367 lastPolledAt: p.lastPolledAt,
368 lastSyncedAt: p.lastSyncedAt,
369 ...records.get(p.id),
370 ...staleProbeField(p.id, now),
371 completeness: completeness(p.id),
372 counts: {
373 models: modelsBy.get(p.id)?.models ?? 0,
374 priced: modelsBy.get(p.id)?.priced ?? 0,
375 reasoning: modelsBy.get(p.id)?.reasoning ?? 0,
376 chat: modelsBy.get(p.id)?.chat ?? 0,
377 deprecated: modelsBy.get(p.id)?.deprecated ?? 0,
378 endpoints: endpointsBy.get(p.id) ?? 0,
379 schemas: schemasBy.get(p.id) ?? 0,
380 },
381 })
382 }
383 // Registered but not yet in the DB (fresh adapter, seed not run).
384 for (const config of providerRegistry) {
385 if (byId.has(config.id)) continue
386 byId.set(config.id, {
387 id: config.id,
388 displayName: config.displayName,
389 status: 'pending',
390 lastPolledAt: null,
391 lastSyncedAt: null,
392 ...staleProbeField(config.id, now),
393 completeness: completeness(config.id),
394 counts: {
395 models: 0,
396 priced: 0,
397 reasoning: 0,
398 chat: 0,
399 deprecated: 0,
400 endpoints: 0,
401 schemas: 0,
402 },
403 })
404 }
405
406 return {
407 service: 'modelschemas',
408 time: now,
409 completenessComputedAt: computedAt,
410 providers: [...byId.values()].sort((a, b) => a.id.localeCompare(b.id)),
411 }
412}