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