Open History to see the last commit
1import { bodyText, requestUrl } from '#/lib/text.ts'
2import { describe, expect, it, vi } from 'vitest'
3import { env } from 'cloudflare:test'
4import { eq } from 'drizzle-orm'
5
6import type { RateCard } from '@modelschemas/rate-card'
7
8import { getDb } from '../../db/index.ts'
9import {
10 cacheMeta,
11 changes,
12 endpoints,
13 models,
14 providers,
15 schemaVersions,
16} from '../../db/schema.ts'
17import { falLlmsTxtUrl } from '../providers/fal.ts'
18import { modelDbId } from './poll-models.ts'
19import { POSTHOG_CAPTURE_URL } from './ingest-signals.ts'
20import type { PostHogBatch } from './ingest-signals.ts'
21import {
22 extractFalPricing,
23 FAL_PRICING_FETCH_CONCURRENCY,
24 FAL_PRICING_FETCH_FAIL_ABORT,
25 falPricingExtractCursorKey,
26 pricingSection,
27 pricingSectionHash,
28} from './extract-fal-pricing.ts'
29import type { ExtractCardArgs, ExtractedCard } from './extract-fal-pricing.ts'
30
31const NOW = 1_781_150_000
32
33/** Real nano-banana-2 text: extras beyond the base rate, so the unit-rate
34 * parser refuses it and the extract model is asked. */
35const NANO_LLMS = `# Nano Banana 2
36
37## Pricing
38
39Your request will cost **$0.08** per image. For **$1.00**, you can run this model **12** times. If web search is used, an additional $0.015 will be charged.
40
41## API Information
42`
43
44/** The shape the unit-rate parser compiles without any model call. */
45const UNIT_LLMS = `# Unit
46
47## Pricing
48
49- **Price**: $0.04 per megapixels
50
51## API Information
52`
53
54function llmsWithRate(rate: string): string {
55 return NANO_LLMS.replace('**$0.08**', `**$${rate}**`)
56}
57
58const STUB_LLMS = `# Stub
59
60## Pricing
61
62For more details, see [fal.ai pricing](https://fal.ai/pricing).
63
64## API Information
65`
66
67function dummySource(url: string): RateCard['source'] {
68 return {
69 url,
70 hash: 'a'.repeat(64),
71 extractedAt: '2026-01-01T00:00:00.000Z',
72 }
73}
74
75function perImageCard(url: string): RateCard {
76 return {
77 inputs: {
78 num_images: { param: 'num_images', kind: 'number', default: 1 },
79 },
80 tables: {},
81 price: { '*': [{ var: 'num_images' }, 0.08] },
82 examples: [
83 {
84 params: {},
85 usd: 0.08,
86 quote: 'Your request will cost $0.08 per image',
87 },
88 ],
89 source: dummySource(url),
90 }
91}
92
93async function seedProvider(providerId: string): Promise<void> {
94 const db = getDb(env)
95 await db.insert(providers).values({
96 id: providerId,
97 displayName: 'FAL',
98 specSourceUrl: 'https://api.fal.ai/v1/models',
99 })
100}
101
102async function seedCandidate(args: {
103 providerId: string
104 rawId: string
105 properties: Record<string, unknown>
106 deprecated?: boolean
107 activity?: 'image' | null
108 pricing?: unknown
109 factSources?: unknown
110}): Promise<string> {
111 const db = getDb(env)
112 const id = modelDbId(args.providerId, args.rawId)
113 const endpointId = `${args.providerId}/${args.rawId}`
114 await db.insert(endpoints).values({
115 id: endpointId,
116 providerId: args.providerId,
117 activity: args.activity === null ? 'image' : (args.activity ?? 'image'),
118 method: 'POST',
119 path: `/${args.rawId}`,
120 })
121 await db.insert(schemaVersions).values({
122 id: `${endpointId}:input`,
123 endpointId,
124 kind: 'input',
125 contentHash: 'b'.repeat(64),
126 schema: JSON.stringify({ properties: args.properties }),
127 derivation: 'upstream-spec',
128 createdAt: NOW,
129 })
130 await db.insert(models).values({
131 id,
132 providerId: args.providerId,
133 rawId: args.rawId,
134 activity: args.activity === undefined ? 'image' : args.activity,
135 pricing: args.pricing ?? null,
136 factSources: args.factSources ?? null,
137 firstSeenAt: NOW,
138 lastSeenAt: NOW,
139 deprecatedAt: args.deprecated ? NOW : null,
140 })
141 return id
142}
143
144describe('extractFalPricing', () => {
145 it('extracts a verified card, hash-skips night two, and rotates the cursor', async () => {
146 const providerId = 'extract-main'
147 await seedProvider(providerId)
148 await seedCandidate({
149 providerId,
150 rawId: 'fal-ai/nano-banana-2',
151 properties: {
152 num_images: { type: 'integer' },
153 prompt: { type: 'string' },
154 },
155 })
156 await seedCandidate({
157 providerId,
158 rawId: 'fal-ai/other',
159 properties: { num_images: { type: 'integer' } },
160 })
161
162 const files = new Map<string, string>([
163 [falLlmsTxtUrl('fal-ai/nano-banana-2'), NANO_LLMS],
164 [falLlmsTxtUrl('fal-ai/other'), NANO_LLMS],
165 ])
166 const extractedRawIds: Array<string> = []
167 const extractCard = async (
168 args: ExtractCardArgs,
169 ): Promise<ExtractedCard> => {
170 extractedRawIds.push(args.sourceUrl)
171 return perImageCard(args.sourceUrl)
172 }
173
174 const db = getDb(env)
175 const deps = {
176 db,
177 kv: env.SCHEMA_CACHE,
178 secrets: {},
179 now: () => NOW,
180 providerId,
181 fetchCap: 10,
182 extractCap: 10,
183 fetchText: (url: string) => Promise.resolve(files.get(url) ?? null),
184 extractCard,
185 }
186
187 const first = await extractFalPricing(deps)
188 expect(first).toMatchObject({
189 candidates: 2,
190 fetched: 2,
191 // Both rows share the Pricing section, so one call serves both.
192 extracted: 1,
193 deduped: 0,
194 written: 2,
195 hashSkipped: 0,
196 })
197 expect(extractedRawIds).toHaveLength(1)
198 const nano = await db.query.models.findFirst({
199 where: eq(models.id, modelDbId(providerId, 'fal-ai/nano-banana-2')),
200 })
201 const card = nano?.pricing as RateCard | null
202 expect(card?.inputs.num_images).toMatchObject({ param: 'num_images' })
203 expect(card?.source.hash).toBe(
204 await pricingSectionHash(pricingSection(NANO_LLMS)),
205 )
206 expect(card?.source.url).toBe(falLlmsTxtUrl('fal-ai/nano-banana-2'))
207 const sources = nano?.factSources as {
208 pricing?: { derivation: string; sourceHash: string }
209 }
210 expect(sources.pricing?.derivation).toBe('docs-extracted')
211 expect(
212 await db.select().from(changes).where(eq(changes.providerId, providerId)),
213 ).toHaveLength(2)
214
215 extractedRawIds.length = 0
216 const second = await extractFalPricing(deps)
217 expect(second).toMatchObject({
218 fetched: 2,
219 extracted: 0,
220 written: 0,
221 hashSkipped: 2,
222 })
223 expect(extractedRawIds).toEqual([])
224 expect(
225 await db.select().from(changes).where(eq(changes.providerId, providerId)),
226 ).toHaveLength(2)
227 })
228
229 it('caps fetches and resumes after the cursor', async () => {
230 const providerId = 'extract-cursor'
231 await seedProvider(providerId)
232 const rawIds = ['fal-ai/a', 'fal-ai/b', 'fal-ai/c']
233 for (const rawId of rawIds) {
234 await seedCandidate({
235 providerId,
236 rawId,
237 properties: { num_images: { type: 'integer' } },
238 })
239 }
240 const seen: Array<string> = []
241 const deps = {
242 db: getDb(env),
243 kv: env.SCHEMA_CACHE,
244 secrets: {},
245 now: () => NOW,
246 providerId,
247 fetchCap: 2,
248 extractCap: 20,
249 fetchText: (url: string) => {
250 seen.push(url)
251 return Promise.resolve(NANO_LLMS)
252 },
253 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> =>
254 perImageCard(args.sourceUrl),
255 }
256 const first = await extractFalPricing(deps)
257 expect(first.fetched).toBe(2)
258 expect(first.cursor).toBe('fal-ai/b')
259 expect(
260 seen.map((url) =>
261 url.replace(/.*\/models\//, '').replace(/\/llms.txt$/, ''),
262 ),
263 ).toEqual(['fal-ai/a', 'fal-ai/b'])
264 const cursorRow = await getDb(env).query.cacheMeta.findFirst({
265 where: eq(cacheMeta.key, falPricingExtractCursorKey(providerId)),
266 })
267 expect(cursorRow?.lastError).toBe('fal-ai/b')
268
269 seen.length = 0
270 const second = await extractFalPricing(deps)
271 expect(second.fetched).toBe(2)
272 expect(
273 seen.map((url) =>
274 url.replace(/.*\/models\//, '').replace(/\/llms.txt$/, ''),
275 ),
276 ).toEqual(['fal-ai/c', 'fal-ai/a'])
277 })
278
279 it('writes null for a stub Pricing section and keeps a previous card on unverified', async () => {
280 const providerId = 'extract-stub'
281 await seedProvider(providerId)
282 const stubId = await seedCandidate({
283 providerId,
284 rawId: 'fal-ai/stub',
285 properties: { prompt: { type: 'string' } },
286 })
287 const keptId = await seedCandidate({
288 providerId,
289 rawId: 'fal-ai/kept',
290 properties: { num_images: { type: 'integer' } },
291 pricing: perImageCard(falLlmsTxtUrl('fal-ai/kept')),
292 })
293 const files = new Map<string, string>([
294 [falLlmsTxtUrl('fal-ai/stub'), STUB_LLMS],
295 [falLlmsTxtUrl('fal-ai/kept'), NANO_LLMS],
296 ])
297 await extractFalPricing({
298 db: getDb(env),
299 kv: env.SCHEMA_CACHE,
300 secrets: {},
301 now: () => NOW,
302 providerId,
303 fetchText: (url: string) => Promise.resolve(files.get(url) ?? null),
304 extractCard: async () => 'unverified',
305 })
306 const stub = await getDb(env).query.models.findFirst({
307 where: eq(models.id, stubId),
308 })
309 const kept = await getDb(env).query.models.findFirst({
310 where: eq(models.id, keptId),
311 })
312 expect(stub?.pricing).toBeNull()
313 expect(kept?.pricing).toMatchObject({
314 inputs: { num_images: { param: 'num_images' } },
315 })
316 expect(
317 (kept!.factSources as { pricing?: { derivation: string } }).pricing
318 ?.derivation,
319 ).toBe('docs-extracted')
320 })
321
322 it('refuses invented request params and expired hash-skips re-extract', async () => {
323 const providerId = 'extract-refuse'
324 await seedProvider(providerId)
325 const inventedId = await seedCandidate({
326 providerId,
327 rawId: 'fal-ai/invented',
328 properties: { prompt: { type: 'string' } },
329 })
330 const expiredId = await seedCandidate({
331 providerId,
332 rawId: 'fal-ai/expired',
333 properties: { num_images: { type: 'integer' } },
334 pricing: {
335 ...perImageCard(falLlmsTxtUrl('fal-ai/expired')),
336 source: {
337 ...dummySource(falLlmsTxtUrl('fal-ai/expired')),
338 hash: await pricingSectionHash(pricingSection(NANO_LLMS)),
339 expiresAt: '2020-01-01T00:00:00.000Z',
340 },
341 },
342 })
343 let extracts = 0
344 const files = new Map<string, string>([
345 [falLlmsTxtUrl('fal-ai/invented'), llmsWithRate('0.09')],
346 [falLlmsTxtUrl('fal-ai/expired'), NANO_LLMS],
347 ])
348 await extractFalPricing({
349 db: getDb(env),
350 kv: env.SCHEMA_CACHE,
351 secrets: {},
352 now: () => NOW,
353 providerId,
354 fetchText: (url: string) => Promise.resolve(files.get(url) ?? null),
355 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> => {
356 extracts++
357 if (args.sourceUrl.includes('invented')) {
358 return {
359 inputs: {
360 quality: { param: 'quality', kind: 'enum', values: ['hd'] },
361 },
362 tables: {},
363 price: 0.08,
364 examples: [
365 { params: {}, usd: 0.08, quote: 'Your request will cost $0.08' },
366 ],
367 source: dummySource(args.sourceUrl),
368 }
369 }
370 return perImageCard(args.sourceUrl)
371 },
372 })
373 expect(extracts).toBe(2)
374 const invented = await getDb(env).query.models.findFirst({
375 where: eq(models.id, inventedId),
376 })
377 expect(invented?.pricing).toBeNull()
378 const expired = await getDb(env).query.models.findFirst({
379 where: eq(models.id, expiredId),
380 })
381 expect(
382 (expired?.pricing as RateCard | null)?.source.expiresAt,
383 ).toBeUndefined()
384 })
385
386 it('prices a unit-rate section with no activity and no input schema (#114)', async () => {
387 const providerId = 'extract-named'
388 await seedProvider(providerId)
389 await getDb(env)
390 .insert(models)
391 .values({
392 id: modelDbId(providerId, 'bria/ad-delayer'),
393 providerId,
394 rawId: 'bria/ad-delayer',
395 activity: null,
396 firstSeenAt: NOW,
397 lastSeenAt: NOW,
398 })
399 await getDb(env)
400 .insert(models)
401 .values({
402 id: modelDbId(providerId, 'fal-ai/aura-flow'),
403 providerId,
404 rawId: 'fal-ai/aura-flow',
405 activity: null,
406 firstSeenAt: NOW,
407 lastSeenAt: NOW,
408 })
409 const files = new Map<string, string>([
410 [
411 falLlmsTxtUrl('bria/ad-delayer'),
412 `# Delayer\n\n## Pricing\n\n- **Price**: $0.3 per requests\n\n## API Information\n`,
413 ],
414 [falLlmsTxtUrl('fal-ai/aura-flow'), STUB_LLMS],
415 ])
416 let extracted = 0
417 const outcome = await extractFalPricing({
418 db: getDb(env),
419 kv: env.SCHEMA_CACHE,
420 secrets: {},
421 now: () => NOW,
422 providerId,
423 fetchText: (url: string) => Promise.resolve(files.get(url) ?? null),
424 extractCard: async (args: ExtractCardArgs) => {
425 extracted++
426 return perImageCard(args.sourceUrl)
427 },
428 })
429 expect(outcome).toMatchObject({
430 candidates: 2,
431 compiled: 1,
432 written: 1,
433 refused: 1,
434 extracted: 0,
435 })
436 expect(extracted).toBe(0)
437 const db = getDb(env)
438 const priced = await db.query.models.findFirst({
439 where: eq(models.id, modelDbId(providerId, 'bria/ad-delayer')),
440 })
441 const card = priced?.pricing as RateCard | null
442 expect(card?.examples[0]).toMatchObject({
443 params: { requests: 1 },
444 usd: 0.3,
445 })
446 const stub = await db.query.models.findFirst({
447 where: eq(models.id, modelDbId(providerId, 'fal-ai/aura-flow')),
448 })
449 expect(stub?.pricing).toBeNull()
450 })
451
452 it('skips deprecated rows and still fetches rows with no input schema', async () => {
453 const providerId = 'extract-skip'
454 await seedProvider(providerId)
455 await seedCandidate({
456 providerId,
457 rawId: 'fal-ai/live',
458 properties: { num_images: { type: 'integer' } },
459 })
460 await seedCandidate({
461 providerId,
462 rawId: 'fal-ai/old',
463 properties: { num_images: { type: 'integer' } },
464 deprecated: true,
465 })
466 await getDb(env)
467 .insert(models)
468 .values({
469 id: modelDbId(providerId, 'fal-ai/no-schema'),
470 providerId,
471 rawId: 'fal-ai/no-schema',
472 activity: 'image',
473 firstSeenAt: NOW,
474 lastSeenAt: NOW,
475 })
476 const fetched: Array<string> = []
477 const outcome = await extractFalPricing({
478 db: getDb(env),
479 kv: env.SCHEMA_CACHE,
480 secrets: {},
481 now: () => NOW,
482 providerId,
483 fetchText: (url: string) => {
484 fetched.push(url)
485 return Promise.resolve(NANO_LLMS)
486 },
487 extractCard: async (args: ExtractCardArgs) =>
488 perImageCard(args.sourceUrl),
489 })
490 expect(outcome.candidates).toBe(2)
491 expect([...fetched].sort()).toEqual(
492 [falLlmsTxtUrl('fal-ai/live'), falLlmsTxtUrl('fal-ai/no-schema')].sort(),
493 )
494 })
495
496 it('stops extracting at the extract cap and retries the leftover next run', async () => {
497 const providerId = 'extract-cap'
498 await seedProvider(providerId)
499 const rates = new Map([
500 ['fal-ai/a', '0.08'],
501 ['fal-ai/b', '0.09'],
502 ['fal-ai/c', '0.10'],
503 ])
504 for (const rawId of rates.keys()) {
505 await seedCandidate({
506 providerId,
507 rawId,
508 properties: { num_images: { type: 'integer' } },
509 })
510 }
511 let extracts = 0
512 const deps = {
513 db: getDb(env),
514 kv: env.SCHEMA_CACHE,
515 secrets: {},
516 now: () => NOW,
517 providerId,
518 fetchCap: 200,
519 extractCap: 1,
520 fetchText: (url: string) => {
521 const rawId = url.replace(/.*\/models\//, '').replace(/\/llms.txt$/, '')
522 return Promise.resolve(llmsWithRate(rates.get(rawId) ?? '0.08'))
523 },
524 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> => {
525 extracts++
526 return perImageCard(args.sourceUrl)
527 },
528 }
529 const first = await extractFalPricing(deps)
530 expect(first.extracted).toBe(1)
531 expect(first.written).toBe(1)
532 expect(extracts).toBe(1)
533 extracts = 0
534 const second = await extractFalPricing(deps)
535 expect(second.extracted).toBe(1)
536 expect(extracts).toBe(1)
537 })
538
539 it('still compiles unit rates without the AI binding and skips only leftovers', async () => {
540 const providerId = 'extract-nokey'
541 await seedProvider(providerId)
542 const unitId = await seedCandidate({
543 providerId,
544 rawId: 'fal-ai/aunit',
545 properties: { num_images: { type: 'integer' } },
546 })
547 await seedCandidate({
548 providerId,
549 rawId: 'fal-ai/bleftover',
550 properties: { num_images: { type: 'integer' } },
551 })
552 const files = new Map<string, string>([
553 [falLlmsTxtUrl('fal-ai/aunit'), UNIT_LLMS],
554 [falLlmsTxtUrl('fal-ai/bleftover'), NANO_LLMS],
555 ])
556 const outcome = await extractFalPricing({
557 db: getDb(env),
558 kv: env.SCHEMA_CACHE,
559 secrets: {},
560 now: () => NOW,
561 providerId,
562 fetchText: (url: string) => Promise.resolve(files.get(url) ?? null),
563 })
564 expect(outcome.skipped).toContain('AI_GATEWAY_ID')
565 expect(outcome).toMatchObject({ compiled: 1, written: 1, extracted: 0 })
566 const unit = await getDb(env).query.models.findFirst({
567 where: eq(models.id, unitId),
568 })
569 expect((unit?.pricing as RateCard | null)?.examples[0]).toMatchObject({
570 params: { megapixels: 1 },
571 usd: 0.04,
572 })
573 })
574
575 it('does not advance the cursor on retryable llms.txt failures', async () => {
576 const providerId = 'extract-fetchfail'
577 await seedProvider(providerId)
578 for (const rawId of ['fal-ai/a', 'fal-ai/b', 'fal-ai/c']) {
579 await seedCandidate({
580 providerId,
581 rawId,
582 properties: { num_images: { type: 'integer' } },
583 })
584 }
585 const seen: Array<string> = []
586 const deps = {
587 db: getDb(env),
588 kv: env.SCHEMA_CACHE,
589 secrets: {},
590 now: () => NOW,
591 providerId,
592 fetchText: (url: string) => {
593 seen.push(url)
594 if (url.includes('/fal-ai/a/')) return Promise.resolve(NANO_LLMS)
595 return Promise.resolve({ status: 503 })
596 },
597 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> =>
598 perImageCard(args.sourceUrl),
599 }
600 const first = await extractFalPricing(deps)
601 expect(first.cursor).toBe('fal-ai/a')
602 expect(first.fetchFailed).toBe(2)
603 expect(first.written).toBe(1)
604 seen.length = 0
605 const second = await extractFalPricing(deps)
606 expect(
607 seen.map((url) =>
608 url.replace(/.*\/models\//, '').replace(/\/llms.txt$/, ''),
609 )[0],
610 ).toBe('fal-ai/b')
611 expect(second.cursor).toBe('fal-ai/a')
612 })
613
614 it('does not leapfrog a retryable hole when a later extract succeeds', async () => {
615 const providerId = 'extract-fetchhole'
616 await seedProvider(providerId)
617 for (const rawId of ['fal-ai/a', 'fal-ai/b', 'fal-ai/c']) {
618 await seedCandidate({
619 providerId,
620 rawId,
621 properties: { num_images: { type: 'integer' } },
622 })
623 }
624 const seen: Array<string> = []
625 const first = await extractFalPricing({
626 db: getDb(env),
627 kv: env.SCHEMA_CACHE,
628 secrets: {},
629 now: () => NOW,
630 providerId,
631 fetchText: (url: string) => {
632 seen.push(url)
633 if (url.includes('/fal-ai/b/')) return Promise.resolve({ status: 503 })
634 return Promise.resolve(NANO_LLMS)
635 },
636 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> =>
637 perImageCard(args.sourceUrl),
638 })
639 expect(first.cursor).toBe('fal-ai/a')
640 expect(first.written).toBe(2)
641 expect(first.fetchFailed).toBe(1)
642 seen.length = 0
643 const second = await extractFalPricing({
644 db: getDb(env),
645 kv: env.SCHEMA_CACHE,
646 secrets: {},
647 now: () => NOW,
648 providerId,
649 fetchCap: 1,
650 fetchText: (url: string) => {
651 seen.push(url)
652 return Promise.resolve(NANO_LLMS)
653 },
654 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> =>
655 perImageCard(args.sourceUrl),
656 })
657 expect(
658 seen.map((url) =>
659 url.replace(/.*\/models\//, '').replace(/\/llms.txt$/, ''),
660 ),
661 ).toEqual(['fal-ai/b'])
662 expect(second.cursor).toBe('fal-ai/b')
663 expect(second.written).toBe(1)
664 })
665
666 it('aborts after consecutive retryable fetches without saving a cursor', async () => {
667 const providerId = 'extract-fetchabort'
668 await seedProvider(providerId)
669 const rawIds = Array.from(
670 { length: FAL_PRICING_FETCH_FAIL_ABORT + 2 },
671 (_, i) => `fal-ai/${String(i).padStart(2, '0')}`,
672 )
673 for (const rawId of rawIds) {
674 await seedCandidate({
675 providerId,
676 rawId,
677 properties: { num_images: { type: 'integer' } },
678 })
679 }
680 const seen: Array<string> = []
681 const outcome = await extractFalPricing({
682 db: getDb(env),
683 kv: env.SCHEMA_CACHE,
684 secrets: {},
685 now: () => NOW,
686 providerId,
687 fetchText: (url: string) => {
688 seen.push(url)
689 return Promise.resolve({ status: 503 })
690 },
691 extractCard: async () => {
692 throw new Error('extract should not run')
693 },
694 })
695 expect(outcome.fetched).toBe(FAL_PRICING_FETCH_FAIL_ABORT)
696 expect(outcome.fetchFailed).toBe(FAL_PRICING_FETCH_FAIL_ABORT)
697 expect(outcome.cursor).toBeNull()
698 // Fetches run a window ahead, so a few more may be in flight than the
699 // abort consumes — never more than the window.
700 expect(seen.length).toBeGreaterThanOrEqual(FAL_PRICING_FETCH_FAIL_ABORT)
701 expect(seen.length).toBeLessThanOrEqual(FAL_PRICING_FETCH_CONCURRENCY)
702 expect(
703 await getDb(env).query.cacheMeta.findFirst({
704 where: eq(cacheMeta.key, falPricingExtractCursorKey(providerId)),
705 }),
706 ).toBeUndefined()
707 })
708
709 it('keeps a previous card and stamps the hash when examples are empty', async () => {
710 const providerId = 'extract-empty-ex'
711 await seedProvider(providerId)
712 const rawId = 'fal-ai/kept'
713 const previous = perImageCard(falLlmsTxtUrl(rawId))
714 const id = await seedCandidate({
715 providerId,
716 rawId,
717 properties: { num_images: { type: 'integer' } },
718 pricing: previous,
719 factSources: {
720 pricing: {
721 derivation: 'docs-extracted',
722 sourceUrl: falLlmsTxtUrl(rawId),
723 sourceHash: previous.source.hash,
724 fetchedAt: NOW,
725 },
726 },
727 })
728 const outcome = await extractFalPricing({
729 db: getDb(env),
730 kv: env.SCHEMA_CACHE,
731 secrets: {},
732 now: () => NOW,
733 providerId,
734 fetchText: () => Promise.resolve(NANO_LLMS),
735 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> => ({
736 ...perImageCard(args.sourceUrl),
737 examples: [],
738 }),
739 })
740 expect(outcome.unverified).toBe(1)
741 expect(outcome.written).toBe(0)
742 const row = await getDb(env).query.models.findFirst({
743 where: eq(models.id, id),
744 })
745 expect(row?.pricing).toMatchObject({
746 inputs: { num_images: { param: 'num_images' } },
747 })
748 const sectionHash = await pricingSectionHash(pricingSection(NANO_LLMS))
749 expect(
750 (row!.factSources as { pricing?: { sourceHash: string } }).pricing
751 ?.sourceHash,
752 ).toBe(sectionHash)
753 })
754
755 it('keeps a previous card and does not stamp the hash when verifyExamples fails', async () => {
756 const providerId = 'extract-verifyfail'
757 await seedProvider(providerId)
758 const rawId = 'fal-ai/kept'
759 const previousHash = 'a'.repeat(64)
760 const previous = perImageCard(falLlmsTxtUrl(rawId))
761 const id = await seedCandidate({
762 providerId,
763 rawId,
764 properties: { num_images: { type: 'integer' } },
765 pricing: previous,
766 factSources: {
767 pricing: {
768 derivation: 'docs-extracted',
769 sourceUrl: falLlmsTxtUrl(rawId),
770 sourceHash: previousHash,
771 fetchedAt: NOW,
772 },
773 },
774 })
775 const outcome = await extractFalPricing({
776 db: getDb(env),
777 kv: env.SCHEMA_CACHE,
778 secrets: {},
779 now: () => NOW,
780 providerId,
781 fetchText: () => Promise.resolve(NANO_LLMS),
782 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> => ({
783 ...perImageCard(args.sourceUrl),
784 examples: [
785 {
786 params: {},
787 usd: 999,
788 quote: 'Your request will cost $0.08 per image',
789 },
790 ],
791 }),
792 })
793 expect(outcome.refused).toBe(1)
794 expect(outcome.written).toBe(0)
795 const row = await getDb(env).query.models.findFirst({
796 where: eq(models.id, id),
797 })
798 expect((row?.pricing as RateCard | null)?.examples[0]?.usd).toBe(0.08)
799 expect(
800 (row!.factSources as { pricing?: { sourceHash: string } }).pricing
801 ?.sourceHash,
802 ).toBe(previousHash)
803 })
804
805 it('writes null over a previous card when Pricing is a stub', async () => {
806 const providerId = 'extract-stub-overwrite'
807 await seedProvider(providerId)
808 const rawId = 'fal-ai/stub'
809 const id = await seedCandidate({
810 providerId,
811 rawId,
812 properties: { prompt: { type: 'string' } },
813 pricing: perImageCard(falLlmsTxtUrl(rawId)),
814 factSources: {
815 pricing: {
816 derivation: 'docs-extracted',
817 sourceUrl: falLlmsTxtUrl(rawId),
818 sourceHash: 'a'.repeat(64),
819 fetchedAt: NOW,
820 },
821 },
822 })
823 const outcome = await extractFalPricing({
824 db: getDb(env),
825 kv: env.SCHEMA_CACHE,
826 secrets: {},
827 now: () => NOW,
828 providerId,
829 fetchText: () => Promise.resolve(STUB_LLMS),
830 extractCard: async () => {
831 throw new Error('extract should not run on a stub')
832 },
833 })
834 expect(outcome.refused).toBe(1)
835 expect(outcome.written).toBe(1)
836 const row = await getDb(env).query.models.findFirst({
837 where: eq(models.id, id),
838 })
839 expect(row?.pricing).toBeNull()
840 const sources = row?.factSources as {
841 pricing?: { derivation: string; sourceHash: string }
842 }
843 expect(sources.pricing?.derivation).toBe('docs-extracted')
844 expect(sources.pricing?.sourceHash).toBe(
845 await pricingSectionHash(pricingSection(STUB_LLMS)),
846 )
847 })
848 it('compiles unit-rate sections without calling the model', async () => {
849 const providerId = 'extract-unit'
850 await seedProvider(providerId)
851 const id = await seedCandidate({
852 providerId,
853 rawId: 'fal-ai/unit',
854 properties: { num_images: { type: 'integer' } },
855 })
856 const outcome = await extractFalPricing({
857 db: getDb(env),
858 kv: env.SCHEMA_CACHE,
859 secrets: {},
860 now: () => NOW,
861 providerId,
862 fetchText: () => Promise.resolve(UNIT_LLMS),
863 extractCard: () => {
864 throw new Error('the parser should have handled this section')
865 },
866 })
867 expect(outcome).toMatchObject({
868 compiled: 1,
869 extracted: 0,
870 written: 1,
871 refused: 0,
872 })
873 const row = await getDb(env).query.models.findFirst({
874 where: eq(models.id, id),
875 })
876 const card = row?.pricing as RateCard | null
877 expect(card?.examples[0]).toMatchObject({
878 params: { megapixels: 1 },
879 usd: 0.04,
880 })
881 expect(card?.source.hash).toBe(
882 await pricingSectionHash(pricingSection(UNIT_LLMS)),
883 )
884 expect(card?.source.url).toBe(falLlmsTxtUrl('fal-ai/unit'))
885 })
886
887 it('copies one extract onto every row sharing a Pricing hash', async () => {
888 const providerId = 'extract-dedup'
889 await seedProvider(providerId)
890 const rawIds = [
891 'fal-ai/happy-horse/a',
892 'fal-ai/happy-horse/b',
893 'fal-ai/happy-horse/c',
894 ]
895 for (const rawId of rawIds) {
896 await seedCandidate({
897 providerId,
898 rawId,
899 properties: { num_images: { type: 'integer' } },
900 })
901 }
902 let extracts = 0
903 const outcome = await extractFalPricing({
904 db: getDb(env),
905 kv: env.SCHEMA_CACHE,
906 secrets: {},
907 now: () => NOW,
908 providerId,
909 fetchText: () => Promise.resolve(NANO_LLMS),
910 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> => {
911 extracts++
912 return perImageCard(args.sourceUrl)
913 },
914 })
915 expect(extracts).toBe(1)
916 expect(outcome).toMatchObject({ extracted: 1, written: 3 })
917 const hash = await pricingSectionHash(pricingSection(NANO_LLMS))
918 for (const rawId of rawIds) {
919 const row = await getDb(env).query.models.findFirst({
920 where: eq(models.id, modelDbId(providerId, rawId)),
921 })
922 const card = row?.pricing as RateCard | null
923 expect(card?.price).toEqual({ '*': [{ var: 'num_images' }, 0.08] })
924 expect(card?.source.hash).toBe(hash)
925 expect(card?.source.url).toBe(falLlmsTxtUrl(rawId))
926 }
927 })
928
929 it('reuses a card another row already stores for the same hash', async () => {
930 const providerId = 'extract-dedup-stored'
931 await seedProvider(providerId)
932 const hash = await pricingSectionHash(pricingSection(NANO_LLMS))
933 await seedCandidate({
934 providerId,
935 rawId: 'fal-ai/apriced',
936 properties: { num_images: { type: 'integer' } },
937 pricing: {
938 ...perImageCard(falLlmsTxtUrl('fal-ai/apriced')),
939 source: { ...dummySource(falLlmsTxtUrl('fal-ai/apriced')), hash },
940 },
941 })
942 const freshId = await seedCandidate({
943 providerId,
944 rawId: 'fal-ai/bfresh',
945 properties: { num_images: { type: 'integer' } },
946 })
947 const outcome = await extractFalPricing({
948 db: getDb(env),
949 kv: env.SCHEMA_CACHE,
950 secrets: {},
951 now: () => NOW,
952 providerId,
953 fetchText: () => Promise.resolve(NANO_LLMS),
954 extractCard: () => {
955 throw new Error('a stored card for this hash should have been reused')
956 },
957 })
958 expect(outcome).toMatchObject({
959 extracted: 0,
960 deduped: 1,
961 hashSkipped: 1,
962 written: 1,
963 })
964 const fresh = await getDb(env).query.models.findFirst({
965 where: eq(models.id, freshId),
966 })
967 expect((fresh?.pricing as RateCard | null)?.source).toMatchObject({
968 hash,
969 url: falLlmsTxtUrl('fal-ai/bfresh'),
970 })
971 })
972
973 // #304: grok-imagine-video edit-video and extend-video share one Pricing
974 // section, but only edit-video has `resolution`. Copying its card onto
975 // extend-video was refused as invented_param on every lap.
976 it('extracts its own card when the shared-hash card binds a param the row lacks', async () => {
977 const providerId = 'extract-dedup-schema'
978 await seedProvider(providerId)
979 const hash = await pricingSectionHash(pricingSection(NANO_LLMS))
980 await seedCandidate({
981 providerId,
982 rawId: 'fal-ai/apriced',
983 properties: { num_images: { type: 'integer' } },
984 pricing: {
985 ...perImageCard(falLlmsTxtUrl('fal-ai/apriced')),
986 source: { ...dummySource(falLlmsTxtUrl('fal-ai/apriced')), hash },
987 },
988 })
989 const ids = []
990 for (const rawId of ['fal-ai/bfresh', 'fal-ai/cfresh']) {
991 ids.push(
992 await seedCandidate({
993 providerId,
994 rawId,
995 properties: { prompt: { type: 'string' } },
996 }),
997 )
998 }
999 const asked: Array<Array<string>> = []
1000 const outcome = await extractFalPricing({
1001 db: getDb(env),
1002 kv: env.SCHEMA_CACHE,
1003 secrets: {},
1004 now: () => NOW,
1005 providerId,
1006 fetchText: () => Promise.resolve(NANO_LLMS),
1007 extractCard: (args: ExtractCardArgs): Promise<ExtractedCard> => {
1008 asked.push([...args.requestProperties].sort())
1009 const card = perImageCard(args.sourceUrl)
1010 return Promise.resolve({
1011 ...card,
1012 inputs: {
1013 num_images: { param: 'num_images', kind: 'number', bound: 'usage' },
1014 },
1015 examples: [{ ...card.examples[0]!, params: { num_images: 1 } }],
1016 })
1017 },
1018 })
1019 expect(asked).toEqual([['prompt']])
1020 expect(outcome).toMatchObject({ extracted: 1, refused: 0, written: 2 })
1021 for (const id of ids) {
1022 const row = await getDb(env).query.models.findFirst({
1023 where: eq(models.id, id),
1024 })
1025 expect((row?.pricing as RateCard | null)?.inputs.num_images).toEqual({
1026 param: 'num_images',
1027 kind: 'number',
1028 bound: 'usage',
1029 })
1030 }
1031 })
1032
1033 it('prefers the fitting card that reads the most from the request', async () => {
1034 const providerId = 'extract-dedup-prefer'
1035 await seedProvider(providerId)
1036 const hash = await pricingSectionHash(pricingSection(NANO_LLMS))
1037 const usage = perImageCard(falLlmsTxtUrl('fal-ai/a-usage'))
1038 await seedCandidate({
1039 providerId,
1040 rawId: 'fal-ai/a-usage',
1041 properties: { prompt: { type: 'string' } },
1042 pricing: {
1043 ...usage,
1044 inputs: {
1045 num_images: { param: 'num_images', kind: 'number', bound: 'usage' },
1046 },
1047 examples: [{ ...usage.examples[0]!, params: { num_images: 1 } }],
1048 source: { ...usage.source, hash },
1049 },
1050 })
1051 await seedCandidate({
1052 providerId,
1053 rawId: 'fal-ai/b-request',
1054 properties: { num_images: { type: 'integer' } },
1055 pricing: {
1056 ...perImageCard(falLlmsTxtUrl('fal-ai/b-request')),
1057 source: { ...dummySource(falLlmsTxtUrl('fal-ai/b-request')), hash },
1058 },
1059 })
1060 const freshId = await seedCandidate({
1061 providerId,
1062 rawId: 'fal-ai/c-fresh',
1063 properties: { num_images: { type: 'integer' } },
1064 })
1065 await extractFalPricing({
1066 db: getDb(env),
1067 kv: env.SCHEMA_CACHE,
1068 secrets: {},
1069 now: () => NOW,
1070 providerId,
1071 fetchText: () => Promise.resolve(NANO_LLMS),
1072 })
1073 const fresh = await getDb(env).query.models.findFirst({
1074 where: eq(models.id, freshId),
1075 })
1076 expect((fresh?.pricing as RateCard | null)?.inputs.num_images).toEqual({
1077 param: 'num_images',
1078 kind: 'number',
1079 default: 1,
1080 })
1081 })
1082
1083 it('re-extracts next run for a group row the shared card does not fit', async () => {
1084 const providerId = 'extract-group-schema'
1085 await seedProvider(providerId)
1086 await seedCandidate({
1087 providerId,
1088 rawId: 'fal-ai/a',
1089 properties: { num_images: { type: 'integer' } },
1090 })
1091 const bId = await seedCandidate({
1092 providerId,
1093 rawId: 'fal-ai/b',
1094 properties: { prompt: { type: 'string' } },
1095 })
1096 const asked: Array<Array<string>> = []
1097 const deps = {
1098 db: getDb(env),
1099 kv: env.SCHEMA_CACHE,
1100 secrets: {},
1101 now: () => NOW,
1102 providerId,
1103 fetchText: () => Promise.resolve(NANO_LLMS),
1104 extractCard: (args: ExtractCardArgs): Promise<ExtractedCard> => {
1105 const allowed = [...args.requestProperties].sort()
1106 asked.push(allowed)
1107 const card = perImageCard(args.sourceUrl)
1108 if (allowed.includes('num_images')) return Promise.resolve(card)
1109 return Promise.resolve({
1110 ...card,
1111 inputs: {
1112 num_images: { param: 'num_images', kind: 'number', bound: 'usage' },
1113 },
1114 examples: [{ ...card.examples[0]!, params: { num_images: 1 } }],
1115 })
1116 },
1117 }
1118 // One group per section: written for a's schema, refused for b, and b
1119 // is held for a retry.
1120 expect(await extractFalPricing(deps)).toMatchObject({
1121 extracted: 1,
1122 refused: 1,
1123 })
1124 // The retry skips a's card (it binds num_images, which b lacks) and
1125 // asks for b's own.
1126 expect(await extractFalPricing(deps)).toMatchObject({
1127 extracted: 1,
1128 refused: 0,
1129 deduped: 0,
1130 })
1131 expect(asked).toEqual([['num_images'], ['prompt']])
1132 const b = await getDb(env).query.models.findFirst({
1133 where: eq(models.id, bId),
1134 })
1135 expect((b?.pricing as RateCard | null)?.inputs.num_images).toMatchObject({
1136 bound: 'usage',
1137 })
1138 })
1139})
1140
1141describe('extractFalPricing retries (#84)', () => {
1142 it('re-extracts a null card stamped by an unverified leftover', async () => {
1143 const providerId = 'extract-retry-null'
1144 await seedProvider(providerId)
1145 const rawId = 'fal-ai/nano-banana-2'
1146 const id = await seedCandidate({
1147 providerId,
1148 rawId,
1149 properties: { num_images: { type: 'integer' } },
1150 })
1151 let extracts = 0
1152 const deps = {
1153 db: getDb(env),
1154 kv: env.SCHEMA_CACHE,
1155 secrets: {},
1156 now: () => NOW,
1157 providerId,
1158 fetchText: () => Promise.resolve(NANO_LLMS),
1159 extractCard: async (): Promise<ExtractedCard> => {
1160 extracts++
1161 return 'unverified'
1162 },
1163 }
1164 const first = await extractFalPricing(deps)
1165 expect(first.unverified).toBe(1)
1166 const stamped = await getDb(env).query.models.findFirst({
1167 where: eq(models.id, id),
1168 })
1169 expect(stamped?.pricing).toBeNull()
1170 expect(
1171 (stamped!.factSources as { pricing?: { sourceHash?: string } }).pricing
1172 ?.sourceHash,
1173 ).toBe(await pricingSectionHash(pricingSection(NANO_LLMS)))
1174
1175 const second = await extractFalPricing({
1176 ...deps,
1177 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> => {
1178 extracts++
1179 return perImageCard(args.sourceUrl)
1180 },
1181 })
1182 expect(second).toMatchObject({ hashSkipped: 0, extracted: 1, written: 1 })
1183 expect(extracts).toBe(2)
1184
1185 // Unchanged hash and a non-null card: no model call.
1186 const third = await extractFalPricing({
1187 ...deps,
1188 extractCard: () => {
1189 throw new Error('unchanged hash with a card must not re-extract')
1190 },
1191 })
1192 expect(third).toMatchObject({ hashSkipped: 1, extracted: 0 })
1193 })
1194
1195 it('hash-skips a stub section that already stored null', async () => {
1196 const providerId = 'extract-stub-skip'
1197 await seedProvider(providerId)
1198 await seedCandidate({
1199 providerId,
1200 rawId: 'fal-ai/stub',
1201 properties: { prompt: { type: 'string' } },
1202 })
1203 const deps = {
1204 db: getDb(env),
1205 kv: env.SCHEMA_CACHE,
1206 secrets: {},
1207 now: () => NOW,
1208 providerId,
1209 fetchText: () => Promise.resolve(STUB_LLMS),
1210 extractCard: () => {
1211 throw new Error('stubs never reach the model')
1212 },
1213 }
1214 const first = await extractFalPricing(deps)
1215 expect(first).toMatchObject({ refused: 1, hashSkipped: 0 })
1216 const second = await extractFalPricing(deps)
1217 expect(second).toMatchObject({ refused: 0, hashSkipped: 1 })
1218 })
1219
1220 it('keeps compiling past the leftover cap and resumes on the first dropped row', async () => {
1221 const providerId = 'extract-cap-walk'
1222 await seedProvider(providerId)
1223 const files = new Map<string, string>([
1224 ['fal-ai/a', llmsWithRate('0.08')],
1225 ['fal-ai/b', llmsWithRate('0.09')],
1226 ['fal-ai/c', UNIT_LLMS],
1227 ])
1228 const ids = new Map<string, string>()
1229 for (const rawId of files.keys()) {
1230 ids.set(
1231 rawId,
1232 await seedCandidate({
1233 providerId,
1234 rawId,
1235 properties: { num_images: { type: 'integer' } },
1236 }),
1237 )
1238 }
1239 const outcome = await extractFalPricing({
1240 db: getDb(env),
1241 kv: env.SCHEMA_CACHE,
1242 secrets: {},
1243 now: () => NOW,
1244 providerId,
1245 extractCap: 1,
1246 fetchText: (url: string) => {
1247 const rawId = url.replace(/.*\/models\//, '').replace(/\/llms.txt$/, '')
1248 return Promise.resolve(files.get(rawId) ?? null)
1249 },
1250 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> =>
1251 perImageCard(args.sourceUrl),
1252 })
1253 expect(outcome).toMatchObject({
1254 fetched: 3,
1255 extracted: 1,
1256 compiled: 1,
1257 cursor: 'fal-ai/a',
1258 })
1259 const c = await getDb(env).query.models.findFirst({
1260 where: eq(models.id, ids.get('fal-ai/c') ?? ''),
1261 })
1262 expect(c?.pricing).not.toBeNull()
1263 })
1264})
1265
1266describe('extractFalPricing failed leftovers (#88)', () => {
1267 it('stamps a failed leftover and rewinds the cursor onto it once', async () => {
1268 const providerId = 'extract-hold'
1269 await seedProvider(providerId)
1270 const files = new Map<string, string>([
1271 ['fal-ai/a', UNIT_LLMS],
1272 ['fal-ai/b', NANO_LLMS],
1273 ['fal-ai/c', UNIT_LLMS],
1274 ])
1275 const ids = new Map<string, string>()
1276 for (const rawId of files.keys()) {
1277 ids.set(
1278 rawId,
1279 await seedCandidate({
1280 providerId,
1281 rawId,
1282 properties: { num_images: { type: 'integer' } },
1283 }),
1284 )
1285 }
1286 const seen: Array<string> = []
1287 let extracts = 0
1288 const deps = {
1289 db: getDb(env),
1290 kv: env.SCHEMA_CACHE,
1291 secrets: {},
1292 now: () => NOW,
1293 providerId,
1294 fetchCap: 2,
1295 fetchText: (url: string) => {
1296 const rawId = url.replace(/.*\/models\//, '').replace(/\/llms.txt$/, '')
1297 seen.push(rawId)
1298 return Promise.resolve(files.get(rawId) ?? null)
1299 },
1300 extractCard: async (): Promise<ExtractedCard> => {
1301 extracts++
1302 return { error: 'xai 503: unavailable' }
1303 },
1304 }
1305
1306 // a compiles, b fails: b is stamped, and the cursor stays on a.
1307 const first = await extractFalPricing(deps)
1308 expect(first).toMatchObject({
1309 extracted: 1,
1310 refused: 1,
1311 cursor: 'fal-ai/a',
1312 })
1313 const b = await getDb(env).query.models.findFirst({
1314 where: eq(models.id, ids.get('fal-ai/b') ?? ''),
1315 })
1316 expect(b?.pricing).toBeNull()
1317 expect(
1318 (b!.factSources as { pricing?: { sourceHash?: string } }).pricing
1319 ?.sourceHash,
1320 ).toBe(await pricingSectionHash(pricingSection(NANO_LLMS)))
1321
1322 // The next shard starts on b and retries it; failing again while held
1323 // moves the walk on instead of stalling there.
1324 seen.length = 0
1325 const second = await extractFalPricing(deps)
1326 expect(seen.slice(0, 2)).toEqual(['fal-ai/b', 'fal-ai/c'])
1327 expect(second).toMatchObject({ extracted: 1, cursor: 'fal-ai/c' })
1328 expect(extracts).toBe(2)
1329
1330 // Once held, a success clears the way as usual.
1331 seen.length = 0
1332 const third = await extractFalPricing({
1333 ...deps,
1334 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> =>
1335 perImageCard(args.sourceUrl),
1336 })
1337 expect(seen.slice(0, 2)).toEqual(['fal-ai/a', 'fal-ai/b'])
1338 expect(third).toMatchObject({ written: 1, cursor: 'fal-ai/b' })
1339 })
1340
1341 it('holds the cursor when an extracted card is refused for a row', async () => {
1342 const providerId = 'extract-hold-refused'
1343 await seedProvider(providerId)
1344 for (const rawId of ['fal-ai/a', 'fal-ai/b']) {
1345 await seedCandidate({
1346 providerId,
1347 rawId,
1348 properties: { num_images: { type: 'integer' } },
1349 })
1350 }
1351 const outcome = await extractFalPricing({
1352 db: getDb(env),
1353 kv: env.SCHEMA_CACHE,
1354 secrets: {},
1355 now: () => NOW,
1356 providerId,
1357 fetchText: (url: string) =>
1358 Promise.resolve(url.includes('/fal-ai/a/') ? UNIT_LLMS : NANO_LLMS),
1359 extractCard: async (args: ExtractCardArgs): Promise<ExtractedCard> => ({
1360 ...perImageCard(args.sourceUrl),
1361 inputs: {
1362 num_images: { param: 'image_count', kind: 'number', default: 1 },
1363 },
1364 }),
1365 })
1366 expect(outcome).toMatchObject({ refused: 1, cursor: 'fal-ai/a' })
1367 })
1368})
1369
1370describe('extractFalPricing failure reasons (#394)', () => {
1371 it('puts why the extract failed on the leftover retry event', async () => {
1372 const providerId = 'extract-fail-reason'
1373 await seedProvider(providerId)
1374 await seedCandidate({
1375 providerId,
1376 rawId: 'fal-ai/a',
1377 properties: { num_images: { type: 'integer' } },
1378 })
1379 const batches: Array<PostHogBatch> = []
1380 vi.stubGlobal(
1381 'fetch',
1382 vi.fn<typeof fetch>(async (input, init) => {
1383 if (requestUrl(input) === POSTHOG_CAPTURE_URL) {
1384 batches.push(JSON.parse(bodyText(init?.body)) as PostHogBatch)
1385 }
1386 return new Response('', { status: 200 })
1387 }),
1388 )
1389 try {
1390 await extractFalPricing({
1391 db: getDb(env),
1392 kv: env.SCHEMA_CACHE,
1393 secrets: { POSTHOG_PROJECT_KEY: 'phc_test' },
1394 now: () => NOW,
1395 providerId,
1396 fetchText: () => Promise.resolve(NANO_LLMS),
1397 extractCard: async (): Promise<ExtractedCard> => ({
1398 error: 'xai 429: rate limited',
1399 }),
1400 })
1401 } finally {
1402 vi.unstubAllGlobals()
1403 }
1404 const failed = batches
1405 .flatMap((batch) => batch.batch)
1406 .filter((event) => event.event === 'ingest_failed')
1407 expect(failed.map((event) => event.properties)).toEqual([
1408 expect.objectContaining({
1409 job: 'fal-pricing-extract',
1410 providerId,
1411 error: 'leftover retry: 1 | xai 429: rate limited',
1412 }),
1413 ])
1414 })
1415})