Open History to see the last commit
1import type { Activity } from '#/db/schema.ts'
2/**
3 * Model poller (PLAN.md task 2.4) — the fast 15-minute tier: per provider,
4 * list currently served models, diff against D1, write
5 * model.added/removed/updated changes, bump lastSeenAt. Listings compile to
6 * RateCards (or null) before insert/update.
7 */
8import { and, eq, inArray, isNull, sql } from 'drizzle-orm'
9
10import {
11 changes,
12 endpoints,
13 models,
14 providers,
15 schemaVersions,
16} from '#/db/schema.ts'
17import { isCapabilityMap } from '#/lib/capabilities.ts'
18import type { CapabilityMap } from '#/lib/capabilities.ts'
19import { errorMessage } from '#/server/errors.ts'
20import { stableStringify } from '#/server/kv.ts'
21import { resolveSpecGrain } from '#/server/providers/connect.ts'
22import {
23 emptySources,
24 mergeListingAndSchema,
25 modelBranchSchemas,
26 requestSchemaPropertyNames,
27 schemaRung,
28 walkRequestSchema,
29} from '#/server/providers/fact-sources.ts'
30import type { SchemaWalk } from '#/server/providers/fact-sources.ts'
31import { keepValidReasoning } from '#/server/providers/reasoning-config.ts'
32import { KNOWLEDGE_CUTOFF } from '#/server/providers/types.ts'
33import { chatRequestMap } from '#/server/providers/request-map.ts'
34import {
35 parseStoredRateCard,
36 reconcilePricingSource,
37 storeListedPricing,
38} from '#/server/rate-card.ts'
39import type { RateCardRefuse } from '#/server/rate-card.ts'
40import type {
41 DocsFailures,
42 ModelFact,
43 ModelFactSources,
44 ModelInfo,
45 ProviderConfig,
46} from '#/server/providers/types.ts'
47import { providerRegistry } from '#/server/providers/index.ts'
48import { storedAliases } from '#/server/providers/provider-aliases.ts'
49import { resolveSchemaEndpointId } from '#/server/schema-binding.ts'
50import { preserveAsyncApiFlag } from './asyncapi.ts'
51import { recordDocsFailing, recordPriceClearsRefused } from './docs-failing.ts'
52import type { DocsFailing } from './docs-failing.ts'
53import {
54 captureIngestEvents,
55 runIngestScope,
56 ingestFailedEvent,
57 noteIngest,
58 observePricingWrite,
59} from './ingest-signals.ts'
60import {
61 deprecateFrozenModelsDevCatalog,
62 dropModelsDevSchemaVersions,
63 isModelsDevRateCard,
64 markModelsDevCatalogSettled,
65 nullModelsDevRateCards,
66 storedCardIsPrior,
67} from './retire-models-dev.ts'
68import { ensureProviderRow } from './sync.ts'
69import type { SyncDeps } from './sync.ts'
70import {
71 persistUpstreamIdentities,
72 reconcileSameAs,
73 sameEvidence,
74} from './model-identity.ts'
75import type { UpstreamIdentityWrite } from './model-identity.ts'
76
77export interface PollOutcome {
78 providerId: string
79 modelsSeen: number
80 added: number
81 removed: number
82 updated: number
83 /** Rows whose firstSeenAt moved back to the upstream release date. */
84 backdated: number
85 /**
86 * Per-row pricing misses and write-gate refusals. A thrown poll is 1
87 * here as well as `error` — not only the whole-provider failure.
88 */
89 failures: number
90 /** Docs sources that failed this poll; their rows kept stored facts. */
91 docsFailures?: DocsFailures
92 /** The provider's `docs-failing` record after this poll, while it fails. */
93 docsFailing?: DocsFailing
94 /** Price clears not applied: too many for one poll (`refusesPriceClears`). */
95 priceClearsRefused?: number
96 skipped?: string
97 error?: string
98}
99
100/** Deterministic model row id: `${providerId}-${slugified rawId}`. */
101export function modelDbId(providerId: string, rawId: string): string {
102 const slug = rawId
103 .toLowerCase()
104 .replace(/[^a-z0-9]+/g, '-')
105 .replace(/^-+|-+$/g, '')
106 return `${providerId}-${slug}`
107}
108
109/**
110 * Reject obviously bogus upstream release timestamps (0, negative, or
111 * pre-2015 — years before any monitored provider existed).
112 */
113const RELEASED_AT_FLOOR = 1_420_070_400 // 2015-01-01T00:00:00Z
114
115/**
116 * Upstream release time usable for firstSeenAt: sane, and never later than
117 * the reference time (we backdate, never forward-date).
118 */
119function usableReleasedAt(info: ModelInfo, before: number): number | null {
120 const releasedAt = info.releasedAt ?? null
121 if (releasedAt === null) return null
122 if (releasedAt < RELEASED_AT_FLOOR || releasedAt >= before) return null
123 return releasedAt
124}
125
126/** Stable reasoning provenance. A silent docs read must be stored, not dropped. */
127function reasoningSourcePath(sources: unknown): string | null {
128 if (typeof sources !== 'object' || sources === null) return null
129 const path = (sources as ModelFactSources).reasoning?.path
130 return typeof path === 'string' ? path : null
131}
132
133/**
134 * A map the listing read from the model's own request schema wins; else the
135 * provider-wide table.
136 */
137function requestMapFor(providerId: string, info: ModelInfo) {
138 return info.requestMap !== undefined
139 ? info.requestMap
140 : chatRequestMap(providerId, info.rawId, info.activity ?? null)
141}
142
143/** The fields whose changes constitute a `model.updated` event. */
144function comparable(
145 providerId: string,
146 info: ModelInfo,
147): Record<string, unknown> {
148 return {
149 displayName: info.displayName ?? null,
150 activity: info.activity ?? null,
151 contextWindow: info.contextWindow ?? null,
152 maxOutput: info.maxOutput ?? null,
153 modalities: info.modalities ?? null,
154 pricing: info.pricing ?? null,
155 capabilities: info.capabilities ?? null,
156 reasoning: info.reasoning ?? null,
157 reasoningSource: reasoningSourcePath(info.factSources),
158 serverTools: info.serverTools ?? null,
159 requestMap: requestMapFor(providerId, info),
160 aliases: storedAliases(info.aliases),
161 schemaEndpointId: info.schemaEndpointId ?? null,
162 deprecated: info.deprecated ?? false,
163 releasedAt: info.releasedAt ?? null,
164 knowledgeCutoff: info.knowledgeCutoff ?? null,
165 openWeights: info.openWeights ?? null,
166 weightsUrl: info.weightsUrl ?? null,
167 providerMetadata: info.providerMetadata ?? null,
168 }
169}
170
171function isStringArray(value: unknown): value is Array<string> {
172 return Array.isArray(value) && value.every((item) => typeof item === 'string')
173}
174
175/**
176 * The provider's own flag vocabulary, for the `false` entries of its
177 * `exactCapabilities` rows: every flag some exact row of this poll lists.
178 * Read from what the adapter emitted, never from a global list, so a flag
179 * the provider has no word for is never a "no".
180 * ponytail: the vocabulary is this poll's rows. When the last model that
181 * lists a flag goes, the others' `false` for it turns to unknown. Give an
182 * adapter a declared vocabulary if that ever churns.
183 */
184function exactVocabulary(listed: Array<ModelInfo>): Array<string> {
185 const flags = new Set<string>()
186 for (const info of listed) {
187 if (info.exactCapabilities !== true) continue
188 if (!isStringArray(info.capabilities)) continue
189 for (const flag of info.capabilities) flags.add(flag)
190 }
191 return [...flags].sort()
192}
193
194/**
195 * The write gate for `capabilities`: the one place a listing's flags become
196 * the stored map. Listed flags are `true`, `unsupportedCapabilities` are
197 * `false`, and an `exactCapabilities` row adds `false` for every flag of
198 * the provider's vocabulary its list leaves out. A map with no entries is
199 * null. A row that is not a flag list, or that names a flag as both
200 * supported and unsupported, is not stored: the row keeps the map and
201 * sources it had (null on a new row) and an `ingest_failed` event says why.
202 */
203function settleCapabilities(
204 provider: ProviderConfig,
205 info: ModelInfo,
206 existing: typeof models.$inferSelect | undefined,
207 vocabulary: Array<string>,
208): { capabilities: CapabilityMap | null; factSources?: ModelFactSources } {
209 const refuse = (why: string) => {
210 noteIngest(
211 ingestFailedEvent(
212 'models-poll',
213 provider.id,
214 `${info.rawId}: capabilities not stored: ${why}`,
215 ),
216 )
217 const { capabilities: _refused, ...sources } = info.factSources ?? {}
218 const prior = (existing?.factSources as ModelFactSources | null)
219 ?.capabilities
220 const factSources = prior ? { ...sources, capabilities: prior } : sources
221 return {
222 capabilities: existing?.capabilities ?? null,
223 factSources: emptySources(factSources) ? undefined : factSources,
224 }
225 }
226 const listed = info.capabilities ?? null
227 // A stored map kept as `unavailable` goes back as it is.
228 if (isCapabilityMap(listed)) {
229 return {
230 capabilities: Object.keys(listed).length > 0 ? listed : null,
231 factSources: info.factSources,
232 }
233 }
234 if (listed !== null && !isStringArray(listed)) {
235 return refuse('not a flag list')
236 }
237 const yes = listed ?? []
238 // `absent.capabilities` speaks for the whole map, its noes included.
239 const stated = info.absent?.capabilities
240 ? []
241 : (info.unsupportedCapabilities ?? [])
242 const both = stated.filter((flag) => yes.includes(flag))
243 if (both.length > 0) {
244 return refuse(`${both.join(', ')} listed as both supported and unsupported`)
245 }
246 const sources = { ...info.factSources?.capabilities }
247 const no = [...stated]
248 if (info.exactCapabilities === true && listed) {
249 // The list is the model's whole one: what it leaves out is a no, and
250 // the document that states the list is the source of each.
251 const source = Object.values(sources).at(0) ?? {
252 derivation: 'listing' as const,
253 sourceUrl: listingSourceUrl(provider),
254 }
255 for (const flag of vocabulary) {
256 if (yes.includes(flag) || no.includes(flag)) continue
257 no.push(flag)
258 sources[flag] = { ...source, path: 'unlisted' }
259 }
260 }
261 const map: CapabilityMap = {}
262 for (const flag of yes) map[flag] = true
263 for (const flag of no) map[flag] = false
264 const factSources: ModelFactSources = { ...info.factSources }
265 if (Object.keys(sources).length > 0) factSources.capabilities = sources
266 return {
267 capabilities: Object.keys(map).length > 0 ? map : null,
268 factSources: emptySources(factSources) ? undefined : factSources,
269 }
270}
271
272/**
273 * The last word on the stated facts before the write (see the table under
274 * `FactAbsence`): the flag map, the release date a row keeps, a cutoff in
275 * the stored format or not at all, and a weights link only beside a stated
276 * yes.
277 */
278function settleStatedFacts(
279 provider: ProviderConfig,
280 info: ModelInfo,
281 existing: typeof models.$inferSelect | undefined,
282 vocabulary: Array<string>,
283 now: number,
284): ModelInfo & { capabilities: CapabilityMap | null } {
285 const releasedAt =
286 info.absent?.releasedAt === 'cleared'
287 ? null
288 : (usableReleasedAt(info, now) ?? existing?.releasedAt ?? null)
289
290 let knowledgeCutoff = info.knowledgeCutoff ?? null
291 if (knowledgeCutoff !== null && !KNOWLEDGE_CUTOFF.test(knowledgeCutoff)) {
292 noteIngest(
293 ingestFailedEvent(
294 'models-poll',
295 provider.id,
296 `${info.rawId}: knowledgeCutoff not stored: ${JSON.stringify(knowledgeCutoff)} is not YYYY-MM or YYYY-MM-DD`,
297 ),
298 )
299 knowledgeCutoff = existing?.knowledgeCutoff ?? null
300 }
301
302 const openWeights = info.openWeights ?? null
303 const weightsUrl = openWeights === true ? (info.weightsUrl ?? null) : null
304
305 return {
306 ...info,
307 ...settleCapabilities(provider, info, existing, vocabulary),
308 releasedAt,
309 knowledgeCutoff,
310 openWeights,
311 weightsUrl,
312 }
313}
314
315type InputWalks = {
316 walks: Map<string, SchemaWalk>
317 properties: Map<string, Set<string>>
318 storedRoutes: Map<string, Activity>
319}
320
321/** Key for the walk of one model's branch of a `model`-discriminated body. */
322function modelWalkKey(endpointId: string, rawId: string): string {
323 return `${endpointId}\n${rawId}`
324}
325
326async function loadInputWalks(
327 db: SyncDeps['db'],
328 provider: ProviderConfig,
329 listed: Array<ModelInfo>,
330): Promise<InputWalks> {
331 const walks = new Map<string, SchemaWalk>()
332 const properties = new Map<string, Set<string>>()
333 const storedRoutes = new Map<string, Activity>()
334 if (provider.bindStoredRoutesWithoutSchemas === true) {
335 const routes = await db
336 .select({ id: endpoints.id, activity: endpoints.activity })
337 .from(endpoints)
338 .where(eq(endpoints.providerId, provider.id))
339 for (const route of routes)
340 storedRoutes.set(route.id.slice(provider.id.length + 1), route.activity)
341 }
342 const skipFactWalk =
343 resolveSpecGrain(provider) === 'model' ||
344 provider.defaultDerivation === 'generated'
345 // Grain=model / generated listings skip the capability walk (thousands of
346 // FAL endpoints; OpenAI-borrowed specs must not stamp flags). Still load
347 // request property names when a listing already carries a RateCard so
348 // invented request-bound params refuse the write.
349 const needsRequestCheck = listed.some(
350 (info) => parseStoredRateCard(info.pricing) !== null,
351 )
352 if (skipFactWalk && !needsRequestCheck) {
353 return { walks, properties, storedRoutes }
354 }
355 const bound = new Set<string>()
356 for (const info of listed) {
357 const id = resolveSchemaEndpointId({
358 providerId: provider.id,
359 rawId: info.rawId,
360 activity: info.activity ?? null,
361 capabilities: info.capabilities,
362 schemaEndpointId: info.schemaEndpointId,
363 })
364 if (id) bound.add(id)
365 }
366 if (bound.size === 0) return { walks, properties, storedRoutes }
367 const dbIds = [...bound].map((id) => `${provider.id}/${id}`)
368 const chunks: Array<Array<string>> = []
369 for (let i = 0; i < dbIds.length; i += 90) {
370 chunks.push(dbIds.slice(i, i + 90))
371 }
372 const rows = (
373 await Promise.all(
374 chunks.map((chunk) =>
375 db
376 .select({
377 endpointId: schemaVersions.endpointId,
378 schema: schemaVersions.schema,
379 derivation: schemaVersions.derivation,
380 sourceUrl: schemaVersions.sourceUrl,
381 sourceHash: schemaVersions.sourceHash,
382 createdAt: schemaVersions.createdAt,
383 })
384 .from(schemaVersions)
385 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
386 .where(
387 and(
388 inArray(schemaVersions.endpointId, chunk),
389 eq(schemaVersions.kind, 'input'),
390 isNull(schemaVersions.supersededAt),
391 ),
392 ),
393 ),
394 )
395 ).flat()
396 const prefix = `${provider.id}/`
397 for (const row of rows) {
398 const publicId = row.endpointId.startsWith(prefix)
399 ? row.endpointId.slice(prefix.length)
400 : row.endpointId
401 const parsed: unknown = JSON.parse(row.schema)
402 properties.set(publicId, requestSchemaPropertyNames(parsed))
403 if (skipFactWalk) continue
404 const rung = schemaRung(row.derivation)
405 if (rung === null) continue
406 const meta = {
407 derivation: rung,
408 endpointId: publicId,
409 sourceUrl: row.sourceUrl,
410 sourceHash: row.sourceHash,
411 fetchedAt: row.createdAt,
412 }
413 const walk = walkRequestSchema(parsed, meta)
414 if (walk) walks.set(publicId, walk)
415 for (const [rawId, branch] of modelBranchSchemas(parsed)) {
416 const own = walkRequestSchema(branch, meta)
417 if (own) walks.set(modelWalkKey(publicId, rawId), own)
418 }
419 }
420 const perModel = new Set(provider.perModelSchemaFlags)
421 if (perModel.size > 0) {
422 for (const [id, walk] of walks) {
423 walks.set(id, {
424 ...walk,
425 flags: walk.flags.filter((flag) => !perModel.has(flag)),
426 })
427 }
428 }
429 return { walks, properties, storedRoutes }
430}
431
432function logRefusedCard(
433 providerId: string,
434 rawId: string,
435 refused: RateCardRefuse,
436 hadStoredCard: boolean,
437): void {
438 // Uncompilable zeros/blobs are the common listing case; only log when we
439 // drop a card that was already stored, or when a RateCard fails the write
440 // gate (invented param / examples).
441 if (refused === 'uncompilable' && !hadStoredCard) return
442 console.error(
443 JSON.stringify({
444 job: 'models-poll',
445 providerId,
446 rawId,
447 error: 'rate_card_refused',
448 reason: refused,
449 }),
450 )
451}
452
453function pricingDerivation(sources: unknown): string | null {
454 if (typeof sources !== 'object' || sources === null) return null
455 const pricing = (sources as ModelFactSources).pricing
456 return pricing?.derivation ?? null
457}
458
459function restorePriorPricing(
460 next: ModelFactSources | null,
461 previous: unknown,
462): ModelFactSources | null {
463 if (typeof previous !== 'object' || previous === null) return next
464 const prior = (previous as ModelFactSources).pricing
465 if (!prior) return next
466 return { ...(next ?? {}), pricing: prior }
467}
468
469function listingSourceUrl(provider: ProviderConfig): string {
470 return (
471 provider.modelsEndpoint ??
472 provider.specSourceUrl ??
473 `https://modelschemas.com/v1/providers/${provider.id}`
474 )
475}
476
477function enrichListed(
478 provider: ProviderConfig,
479 info: ModelInfo,
480 walks: Map<string, SchemaWalk>,
481): ModelInfo {
482 const bound = resolveSchemaEndpointId({
483 providerId: provider.id,
484 rawId: info.rawId,
485 activity: info.activity ?? null,
486 capabilities: info.capabilities,
487 schemaEndpointId: info.schemaEndpointId,
488 })
489 const walk = bound
490 ? (walks.get(modelWalkKey(bound, info.rawId)) ?? walks.get(bound) ?? null)
491 : null
492 const merged = mergeListingAndSchema(info, walk)
493 return {
494 ...info,
495 contextWindow: merged.contextWindow,
496 maxOutput: merged.maxOutput,
497 modalities: merged.modalities,
498 pricing: merged.pricing,
499 capabilities: merged.capabilities,
500 factSources: merged.factSources ?? undefined,
501 }
502}
503
504type StoredFact = Exclude<ModelFact, 'pricing'>
505
506/** A stored row's facts in listing shape. With no row, every fact is empty. */
507function storedFacts(
508 row: typeof models.$inferSelect | undefined,
509): Record<StoredFact, unknown> {
510 return {
511 displayName: row?.displayName ?? null,
512 activity: row?.activity ?? null,
513 contextWindow: row?.contextWindow ?? null,
514 maxOutput: row?.maxOutput ?? null,
515 modalities: row?.modalities ?? null,
516 capabilities: row?.capabilities ?? null,
517 reasoning: row?.reasoning ?? null,
518 serverTools: row?.serverTools ?? null,
519 requestMap: row?.requestMap ?? null,
520 aliases: row?.aliases ?? null,
521 schemaEndpointId: row?.schemaEndpointId ?? null,
522 releasedAt: row?.releasedAt ?? null,
523 knowledgeCutoff: row?.knowledgeCutoff ?? null,
524 openWeights: row?.openWeights ?? null,
525 providerMetadata: row?.providerMetadata ?? null,
526 }
527}
528
529const SOURCED_FACTS = [
530 'contextWindow',
531 'maxOutput',
532 'modalities',
533 'capabilities',
534 'reasoning',
535 'serverTools',
536 'requestMap',
537 'knowledgeCutoff',
538 'openWeights',
539] as const
540
541/** The facts `enrichListed` fills from the bound request schema. */
542const WALKED_FACTS = ['capabilities'] as const
543
544/**
545 * Apply `info.absent` (see `FactAbsence`) to every fact but pricing, which
546 * the card path owns: `unavailable` takes the stored value and its source,
547 * `cleared` takes none. It runs twice. Before the schema walks, so a row
548 * whose docs failed binds, and is checked, against its stored endpoint.
549 * Then for `WALKED_FACTS` alone after the walk, which would otherwise
550 * refill a kept or cleared fact.
551 */
552function resolveAbsent(
553 info: ModelInfo,
554 existing: typeof models.$inferSelect | undefined,
555 only?: ReadonlyArray<StoredFact>,
556): ModelInfo {
557 const absent = info.absent
558 if (!absent) return info
559 const stored = storedFacts(existing)
560 const none = storedFacts(undefined)
561 const next: ModelInfo = { ...info }
562 for (const fact of only ?? (Object.keys(none) as Array<StoredFact>)) {
563 const why = absent[fact]
564 if (!why) continue
565 Object.assign(next, {
566 [fact]: (why === 'unavailable' ? stored : none)[fact],
567 })
568 // The link is part of the open-weights fact.
569 if (fact === 'openWeights') {
570 next.weightsUrl =
571 why === 'unavailable' ? (existing?.weightsUrl ?? null) : null
572 }
573 }
574 const sources: ModelFactSources = { ...info.factSources }
575 const prior = (existing?.factSources ?? {}) as ModelFactSources
576 for (const fact of SOURCED_FACTS) {
577 const why = absent[fact]
578 if (!why || (only && !only.includes(fact))) continue
579 delete sources[fact]
580 if (why === 'unavailable' && prior[fact]) {
581 Object.assign(sources, { [fact]: prior[fact] })
582 }
583 }
584 next.factSources = emptySources(sources) ? undefined : sources
585 return next
586}
587
588/**
589 * One poll may not clear most of a provider's prices. `cleared` is an
590 * adapter's word that a price is gone, and an adapter that misreads a
591 * reshaped listing would say it for every row at once. When a poll would
592 * clear at least `PRICE_CLEARS_MIN` stored cards and more than
593 * `PRICE_CLEARS_SHARE` of the priced rows it lists, none of its clears is
594 * applied: the cards stay and the poll logs one failure. Fewer than the
595 * minimum always passes, so a small provider can still lose every price.
596 * The refusal repeats every poll until the adapter or this bound changes,
597 * or the stale cards are nulled by hand in D1.
598 */
599const PRICE_CLEARS_MIN = 5
600const PRICE_CLEARS_SHARE = 0.5
601
602/** Stored cards this poll asks to clear, when that is too many to believe. */
603function refusesPriceClears(
604 listed: Array<ModelInfo>,
605 existingById: Map<string, typeof models.$inferSelect>,
606 providerId: string,
607): { clears: number; priced: number } | null {
608 const clears = listed.filter(
609 (info) =>
610 info.absent?.pricing === 'cleared' &&
611 storedCardIsPrior(
612 existingById.get(modelDbId(providerId, info.rawId))?.pricing,
613 ),
614 ).length
615 if (clears < PRICE_CLEARS_MIN) return null
616 // Of the rows this poll lists: a delisted row that still holds a card
617 // must not make room for clearing every live one.
618 const priced = listed.filter((info) =>
619 storedCardIsPrior(
620 existingById.get(modelDbId(providerId, info.rawId))?.pricing,
621 ),
622 ).length
623 return clears > priced * PRICE_CLEARS_SHARE ? { clears, priced } : null
624}
625
626export async function pollProviderModels(
627 deps: SyncDeps,
628 provider: ProviderConfig,
629): Promise<PollOutcome> {
630 const { db, secrets } = deps
631 const now = deps.now?.() ?? Math.floor(Date.now() / 1000)
632 const outcome: PollOutcome = {
633 providerId: provider.id,
634 modelsSeen: 0,
635 added: 0,
636 removed: 0,
637 updated: 0,
638 backdated: 0,
639 failures: 0,
640 }
641 await ensureProviderRow(db, provider)
642 await dropModelsDevSchemaVersions(db, provider.id)
643 await nullModelsDevRateCards(db, provider.id)
644
645 const listed = await provider.listModels(secrets, deps.kv)
646 if (listed.skipped) {
647 // Not an empty list. An empty list would also drop a later first-party
648 // row the next time this adapter skips.
649 outcome.skipped = listed.skipped
650 outcome.removed = await deprecateFrozenModelsDevCatalog(
651 db,
652 provider.id,
653 now,
654 )
655 return outcome
656 }
657 outcome.modelsSeen = listed.models.length
658 // A docs source that failed does not fail the poll: its rows carry
659 // `absent: unavailable` and keep what is stored. Every failing poll says
660 // so again, here and in the outcome, so an outage never goes quiet.
661 const docs = listed.docsFailures
662 if (docs) {
663 // Kept across polls (`docs-failing.ts`): when it began, how long.
664 // The record describes the poll; it must never be what fails it.
665 try {
666 const failing = await recordDocsFailing(db, provider.id, docs, now)
667 if (failing) outcome.docsFailing = failing
668 } catch (error) {
669 console.error(
670 JSON.stringify({
671 job: 'models-poll',
672 providerId: provider.id,
673 error: `docs-failing record not written: ${errorMessage(error)}`,
674 }),
675 )
676 }
677 }
678 if (docs && docs.failed + docs.skipped > 0) {
679 outcome.docsFailures = docs
680 outcome.failures += docs.failed + docs.skipped
681 const report = (error: string, source?: string) => {
682 console.error(
683 JSON.stringify({
684 job: 'models-poll',
685 providerId: provider.id,
686 ...(source ? { docs: source } : {}),
687 error,
688 }),
689 )
690 noteIngest(ingestFailedEvent('models-poll', provider.id, error, source))
691 }
692 for (const { source, error } of docs.first) report(error, source)
693 // The rest are a count: a whole docs host down is one line, not eighty.
694 const more = docs.failed - docs.first.length
695 if (more + docs.skipped > 0) {
696 report(
697 `docs: ${String(more)} more failed, ${String(docs.skipped)} not attempted after the failure budget`,
698 )
699 }
700 }
701
702 const existingRows = await db
703 .select()
704 .from(models)
705 .where(eq(models.providerId, provider.id))
706 const existingById = new Map(existingRows.map((m) => [m.id, m]))
707 const listedModels = listed.models.map((info) =>
708 resolveAbsent(info, existingById.get(modelDbId(provider.id, info.rawId))),
709 )
710 const { walks, properties, storedRoutes } = await loadInputWalks(
711 db,
712 provider,
713 listedModels,
714 )
715 const refused = refusesPriceClears(listedModels, existingById, provider.id)
716 // Kept across polls like the docs record; it cannot fail the poll.
717 await recordPriceClearsRefused(db, provider.id, refused, now)
718 if (refused) {
719 const error = `refused to clear ${String(refused.clears)} of ${String(refused.priced)} stored prices in one poll`
720 console.error(
721 JSON.stringify({ job: 'models-poll', providerId: provider.id, error }),
722 )
723 noteIngest(ingestFailedEvent('models-poll', provider.id, error))
724 outcome.priceClearsRefused = refused.clears
725 outcome.failures++
726 }
727 const seenIds = new Set<string>()
728 const identities: Array<UpstreamIdentityWrite> = []
729 // Unchanged rows only need their lastSeenAt bumped; collect them and write
730 // in chunked bulk UPDATEs. One-per-row writes here previously cost ~2,000
731 // sequential D1 round trips per poll (~10 min wall), starving the crons.
732 const cleanIds: Array<string> = []
733 // Otherwise-unchanged rows that need firstSeenAt backdated. Written in
734 // chunked bulk UPDATEs like cleanIds: each D1 query is a subrequest
735 // against the invocation's 1,000 budget, and the first pass after deploy
736 // backdates nearly every row (~1,900 across providers) — one-per-row
737 // writes would exhaust the budget mid-poll.
738 // The same list carries a row's first `releasedAt` (stored null, now
739 // stated): after the deploy that adds the column that is every dated row.
740 const backdates: Array<{
741 id: string
742 firstSeenAt: number
743 releasedAt: number | null
744 }> = []
745 const vocabulary = exactVocabulary(listedModels)
746
747 for (const listedModel of listedModels) {
748 const raw =
749 provider.bindSyncedRoutesOnly === true &&
750 listedModel.schemaEndpointId &&
751 !properties.has(listedModel.schemaEndpointId) &&
752 !(
753 provider.bindStoredRoutesWithoutSchemas === true &&
754 storedRoutes.get(listedModel.schemaEndpointId) === listedModel.activity
755 )
756 ? { ...listedModel, schemaEndpointId: null }
757 : listedModel
758 const id = modelDbId(provider.id, raw.rawId)
759 // Two raw ids can slug to one row (Mistral lists `mistral-medium-3-5`
760 // and `mistral-medium-3.5`). The first spelling is the row; a later one
761 // is skipped before any check, so it cannot count against the row.
762 if (seenIds.has(id)) continue
763 seenIds.add(id)
764 const existing = existingById.get(id)
765 const enriched = resolveAbsent(
766 enrichListed(provider, raw, walks),
767 existing,
768 WALKED_FACTS,
769 )
770 const bound = resolveSchemaEndpointId({
771 providerId: provider.id,
772 rawId: enriched.rawId,
773 activity: enriched.activity ?? null,
774 capabilities: enriched.capabilities,
775 schemaEndpointId: enriched.schemaEndpointId,
776 })
777 const existingPricing = existing?.pricing
778 // A models.dev card is not a prior. A docs-extracted card, and any
779 // other provider source, still is.
780 const hadStoredCard = storedCardIsPrior(existingPricing)
781 const keepExtracted =
782 raw.pricing == null &&
783 pricingDerivation(existing?.factSources) === 'docs-extracted' &&
784 !isModelsDevRateCard(existingPricing)
785 // A refused clear is treated as a source that could not be read.
786 const absentPricing =
787 refused && raw.absent?.pricing === 'cleared'
788 ? 'unavailable'
789 : raw.absent?.pricing
790 const incomingPricing =
791 absentPricing || isModelsDevRateCard(enriched.pricing)
792 ? null
793 : enriched.pricing
794 const incomingNull = incomingPricing == null
795 const stored =
796 absentPricing === 'unavailable' ||
797 (absentPricing !== 'cleared' &&
798 (keepExtracted || (incomingNull && hadStoredCard)))
799 ? { card: parseStoredRateCard(existingPricing) }
800 : await storeListedPricing(incomingPricing, {
801 existing: existingPricing,
802 requestProperties: bound
803 ? (properties.get(bound) ?? new Set())
804 : undefined,
805 sourceUrl: listingSourceUrl(provider),
806 now,
807 })
808 const decision = observePricingWrite({
809 providerId: provider.id,
810 rawId: enriched.rawId,
811 incomingNull,
812 hadStoredCard,
813 keepExtracted,
814 absent: absentPricing,
815 refused: stored.refused,
816 })
817 for (const event of decision.events) noteIngest(event)
818 outcome.failures += decision.failure
819 if (!keepExtracted && stored.refused) {
820 logRefusedCard(provider.id, enriched.rawId, stored.refused, hadStoredCard)
821 }
822 const card = decision.keepPrior
823 ? parseStoredRateCard(existingPricing)
824 : stored.card
825 let factSources = reconcilePricingSource(enriched.factSources, card)
826 if (decision.keepPrior) {
827 factSources = restorePriorPricing(factSources, existing?.factSources)
828 }
829 const info = settleStatedFacts(
830 provider,
831 keepValidReasoning(
832 provider.id,
833 { ...enriched, pricing: card, factSources: factSources ?? undefined },
834 existing,
835 ),
836 existing,
837 vocabulary,
838 now,
839 )
840 const identity = provider.upstreamModelIdentity?.(info.rawId) ?? null
841 // Only changed evidence is written: most rows restate it every poll.
842 if (!sameEvidence(existing, identity)) identities.push({ id, identity })
843
844 if (!existing) {
845 await db.insert(models).values({
846 id,
847 providerId: provider.id,
848 rawId: info.rawId,
849 activity: info.activity ?? null,
850 displayName: info.displayName ?? null,
851 contextWindow: info.contextWindow ?? null,
852 maxOutput: info.maxOutput ?? null,
853 modalities: info.modalities ?? null,
854 pricing: info.pricing ?? null,
855 capabilities: info.capabilities ?? null,
856 providerMetadata: info.providerMetadata ?? null,
857 reasoning: info.reasoning ?? null,
858 serverTools: info.serverTools ?? null,
859 requestMap: requestMapFor(provider.id, info),
860 aliases: storedAliases(info.aliases),
861 factSources: info.factSources ?? null,
862 schemaEndpointId: info.schemaEndpointId ?? null,
863 releasedAt: info.releasedAt ?? null,
864 knowledgeCutoff: info.knowledgeCutoff ?? null,
865 openWeights: info.openWeights ?? null,
866 weightsUrl: info.weightsUrl ?? null,
867 // Providers that report a release date get it as firstSeenAt, so
868 // models predating our monitoring carry their historical date.
869 firstSeenAt: usableReleasedAt(info, now) ?? now,
870 lastSeenAt: now,
871 deprecatedAt: info.deprecated ? now : null,
872 })
873 await db.insert(changes).values({
874 id: crypto.randomUUID(),
875 type: 'model.added',
876 providerId: provider.id,
877 subjectId: id,
878 summary: `Model ${info.rawId} added`,
879 createdAt: now,
880 })
881 outcome.added++
882 continue
883 }
884
885 const before = {
886 displayName: existing.displayName,
887 activity: existing.activity,
888 contextWindow: existing.contextWindow,
889 maxOutput: existing.maxOutput,
890 modalities: existing.modalities,
891 pricing: existing.pricing,
892 capabilities: existing.capabilities,
893 reasoning: existing.reasoning,
894 reasoningSource: reasoningSourcePath(existing.factSources),
895 serverTools: existing.serverTools,
896 requestMap: existing.requestMap,
897 aliases: storedAliases(existing.aliases),
898 schemaEndpointId: existing.schemaEndpointId,
899 deprecated: existing.deprecatedAt !== null,
900 releasedAt: existing.releasedAt,
901 knowledgeCutoff: existing.knowledgeCutoff,
902 openWeights: existing.openWeights,
903 weightsUrl: existing.weightsUrl,
904 providerMetadata: existing.providerMetadata,
905 }
906 const capabilities = preserveAsyncApiFlag(
907 existing.capabilities,
908 info.capabilities,
909 )
910 const after = comparable(provider.id, { ...info, capabilities })
911 // A first `releasedAt` on a stored row is not a change to the model: we
912 // learned a date it always had. It is written with the backdates, with
913 // no `model.updated`. A date that moves or goes still emits one.
914 const firstRelease = existing.releasedAt === null && info.releasedAt != null
915 // Likewise the listing object a row gains the first time: rows written
916 // before the column existed had nowhere to keep it.
917 const firstMetadata =
918 existing.providerMetadata === null && info.providerMetadata != null
919 const dirty =
920 stableStringify({
921 ...before,
922 ...(firstRelease ? { releasedAt: info.releasedAt } : {}),
923 ...(firstMetadata ? { providerMetadata: info.providerMetadata } : {}),
924 }) !== stableStringify(after)
925
926 // Upstream reports a release date earlier than our observed firstSeenAt
927 // → backdate in place. A silent correction (no model.updated event):
928 // it converges once per row, and the fleet-wide first pass would
929 // otherwise flood the changes feed and webhook fan-out.
930 const backdatedFirstSeen = usableReleasedAt(info, existing.firstSeenAt)
931 if (backdatedFirstSeen !== null) outcome.backdated++
932
933 if (!dirty) {
934 if (firstMetadata) {
935 // One write per row: few rows gain one (a provider's chat rows).
936 await db
937 .update(models)
938 .set({
939 providerMetadata: info.providerMetadata ?? null,
940 releasedAt: info.releasedAt ?? null,
941 firstSeenAt: backdatedFirstSeen ?? existing.firstSeenAt,
942 lastSeenAt: now,
943 })
944 .where(eq(models.id, id))
945 } else if (backdatedFirstSeen === null && !firstRelease) cleanIds.push(id)
946 else {
947 backdates.push({
948 id,
949 firstSeenAt: backdatedFirstSeen ?? existing.firstSeenAt,
950 releasedAt: info.releasedAt ?? null,
951 })
952 }
953 continue
954 }
955
956 await db
957 .update(models)
958 .set({
959 lastSeenAt: now,
960 ...(backdatedFirstSeen !== null
961 ? { firstSeenAt: backdatedFirstSeen }
962 : {}),
963 displayName: info.displayName ?? null,
964 activity: info.activity ?? null,
965 contextWindow: info.contextWindow ?? null,
966 maxOutput: info.maxOutput ?? null,
967 modalities: info.modalities ?? null,
968 pricing: info.pricing ?? null,
969 capabilities,
970 providerMetadata: info.providerMetadata ?? null,
971 reasoning: info.reasoning ?? null,
972 serverTools: info.serverTools ?? null,
973 requestMap: requestMapFor(provider.id, info),
974 aliases: storedAliases(info.aliases),
975 factSources: info.factSources ?? null,
976 schemaEndpointId: info.schemaEndpointId ?? null,
977 releasedAt: info.releasedAt ?? null,
978 knowledgeCutoff: info.knowledgeCutoff ?? null,
979 openWeights: info.openWeights ?? null,
980 weightsUrl: info.weightsUrl ?? null,
981 // A model that reappears (or upstream re-activates) clears
982 // its deprecation; an upstream-deprecated one gains it.
983 deprecatedAt:
984 (info.deprecated ?? false) ? (existing.deprecatedAt ?? now) : null,
985 })
986 .where(eq(models.id, id))
987
988 await db.insert(changes).values({
989 id: crypto.randomUUID(),
990 type: 'model.updated',
991 providerId: provider.id,
992 subjectId: id,
993 summary: `Model ${info.rawId} updated`,
994 payload: { before, after },
995 createdAt: now,
996 })
997 outcome.updated++
998 }
999
1000 // Bump lastSeenAt for the unchanged majority in chunks that stay under
1001 // D1's 100-bound-parameter-per-statement limit.
1002 for (let i = 0; i < cleanIds.length; i += 90) {
1003 await db
1004 .update(models)
1005 .set({ lastSeenAt: now })
1006 .where(inArray(models.id, cleanIds.slice(i, i + 90)))
1007 }
1008
1009 // Backdates carry per-row values, so bulk-update via CASE. Five bound
1010 // params per row (two CASE arms + IN member) + one for lastSeenAt → 19
1011 // rows stays under the 100-param limit.
1012 for (let i = 0; i < backdates.length; i += 19) {
1013 const chunk = backdates.slice(i, i + 19)
1014 const arms = (value: (b: (typeof chunk)[number]) => number | null) =>
1015 sql.join(
1016 chunk.map((b) => sql`WHEN ${b.id} THEN ${value(b)}`),
1017 sql` `,
1018 )
1019 await db
1020 .update(models)
1021 .set({
1022 firstSeenAt: sql`CASE ${models.id} ${arms((b) => b.firstSeenAt)} END`,
1023 releasedAt: sql`CASE ${models.id} ${arms((b) => b.releasedAt)} END`,
1024 lastSeenAt: now,
1025 })
1026 .where(
1027 inArray(
1028 models.id,
1029 chunk.map((b) => b.id),
1030 ),
1031 )
1032 }
1033
1034 // Models in D1 the provider no longer lists → mark deprecated once.
1035 for (const existing of existingRows) {
1036 if (seenIds.has(existing.id) || existing.deprecatedAt !== null) continue
1037 await db
1038 .update(models)
1039 .set({ deprecatedAt: now })
1040 .where(eq(models.id, existing.id))
1041 await db.insert(changes).values({
1042 id: crypto.randomUUID(),
1043 type: 'model.removed',
1044 providerId: provider.id,
1045 subjectId: existing.id,
1046 summary: `Model ${existing.rawId} no longer listed`,
1047 createdAt: now,
1048 })
1049 outcome.removed++
1050 }
1051
1052 await db
1053 .update(providers)
1054 .set({ lastPolledAt: now })
1055 .where(eq(providers.id, provider.id))
1056 await markModelsDevCatalogSettled(db, provider.id, now)
1057 await persistUpstreamIdentities(db, identities)
1058
1059 return outcome
1060}
1061
1062/** Poll every registered provider with per-provider failure isolation. */
1063export async function pollAllProviders(
1064 deps: SyncDeps,
1065 registry: ReadonlyArray<ProviderConfig> = providerRegistry,
1066): Promise<Array<PollOutcome>> {
1067 const outcomes: Array<PollOutcome> = []
1068 for (const provider of registry) {
1069 await runIngestScope(async () => {
1070 try {
1071 outcomes.push(await pollProviderModels(deps, provider))
1072 } catch (error) {
1073 const message = errorMessage(error)
1074 // Own log line per failure: the aggregate outcomes blob can exceed
1075 // what Workers Logs stores, which silently loses these errors.
1076 console.error(
1077 JSON.stringify({
1078 job: 'models-poll',
1079 providerId: provider.id,
1080 error: message,
1081 }),
1082 )
1083 noteIngest(ingestFailedEvent('models-poll', provider.id, message))
1084 outcomes.push({
1085 providerId: provider.id,
1086 modelsSeen: 0,
1087 added: 0,
1088 removed: 0,
1089 updated: 0,
1090 backdated: 0,
1091 failures: 1,
1092 error: message,
1093 })
1094 } finally {
1095 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
1096 }
1097 })
1098 }
1099 // Links span providers, so resolve them once per run, outside any one
1100 // provider's outcome: a failure here must not read as every poll failing.
1101 await runIngestScope(async () => {
1102 try {
1103 await reconcileSameAs(
1104 deps.db,
1105 deps.now?.() ?? Math.floor(Date.now() / 1000),
1106 )
1107 } catch (error) {
1108 const message = errorMessage(error)
1109 console.error(
1110 JSON.stringify({ job: 'same-as-reconcile', error: message }),
1111 )
1112 noteIngest(ingestFailedEvent('same-as-reconcile', '*', message))
1113 } finally {
1114 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
1115 }
1116 })
1117 return outcomes
1118}