Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

poll-models.ts

1,151 lines39.8 KB

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