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

poll-models.ts

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