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