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

extract-fal-pricing.ts

1,154 lines39.2 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 { createAnthropicChat } from '@tanstack/ai-anthropic'
10import { cloudflareBindingFetch } from '@tanstack/ai-cloudflare'
11import { chat } from '@tanstack/ai'
12import { z } from 'zod'
13​
14import { cardParams, verifyExamples } from '@modelschemas/rate-card'
15import { rateCardSchema } from '@modelschemas/rate-card/schema'
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}`
71​
72/**
73 * Single extract model — fail-closed; never a second guess. Picked by
74 * `scripts/compare-fal-extract-models.ts` (#550). Anthropic's id, which the
75 * adapter needs for its model table; `GATEWAY_MODEL_IDS` names it on the wire.
76 */
77export const FAL_PRICING_EXTRACT_MODEL = 'claude-sonnet-5-5'
78​
79/**
80 * Cloudflare's catalog id for each Anthropic id (#556): the gateway knows
81 * `anthropic/claude-sonnet-5.5` and 500s on Anthropic's `claude-sonnet-5-5`.
82 * The binding fetch adds the `anthropic/` prefix.
83 */
84export const GATEWAY_MODEL_IDS = {
85 'claude-sonnet-5-5': 'claude-sonnet-5.5',
86 'claude-haiku-5-5': 'claude-haiku-5.5',
87} as const
88​
89const extractedBodySchema = rateCardSchema.omit({ source: true }).extend({
90 expiresAt: z.iso.datetime().optional(),
91})
92​
93const extractedResponseSchema = z.union([
94 // expiresAt: the section's only price is a promo that ended then (#552).
95 z.object({
96 unverified: z.literal(true),
97 expiresAt: z.iso.datetime().optional(),
98 }),
99 extractedBodySchema,
100])
101​
102export type FalPricingExtractRefuse = RateCardRefuse | 'unverified' | 'stub'
103​
104export interface FalPricingExtractOutcome {
105 providerId: string
106 candidates: number
107 fetched: number
108 /** Cards built by the unit-rate parser, no model call. */
109 compiled: number
110 /** Rows filled by copying a card already known for that section hash. */
111 deduped: number
112 extracted: number
113 written: number
114 hashSkipped: number
115 refused: number
116 unverified: number
117 fetchFailed: number
118 cursor: string | null
119 skipped?: string
120 error?: string
122​
123/** `{ error }` = no card this run, and why (gateway error or empty reply, a throw, or two rejections). */
124export type ExtractedCard = RateCard | 'unverified' | { error: string }
125​
126export interface ExtractCardArgs {
127 pricingText: string
128 requestProperties: ReadonlySet<string>
129 sourceUrl: string
130 sourceHash: string
131 now: number
133​
134/** string body, `null` = 404, `{ status }` for HTTP/network (`0` = network). */
135export type FalLlmsFetchResult = string | null | { status: number }
136​
137export interface FalPricingExtractDeps extends SyncDeps {
138 fetchText?: (url: string) => Promise<FalLlmsFetchResult>
139 extractCard?: (args: ExtractCardArgs) => Promise<ExtractedCard>
140 /** Workers AI binding + AI Gateway id; both unset = leftovers skipped. */
141 ai?: Ai
142 gatewayId?: string
143 fetchCap?: number
144 extractCap?: number
145 providerId?: string
147​
148function isRecord(value: unknown): value is Record<string, unknown> {
149 return typeof value === 'object' && value !== null && !Array.isArray(value)
151​
152export function pricingSection(llmsTxt: string): string {
153 return markdownSection(llmsTxt, 'Pricing').trim()
155​
156/**
157 * No positive dollar amount — empty, boilerplate, or zeros. Bold and
158 * suffix-`$` spellings (`$**0.04**`, `**0.17** $`) are real prices, not
159 * stubs (issue #70).
160 */
161/** A section that names a promo or its end; only these may answer "ended". */
162const PROMO_WORDS =
163 /\b(?:promo(?:tion(?:al)?)?|limited[- ]time|until|through|ends?|expires?)\b/i
164​
165export function isStubPricingSection(section: string): boolean {
166 return usdAmounts(section).length === 0
168​
169export async function pricingSectionHash(section: string): Promise<string> {
170 return sha256Text(section)
172​
173/**
174 * Index to resume from after `cursor` (the last processed rawId). Wraps
175 * when the cursor is the tail or no longer in the roster.
176 */
177export function resumeIndex(
178 rawIds: ReadonlyArray<string>,
179 cursor: string | null,
180): number {
181 if (rawIds.length === 0 || cursor === null) return 0
182 const exact = rawIds.indexOf(cursor)
183 if (exact >= 0) return (exact + 1) % rawIds.length
184 const next = rawIds.findIndex((id) => id > cursor)
185 return next < 0 ? 0 : next
187​
188/**
189 * Unchanged Pricing hash skips extract unless a promo `expiresAt` is
190 * already in the past, or the stored card is still null (an unverified
191 * leftover) and the section is not a stub — those retry every lap (#84).
192 */
193export function shouldSkipExtract(args: {
194 storedHash: string | null
195 sectionHash: string
196 hasCard: boolean
197 stub: boolean
198 expiresAt: string | undefined
199 now: number
200}): boolean {
201 if (args.storedHash !== args.sectionHash) return false
202 if (!args.hasCard && !args.stub) return false
203 if (args.expiresAt === undefined) return true
204 return Date.parse(args.expiresAt) > args.now * 1000
206​
207function factSourcesOf(value: unknown): ModelFactSources | null {
208 if (!isRecord(value)) return null
209 return value
211​
212function storedPricingHash(
213 card: RateCard | null,
214 sources: ModelFactSources | null,
215): string | null {
216 return sources?.pricing?.sourceHash ?? card?.source.hash ?? null
218​
219export function isRetryableLlmsStatus(status: number): boolean {
220 return status === 0 || status === 408 || status === 429 || status >= 500
222​
223function llmsFetchOutcome(
224 result: FalLlmsFetchResult,
225): { text: string } | { status: number } {
226 if (typeof result === 'string') return { text: result }
227 if (result === null) return { status: 404 }
228 return { status: result.status }
230​
231async function fetchLlmsTxt(url: string): Promise<FalLlmsFetchResult> {
232 try {
233 const response = await fetch(url)
234 if (!response.ok) return { status: response.status }
235 return await response.text()
236 } catch {
237 return { status: 0 }
238 }
240​
241function logFetchFailure(
242 providerId: string,
243 rawId: string,
244 status: number,
245): void {
246 console.error(
247 JSON.stringify({
248 job: 'fal-pricing-extract',
249 providerId,
250 rawId,
251 error: 'llms_txt_fetch_failed',
252 status,
253 }),
254 )
256​
257function parseJsonObject(text: string): unknown {
258 const trimmed = text.trim()
259 // The model often explains itself first, fenced or not; the object is
260 // the reply (#552 — the repair turn was paying for the prose). The
261 // schema and verifyExamples still judge what it holds.
262 const fenced = /```(?:json)?\s*([\s\S]*?)\s*```/i.exec(trimmed)
263 const body =
264 fenced?.[1] ??
265 trimmed.slice(trimmed.indexOf('{'), trimmed.lastIndexOf('}') + 1)
266 return JSON.parse(body) as unknown
268​
269export const EXTRACT_SYSTEM = `You write a modelschemas RateCard — a price calculator — from a FAL model's llms.txt Pricing section.
270Return JSON only: {"inputs": {...}, "tables": {...}, "price": <JSONLogic>, "examples": [...]}, optionally "expiresAt" (ISO datetime) when the text names a promo end. Do not include a source object.
271A promo whose end is before today (the message states today) is over: price at the regular rate the text states, with no expiresAt; if it states no regular rate, return {"unverified": true, "expiresAt": <the promo end>}.
272​
273inputs: name → {"param": <field>, "kind": "number"|"enum"|"boolean"|"count", "bound": "request"|"usage", "default"?: ..., "values"?: [...] (enum only)}.
274- 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.
275- A quantity the request cannot state (seconds of output, megapixels, characters, tokens) is "bound": "usage" — never invent a request field.
276- 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.
277- "count" prices the items of a list param (image_urls, reference_image_urls): {"var": x} is the list's length. An example's params give the list itself ({"image_urls": ["https://example.com/a.png", "https://example.com/b.png"]}), never a number, and there is no ".length". A count input has no default: omit the param for zero items. Per output item (num_images) and any quantity the request does not send as a list (characters, seconds) is "number".
278tables: name → nested {key: number}, read with {"lookup": {"table": name, "keys": [{"var": input}]}}.
279price: 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.
280examples: [{"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%.
281​
282Rules:
283- 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.
284- 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.
285- Prefer the page's own worked total when it states one ("a 5 second video costs $0.70").
286- Return {"unverified": true} ONLY when the section names no positive price (empty, zeros, or "see pricing page" boilerplate).
287​
288Example. 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.
289{"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"}]}
290​
291Example. Section: "Each edit costs $0.10, plus $0.02 per reference image." Allowed: prompt, reference_image_urls.
292{"inputs":{"reference_images":{"param":"reference_image_urls","kind":"count","bound":"request"}},"tables":{},"price":{"+":[0.1,{"*":[{"var":"reference_images"},0.02]}]},"examples":[{"params":{},"usd":0.1,"quote":"Each edit costs $0.10"},{"params":{"reference_image_urls":["https://example.com/a.png","https://example.com/b.png"]},"usd":0.14,"quote":"plus $0.02 per reference image"}]}`
293​
294function extractUserPrompt(
295 pricingText: string,
296 requestProperties: ReadonlySet<string>,
297 now: number,
298): string {
299 const allowed = [...requestProperties].sort().join(', ')
300 return `Today: ${new Date(now * 1000).toISOString().slice(0, 10)}
301Allowed request properties: ${allowed || '(none)'}
302​
303Pricing section:
304${pricingText}`
306​
307function withSource(
308 body: z.infer<typeof extractedBodySchema>,
309 args: ExtractCardArgs,
310): RateCard {
311 const { expiresAt, ...rest } = body
312 return {
313 ...rest,
314 source: {
315 url: args.sourceUrl,
316 hash: args.sourceHash,
317 extractedAt: new Date(args.now * 1000).toISOString(),
318 ...(expiresAt !== undefined ? { expiresAt } : {}),
319 },
320 }
322​
323/**
324 * The model's reply as a card, `'unverified'`, or why it was rejected.
325 * `{unverified: true}` and an example-less card are only legal for a
326 * section that names no price (#88) — a priced section must become a card.
327 */
328export function checkExtractedCard(
329 content: string,
330 args: ExtractCardArgs,
331): RateCard | 'unverified' | { error: string } {
332 let json: unknown
333 try {
334 json = parseJsonObject(content)
335 } catch {
336 return { error: 'reply is not JSON' }
337 }
338 const parsed = extractedResponseSchema.safeParse(json)
339 if (!parsed.success) {
340 return { error: `not a RateCard: ${z.prettifyError(parsed.error)}` }
341 }
342 const priced = !isStubPricingSection(args.pricingText)
343 if ('unverified' in parsed.data || parsed.data.examples.length === 0) {
344 // An ended promo with no regular rate stated is no price: the reply
345 // names the end, the section names a promo, and the clock agrees
346 // (#552). The section check keeps a lazy refusal from unpricing a row.
347 const ended =
348 'unverified' in parsed.data &&
349 parsed.data.expiresAt !== undefined &&
350 PROMO_WORDS.test(args.pricingText) &&
351 Date.parse(parsed.data.expiresAt) <= args.now * 1000
352 return priced && !ended
353 ? {
354 error: `the section names ${usdAmounts(args.pricingText)
355 .map((usd) => `$${usd}`)
356 .join(
357 ', ',
358 )}; write the card with one example per quoted rate, or {"unverified": true, "expiresAt": <end>} if its only price is a promo that has ended`,
359 }
360 : 'unverified'
361 }
362 const card = withSource(parsed.data, args)
363 // A card must not arrive already expired: the catalog would serve the
364 // ended promo until the next lap re-read it the same way (#552).
365 const expiresAt = card.source.expiresAt
366 if (expiresAt !== undefined && Date.parse(expiresAt) <= args.now * 1000) {
367 return {
368 error: `the promo ended ${expiresAt}; price at the regular rate the section states, without expiresAt`,
369 }
370 }
371 if (!cardRequestParamsOk(card, args.requestProperties)) {
372 return {
373 error:
374 'a request-bound input param is not an allowed request property; bind it to an allowed property or make it "bound": "usage"',
375 }
376 }
377 // A usage-bound choice (output resolution) is the caller's to state; a
378 // default would price a guess (#304). Number defaults (an add-on's 0)
379 // stay legal, as on compiled token cards.
380 const usageDefaults = Object.entries(card.inputs)
381 .filter(
382 ([, input]) =>
383 input.bound === 'usage' && input.kind === 'enum' && 'default' in input,
384 )
385 .map(([name]) => name)
386 if (usageDefaults.length > 0) {
387 return {
388 error: `usage-bound enums have a default (${usageDefaults.join(', ')}); the caller states them — remove the default`,
389 }
390 }
391 const failed = verifyExamples(card).filter((result) => !result.ok)
392 if (failed.length > 0) {
393 return {
394 error: `verifyExamples failed: ${failed
395 .map((r) => `${JSON.stringify(r.example.params)} → ${r.error}`)
396 .join('; ')}`,
397 }
398 }
399 return card
401​
402export type ChatTurn = { role: 'user' | 'assistant'; content: string }
403​
404/** The model's reply to these turns after `EXTRACT_SYSTEM`; throws on error. */
405export type ExtractChat = (turns: Array<ChatTurn>) => Promise<string>
406​
407/**
408 * The extract model through Cloudflare AI Gateway on Unified Billing: the
409 * TanStack AI Anthropic adapter, its requests sent over the `env.AI`
410 * binding (which authenticates, so no provider key). No temperature: Claude 5
411 * models 400 on it (`anthropic-features.ts`). A gateway or provider error
412 * throws.
413 */
414export function gatewayChat(
415 ai: Ai,
416 gatewayId: string,
417 model: keyof typeof GATEWAY_MODEL_IDS = FAL_PRICING_EXTRACT_MODEL,
418): ExtractChat {
419 const bindingFetch = cloudflareBindingFetch({
420 binding: ai,
421 vendor: 'anthropic',
422 gateway: { id: gatewayId },
423 })
424 // The Anthropic SDK reports a thrown fetch as a bare "Connection error."
425 // and drops the binding's error, so keep it and rethrow it as the cause.
426 let bindingError: unknown
427 const adapter = createAnthropicChat(model, 'cloudflare-binding', {
428 fetch: async (
429 input: Parameters<typeof bindingFetch>[0],
430 init?: RequestInit,
431 ) => {
432 try {
433 const response = await bindingFetch(input, withGatewayModel(init))
434 // A retry got through: an earlier throw is not this call's cause.
435 bindingError = undefined
436 return response
437 } catch (error) {
438 bindingError = error
439 throw error
440 }
441 },
442 })
443 const threadId = crypto.randomUUID()
444 return async (turns) => {
445 bindingError = undefined
446 try {
447 const { text } = await chat({
448 adapter,
449 threadId,
450 stream: false,
451 systemPrompts: [EXTRACT_SYSTEM],
452 messages: turns,
453 })
454 return text
455 } catch (error) {
456 if (bindingError === undefined) throw error
457 throw new Error(errorMessage(error), { cause: bindingError })
458 }
459 }
461​
462/** The request with its `model` swapped for the gateway catalog id. */
463function withGatewayModel(
464 init: RequestInit | undefined,
465): RequestInit | undefined {
466 if (typeof init?.body !== 'string') return init
467 const body = JSON.parse(init.body) as { model?: string }
468 const ids: Partial<Record<string, string>> = GATEWAY_MODEL_IDS
469 const id = ids[body.model ?? '']
470 if (id === undefined)
471 throw new Error(`no gateway catalog id for model ${body.model}`)
472 return { ...init, body: JSON.stringify({ ...body, model: id }) }
474​
475/**
476 * One model, at most two turns: a rejected card goes back once with the
477 * reason (same model — not a fallback). `{ error }` = no card this run; the
478 * caller holds the cursor so the next shard retries it, and reports why.
479 */
480export async function extractRateCard(
481 args: ExtractCardArgs & { chat: ExtractChat },
482): Promise<ExtractedCard> {
483 const turns: Array<ChatTurn> = [
484 {
485 role: 'user',
486 content: extractUserPrompt(
487 args.pricingText,
488 args.requestProperties,
489 args.now,
490 ),
491 },
492 ]
493 try {
494 let rejected = ''
495 for (let turn = 0; turn < 2; turn++) {
496 const content = await args.chat(turns)
497 const checked = checkExtractedCard(content, args)
498 if (checked === 'unverified' || !('error' in checked)) return checked
499 rejected = checked.error
500 turns.push(
501 { role: 'assistant', content },
502 {
503 role: 'user',
504 content: `Rejected: ${checked.error}. Return the corrected full JSON.`,
505 },
506 )
507 }
508 return { error: `rejected twice: ${rejected.slice(0, 200)}` }
509 } catch (error) {
510 return { error: errorMessage(error) }
511 }
513​
514function logRefusal(
515 providerId: string,
516 rawId: string,
517 reason: FalPricingExtractRefuse,
518): void {
519 console.error(
520 JSON.stringify({
521 job: 'fal-pricing-extract',
522 providerId,
523 rawId,
524 error: 'rate_card_refused',
525 reason,
526 }),
527 )
528 noteIngest({
529 event: 'rate_card_refused',
530 properties: { providerId, rawId, reason },
531 })
533​
534/** Cursor and held rawId live in `cache_meta.lastError` under their own keys. */
535async function loadCursor(
536 db: SyncDeps['db'],
537 key: string,
538): Promise<string | null> {
539 const row = await db.query.cacheMeta.findFirst({
540 where: eq(cacheMeta.key, key),
541 })
542 const cursor = row?.lastError
543 return cursor && cursor.length > 0 ? cursor : null
545​
546async function saveCursor(
547 db: SyncDeps['db'],
548 key: string,
549 cursor: string,
550 now: number,
551): Promise<void> {
552 await db
553 .insert(cacheMeta)
554 .values({
555 key,
556 fetchedAt: now,
557 staleTime: 0,
558 lastError: cursor,
559 })
560 .onConflictDoUpdate({
561 target: cacheMeta.key,
562 set: { fetchedAt: now, lastError: cursor },
563 })
565​
566interface Candidate {
567 id: string
568 rawId: string
569 pricing: unknown
570 factSources: unknown
571 schemaEndpointId: string | null
572 boundId: string
574​
575async function loadCandidates(
576 db: SyncDeps['db'],
577 providerId: string,
578): Promise<Array<Candidate>> {
579 const rows = await db
580 .select({
581 id: models.id,
582 rawId: models.rawId,
583 pricing: models.pricing,
584 factSources: models.factSources,
585 schemaEndpointId: models.schemaEndpointId,
586 })
587 .from(models)
588 .where(and(eq(models.providerId, providerId), isNull(models.deprecatedAt)))
589 const candidates: Array<Candidate> = []
590 for (const row of rows) {
591 const boundId = row.schemaEndpointId ?? row.rawId
592 candidates.push({ ...row, boundId })
593 }
594 candidates.sort((a, b) =>
595 a.rawId < b.rawId ? -1 : a.rawId > b.rawId ? 1 : 0,
596 )
597 return candidates
599​
600async function loadRequestProperties(
601 db: SyncDeps['db'],
602 providerId: string,
603 boundIds: ReadonlyArray<string>,
604): Promise<Map<string, Set<string>>> {
605 const properties = new Map<string, Set<string>>()
606 const dbIds = [...new Set(boundIds)].map((id) => `${providerId}/${id}`)
607 for (let i = 0; i < dbIds.length; i += 90) {
608 const chunk = dbIds.slice(i, i + 90)
609 const versions = await db
610 .select({
611 endpointId: schemaVersions.endpointId,
612 schema: schemaVersions.schema,
613 })
614 .from(schemaVersions)
615 .where(
616 and(
617 inArray(schemaVersions.endpointId, chunk),
618 eq(schemaVersions.kind, 'input'),
619 isNull(schemaVersions.supersededAt),
620 ),
621 )
622 const prefix = `${providerId}/`
623 for (const version of versions) {
624 const publicId = version.endpointId.startsWith(prefix)
625 ? version.endpointId.slice(prefix.length)
626 : version.endpointId
627 const parsed: unknown = JSON.parse(version.schema)
628 properties.set(publicId, requestSchemaPropertyNames(parsed))
629 }
630 }
631 return properties
633​
634function docsExtractedSource(sources: ModelFactSources | null): {
635 derivation: 'docs-extracted'
636 sourceUrl?: string
637 sourceHash?: string
638 fetchedAt?: number
639} {
640 return {
641 derivation: 'docs-extracted',
642 ...(sources?.pricing?.sourceUrl
643 ? { sourceUrl: sources.pricing.sourceUrl }
644 : {}),
645 ...(sources?.pricing?.sourceHash
646 ? { sourceHash: sources.pricing.sourceHash }
647 : {}),
648 ...(sources?.pricing?.fetchedAt !== undefined
649 ? { fetchedAt: sources.pricing.fetchedAt }
650 : {}),
651 }
653​
654async function writePricing(args: {
655 db: SyncDeps['db']
656 providerId: string
657 candidate: Candidate
658 card: RateCard | null
659 sourceUrl: string
660 sourceHash: string
661 now: number
662}): Promise<boolean> {
663 const prior = factSourcesOf(args.candidate.factSources)
664 const nextSources: ModelFactSources = {
665 ...prior,
666 pricing: {
667 derivation: 'docs-extracted',
668 sourceUrl: args.sourceUrl,
669 sourceHash: args.sourceHash,
670 fetchedAt: args.now,
671 },
672 }
673 const before = { pricing: args.candidate.pricing }
674 const after = { pricing: args.card }
675 const changed = changedFactPaths(before, after)
676 await args.db
677 .update(models)
678 .set({
679 // A stamp or an operand reorder is not a new card. The stored source
680 // stays the read on which the price last changed.
681 ...(changed.length > 0 ? { pricing: args.card } : {}),
682 factSources: nextSources,
683 })
684 .where(eq(models.id, args.candidate.id))
685 if (changed.length === 0) return false
686 await args.db.insert(changes).values({
687 id: crypto.randomUUID(),
688 type: 'model.updated',
689 providerId: args.providerId,
690 subjectId: args.candidate.id,
691 summary: `Model ${args.candidate.rawId} updated`,
692 payload: modelUpdatedPayload(before, after, changed),
693 createdAt: args.now,
694 })
695 return true
697​
698async function stampPricingHash(args: {
699 db: SyncDeps['db']
700 candidate: Candidate
701 sourceUrl: string
702 sourceHash: string
703 now: number
704}): Promise<void> {
705 const prior = factSourcesOf(args.candidate.factSources)
706 await args.db
707 .update(models)
708 .set({
709 factSources: {
710 ...prior,
711 pricing: {
712 ...docsExtractedSource(prior),
713 derivation: 'docs-extracted',
714 sourceUrl: args.sourceUrl,
715 sourceHash: args.sourceHash,
716 fetchedAt: args.now,
717 },
718 },
719 })
720 .where(eq(models.id, args.candidate.id))
722​
723/** Run `fn` over `items` with at most `limit` in flight, preserving order. */
724async function mapLimit<T, TResult>(
725 items: ReadonlyArray<T>,
726 limit: number,
727 fn: (item: T) => Promise<TResult>,
728): Promise<Array<TResult>> {
729 const out: Array<TResult> = Array.from({ length: items.length })
730 let next = 0
731 const workers = Array.from(
732 { length: Math.min(limit, items.length) },
733 async () => {
734 for (let i = next++; i < items.length; i = next++) {
735 out[i] = await fn(items[i] as T)
736 }
737 },
738 )
739 await Promise.all(workers)
740 return out
742​
743interface LeftoverGroup {
744 section: string
745 sourceUrl: string
746 rows: Array<Candidate>
748​
749export async function extractFalPricing(
750 deps: FalPricingExtractDeps,
751): Promise<FalPricingExtractOutcome> {
752 return runIngestScope(() => extractFalPricingScoped(deps))
754​
755async function extractFalPricingScoped(
756 deps: FalPricingExtractDeps,
757): Promise<FalPricingExtractOutcome> {
758 const providerId = deps.providerId ?? 'fal'
759 const now = deps.now?.() ?? Math.floor(Date.now() / 1000)
760 const fetchCap = deps.fetchCap ?? FAL_PRICING_FETCH_CAP
761 const extractCap = deps.extractCap ?? FAL_PRICING_EXTRACT_CAP
762 const outcome: FalPricingExtractOutcome = {
763 providerId,
764 candidates: 0,
765 fetched: 0,
766 compiled: 0,
767 deduped: 0,
768 extracted: 0,
769 written: 0,
770 hashSkipped: 0,
771 refused: 0,
772 unverified: 0,
773 fetchFailed: 0,
774 cursor: null,
775 }
776​
777 const { ai, gatewayId } = deps
778 const extract =
779 deps.extractCard ??
780 (ai && gatewayId
781 ? (args: ExtractCardArgs) =>
782 extractRateCard({ ...args, chat: gatewayChat(ai, gatewayId) })
783 : null)
784​
785 try {
786 const all = await loadCandidates(deps.db, providerId)
787 const properties = await loadRequestProperties(
788 deps.db,
789 providerId,
790 all.map((row) => row.boundId),
791 )
792 // A missing input schema still gets a usage-bound unit card. Rows with
793 // no activity (3d, vision, json) are catalog models too (#114).
794 const candidates = all
795 outcome.candidates = candidates.length
796 if (candidates.length === 0) return outcome
797​
798 // Cards already stored against a Pricing-section hash — reused across
799 // rows in this run and across nights, so the model is never asked
800 // twice for the same text. Several per hash: endpoints sharing one
801 // section can have different request schemas (#304), and a card is only
802 // copied onto a row whose schema has every request param it binds.
803 const byHash = new Map<string, Array<RateCard>>()
804 const remember = (hash: string, card: RateCard): void => {
805 const cards = byHash.get(hash)
806 if (cards) cards.push(card)
807 else byHash.set(hash, [card])
808 }
809 for (const row of candidates) {
810 const card = parseStoredRateCard(row.pricing)
811 // A promo card past its expiresAt must be re-read, not copied on.
812 if (!card) continue
813 const expiresAt = card.source.expiresAt
814 if (expiresAt !== undefined && Date.parse(expiresAt) <= now * 1000) {
815 continue
816 }
817 remember(card.source.hash, card)
818 }
819​
820 const requestPropertiesOf = (candidate: Candidate): ReadonlySet<string> =>
821 properties.get(candidate.boundId) ?? new Set<string>()
822​
823 const applyCard = async (
824 candidate: Candidate,
825 card: RateCard,
826 sourceUrl: string,
827 sectionHash: string,
828 ): Promise<boolean> => {
829 const stamped: RateCard = {
830 ...card,
831 source: {
832 ...card.source,
833 url: sourceUrl,
834 hash: sectionHash,
835 extractedAt: new Date(now * 1000).toISOString(),
836 },
837 }
838 const stored = await storeListedPricing(stamped, {
839 existing: candidate.pricing,
840 requestProperties: requestPropertiesOf(candidate),
841 sourceUrl,
842 now,
843 })
844 if (stored.refused || stored.card === null) {
845 outcome.refused++
846 logRefusal(
847 providerId,
848 candidate.rawId,
849 stored.refused ?? 'uncompilable',
850 )
851 return false
852 }
853 if (
854 await writePricing({
855 db: deps.db,
856 providerId,
857 candidate,
858 card: stored.card,
859 sourceUrl,
860 sourceHash: sectionHash,
861 now,
862 })
863 ) {
864 outcome.written++
865 }
866 return true
867 }
868​
869 const rawIds = candidates.map((row) => row.rawId)
870 const cursorKey = falPricingExtractCursorKey(providerId)
871 const heldKey = `${cursorKey}:held`
872 const cursor = await loadCursor(deps.db, cursorKey)
873 const start = resumeIndex(rawIds, cursor)
874 const order = [...candidates.slice(start), ...candidates.slice(0, start)]
875​
876 // Held in an object: `mark` assigns it from a closure, where TS's
877 // control-flow analysis would otherwise keep narrowing it to null.
878 const walked: { last: string | null } = { last: null }
879 let consecutiveFetchFails = 0
880 let cursorFrozen = false
881 const fetchLlms = deps.fetchText ?? fetchLlmsTxt
882 const leftovers = new Map<string, LeftoverGroup>()
883 // Each queued leftover row → the cursor just before it, in walk order,
884 // so a failed extract can rewind the cursor onto it.
885 const cursorBefore = new Map<string, string | null>()
886​
887 // llms.txt is pure I/O — fetch a window ahead so a shard is not 250
888 // sequential round trips. Order of processing is unchanged.
889 const buffer = new Map<number, FalLlmsFetchResult>()
890 const fetchAt = async (i: number): Promise<FalLlmsFetchResult> => {
891 const cached = buffer.get(i)
892 if (cached !== undefined) return cached
893 const width = Math.max(
894 1,
895 Math.min(FAL_PRICING_FETCH_CONCURRENCY, fetchCap - i, order.length - i),
896 )
897 const results = await Promise.all(
898 order
899 .slice(i, i + width)
900 .map((row) => fetchLlms(falLlmsTxtUrl(row.rawId))),
901 )
902 results.forEach((result, k) => buffer.set(i + k, result))
903 return results[0] as FalLlmsFetchResult
904 }
905​
906 for (let i = 0; i < order.length && outcome.fetched < fetchCap; i++) {
907 const candidate = order[i] as Candidate
908 const mark = (): void => {
909 if (!cursorFrozen) walked.last = candidate.rawId
910 }
911​
912 const sourceUrl = falLlmsTxtUrl(candidate.rawId)
913 const fetched = llmsFetchOutcome(await fetchAt(i))
914 outcome.fetched++
915​
916 if ('status' in fetched) {
917 logFetchFailure(providerId, candidate.rawId, fetched.status)
918 outcome.fetchFailed++
919 if (isRetryableLlmsStatus(fetched.status)) {
920 consecutiveFetchFails++
921 cursorFrozen = true
922 if (consecutiveFetchFails >= FAL_PRICING_FETCH_FAIL_ABORT) break
923 continue
924 }
925 consecutiveFetchFails = 0
926 mark()
927 continue
928 }
929​
930 consecutiveFetchFails = 0
931 const section = pricingSection(fetched.text)
932 const sectionHash = await pricingSectionHash(section)
933 const existingCard = parseStoredRateCard(candidate.pricing)
934 const sources = factSourcesOf(candidate.factSources)
935 const stub = isStubPricingSection(section)
936 if (
937 shouldSkipExtract({
938 storedHash: storedPricingHash(existingCard, sources),
939 sectionHash,
940 hasCard: existingCard !== null,
941 stub,
942 expiresAt: existingCard?.source.expiresAt,
943 now,
944 })
945 ) {
946 outcome.hashSkipped++
947 mark()
948 continue
949 }
950​
951 if (stub) {
952 logRefusal(providerId, candidate.rawId, 'stub')
953 outcome.refused++
954 if (
955 await writePricing({
956 db: deps.db,
957 providerId,
958 candidate,
959 card: null,
960 sourceUrl,
961 sourceHash: sectionHash,
962 now,
963 })
964 ) {
965 outcome.written++
966 }
967 mark()
968 continue
969 }
970​
971 // Of the cards that fit, the one reading the most from the request:
972 // a sibling's usage-bound `resolution` must not shadow this row's
973 // request field.
974 const known = (byHash.get(sectionHash) ?? [])
975 .filter((card) =>
976 cardRequestParamsOk(card, requestPropertiesOf(candidate)),
977 )
978 .sort(
979 (a, b) => cardParams(b).request.length - cardParams(a).request.length,
980 )[0]
981 if (known) {
982 outcome.deduped++
983 await applyCard(candidate, known, sourceUrl, sectionHash)
984 mark()
985 continue
986 }
987​
988 const compiled = priceFalNamedSection(
989 section,
990 requestPropertiesOf(candidate),
991 {
992 url: sourceUrl,
993 hash: sectionHash,
994 extractedAt: new Date(now * 1000).toISOString(),
995 },
996 )
997 if (compiled) {
998 outcome.compiled++
999 remember(sectionHash, compiled)
1000 await applyCard(candidate, compiled, sourceUrl, sectionHash)
1001 mark()
1002 continue
1004​
1005 const group = leftovers.get(sectionHash)
1006 if (group) {
1007 group.rows.push(candidate)
1008 cursorBefore.set(candidate.rawId, walked.last)
1009 mark()
1010 continue
1012 // The cap counts distinct sections, not rows — a row joining a
1013 // section already queued is free. Past the cap, keep walking so the
1014 // rest of the fetch window still compiles/dedups/stamps, but freeze
1015 // the cursor so the next shard resumes on this row (#84).
1016 if (leftovers.size >= extractCap) {
1017 cursorFrozen = true
1018 continue
1020 leftovers.set(sectionHash, { section, sourceUrl, rows: [candidate] })
1021 cursorBefore.set(candidate.rawId, walked.last)
1022 mark()
1024​
1025 // Everything the parser could not stand behind: one extract call per
1026 // distinct Pricing section, then copied onto every row sharing it.
1027 const failed = new Set<string>()
1028 const reasons = new Set<string>()
1029 if (leftovers.size > 0 && extract === null) {
1030 outcome.skipped =
1031 'AI binding or AI_GATEWAY_ID not set — leftovers skipped'
1032 } else if (leftovers.size > 0 && extract !== null) {
1033 const groups = [...leftovers.entries()]
1034 const results = await mapLimit(
1035 groups,
1036 FAL_PRICING_EXTRACT_CONCURRENCY,
1037 async ([hash, group]) => {
1038 outcome.extracted++
1039 return await extract({
1040 pricingText: group.section,
1041 requestProperties: requestPropertiesOf(group.rows[0] as Candidate),
1042 sourceUrl: group.sourceUrl,
1043 sourceHash: hash,
1044 now,
1045 })
1046 },
1048​
1049 for (const [index, [hash, group]] of groups.entries()) {
1050 const result = results[index]
1051 if (
1052 result === 'unverified' ||
1053 (result !== undefined &&
1054 !('error' in result) &&
1055 result.examples.length === 0)
1056 ) {
1057 for (const row of group.rows) {
1058 outcome.unverified++
1059 logRefusal(providerId, row.rawId, 'unverified')
1060 await stampPricingHash({
1061 db: deps.db,
1062 candidate: row,
1063 sourceUrl: falLlmsTxtUrl(row.rawId),
1064 sourceHash: hash,
1065 now,
1066 })
1068 continue
1070 const card = result === undefined || 'error' in result ? null : result
1071 if (result !== undefined && 'error' in result) reasons.add(result.error)
1072 if (card) remember(hash, card)
1073 for (const row of group.rows) {
1074 const sourceUrl = falLlmsTxtUrl(row.rawId)
1075 if (card && (await applyCard(row, card, sourceUrl, hash))) {
1076 continue
1078 if (card) {
1079 reasons.add(
1080 `card extracted for ${(group.rows[0] as Candidate).rawId} refused for ${row.rawId}`,
1083 if (!card) {
1084 outcome.refused++
1085 logRefusal(providerId, row.rawId, 'uncompilable')
1087 failed.add(row.rawId)
1088 // Stamp so the row is not left unwritten; a card it already
1089 // has is kept, and its old hash keeps it due for a retry.
1090 if (parseStoredRateCard(row.pricing) === null) {
1091 await stampPricingHash({
1092 db: deps.db,
1093 candidate: row,
1094 sourceUrl,
1095 sourceHash: hash,
1096 now,
1097 })
1102​
1103 // A leftover with no card this run rewinds the cursor onto itself so
1104 // the next shard retries it (#88). Only once: a row that fails again
1105 // while already held moves on and waits for the next lap, so one bad
1106 // page cannot stall the walk.
1107 let last = walked.last
1108 if (failed.size > 0) {
1109 noteIngest(
1110 ingestFailedEvent(
1111 'fal-pricing-extract',
1112 providerId,
1114 `leftover retry: ${failed.size}`,
1115 ...[...reasons].slice(0, 3),
1116 ...(reasons.size > 3 ? [`+${reasons.size - 3} more`] : []),
1117 ].join(' | '),
1118 ),
1120 const held = await loadCursor(deps.db, heldKey)
1121 const retry = [...cursorBefore.keys()].find(
1122 (rawId) => failed.has(rawId) && rawId !== held,
1124 if (retry !== undefined) {
1125 // null: nothing was walked before it — the stored cursor already
1126 // sits just before it.
1127 last = cursorBefore.get(retry) ?? null
1128 await saveCursor(deps.db, heldKey, retry, now)
1131 if (last !== null) {
1132 await saveCursor(deps.db, cursorKey, last, now)
1133 outcome.cursor = last
1134 } else {
1135 outcome.cursor = cursor
1137 return outcome
1138 } catch (error) {
1139 outcome.error = errorMessage(error)
1140 console.error(
1141 JSON.stringify({
1142 job: 'fal-pricing-extract',
1143 providerId,
1144 error: outcome.error,
1145 }),
1147 noteIngest(
1148 ingestFailedEvent('fal-pricing-extract', providerId, outcome.error),
1150 return outcome
1151 } finally {
1152 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)