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 // No `docsFailures` is a healthy run. An adapter that stopped loading
699 // docs (OpenCode Go after #676 returns `{ models }` only) must still
700 // delete its old `docs-failing` row. A skipped listing returned above
701 // and leaves the record alone.
702 const docs = listed.docsFailures
703 try {
704 // Kept across polls (`docs-failing.ts`): when it began, how long.
705 // The record describes the poll; it must never be what fails it.
706 const failing = await recordDocsFailing(
707 db,
708 provider.id,
709 docs ?? { failed: 0, skipped: 0, first: [] },
710 now,
711 )
712 if (failing) outcome.docsFailing = failing
713 } catch (error) {
714 console.error(
715 JSON.stringify({
716 job: 'models-poll',
717 providerId: provider.id,
718 error: `docs-failing record not written: ${errorMessage(error)}`,
719 }),
720 )
721 }
722 if (docs && docs.failed + docs.skipped > 0) {
723 outcome.docsFailures = docs
724 outcome.failures += docs.failed + docs.skipped
725 const report = (error: string, source?: string) => {
726 console.error(
727 JSON.stringify({
728 job: 'models-poll',
729 providerId: provider.id,
730 ...(source ? { docs: source } : {}),
731 error,
732 }),
733 )
734 noteIngest(ingestFailedEvent('models-poll', provider.id, error, source))
735 }
736 for (const { source, error } of docs.first) report(error, source)
737 // The rest are a count: a whole docs host down is one line, not eighty.
738 const more = docs.failed - docs.first.length
739 if (more + docs.skipped > 0) {
740 report(
741 `docs: ${String(more)} more failed, ${String(docs.skipped)} not attempted after the failure budget`,
742 )
743 }
744 }
745
746 const existingRows = await db
747 .select()
748 .from(models)
749 .where(eq(models.providerId, provider.id))
750 const existingById = new Map(existingRows.map((m) => [m.id, m]))
751 // Row id → deprecations page entry; the first spelling of an id wins.
752 let deprecationIndex: Map<string, ModelDeprecation> | null = null
753 if (listed.deprecations) {
754 deprecationIndex = new Map()
755 for (const entry of listed.deprecations) {
756 const id = modelDbId(provider.id, entry.rawId)
757 if (!deprecationIndex.has(id)) deprecationIndex.set(id, entry)
758 }
759 }
760 const listedModels = listed.models.map((info) =>
761 resolveAbsent(info, existingById.get(modelDbId(provider.id, info.rawId))),
762 )
763 const { walks, properties, storedRoutes } = await loadInputWalks(
764 db,
765 provider,
766 listedModels,
767 )
768 const refused = refusesPriceClears(listedModels, existingById, provider.id)
769 // Kept across polls like the docs record; it cannot fail the poll.
770 await recordPriceClearsRefused(db, provider.id, refused, now)
771 if (refused) {
772 const error = `refused to clear ${String(refused.clears)} of ${String(refused.priced)} stored prices in one poll`
773 console.error(
774 JSON.stringify({ job: 'models-poll', providerId: provider.id, error }),
775 )
776 noteIngest(ingestFailedEvent('models-poll', provider.id, error))
777 outcome.priceClearsRefused = refused.clears
778 outcome.failures++
779 }
780 const seenIds = new Set<string>()
781 const identities: Array<UpstreamIdentityWrite> = []
782 // Unchanged rows only need their lastSeenAt bumped; collect them and write
783 // in chunked bulk UPDATEs. One-per-row writes here previously cost ~2,000
784 // sequential D1 round trips per poll (~10 min wall), starving the crons.
785 const cleanIds: Array<string> = []
786 // Otherwise-unchanged rows that need firstSeenAt backdated. Written in
787 // chunked bulk UPDATEs like cleanIds: each D1 query is a subrequest
788 // against the invocation's 1,000 budget, and the first pass after deploy
789 // backdates nearly every row (~1,900 across providers) — one-per-row
790 // writes would exhaust the budget mid-poll.
791 // The same list carries a row's first `releasedAt` (stored null, now
792 // stated): after the deploy that adds the column that is every dated row.
793 const backdates: Array<{
794 id: string
795 firstSeenAt: number
796 releasedAt: number | null
797 }> = []
798 const vocabulary = exactVocabulary(listedModels)
799
800 for (const listedModel of listedModels) {
801 const raw =
802 provider.bindSyncedRoutesOnly === true &&
803 listedModel.schemaEndpointId &&
804 !properties.has(listedModel.schemaEndpointId) &&
805 !(
806 provider.bindStoredRoutesWithoutSchemas === true &&
807 storedRoutes.get(listedModel.schemaEndpointId) === listedModel.activity
808 )
809 ? { ...listedModel, schemaEndpointId: null }
810 : listedModel
811 const id = modelDbId(provider.id, raw.rawId)
812 // Two raw ids can slug to one row (Mistral lists `mistral-medium-3-5`
813 // and `mistral-medium-3.5`). The first spelling is the row; a later one
814 // is skipped before any check, so it cannot count against the row.
815 if (seenIds.has(id)) continue
816 seenIds.add(id)
817 const existing = existingById.get(id)
818 const enriched = resolveAbsent(
819 enrichListed(provider, raw, walks),
820 existing,
821 WALKED_FACTS,
822 )
823 const bound = resolveSchemaEndpointId({
824 providerId: provider.id,
825 rawId: enriched.rawId,
826 activity: enriched.activity ?? null,
827 capabilities: enriched.capabilities,
828 schemaEndpointId: enriched.schemaEndpointId,
829 })
830 const existingPricing = existing?.pricing
831 // A models.dev card is not a prior. A docs-extracted card, and any
832 // other provider source, still is.
833 const hadStoredCard = storedCardIsPrior(existingPricing)
834 const keepExtracted =
835 raw.pricing == null &&
836 pricingDerivation(existing?.factSources) === 'docs-extracted' &&
837 !isModelsDevRateCard(existingPricing)
838 // A refused clear is treated as a source that could not be read.
839 const absentPricing =
840 refused && raw.absent?.pricing === 'cleared'
841 ? 'unavailable'
842 : raw.absent?.pricing
843 // A models.dev card is foreign everywhere, OpenCode included (#314).
844 const incomingPricing =
845 absentPricing || isModelsDevRateCard(enriched.pricing)
846 ? null
847 : enriched.pricing
848 const incomingNull = incomingPricing == null
849 const stored =
850 absentPricing === 'unavailable' ||
851 (absentPricing !== 'cleared' &&
852 (keepExtracted || (incomingNull && hadStoredCard)))
853 ? { card: parseStoredRateCard(existingPricing) }
854 : await storeListedPricing(incomingPricing, {
855 existing: existingPricing,
856 requestProperties: bound
857 ? (properties.get(bound) ?? new Set())
858 : undefined,
859 sourceUrl: listingSourceUrl(provider),
860 now,
861 })
862 const decision = observePricingWrite({
863 providerId: provider.id,
864 rawId: enriched.rawId,
865 incomingNull,
866 hadStoredCard,
867 keepExtracted,
868 absent: absentPricing,
869 refused: stored.refused,
870 })
871 for (const event of decision.events) noteIngest(event)
872 outcome.failures += decision.failure
873 if (!keepExtracted && stored.refused) {
874 logRefusedCard(provider.id, enriched.rawId, stored.refused, hadStoredCard)
875 }
876 const card = decision.keepPrior
877 ? parseStoredRateCard(existingPricing)
878 : stored.card
879 let factSources = reconcilePricingSource(enriched.factSources, card)
880 if (decision.keepPrior) {
881 factSources = restorePriorPricing(factSources, existing?.factSources)
882 }
883 const info = settleStatedFacts(
884 provider,
885 keepValidReasoning(
886 provider.id,
887 { ...enriched, pricing: card, factSources: factSources ?? undefined },
888 existing,
889 ),
890 existing,
891 vocabulary,
892 now,
893 )
894 // A listing that says there is no single price, and does not itself
895 // fetch the per-route prices, keeps a range a separate job stored
896 // (Vercel /endpoints, issue #451). A card on the listing clears it.
897 if (
898 existing &&
899 info.pricingRange === undefined &&
900 info.absent?.pricing === 'cleared'
901 ) {
902 info.pricingRange = existing.pricingRange
903 const priorFacts = existing.factSources
904 const priorRange =
905 priorFacts &&
906 typeof priorFacts === 'object' &&
907 'pricingRange' in priorFacts &&
908 priorFacts.pricingRange &&
909 typeof priorFacts.pricingRange === 'object' &&
910 'derivation' in priorFacts.pricingRange
911 ? (priorFacts.pricingRange as FactSource)
912 : undefined
913 if (priorRange && info.pricingRange) {
914 info.factSources = {
915 ...info.factSources,
916 pricingRange: priorRange,
917 }
918 }
919 }
920 // On the provider's deprecations page → deprecated (issue #410).
921 if (rowDeprecation(deprecationIndex, id, existing?.deprecation)) {
922 info.deprecated = true
923 }
924 const identity =
925 info.upstream !== undefined
926 ? info.upstream
927 : (provider.upstreamModelIdentity?.(info.rawId) ?? null)
928 // Only changed evidence is written: most rows restate it every poll.
929 if (!sameEvidence(existing, identity)) identities.push({ id, identity })
930
931 if (!existing) {
932 await db.insert(models).values({
933 id,
934 providerId: provider.id,
935 rawId: info.rawId,
936 activity: info.activity ?? null,
937 displayName: info.displayName ?? null,
938 contextWindow: info.contextWindow ?? null,
939 maxOutput: info.maxOutput ?? null,
940 modalities: info.modalities ?? null,
941 pricing: info.pricing ?? null,
942 pricingRange: storedRange(info),
943 capabilities: info.capabilities ?? null,
944 providerMetadata: info.providerMetadata ?? null,
945 reasoning: info.reasoning ?? null,
946 serverTools: info.serverTools ?? null,
947 requestMap: requestMapFor(provider.id, info),
948 aliases: storedAliases(info.aliases),
949 factSources: info.factSources ?? null,
950 schemaEndpointId: info.schemaEndpointId ?? null,
951 releasedAt: info.releasedAt ?? null,
952 knowledgeCutoff: info.knowledgeCutoff ?? null,
953 openWeights: info.openWeights ?? null,
954 weightsUrl: info.weightsUrl ?? null,
955 trainsOnRequestData: info.trainsOnRequestData ?? null,
956 // Providers that report a release date get it as firstSeenAt, so
957 // models predating our monitoring carry their historical date.
958 firstSeenAt: usableReleasedAt(info, now) ?? now,
959 lastSeenAt: now,
960 deprecatedAt: info.deprecated ? now : null,
961 })
962 await db.insert(changes).values({
963 id: crypto.randomUUID(),
964 type: 'model.added',
965 providerId: provider.id,
966 subjectId: id,
967 summary: `Model ${info.rawId} added`,
968 createdAt: now,
969 })
970 outcome.added++
971 continue
972 }
973
974 const before = {
975 displayName: existing.displayName,
976 activity: existing.activity,
977 contextWindow: existing.contextWindow,
978 maxOutput: existing.maxOutput,
979 modalities: existing.modalities,
980 pricing: existing.pricing,
981 capabilities: existing.capabilities,
982 reasoning: existing.reasoning,
983 reasoningSource: reasoningSourcePath(existing.factSources),
984 serverTools: existing.serverTools,
985 requestMap: existing.requestMap,
986 aliases: storedAliases(existing.aliases),
987 schemaEndpointId: existing.schemaEndpointId,
988 deprecated: existing.deprecatedAt !== null,
989 releasedAt: existing.releasedAt,
990 knowledgeCutoff: existing.knowledgeCutoff,
991 openWeights: existing.openWeights,
992 weightsUrl: existing.weightsUrl,
993 trainsOnRequestData: existing.trainsOnRequestData,
994 providerMetadata: existing.providerMetadata,
995 pricingRange: existing.pricingRange,
996 }
997 const capabilities = preserveAsyncApiFlag(
998 existing.capabilities,
999 info.capabilities,
1000 )
1001 const after = comparable(provider.id, { ...info, capabilities })
1002 // A first `releasedAt` on a stored row is not a change to the model: we
1003 // learned a date it always had. It is written with the backdates, with
1004 // no `model.updated`. A date that moves or goes still emits one.
1005 const firstRelease = existing.releasedAt === null && info.releasedAt != null
1006 // Likewise the listing object a row gains the first time: rows written
1007 // before the column existed had nowhere to keep it.
1008 const firstMetadata =
1009 existing.providerMetadata === null && info.providerMetadata != null
1010 // Facts, not bytes: a source hash, an extract time, `+` operand order,
1011 // and an input's `values` order are not a change. A first release date
1012 // or listing object is written below with no event.
1013 const changed = changedFactPaths(
1014 {
1015 ...before,
1016 ...(firstRelease ? { releasedAt: info.releasedAt } : {}),
1017 ...(firstMetadata ? { providerMetadata: info.providerMetadata } : {}),
1018 },
1019 after,
1020 )
1021 const dirty = changed.length > 0
1022
1023 // Upstream reports a release date earlier than our observed firstSeenAt
1024 // → backdate in place. A silent correction (no model.updated event):
1025 // it converges once per row, and the fleet-wide first pass would
1026 // otherwise flood the changes feed and webhook fan-out.
1027 const backdatedFirstSeen = usableReleasedAt(info, existing.firstSeenAt)
1028 if (backdatedFirstSeen !== null) outcome.backdated++
1029
1030 if (!dirty) {
1031 if (firstMetadata) {
1032 // One write per row: few rows gain one (a provider's chat rows).
1033 await db
1034 .update(models)
1035 .set({
1036 providerMetadata: info.providerMetadata ?? null,
1037 releasedAt: info.releasedAt ?? null,
1038 firstSeenAt: backdatedFirstSeen ?? existing.firstSeenAt,
1039 lastSeenAt: now,
1040 })
1041 .where(eq(models.id, id))
1042 } else if (backdatedFirstSeen === null && !firstRelease) cleanIds.push(id)
1043 else {
1044 backdates.push({
1045 id,
1046 firstSeenAt: backdatedFirstSeen ?? existing.firstSeenAt,
1047 releasedAt: info.releasedAt ?? null,
1048 })
1049 }
1050 continue
1051 }
1052
1053 await db
1054 .update(models)
1055 .set({
1056 lastSeenAt: now,
1057 ...(backdatedFirstSeen !== null
1058 ? { firstSeenAt: backdatedFirstSeen }
1059 : {}),
1060 displayName: info.displayName ?? null,
1061 activity: info.activity ?? null,
1062 contextWindow: info.contextWindow ?? null,
1063 maxOutput: info.maxOutput ?? null,
1064 modalities: info.modalities ?? null,
1065 pricing: info.pricing ?? null,
1066 pricingRange: storedRange(info),
1067 capabilities,
1068 providerMetadata: info.providerMetadata ?? null,
1069 reasoning: info.reasoning ?? null,
1070 serverTools: info.serverTools ?? null,
1071 requestMap: requestMapFor(provider.id, info),
1072 aliases: storedAliases(info.aliases),
1073 factSources: info.factSources ?? null,
1074 schemaEndpointId: info.schemaEndpointId ?? null,
1075 releasedAt: info.releasedAt ?? null,
1076 knowledgeCutoff: info.knowledgeCutoff ?? null,
1077 openWeights: info.openWeights ?? null,
1078 weightsUrl: info.weightsUrl ?? null,
1079 trainsOnRequestData: info.trainsOnRequestData ?? null,
1080 // A model that reappears (or upstream re-activates) clears
1081 // its deprecation; an upstream-deprecated one gains it.
1082 deprecatedAt:
1083 (info.deprecated ?? false) ? (existing.deprecatedAt ?? now) : null,
1084 })
1085 .where(eq(models.id, id))
1086
1087 await db.insert(changes).values({
1088 id: crypto.randomUUID(),
1089 type: 'model.updated',
1090 providerId: provider.id,
1091 subjectId: id,
1092 summary: `Model ${info.rawId} updated`,
1093 payload: modelUpdatedPayload(before, after, changed),
1094 createdAt: now,
1095 })
1096 outcome.updated++
1097 }
1098
1099 // Bump lastSeenAt for the unchanged majority, in small IN-lists.
1100 for (let i = 0; i < cleanIds.length; i += LAST_SEEN_CHUNK) {
1101 await db
1102 .update(models)
1103 .set({ lastSeenAt: now })
1104 .where(inArray(models.id, cleanIds.slice(i, i + LAST_SEEN_CHUNK)))
1105 }
1106
1107 // Backdates carry per-row values, so bulk-update via CASE. Five bound
1108 // params per row (two CASE arms + IN member) + one for lastSeenAt → 19
1109 // rows stays under the 100-param limit.
1110 for (let i = 0; i < backdates.length; i += 19) {
1111 const chunk = backdates.slice(i, i + 19)
1112 const arms = (value: (b: (typeof chunk)[number]) => number | null) =>
1113 sql.join(
1114 chunk.map((b) => sql`WHEN ${b.id} THEN ${value(b)}`),
1115 sql` `,
1116 )
1117 await db
1118 .update(models)
1119 .set({
1120 firstSeenAt: sql`CASE ${models.id} ${arms((b) => b.firstSeenAt)} END`,
1121 releasedAt: sql`CASE ${models.id} ${arms((b) => b.releasedAt)} END`,
1122 lastSeenAt: now,
1123 })
1124 .where(
1125 inArray(
1126 models.id,
1127 chunk.map((b) => b.id),
1128 ),
1129 )
1130 }
1131
1132 // Models in D1 the provider no longer lists → mark deprecated once.
1133 for (const existing of existingRows) {
1134 if (seenIds.has(existing.id) || existing.deprecatedAt !== null) continue
1135 await db
1136 .update(models)
1137 .set({ deprecatedAt: now })
1138 .where(eq(models.id, existing.id))
1139 await db.insert(changes).values({
1140 id: crypto.randomUUID(),
1141 type: 'model.removed',
1142 providerId: provider.id,
1143 subjectId: existing.id,
1144 summary: `Model ${existing.rawId} no longer listed`,
1145 createdAt: now,
1146 })
1147 outcome.removed++
1148 }
1149 if (deprecationIndex) {
1150 await applyDeprecations(db, provider.id, deprecationIndex, now)
1151 }
1152
1153 const live = existingRows.filter((row) => row.deprecatedAt === null).length
1154 const storm = updateStormOf(outcome.updated, live)
1155 await recordUpdateStorm(db, provider.id, storm, now)
1156 if (storm) {
1157 const error = `update storm: ${String(storm.updated)} of ${String(storm.live)} live rows`
1158 console.error(
1159 JSON.stringify({ job: 'models-poll', providerId: provider.id, error }),
1160 )
1161 noteIngest({
1162 event: 'update_storm',
1163 properties: {
1164 providerId: provider.id,
1165 updated: storm.updated,
1166 live: storm.live,
1167 },
1168 })
1169 }
1170
1171 await db
1172 .update(providers)
1173 .set({ lastPolledAt: now })
1174 .where(eq(providers.id, provider.id))
1175 await markModelsDevCatalogSettled(db, provider.id, now)
1176 await persistUpstreamIdentities(db, identities)
1177
1178 return outcome
1179}
1180
1181export { D1_WINDOW_WAIT_MS, d1WindowExhausted }
1182
1183/** Poll every registered provider with per-provider failure isolation. */
1184export async function pollAllProviders(
1185 deps: SyncDeps,
1186 registry: ReadonlyArray<ProviderConfig> = providerRegistry,
1187 wait: (ms: number) => Promise<void> = sleep,
1188): Promise<Array<PollOutcome>> {
1189 const outcomes: Array<PollOutcome> = []
1190 for (const provider of registry) {
1191 // A spent window is retried once (issue #635). The failure recorded
1192 // below is the second attempt, or a failure that was not a spent window.
1193 const exhausted = await runIngestScope(async () => {
1194 try {
1195 outcomes.push(
1196 await retryOnceAfterD1Window(
1197 'models-poll',
1198 provider.id,
1199 () => pollProviderModels(deps, provider),
1200 wait,
1201 ),
1202 )
1203 return false
1204 } catch (error) {
1205 const message = errorMessage(error)
1206 // Own log line per failure: the aggregate outcomes blob can exceed
1207 // what Workers Logs stores, which silently loses these errors.
1208 console.error(
1209 JSON.stringify({
1210 job: 'models-poll',
1211 providerId: provider.id,
1212 error: message,
1213 }),
1214 )
1215 noteIngest(ingestFailedEvent('models-poll', provider.id, message))
1216 outcomes.push({
1217 providerId: provider.id,
1218 modelsSeen: 0,
1219 added: 0,
1220 removed: 0,
1221 updated: 0,
1222 backdated: 0,
1223 failures: 1,
1224 error: message,
1225 })
1226 return d1WindowExhausted(message)
1227 } finally {
1228 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
1229 }
1230 })
1231 // The next provider would fail inside the same window.
1232 if (exhausted) await wait(D1_WINDOW_WAIT_MS)
1233 }
1234 // Links span providers, so resolve them once per run, outside any one
1235 // provider's outcome: a failure here must not read as every poll failing.
1236 await runIngestScope(async () => {
1237 try {
1238 await reconcileSameAs(
1239 deps.db,
1240 deps.now?.() ?? Math.floor(Date.now() / 1000),
1241 )
1242 } catch (error) {
1243 const message = errorMessage(error)
1244 console.error(
1245 JSON.stringify({ job: 'same-as-reconcile', error: message }),
1246 )
1247 noteIngest(ingestFailedEvent('same-as-reconcile', '*', message))
1248 } finally {
1249 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
1250 }
1251 })
1252 return outcomes
1253}