Open History to see the last commit
1import { bodyText, requestUrl } from '#/lib/text.ts'
2import { describe, expect, it } from 'vitest'
3
4import { assertParsed } from '#/server/providers/model-facts.ts'
5
6import {
7 CF_TRACE_URL,
8 POSTHOG_CAPTURE_URL,
9 captureIngestEvents,
10 ingestFailedEvent,
11 noteIngest,
12 observePricingWrite,
13 parseRowsEvent,
14 posthogBatch,
15 runIngestScope,
16 takeIngestEvents,
17} from './ingest-signals.ts'
18
19describe('observePricingWrite', () => {
20 it('keeps a stored card and emits pricing_lost when the parser misses the row', () => {
21 expect(
22 observePricingWrite({
23 providerId: 'byteplus',
24 rawId: 'seedream-5-0-pro',
25 incomingNull: true,
26 hadStoredCard: true,
27 keepExtracted: false,
28 }),
29 ).toEqual({
30 keepPrior: true,
31 failure: 1,
32 events: [
33 {
34 event: 'pricing_lost',
35 properties: {
36 providerId: 'byteplus',
37 rawId: 'seedream-5-0-pro',
38 reason: 'parser_miss',
39 },
40 },
41 ],
42 })
43 })
44
45 it('does not treat a FAL docs-extracted keep as a loss', () => {
46 expect(
47 observePricingWrite({
48 providerId: 'fal',
49 rawId: 'fal-ai/flux',
50 incomingNull: true,
51 hadStoredCard: true,
52 keepExtracted: true,
53 }),
54 ).toEqual({ keepPrior: true, events: [], failure: 0 })
55 })
56
57 it('obeys a stated reason quietly: cleared drops the card, unavailable keeps it', () => {
58 const lost = {
59 providerId: 'huggingface',
60 rawId: 'a/b',
61 incomingNull: true,
62 hadStoredCard: true,
63 }
64 // `cleared` beats even the FAL docs-extracted keep.
65 expect(
66 observePricingWrite({ ...lost, keepExtracted: true, absent: 'cleared' }),
67 ).toEqual({ keepPrior: false, events: [], failure: 0 })
68 expect(
69 observePricingWrite({
70 ...lost,
71 keepExtracted: false,
72 absent: 'unavailable',
73 }),
74 ).toEqual({ keepPrior: true, events: [], failure: 0 })
75 })
76
77 it('emits rate_card_refused when a stored card fails the write gate', () => {
78 const decision = observePricingWrite({
79 providerId: 'byteplus',
80 rawId: 'seedream-5-0-pro',
81 incomingNull: false,
82 hadStoredCard: true,
83 keepExtracted: false,
84 refused: 'invented_param',
85 })
86 expect(decision.keepPrior).toBe(false)
87 expect(decision.failure).toBe(1)
88 expect(decision.events).toEqual([
89 {
90 event: 'rate_card_refused',
91 properties: {
92 providerId: 'byteplus',
93 rawId: 'seedream-5-0-pro',
94 reason: 'invented_param',
95 },
96 },
97 ])
98 })
99
100 it('stays quiet for an uncompilable listing that never had a card', () => {
101 expect(
102 observePricingWrite({
103 providerId: 'openrouter',
104 rawId: 'openrouter/auto',
105 incomingNull: false,
106 hadStoredCard: false,
107 keepExtracted: false,
108 refused: 'uncompilable',
109 }).events,
110 ).toEqual([])
111 })
112})
113
114describe('posthog capture', () => {
115 it('batches a zero-row poll failure without putting the key in properties', () => {
116 const body = posthogBatch(
117 [
118 ingestFailedEvent(
119 'models-poll',
120 'byteplus',
121 'byteplus pricing page: parsed 0 model rows',
122 ),
123 ],
124 'phc_test',
125 )
126 expect(body.api_key).toBe('phc_test')
127 expect(body.batch).toEqual([
128 {
129 event: 'ingest_failed',
130 distinct_id: 'modelschemas',
131 properties: {
132 job: 'models-poll',
133 providerId: 'byteplus',
134 error: 'byteplus pricing page: parsed 0 model rows',
135 },
136 },
137 ])
138 expect(JSON.stringify(body.batch)).not.toContain('phc_test')
139 })
140
141 it('records parse_rows from assertParsed and still captures if PostHog throws', async () => {
142 takeIngestEvents()
143 assertParsed(new Map([['seedream-5-0', 1]]), 'byteplus pricing page')
144 const calls: Array<[string, RequestInit | undefined]> = []
145 const fetchImpl: typeof fetch = (input, init) => {
146 calls.push([requestUrl(input), init])
147 return Promise.reject(new Error('down'))
148 }
149 await expect(
150 captureIngestEvents('phc_test', fetchImpl),
151 ).resolves.toBeUndefined()
152 expect(calls[0]?.[0]).toBe(POSTHOG_CAPTURE_URL)
153 expect(calls[0]?.[1]?.method).toBe('POST')
154 const body = JSON.parse(bodyText(calls[0]?.[1]?.body)) as {
155 batch: Array<{ event: string; properties: { rows: number } }>
156 }
157 expect(body.batch[0]).toMatchObject({
158 event: 'parse_rows',
159 properties: { source: 'byteplus pricing page', rows: 1 },
160 })
161 })
162
163 it('keeps overlapping scopes from mixing events', async () => {
164 takeIngestEvents()
165 const outer = runIngestScope(async () => {
166 noteIngest(parseRowsEvent('outer', 1))
167 const inner = await runIngestScope(async () => {
168 noteIngest(parseRowsEvent('inner', 2))
169 return takeIngestEvents()
170 })
171 return { inner, outer: takeIngestEvents() }
172 })
173 const taken = await outer
174 expect(taken.inner).toEqual([parseRowsEvent('inner', 2)])
175 expect(taken.outer).toEqual([parseRowsEvent('outer', 1)])
176 expect(takeIngestEvents()).toEqual([])
177 })
178
179 it('passes an abort signal so a hung PostHog capture cannot stall the cron', async () => {
180 takeIngestEvents()
181 noteIngest(parseRowsEvent('page', 1))
182 const fetchImpl: typeof fetch = (_input, init) => {
183 expect(init?.signal?.aborted).toBe(false)
184 return Promise.reject(new Error('down'))
185 }
186 await expect(
187 captureIngestEvents('phc_test', fetchImpl),
188 ).resolves.toBeUndefined()
189 })
190
191 it('stamps the colo on ingest_failed events and on no other event', async () => {
192 takeIngestEvents()
193 noteIngest(ingestFailedEvent('models-poll', 'gemini', 'GET → 400'))
194 noteIngest(parseRowsEvent('page', 1))
195 const urls: Array<string> = []
196 let body = ''
197 const fetchImpl: typeof fetch = (input, init) => {
198 urls.push(requestUrl(input))
199 if (requestUrl(input) === CF_TRACE_URL) {
200 return Promise.resolve(
201 new Response('fl=1\nh=www.cloudflare.com\ncolo=HKG\nloc=US\n'),
202 )
203 }
204 body = bodyText(init?.body)
205 return Promise.resolve(new Response('{}'))
206 }
207 await captureIngestEvents('phc_test', fetchImpl)
208 expect(urls).toEqual([CF_TRACE_URL, POSTHOG_CAPTURE_URL])
209 const { batch } = JSON.parse(body) as {
210 batch: Array<{ properties: Record<string, unknown> }>
211 }
212 expect(batch[0]?.properties).toMatchObject({
213 providerId: 'gemini',
214 colo: 'HKG',
215 })
216 expect(batch[1]?.properties).not.toHaveProperty('colo')
217 })
218
219 it('still captures ingest_failed without a colo when the trace fails', async () => {
220 takeIngestEvents()
221 noteIngest(ingestFailedEvent('models-poll', 'anthropic', 'GET → 403'))
222 let body = ''
223 const fetchImpl: typeof fetch = (input, init) => {
224 if (requestUrl(input) === CF_TRACE_URL) {
225 return Promise.reject(new Error('down'))
226 }
227 body = bodyText(init?.body)
228 return Promise.resolve(new Response('{}'))
229 }
230 await captureIngestEvents('phc_test', fetchImpl)
231 const { batch } = JSON.parse(body) as {
232 batch: Array<{ properties: Record<string, unknown> }>
233 }
234 expect(batch[0]?.properties).toEqual({
235 job: 'models-poll',
236 providerId: 'anthropic',
237 error: 'GET → 403',
238 })
239 })
240
241 it('reads no trace when no event is ingest_failed', async () => {
242 takeIngestEvents()
243 noteIngest(parseRowsEvent('page', 1))
244 const urls: Array<string> = []
245 const fetchImpl: typeof fetch = (input) => {
246 urls.push(requestUrl(input))
247 return Promise.resolve(new Response('{}'))
248 }
249 await captureIngestEvents('phc_test', fetchImpl)
250 expect(urls).toEqual([POSTHOG_CAPTURE_URL])
251 })
252
253 it('assertParsed throws on zero rows and does not emit parse_rows', () => {
254 takeIngestEvents()
255 expect(() => assertParsed(new Map(), 'gemini pricing page')).toThrow(
256 /parsed 0 model rows/,
257 )
258 expect(takeIngestEvents()).toEqual([])
259 })
260})