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

model-identity.worker.test.ts

424 lines13.9 KB

1import { describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3import { and, eq } from 'drizzle-orm'
4​
5import { getDb } from '#/db/index.ts'
6import { changes, models } from '#/db/schema.ts'
7import { getModelDetail } from '#/server/catalog.ts'
8import { anthropicProvider } from '#/server/providers/anthropic.ts'
9import { geminiProvider } from '#/server/providers/gemini.ts'
10import { openaiProvider } from '#/server/providers/openai.ts'
11import { openrouterProvider } from '#/server/providers/openrouter.ts'
12import { provider as vercel } from '#/server/providers/adapters/vercel.ts'
13import { provider as azure } from '#/server/providers/adapters/azure.ts'
14import { namespacedUpstreamIdentity } from '#/server/providers/upstream-model.ts'
15import type { ModelInfo, ProviderConfig } from '#/server/providers/types.ts'
16import { GPT_4O } from '../../../packages/rate-card/src/fixtures/gpt-4o.ts'
17import {
18 modelDbId,
19 pollAllProviders,
20 pollProviderModels,
21} from './poll-models.ts'
22import type { SyncDeps } from './sync.ts'
23import { reconcileSameAs } from './model-identity.ts'
24​
25const SOURCE = {
26 derivation: 'listing' as const,
27 sourceUrl: 'https://example.com/models',
28 path: 'data[].id',
30const NOW = 1_781_150_100
31​
32function deps(): SyncDeps {
33 let now = 1_781_150_000
34 return { db: getDb(env), kv: env.SCHEMA_CACHE, secrets: {}, now: () => now++ }
36​
37function stub(
38 id: string,
39 listed: Array<ModelInfo>,
40 extra: Partial<ProviderConfig> = {},
41): ProviderConfig {
42 return {
43 id,
44 displayName: id,
45 specSourceUrl: `https://example.com/${id}`,
46 defaultDerivation: 'upstream-spec',
47 fetchSpec: async () => ({
48 specs: [],
49 sources: [],
50 outputStrategy: 'post-200',
51 }),
52 listModels: async () => ({ models: listed }),
53 classify: () => null,
54 ...extra,
55 }
57​
58const identify = (rawId: string) => namespacedUpstreamIdentity(rawId, SOURCE)
59const gateway = { upstreamModelIdentity: identify }
60​
61function linkChanges(d: SyncDeps, subjectId: string) {
62 return d.db
63 .select()
64 .from(changes)
65 .where(
66 and(
67 eq(changes.subjectId, subjectId),
68 eq(changes.summary, 'Upstream model link updated'),
69 ),
70 )
72​
73describe('sameAs links', () => {
74 it('links when the upstream arrives later, without touching the row or repeating the event', async () => {
75 const d = deps()
76 const makerId = 'identity-new-maker'
77 const resellerId = 'identity-new-reseller'
78 const rawId = 'publisher/native-alias'
79 const rowId = modelDbId(resellerId, rawId)
80 const row = () =>
81 d.db.query.models.findFirst({ where: eq(models.id, rowId) })
82 const reseller = stub(resellerId, [{ rawId, contextWindow: 1234 }], gateway)
83 await pollProviderModels(d, reseller)
84 await reconcileSameAs(d.db, NOW)
85 const before = await row()
86 expect(before).toMatchObject({
87 upstreamProvider: 'publisher',
88 upstreamRawId: 'native-alias',
89 upstreamSource: SOURCE,
90 sameAsModelId: null,
91 })
92 const unresolved = await getModelDetail(d.db, resellerId, rawId)
93 expect(unresolved?.sameAs).toBeNull()
94 expect(unresolved?.factSources).not.toHaveProperty('sameAs')
95​
96 const native = {
97 rawId: 'native-dated',
98 aliases: ['native-alias'],
99 pricing: GPT_4O,
100 contextWindow: 200_000,
101 }
102 const claim = { modelNamespaces: ['publisher'] }
103 await pollProviderModels(d, stub(makerId, [native], claim))
104 await reconcileSameAs(d.db, NOW)
105 const targetId = modelDbId(makerId, native.rawId)
106 // The link is the only thing that changes on the reseller's row.
107 expect(await row()).toEqual({ ...before, sameAsModelId: targetId })
108 const linked = await getModelDetail(d.db, resellerId, rawId)
109 expect(linked?.sameAs).toEqual({ provider: makerId, rawId: native.rawId })
110 expect(linked?.pricing).toBeNull()
111 expect(linked?.contextWindow).toBe(1234)
112 expect(linked?.factSources?.sameAs).toEqual(SOURCE)
113 const [event, ...extra] = await linkChanges(d, rowId)
114 expect(extra).toHaveLength(0)
115 expect(event).toMatchObject({
116 type: 'model.updated',
117 providerId: resellerId,
118 payload: {
119 before: { sameAsModelId: null },
120 after: { sameAsModelId: targetId },
121 },
122 })
123​
124 expect((await pollProviderModels(d, reseller)).updated).toBe(0)
125 await reconcileSameAs(d.db, NOW)
126 // A delisted upstream is deprecated, not deleted: the row still exists.
127 await pollProviderModels(d, stub(makerId, [], claim))
128 await reconcileSameAs(d.db, NOW)
129 expect((await row())?.sameAsModelId).toBe(targetId)
130 expect(await linkChanges(d, rowId)).toHaveLength(1)
131​
132 // The provider stops stating an upstream: evidence and link both go.
133 await pollProviderModels(
134 d,
135 stub(resellerId, [{ rawId, contextWindow: 1234 }]),
136 )
137 await reconcileSameAs(d.db, NOW)
138 expect(await row()).toMatchObject({
139 upstreamProvider: null,
140 upstreamRawId: null,
141 upstreamSource: null,
142 sameAsModelId: null,
143 })
144 expect(await linkChanges(d, rowId)).toHaveLength(2)
145 })
146​
147 it('resolves namespaces through the database and prefers exact ids, then aliases, then dots as hyphens', async () => {
148 const d = deps()
149 await pollProviderModels(
150 d,
151 stub(
152 'identity-a',
153 [
154 { rawId: 'model', aliases: ['ambiguous'] },
155 { rawId: 'other', aliases: ['ambiguous', 'model'] },
156 { rawId: 'model-x' },
157 { rawId: 'v-4-5-dated', aliases: ['v-4-5'] },
158 { rawId: 'v.1' },
159 { rawId: 'v-1' },
160 { rawId: 'dup-a', aliases: ['dup-1'] },
161 { rawId: 'dup-b', aliases: ['dup-1'] },
162 ],
163 { modelNamespaces: ['shared-publisher'] },
164 ),
165 )
166 // A second claimant makes the namespace ambiguous; a provider id still
167 // beats a namespace of the same name.
168 const rival = (modelNamespaces: Array<string>) =>
169 pollProviderModels(
170 d,
171 stub('identity-b', [{ rawId: 'model' }], { modelNamespaces }),
172 )
173 await rival(['shared-publisher', 'identity-a'])
174 const host = 'identity-host'
175 await pollProviderModels(
176 d,
177 stub(
178 host,
179 [
180 'identity-a/model',
181 'identity-a/ambiguous',
182 'identity-a/MODEL-X',
183 'identity-a/model:free',
184 'identity-a/v-4.5',
185 'identity-a/v.1',
186 'identity-a/dup.1',
187 'identity-unlisted/model',
188 'shared-publisher/model',
189 ].map((rawId) => ({ rawId })),
190 gateway,
191 ),
192 )
193 // A row whose own alias matches its stated upstream must not self-link.
194 await pollProviderModels(
195 d,
196 stub(
197 'identity-self',
198 [{ rawId: 'identity-self/m', aliases: ['m'] }],
199 gateway,
200 ),
201 )
202 // No stated upstream: a matching name alone is not evidence.
203 await pollProviderModels(
204 d,
205 stub('identity-unproven-host', [{ rawId: 'identity-a/model' }]),
206 )
207 await reconcileSameAs(d.db, NOW)
208​
209 const detail = (provider: string, rawId: string) =>
210 getModelDetail(d.db, provider, rawId)
211 for (const [rawId, target] of [
212 ['identity-a/model', 'model'],
213 ['identity-a/v.1', 'v.1'],
214 ] as const) {
215 const exact = await detail(host, rawId)
216 expect(exact?.sameAs).toEqual({ provider: 'identity-a', rawId: target })
217 expect(exact?.factSources?.sameAs).toEqual(SOURCE)
218 }
219 const normalized = await detail(host, 'identity-a/v-4.5')
220 expect(normalized?.sameAs).toEqual({
221 provider: 'identity-a',
222 rawId: 'v-4-5-dated',
223 })
224 expect(normalized?.factSources?.sameAs).toEqual({
225 ...SOURCE,
226 normalized: true,
227 })
228 for (const rawId of [
229 'identity-a/ambiguous',
230 'identity-a/MODEL-X',
231 'identity-a/model:free',
232 'identity-a/dup.1',
233 'identity-unlisted/model',
234 'shared-publisher/model',
235 ]) {
236 expect((await detail(host, rawId))?.sameAs).toBeNull()
237 }
238 expect(
239 (await detail('identity-self', 'identity-self/m'))?.sameAs,
240 ).toBeNull()
241 expect(
242 (await detail('identity-unproven-host', 'identity-a/model'))?.sameAs,
243 ).toBeNull()
244​
245 // Dropping the rival claim from config removes its row, so the namespace
246 // resolves again.
247 await rival([])
248 await reconcileSameAs(d.db, NOW)
249 expect((await detail(host, 'shared-publisher/model'))?.sameAs).toEqual({
250 provider: 'identity-a',
251 rawId: 'model',
252 })
253 })
254​
255 it('writes every link when one run changes more than a batch', async () => {
256 const d = deps()
257 const ids = Array.from({ length: 12 }, (_, i) => `m${i}`)
258 await pollProviderModels(
259 d,
260 stub(
261 'identity-bulk-maker',
262 ids.map((rawId) => ({ rawId })),
263 ),
264 )
265 await pollProviderModels(
266 d,
267 stub(
268 'identity-bulk-host',
269 ids.map((id) => ({ rawId: `identity-bulk-maker/${id}` })),
270 gateway,
271 ),
272 )
273 await reconcileSameAs(d.db, NOW)
274 const rows = await d.db
275 .select()
276 .from(models)
277 .where(eq(models.providerId, 'identity-bulk-host'))
278 expect(rows.filter((row) => row.sameAsModelId !== null)).toHaveLength(12)
279 expect(
280 await d.db
281 .select()
282 .from(changes)
283 .where(eq(changes.providerId, 'identity-bulk-host')),
284 ).toHaveLength(12 * 2) // model.added + the link
285 })
286​
287 it('resolves links at the end of a poll run, whatever order providers poll in', async () => {
288 const d = deps()
289 const outcomes = await pollAllProviders(d, [
290 stub('identity-run-host', [{ rawId: 'identity-run-maker/m' }], gateway),
291 stub('identity-run-maker', [{ rawId: 'm' }]),
292 ])
293 expect(outcomes.map((outcome) => outcome.failures)).toEqual([0, 0])
294 const rowId = modelDbId('identity-run-host', 'identity-run-maker/m')
295 const row = await d.db.query.models.findFirst({
296 where: eq(models.id, rowId),
297 })
298 expect(row?.sameAsModelId).toBe(modelDbId('identity-run-maker', 'm'))
299 expect(await linkChanges(d, rowId)).toHaveLength(1)
300 })
301​
302 it("keeps a failed reconcile out of the providers' poll outcomes", async () => {
303 // The clock is read once per provider poll, then once by the reconcile
304 // step, so failing the second read fails only the reconcile.
305 let reads = 0
306 const d: SyncDeps = {
307 ...deps(),
308 now: () => {
309 if (++reads > 1) throw new Error('reconcile failed')
310 return NOW
311 },
312 }
313 const outcomes = await pollAllProviders(d, [
314 stub('identity-run-solo', [{ rawId: 'm' }]),
315 ])
316 expect(outcomes).toMatchObject([{ failures: 0, added: 1 }])
317 })
318​
319 it('enforces the target foreign key and rejects a self link', async () => {
320 const d = deps()
321 await pollProviderModels(d, stub('identity-fk', [{ rawId: 'model' }]))
322 const id = modelDbId('identity-fk', 'model')
323 await expect(
324 d.db
325 .update(models)
326 .set({ sameAsModelId: 'does-not-exist' })
327 .where(eq(models.id, id)),
328 ).rejects.toThrow()
329 await expect(
330 d.db.update(models).set({ sameAsModelId: id }).where(eq(models.id, id)),
331 ).rejects.toThrow()
332 await expect(
333 d.db
334 .update(models)
335 .set({ upstreamProvider: 'half-an-identity' })
336 .where(eq(models.id, id)),
337 ).rejects.toThrow()
338 })
339​
340 it('links OpenRouter, Vercel, and Azure rows to the upstream they state (#199)', async () => {
341 const d = deps()
342 const pollFixture = (p: ProviderConfig, listed: Array<ModelInfo>) =>
343 pollProviderModels(d, {
344 ...p,
345 listModels: async () => ({ models: listed }),
346 })
347 await pollFixture(anthropicProvider, [
348 {
349 rawId: 'claude-opus-4-5-20251101',
350 aliases: ['claude-opus-4-5'],
351 pricing: GPT_4O,
352 },
353 { rawId: 'claude-fable-5' },
354 ])
355 await pollFixture(openaiProvider, [{ rawId: 'gpt-4o-2024-11-20' }])
356 await pollFixture(geminiProvider, [{ rawId: 'gemini-2.5-pro' }])
357 // Ids as the gateways publish them: dotted versions, `google` for Gemini.
358 await pollFixture(openrouterProvider, [
359 { rawId: 'anthropic/claude-opus-4.5', contextWindow: 1234 },
360 { rawId: 'anthropic/claude-opus-4.5:batch' },
361 { rawId: 'anthropic/claude-fable-5' },
362 { rawId: 'claude-opus-4-5' },
363 { rawId: 'openai/missing-native-model' },
364 ])
365 await pollFixture(vercel, [
366 { rawId: 'google/gemini-2.5-pro' },
367 { rawId: 'anthropic/claude-opus-4.5' },
368 ])
369 await pollFixture(azure, [{ rawId: 'gpt-4o-2024-11-20' }])
370 await reconcileSameAs(d.db, NOW)
371​
372 const opus = 'claude-opus-4-5-20251101'
373 const cases = [
374 ['openrouter', 'anthropic/claude-opus-4.5', 'anthropic', opus, 'listing'],
375 [
376 'openrouter',
377 'anthropic/claude-fable-5',
378 'anthropic',
379 'claude-fable-5',
380 'listing',
381 ],
382 ['vercel', 'anthropic/claude-opus-4.5', 'anthropic', opus, 'listing'],
383 [
384 'vercel',
385 'google/gemini-2.5-pro',
386 'gemini',
387 'gemini-2.5-pro',
388 'listing',
389 ],
390 [
391 'azure',
392 'gpt-4o-2024-11-20',
393 'openai',
394 'gpt-4o-2024-11-20',
395 'docs-derived',
396 ],
397 ] as const
398 for (const [provider, rawId, upstream, nativeId, derivation] of cases) {
399 const result = await getModelDetail(d.db, provider, rawId)
400 expect(result?.sameAs).toEqual({ provider: upstream, rawId: nativeId })
401 expect(result?.factSources?.sameAs?.derivation).toBe(derivation)
402 // Only the dotted spelling needed normalizing.
403 expect(result?.factSources?.sameAs?.normalized).toBe(
404 rawId.endsWith('4.5') ? true : undefined,
405 )
406 }
407 const linked = await getModelDetail(
408 d.db,
409 'openrouter',
410 'anthropic/claude-opus-4.5',
411 )
412 expect(linked?.contextWindow).toBe(1234)
413 expect(linked?.pricing).toBeNull()
414 for (const rawId of [
415 'anthropic/claude-opus-4.5:batch',
416 'claude-opus-4-5',
417 'openai/missing-native-model',
418 ]) {
419 const unlinked = await getModelDetail(d.db, 'openrouter', rawId)
420 expect(unlinked?.sameAs).toBeNull()
421 expect(unlinked?.factSources?.sameAs).toBeUndefined()
422 }
423 })
424})