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