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

extract-fal-pricing.ts

1,000 lines31.7 KB

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