Open History to see the last commit
1/**
2 * Nightly FAL rate-card extract (issue #68): page candidate catalog rows,
3 * fetch each endpoint's llms.txt, hash-skip the Pricing section, and ask
4 * one model to write a RateCard. Own cron / admin route — not FAL's
5 * spec-sync shard. Chat token sections compile in `compileFalTokenCard`
6 * and the model poll stores those; this job still owns every other section.
7 */
8import { and, eq, inArray, isNull } from 'drizzle-orm'
9import { z } from 'zod'
10
11import {
12 cardParams,
13 rateCardSchema,
14 verifyExamples,
15} from '@modelschemas/rate-card'
16import type { RateCard } from '@modelschemas/rate-card'
17
18import { cacheMeta, changes, models, schemaVersions } from '#/db/schema.ts'
19import { errorMessage } from '#/server/errors.ts'
20import { falLlmsTxtUrl } from '#/server/providers/fal.ts'
21import { priceFalNamedSection, usdAmounts } from './fal-unit-rate.ts'
22import { markdownSection } from '#/server/providers/model-facts.ts'
23import { requestSchemaPropertyNames } from '#/server/providers/fact-sources.ts'
24import type { ModelFactSources } from '#/server/providers/types.ts'
25import { sha256Text } from '#/server/providers/types.ts'
26import {
27 cardRequestParamsOk,
28 parseStoredRateCard,
29 storeListedPricing,
30} from '#/server/rate-card.ts'
31import type { RateCardRefuse } from '#/server/rate-card.ts'
32import { changedFactPaths, modelUpdatedPayload } from './change-facts.ts'
33import {
34 captureIngestEvents,
35 ingestFailedEvent,
36 noteIngest,
37 runIngestScope,
38} from './ingest-signals.ts'
39import type { SyncDeps } from './sync.ts'
40
41/**
42 * Own invocations, after the 05:00–05:30 spec-sync shards. Six hourly
43 * firings so the whole FAL roster fits in one calendar day within the
44 * per-invocation subrequest budget. Keep in lockstep with `wrangler.jsonc`
45 * `triggers.crons` (unit-tested).
46 */
47export const FAL_PRICING_EXTRACT_CRONS = [
48 '0 6 * * *',
49 '0 7 * * *',
50 '0 8 * * *',
51 '0 9 * * *',
52 '0 10 * * *',
53 '0 11 * * *',
54] as const
55
56/** ~250 llms.txt fetches + leftovers stays well under the 1000 limit. */
57export const FAL_PRICING_FETCH_CAP = 250
58export const FAL_PRICING_EXTRACT_CAP = 40
59/** llms.txt fetches in flight at once. */
60export const FAL_PRICING_FETCH_CONCURRENCY = 20
61/** Extract calls in flight at once. */
62export const FAL_PRICING_EXTRACT_CONCURRENCY = 5
63/** Consecutive 408/429/5xx/network failures before the run stops walking. */
64export const FAL_PRICING_FETCH_FAIL_ABORT = 8
65
66export const FAL_PRICING_EXTRACT_CURSOR_KEY = 'fal-pricing-extract-cursor'
67
68export function falPricingExtractCursorKey(providerId = 'fal'): string {
69 return `${FAL_PRICING_EXTRACT_CURSOR_KEY}:${providerId}`
70}
71
72/** Single extract model — fail-closed; never a second guess. */
73export const FAL_PRICING_EXTRACT_MODEL = 'grok-4-fast'
74
75const XAI_CHAT_URL = 'https://api.x.ai/v1/chat/completions'
76
77const extractedBodySchema = rateCardSchema.omit({ source: true }).extend({
78 expiresAt: z.iso.datetime().optional(),
79})
80
81const extractedResponseSchema = z.union([
82 z.object({ unverified: z.literal(true) }),
83 extractedBodySchema,
84])
85
86export type FalPricingExtractRefuse = RateCardRefuse | 'unverified' | 'stub'
87
88export interface FalPricingExtractOutcome {
89 providerId: string
90 candidates: number
91 fetched: number
92 /** Cards built by the unit-rate parser, no model call. */
93 compiled: number
94 /** Rows filled by copying a card already known for that section hash. */
95 deduped: number
96 extracted: number
97 written: number
98 hashSkipped: number
99 refused: number
100 unverified: number
101 fetchFailed: number
102 cursor: string | null
103 skipped?: string
104 error?: string
105}
106
107/** `{ error }` = no card this run, and why (xAI HTTP error or empty reply, a throw, or two rejections). */
108export type ExtractedCard = RateCard | 'unverified' | { error: string }
109
110export interface ExtractCardArgs {
111 pricingText: string
112 requestProperties: ReadonlySet<string>
113 sourceUrl: string
114 sourceHash: string
115 now: number
116}
117
118/** string body, `null` = 404, `{ status }` for HTTP/network (`0` = network). */
119export type FalLlmsFetchResult = string | null | { status: number }
120
121export interface FalPricingExtractDeps extends SyncDeps {
122 fetchText?: (url: string) => Promise<FalLlmsFetchResult>
123 extractCard?: (args: ExtractCardArgs) => Promise<ExtractedCard>
124 fetchCap?: number
125 extractCap?: number
126 providerId?: string
127}
128
129function isRecord(value: unknown): value is Record<string, unknown> {
130 return typeof value === 'object' && value !== null && !Array.isArray(value)
131}
132
133export function pricingSection(llmsTxt: string): string {
134 return markdownSection(llmsTxt, 'Pricing').trim()
135}
136
137/**
138 * No positive dollar amount — empty, boilerplate, or zeros. Bold and
139 * suffix-`$` spellings (`$**0.04**`, `**0.17** $`) are real prices, not
140 * stubs (issue #70).
141 */
142export function isStubPricingSection(section: string): boolean {
143 return usdAmounts(section).length === 0
144}
145
146export async function pricingSectionHash(section: string): Promise<string> {
147 return sha256Text(section)
148}
149
150/**
151 * Index to resume from after `cursor` (the last processed rawId). Wraps
152 * when the cursor is the tail or no longer in the roster.
153 */
154export function resumeIndex(
155 rawIds: ReadonlyArray<string>,
156 cursor: string | null,
157): number {
158 if (rawIds.length === 0 || cursor === null) return 0
159 const exact = rawIds.indexOf(cursor)
160 if (exact >= 0) return (exact + 1) % rawIds.length
161 const next = rawIds.findIndex((id) => id > cursor)
162 return next < 0 ? 0 : next
163}
164
165/**
166 * Unchanged Pricing hash skips extract unless a promo `expiresAt` is
167 * already in the past, or the stored card is still null (an unverified
168 * leftover) and the section is not a stub — those retry every lap (#84).
169 */
170export function shouldSkipExtract(args: {
171 storedHash: string | null
172 sectionHash: string
173 hasCard: boolean
174 stub: boolean
175 expiresAt: string | undefined
176 now: number
177}): boolean {
178 if (args.storedHash !== args.sectionHash) return false
179 if (!args.hasCard && !args.stub) return false
180 if (args.expiresAt === undefined) return true
181 return Date.parse(args.expiresAt) > args.now * 1000
182}
183
184function factSourcesOf(value: unknown): ModelFactSources | null {
185 if (!isRecord(value)) return null
186 return value
187}
188
189function storedPricingHash(
190 card: RateCard | null,
191 sources: ModelFactSources | null,
192): string | null {
193 return sources?.pricing?.sourceHash ?? card?.source.hash ?? null
194}
195
196export function isRetryableLlmsStatus(status: number): boolean {
197 return status === 0 || status === 408 || status === 429 || status >= 500
198}
199
200function llmsFetchOutcome(
201 result: FalLlmsFetchResult,
202): { text: string } | { status: number } {
203 if (typeof result === 'string') return { text: result }
204 if (result === null) return { status: 404 }
205 return { status: result.status }
206}
207
208async function fetchLlmsTxt(url: string): Promise<FalLlmsFetchResult> {
209 try {
210 const response = await fetch(url)
211 if (!response.ok) return { status: response.status }
212 return await response.text()
213 } catch {
214 return { status: 0 }
215 }
216}
217
218function logFetchFailure(
219 providerId: string,
220 rawId: string,
221 status: number,
222): void {
223 console.error(
224 JSON.stringify({
225 job: 'fal-pricing-extract',
226 providerId,
227 rawId,
228 error: 'llms_txt_fetch_failed',
229 status,
230 }),
231 )
232}
233
234function chatContent(data: unknown): string | null {
235 if (!isRecord(data)) return null
236 const choices = data.choices
237 if (!Array.isArray(choices)) return null
238 const first: unknown = choices[0]
239 if (!isRecord(first)) return null
240 const message = first.message
241 if (!isRecord(message) || typeof message.content !== 'string') return null
242 return message.content
243}
244
245function parseJsonObject(text: string): unknown {
246 const trimmed = text.trim()
247 const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(trimmed)
248 const body = fenced?.[1] ?? trimmed
249 return JSON.parse(body) as unknown
250}
251
252const EXTRACT_SYSTEM = `You write a modelschemas RateCard — a price calculator — from a FAL model's llms.txt Pricing section.
253Return JSON only: {"inputs": {...}, "tables": {...}, "price": <JSONLogic>, "examples": [...]}, optionally "expiresAt" (ISO datetime) when the text names a promo end. Do not include a source object.
254
255inputs: name → {"param": <field>, "kind": "number"|"enum"|"boolean"|"count", "bound": "request"|"usage", "default"?: ..., "values"?: [...] (enum only)}.
256- A request-bound param MUST be one of the allowed request properties (or a dotted child of one). Give it a default when the request may omit it.
257- A quantity the request cannot state (seconds of output, megapixels, characters, tokens) is "bound": "usage" — never invent a request field.
258- So is a priced choice no allowed property sets (an output resolution the request has no field for): a "bound": "usage" enum the caller states, with no default.
259tables: name → nested {key: number}, read with {"lookup": {"table": name, "keys": [{"var": input}]}}.
260price: JSONLogic over var, +, -, *, /, max, min, if, ==, !=, <, <=, >, >=, and, or, ceil, floor, lookup. {"var": x} reads the input named x. "==" is strict: compare enum inputs to strings.
261examples: [{"params": {param: value}, "usd": number, "quote": text copied verbatim from the section}]. The card is rejected unless evaluating price on each example's params reproduces usd within 1%.
262
263Rules:
264- If the section names ANY positive dollar amount you MUST write a card. Several prices, multipliers, add-ons and per-resolution / per-duration tables are what this format is for: combine them with *, +, if and lookup.
265- Quoted rates ARE worked numbers: synthesize one example per stated rate. "$0.08 per image" → params {"num_images": 1}, usd 0.08. "per 1000 characters" → 1000 units at the quoted price. "2K at 1.5 times" → params {"resolution": "2K"}, usd 0.12. "an additional $0.015 if web search is used" → params {"enable_web_search": true}, usd 0.095.
266- Prefer the page's own worked total when it states one ("a 5 second video costs $0.70").
267- Return {"unverified": true} ONLY when the section names no positive price (empty, zeros, or "see pricing page" boilerplate).
268
269Example. Section: "Your request will cost $0.08 per image. 2K outputs are charged at 1.5 times the standard rate. If web search is used, an additional $0.015 will be charged." Allowed: num_images, resolution, enable_web_search.
270{"inputs":{"num_images":{"param":"num_images","kind":"number","bound":"request","default":1},"resolution":{"param":"resolution","kind":"enum","bound":"request","values":["1K","2K"],"default":"1K"},"enable_web_search":{"param":"enable_web_search","kind":"boolean","bound":"request","default":false}},"tables":{"multiplier":{"1K":1,"2K":1.5}},"price":{"+":[{"*":[{"var":"num_images"},0.08,{"lookup":{"table":"multiplier","keys":[{"var":"resolution"}]}}]},{"if":[{"var":"enable_web_search"},0.015,0]}]},"examples":[{"params":{"num_images":1},"usd":0.08,"quote":"Your request will cost $0.08 per image"},{"params":{"resolution":"2K"},"usd":0.12,"quote":"2K outputs are charged at 1.5 times the standard rate"},{"params":{"enable_web_search":true},"usd":0.095,"quote":"If web search is used, an additional $0.015 will be charged"}]}`
271
272function extractUserPrompt(
273 pricingText: string,
274 requestProperties: ReadonlySet<string>,
275): string {
276 const allowed = [...requestProperties].sort().join(', ')
277 return `Allowed request properties: ${allowed || '(none)'}
278
279Pricing section:
280${pricingText}`
281}
282
283function withSource(
284 body: z.infer<typeof extractedBodySchema>,
285 args: ExtractCardArgs,
286): RateCard {
287 const { expiresAt, ...rest } = body
288 return {
289 ...rest,
290 source: {
291 url: args.sourceUrl,
292 hash: args.sourceHash,
293 extractedAt: new Date(args.now * 1000).toISOString(),
294 ...(expiresAt !== undefined ? { expiresAt } : {}),
295 },
296 }
297}
298
299/**
300 * The model's reply as a card, `'unverified'`, or why it was rejected.
301 * `{unverified: true}` and an example-less card are only legal for a
302 * section that names no price (#88) — a priced section must become a card.
303 */
304export function checkExtractedCard(
305 content: string,
306 args: ExtractCardArgs,
307): RateCard | 'unverified' | { error: string } {
308 let json: unknown
309 try {
310 json = parseJsonObject(content)
311 } catch {
312 return { error: 'reply is not JSON' }
313 }
314 const parsed = extractedResponseSchema.safeParse(json)
315 if (!parsed.success) {
316 return { error: `not a RateCard: ${z.prettifyError(parsed.error)}` }
317 }
318 const priced = !isStubPricingSection(args.pricingText)
319 if ('unverified' in parsed.data || parsed.data.examples.length === 0) {
320 return priced
321 ? {
322 error: `the section names ${usdAmounts(args.pricingText)
323 .map((usd) => `$${usd}`)
324 .join(', ')}; write the card with one example per quoted rate`,
325 }
326 : 'unverified'
327 }
328 const card = withSource(parsed.data, args)
329 if (!cardRequestParamsOk(card, args.requestProperties)) {
330 return {
331 error:
332 'a request-bound input param is not an allowed request property; bind it to an allowed property or make it "bound": "usage"',
333 }
334 }
335 // A usage-bound choice (output resolution) is the caller's to state; a
336 // default would price a guess (#304). Number defaults (an add-on's 0)
337 // stay legal, as on compiled token cards.
338 const usageDefaults = Object.entries(card.inputs)
339 .filter(
340 ([, input]) =>
341 input.bound === 'usage' && input.kind === 'enum' && 'default' in input,
342 )
343 .map(([name]) => name)
344 if (usageDefaults.length > 0) {
345 return {
346 error: `usage-bound enums have a default (${usageDefaults.join(', ')}); the caller states them — remove the default`,
347 }
348 }
349 const failed = verifyExamples(card).filter((result) => !result.ok)
350 if (failed.length > 0) {
351 return {
352 error: `verifyExamples failed: ${failed
353 .map((r) => `${JSON.stringify(r.example.params)} → ${r.error}`)
354 .join('; ')}`,
355 }
356 }
357 return card
358}
359
360type ChatMessage = { role: 'system' | 'user' | 'assistant'; content: string }
361
362async function grokChat(
363 apiKey: string,
364 messages: Array<ChatMessage>,
365): Promise<string | { error: string }> {
366 const response = await fetch(XAI_CHAT_URL, {
367 method: 'POST',
368 headers: {
369 Authorization: `Bearer ${apiKey}`,
370 'Content-Type': 'application/json',
371 },
372 body: JSON.stringify({
373 model: FAL_PRICING_EXTRACT_MODEL,
374 temperature: 0,
375 response_format: { type: 'json_object' },
376 messages,
377 }),
378 })
379 if (!response.ok) {
380 const body = (await response.text()).slice(0, 200)
381 return { error: `xai ${response.status}: ${body}` }
382 }
383 return (
384 chatContent((await response.json()) as unknown) ?? {
385 error: 'xai reply has no message content',
386 }
387 )
388}
389
390/**
391 * One model, at most two turns: a rejected card goes back once with the
392 * reason (same model — not a fallback). `{ error }` = no card this run; the
393 * caller holds the cursor so the next shard retries it, and reports why.
394 */
395export async function extractRateCardWithGrok(
396 args: ExtractCardArgs & { apiKey: string },
397): Promise<ExtractedCard> {
398 const messages: Array<ChatMessage> = [
399 { role: 'system', content: EXTRACT_SYSTEM },
400 {
401 role: 'user',
402 content: extractUserPrompt(args.pricingText, args.requestProperties),
403 },
404 ]
405 try {
406 let rejected = ''
407 for (let turn = 0; turn < 2; turn++) {
408 const content = await grokChat(args.apiKey, messages)
409 if (typeof content !== 'string') return content
410 const checked = checkExtractedCard(content, args)
411 if (checked === 'unverified' || !('error' in checked)) return checked
412 rejected = checked.error
413 messages.push(
414 { role: 'assistant', content },
415 {
416 role: 'user',
417 content: `Rejected: ${checked.error}. Return the corrected full JSON.`,
418 },
419 )
420 }
421 return { error: `rejected twice: ${rejected.slice(0, 200)}` }
422 } catch (error) {
423 return { error: errorMessage(error) }
424 }
425}
426
427function logRefusal(
428 providerId: string,
429 rawId: string,
430 reason: FalPricingExtractRefuse,
431): void {
432 console.error(
433 JSON.stringify({
434 job: 'fal-pricing-extract',
435 providerId,
436 rawId,
437 error: 'rate_card_refused',
438 reason,
439 }),
440 )
441 noteIngest({
442 event: 'rate_card_refused',
443 properties: { providerId, rawId, reason },
444 })
445}
446
447/** Cursor and held rawId live in `cache_meta.lastError` under their own keys. */
448async function loadCursor(
449 db: SyncDeps['db'],
450 key: string,
451): Promise<string | null> {
452 const row = await db.query.cacheMeta.findFirst({
453 where: eq(cacheMeta.key, key),
454 })
455 const cursor = row?.lastError
456 return cursor && cursor.length > 0 ? cursor : null
457}
458
459async function saveCursor(
460 db: SyncDeps['db'],
461 key: string,
462 cursor: string,
463 now: number,
464): Promise<void> {
465 await db
466 .insert(cacheMeta)
467 .values({
468 key,
469 fetchedAt: now,
470 staleTime: 0,
471 lastError: cursor,
472 })
473 .onConflictDoUpdate({
474 target: cacheMeta.key,
475 set: { fetchedAt: now, lastError: cursor },
476 })
477}
478
479interface Candidate {
480 id: string
481 rawId: string
482 pricing: unknown
483 factSources: unknown
484 schemaEndpointId: string | null
485 boundId: string
486}
487
488async function loadCandidates(
489 db: SyncDeps['db'],
490 providerId: string,
491): Promise<Array<Candidate>> {
492 const rows = await db
493 .select({
494 id: models.id,
495 rawId: models.rawId,
496 pricing: models.pricing,
497 factSources: models.factSources,
498 schemaEndpointId: models.schemaEndpointId,
499 })
500 .from(models)
501 .where(and(eq(models.providerId, providerId), isNull(models.deprecatedAt)))
502 const candidates: Array<Candidate> = []
503 for (const row of rows) {
504 const boundId = row.schemaEndpointId ?? row.rawId
505 candidates.push({ ...row, boundId })
506 }
507 candidates.sort((a, b) =>
508 a.rawId < b.rawId ? -1 : a.rawId > b.rawId ? 1 : 0,
509 )
510 return candidates
511}
512
513async function loadRequestProperties(
514 db: SyncDeps['db'],
515 providerId: string,
516 boundIds: ReadonlyArray<string>,
517): Promise<Map<string, Set<string>>> {
518 const properties = new Map<string, Set<string>>()
519 const dbIds = [...new Set(boundIds)].map((id) => `${providerId}/${id}`)
520 for (let i = 0; i < dbIds.length; i += 90) {
521 const chunk = dbIds.slice(i, i + 90)
522 const versions = await db
523 .select({
524 endpointId: schemaVersions.endpointId,
525 schema: schemaVersions.schema,
526 })
527 .from(schemaVersions)
528 .where(
529 and(
530 inArray(schemaVersions.endpointId, chunk),
531 eq(schemaVersions.kind, 'input'),
532 isNull(schemaVersions.supersededAt),
533 ),
534 )
535 const prefix = `${providerId}/`
536 for (const version of versions) {
537 const publicId = version.endpointId.startsWith(prefix)
538 ? version.endpointId.slice(prefix.length)
539 : version.endpointId
540 const parsed: unknown = JSON.parse(version.schema)
541 properties.set(publicId, requestSchemaPropertyNames(parsed))
542 }
543 }
544 return properties
545}
546
547function docsExtractedSource(sources: ModelFactSources | null): {
548 derivation: 'docs-extracted'
549 sourceUrl?: string
550 sourceHash?: string
551 fetchedAt?: number
552} {
553 return {
554 derivation: 'docs-extracted',
555 ...(sources?.pricing?.sourceUrl
556 ? { sourceUrl: sources.pricing.sourceUrl }
557 : {}),
558 ...(sources?.pricing?.sourceHash
559 ? { sourceHash: sources.pricing.sourceHash }
560 : {}),
561 ...(sources?.pricing?.fetchedAt !== undefined
562 ? { fetchedAt: sources.pricing.fetchedAt }
563 : {}),
564 }
565}
566
567async function writePricing(args: {
568 db: SyncDeps['db']
569 providerId: string
570 candidate: Candidate
571 card: RateCard | null
572 sourceUrl: string
573 sourceHash: string
574 now: number
575}): Promise<boolean> {
576 const prior = factSourcesOf(args.candidate.factSources)
577 const nextSources: ModelFactSources = {
578 ...(prior ?? {}),
579 pricing: {
580 derivation: 'docs-extracted',
581 sourceUrl: args.sourceUrl,
582 sourceHash: args.sourceHash,
583 fetchedAt: args.now,
584 },
585 }
586 const before = { pricing: args.candidate.pricing }
587 const after = { pricing: args.card }
588 const changed = changedFactPaths(before, after)
589 await args.db
590 .update(models)
591 .set({
592 // A stamp or an operand reorder is not a new card. The stored source
593 // stays the read on which the price last changed.
594 ...(changed.length > 0 ? { pricing: args.card } : {}),
595 factSources: nextSources,
596 })
597 .where(eq(models.id, args.candidate.id))
598 if (changed.length === 0) return false
599 await args.db.insert(changes).values({
600 id: crypto.randomUUID(),
601 type: 'model.updated',
602 providerId: args.providerId,
603 subjectId: args.candidate.id,
604 summary: `Model ${args.candidate.rawId} updated`,
605 payload: modelUpdatedPayload(before, after, changed),
606 createdAt: args.now,
607 })
608 return true
609}
610
611async function stampPricingHash(args: {
612 db: SyncDeps['db']
613 candidate: Candidate
614 sourceUrl: string
615 sourceHash: string
616 now: number
617}): Promise<void> {
618 const prior = factSourcesOf(args.candidate.factSources)
619 await args.db
620 .update(models)
621 .set({
622 factSources: {
623 ...(prior ?? {}),
624 pricing: {
625 ...docsExtractedSource(prior),
626 derivation: 'docs-extracted',
627 sourceUrl: args.sourceUrl,
628 sourceHash: args.sourceHash,
629 fetchedAt: args.now,
630 },
631 },
632 })
633 .where(eq(models.id, args.candidate.id))
634}
635
636/** Run `fn` over `items` with at most `limit` in flight, preserving order. */
637async function mapLimit<T, TResult>(
638 items: ReadonlyArray<T>,
639 limit: number,
640 fn: (item: T) => Promise<TResult>,
641): Promise<Array<TResult>> {
642 const out = new Array<TResult>(items.length)
643 let next = 0
644 const workers = Array.from(
645 { length: Math.min(limit, items.length) },
646 async () => {
647 for (let i = next++; i < items.length; i = next++) {
648 out[i] = await fn(items[i] as T)
649 }
650 },
651 )
652 await Promise.all(workers)
653 return out
654}
655
656interface LeftoverGroup {
657 section: string
658 sourceUrl: string
659 rows: Array<Candidate>
660}
661
662export async function extractFalPricing(
663 deps: FalPricingExtractDeps,
664): Promise<FalPricingExtractOutcome> {
665 return runIngestScope(() => extractFalPricingScoped(deps))
666}
667
668async function extractFalPricingScoped(
669 deps: FalPricingExtractDeps,
670): Promise<FalPricingExtractOutcome> {
671 const providerId = deps.providerId ?? 'fal'
672 const now = deps.now?.() ?? Math.floor(Date.now() / 1000)
673 const fetchCap = deps.fetchCap ?? FAL_PRICING_FETCH_CAP
674 const extractCap = deps.extractCap ?? FAL_PRICING_EXTRACT_CAP
675 const outcome: FalPricingExtractOutcome = {
676 providerId,
677 candidates: 0,
678 fetched: 0,
679 compiled: 0,
680 deduped: 0,
681 extracted: 0,
682 written: 0,
683 hashSkipped: 0,
684 refused: 0,
685 unverified: 0,
686 fetchFailed: 0,
687 cursor: null,
688 }
689
690 const apiKey = deps.secrets.XAI_API_KEY
691 const extract =
692 deps.extractCard ??
693 (apiKey
694 ? (args: ExtractCardArgs) => extractRateCardWithGrok({ ...args, apiKey })
695 : null)
696
697 try {
698 const all = await loadCandidates(deps.db, providerId)
699 const properties = await loadRequestProperties(
700 deps.db,
701 providerId,
702 all.map((row) => row.boundId),
703 )
704 // A missing input schema still gets a usage-bound unit card. Rows with
705 // no activity (3d, vision, json) are catalog models too (#114).
706 const candidates = all
707 outcome.candidates = candidates.length
708 if (candidates.length === 0) return outcome
709
710 // Cards already stored against a Pricing-section hash — reused across
711 // rows in this run and across nights, so the model is never asked
712 // twice for the same text. Several per hash: endpoints sharing one
713 // section can have different request schemas (#304), and a card is only
714 // copied onto a row whose schema has every request param it binds.
715 const byHash = new Map<string, Array<RateCard>>()
716 const remember = (hash: string, card: RateCard): void => {
717 const cards = byHash.get(hash)
718 if (cards) cards.push(card)
719 else byHash.set(hash, [card])
720 }
721 for (const row of candidates) {
722 const card = parseStoredRateCard(row.pricing)
723 // A promo card past its expiresAt must be re-read, not copied on.
724 if (!card) continue
725 const expiresAt = card.source.expiresAt
726 if (expiresAt !== undefined && Date.parse(expiresAt) <= now * 1000) {
727 continue
728 }
729 remember(card.source.hash, card)
730 }
731
732 const requestPropertiesOf = (candidate: Candidate): ReadonlySet<string> =>
733 properties.get(candidate.boundId) ?? new Set<string>()
734
735 const applyCard = async (
736 candidate: Candidate,
737 card: RateCard,
738 sourceUrl: string,
739 sectionHash: string,
740 ): Promise<boolean> => {
741 const stamped: RateCard = {
742 ...card,
743 source: {
744 ...card.source,
745 url: sourceUrl,
746 hash: sectionHash,
747 extractedAt: new Date(now * 1000).toISOString(),
748 },
749 }
750 const stored = await storeListedPricing(stamped, {
751 existing: candidate.pricing,
752 requestProperties: requestPropertiesOf(candidate),
753 sourceUrl,
754 now,
755 })
756 if (stored.refused || stored.card === null) {
757 outcome.refused++
758 logRefusal(
759 providerId,
760 candidate.rawId,
761 stored.refused ?? 'uncompilable',
762 )
763 return false
764 }
765 if (
766 await writePricing({
767 db: deps.db,
768 providerId,
769 candidate,
770 card: stored.card,
771 sourceUrl,
772 sourceHash: sectionHash,
773 now,
774 })
775 ) {
776 outcome.written++
777 }
778 return true
779 }
780
781 const rawIds = candidates.map((row) => row.rawId)
782 const cursorKey = falPricingExtractCursorKey(providerId)
783 const heldKey = `${cursorKey}:held`
784 const cursor = await loadCursor(deps.db, cursorKey)
785 const start = resumeIndex(rawIds, cursor)
786 const order = [...candidates.slice(start), ...candidates.slice(0, start)]
787
788 // Held in an object: `mark` assigns it from a closure, where TS's
789 // control-flow analysis would otherwise keep narrowing it to null.
790 const walked: { last: string | null } = { last: null }
791 let consecutiveFetchFails = 0
792 let cursorFrozen = false
793 const fetchLlms = deps.fetchText ?? fetchLlmsTxt
794 const leftovers = new Map<string, LeftoverGroup>()
795 // Each queued leftover row → the cursor just before it, in walk order,
796 // so a failed extract can rewind the cursor onto it.
797 const cursorBefore = new Map<string, string | null>()
798
799 // llms.txt is pure I/O — fetch a window ahead so a shard is not 250
800 // sequential round trips. Order of processing is unchanged.
801 const buffer = new Map<number, FalLlmsFetchResult>()
802 const fetchAt = async (i: number): Promise<FalLlmsFetchResult> => {
803 const cached = buffer.get(i)
804 if (cached !== undefined) return cached
805 const width = Math.max(
806 1,
807 Math.min(FAL_PRICING_FETCH_CONCURRENCY, fetchCap - i, order.length - i),
808 )
809 const results = await Promise.all(
810 order
811 .slice(i, i + width)
812 .map((row) => fetchLlms(falLlmsTxtUrl(row.rawId))),
813 )
814 results.forEach((result, k) => buffer.set(i + k, result))
815 return results[0] as FalLlmsFetchResult
816 }
817
818 for (let i = 0; i < order.length && outcome.fetched < fetchCap; i++) {
819 const candidate = order[i] as Candidate
820 const mark = (): void => {
821 if (!cursorFrozen) walked.last = candidate.rawId
822 }
823
824 const sourceUrl = falLlmsTxtUrl(candidate.rawId)
825 const fetched = llmsFetchOutcome(await fetchAt(i))
826 outcome.fetched++
827
828 if ('status' in fetched) {
829 logFetchFailure(providerId, candidate.rawId, fetched.status)
830 outcome.fetchFailed++
831 if (isRetryableLlmsStatus(fetched.status)) {
832 consecutiveFetchFails++
833 cursorFrozen = true
834 if (consecutiveFetchFails >= FAL_PRICING_FETCH_FAIL_ABORT) break
835 continue
836 }
837 consecutiveFetchFails = 0
838 mark()
839 continue
840 }
841
842 consecutiveFetchFails = 0
843 const section = pricingSection(fetched.text)
844 const sectionHash = await pricingSectionHash(section)
845 const existingCard = parseStoredRateCard(candidate.pricing)
846 const sources = factSourcesOf(candidate.factSources)
847 const stub = isStubPricingSection(section)
848 if (
849 shouldSkipExtract({
850 storedHash: storedPricingHash(existingCard, sources),
851 sectionHash,
852 hasCard: existingCard !== null,
853 stub,
854 expiresAt: existingCard?.source.expiresAt,
855 now,
856 })
857 ) {
858 outcome.hashSkipped++
859 mark()
860 continue
861 }
862
863 if (stub) {
864 logRefusal(providerId, candidate.rawId, 'stub')
865 outcome.refused++
866 if (
867 await writePricing({
868 db: deps.db,
869 providerId,
870 candidate,
871 card: null,
872 sourceUrl,
873 sourceHash: sectionHash,
874 now,
875 })
876 ) {
877 outcome.written++
878 }
879 mark()
880 continue
881 }
882
883 // Of the cards that fit, the one reading the most from the request:
884 // a sibling's usage-bound `resolution` must not shadow this row's
885 // request field.
886 const known = (byHash.get(sectionHash) ?? [])
887 .filter((card) =>
888 cardRequestParamsOk(card, requestPropertiesOf(candidate)),
889 )
890 .sort(
891 (a, b) => cardParams(b).request.length - cardParams(a).request.length,
892 )[0]
893 if (known) {
894 outcome.deduped++
895 await applyCard(candidate, known, sourceUrl, sectionHash)
896 mark()
897 continue
898 }
899
900 const compiled = priceFalNamedSection(
901 section,
902 requestPropertiesOf(candidate),
903 {
904 url: sourceUrl,
905 hash: sectionHash,
906 extractedAt: new Date(now * 1000).toISOString(),
907 },
908 )
909 if (compiled) {
910 outcome.compiled++
911 remember(sectionHash, compiled)
912 await applyCard(candidate, compiled, sourceUrl, sectionHash)
913 mark()
914 continue
915 }
916
917 const group = leftovers.get(sectionHash)
918 if (group) {
919 group.rows.push(candidate)
920 cursorBefore.set(candidate.rawId, walked.last)
921 mark()
922 continue
923 }
924 // The cap counts distinct sections, not rows — a row joining a
925 // section already queued is free. Past the cap, keep walking so the
926 // rest of the fetch window still compiles/dedups/stamps, but freeze
927 // the cursor so the next shard resumes on this row (#84).
928 if (leftovers.size >= extractCap) {
929 cursorFrozen = true
930 continue
931 }
932 leftovers.set(sectionHash, { section, sourceUrl, rows: [candidate] })
933 cursorBefore.set(candidate.rawId, walked.last)
934 mark()
935 }
936
937 // Everything the parser could not stand behind: one extract call per
938 // distinct Pricing section, then copied onto every row sharing it.
939 const failed = new Set<string>()
940 const reasons = new Set<string>()
941 if (leftovers.size > 0 && extract === null) {
942 outcome.skipped = 'XAI_API_KEY not set — leftovers skipped'
943 } else if (leftovers.size > 0 && extract !== null) {
944 const groups = [...leftovers.entries()]
945 const results = await mapLimit(
946 groups,
947 FAL_PRICING_EXTRACT_CONCURRENCY,
948 async ([hash, group]) => {
949 outcome.extracted++
950 return await extract({
951 pricingText: group.section,
952 requestProperties: requestPropertiesOf(group.rows[0] as Candidate),
953 sourceUrl: group.sourceUrl,
954 sourceHash: hash,
955 now,
956 })
957 },
958 )
959
960 for (const [index, [hash, group]] of groups.entries()) {
961 const result = results[index]
962 if (
963 result === 'unverified' ||
964 (result !== undefined &&
965 !('error' in result) &&
966 result.examples.length === 0)
967 ) {
968 for (const row of group.rows) {
969 outcome.unverified++
970 logRefusal(providerId, row.rawId, 'unverified')
971 await stampPricingHash({
972 db: deps.db,
973 candidate: row,
974 sourceUrl: falLlmsTxtUrl(row.rawId),
975 sourceHash: hash,
976 now,
977 })
978 }
979 continue
980 }
981 const card = result === undefined || 'error' in result ? null : result
982 if (result !== undefined && 'error' in result) reasons.add(result.error)
983 if (card) remember(hash, card)
984 for (const row of group.rows) {
985 const sourceUrl = falLlmsTxtUrl(row.rawId)
986 if (card && (await applyCard(row, card, sourceUrl, hash))) {
987 continue
988 }
989 if (card) {
990 reasons.add(
991 `card extracted for ${(group.rows[0] as Candidate).rawId} refused for ${row.rawId}`,
992 )
993 }
994 if (!card) {
995 outcome.refused++
996 logRefusal(providerId, row.rawId, 'uncompilable')
997 }
998 failed.add(row.rawId)
999 // Stamp so the row is not left unwritten; a card it already
1000 // has is kept, and its old hash keeps it due for a retry.
1001 if (parseStoredRateCard(row.pricing) === null) {
1002 await stampPricingHash({
1003 db: deps.db,
1004 candidate: row,
1005 sourceUrl,
1006 sourceHash: hash,
1007 now,
1008 })
1009 }
1010 }
1011 }
1012 }
1013
1014 // A leftover with no card this run rewinds the cursor onto itself so
1015 // the next shard retries it (#88). Only once: a row that fails again
1016 // while already held moves on and waits for the next lap, so one bad
1017 // page cannot stall the walk.
1018 let last = walked.last
1019 if (failed.size > 0) {
1020 noteIngest(
1021 ingestFailedEvent(
1022 'fal-pricing-extract',
1023 providerId,
1024 [
1025 `leftover retry: ${failed.size}`,
1026 ...[...reasons].slice(0, 3),
1027 ...(reasons.size > 3 ? [`+${reasons.size - 3} more`] : []),
1028 ].join(' | '),
1029 ),
1030 )
1031 const held = await loadCursor(deps.db, heldKey)
1032 const retry = [...cursorBefore.keys()].find(
1033 (rawId) => failed.has(rawId) && rawId !== held,
1034 )
1035 if (retry !== undefined) {
1036 // null: nothing was walked before it — the stored cursor already
1037 // sits just before it.
1038 last = cursorBefore.get(retry) ?? null
1039 await saveCursor(deps.db, heldKey, retry, now)
1040 }
1041 }
1042 if (last !== null) {
1043 await saveCursor(deps.db, cursorKey, last, now)
1044 outcome.cursor = last
1045 } else {
1046 outcome.cursor = cursor
1047 }
1048 return outcome
1049 } catch (error) {
1050 outcome.error = errorMessage(error)
1051 console.error(
1052 JSON.stringify({
1053 job: 'fal-pricing-extract',
1054 providerId,
1055 error: outcome.error,
1056 }),
1057 )
1058 noteIngest(
1059 ingestFailedEvent('fal-pricing-extract', providerId, outcome.error),
1060 )
1061 return outcome
1062 } finally {
1063 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
1064 }
1065}