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