Open History to see the last commit
1import { providerRegistry } from '../providers/index.ts'
2import { assembleProviderOpenApi } from '../provider-openapi.ts'
3import { pollProviderModels } from './poll-models.ts'
4import { provider as gatewayProvider } from '../providers/adapters/cloudflare-ai-gateway.ts'
5import { getActivitySchemaMap, getEndpointSchema } from '../schemas-api.ts'
6import { describe, expect, it } from 'vitest'
7import { env } from 'cloudflare:test'
8import { and, eq } from 'drizzle-orm'
9
10import { getDb } from '../../db/index.ts'
11import {
12 changes,
13 endpoints,
14 providers,
15 schemaVersions,
16} from '../../db/schema.ts'
17import { getByHash } from '../kv.ts'
18import type { OpenApiDocument, ProviderConfig } from '../providers/types.ts'
19import { EXTRACTOR_VERSION } from './bundle.ts'
20import { MODELS_DEV_API_URL } from './retire-models-dev.ts'
21import { syncProvider } from './sync.ts'
22import type { SyncDeps } from './sync.ts'
23
24const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` })
25
26function fixtureSpec(maxTokens: boolean): OpenApiDocument {
27 return {
28 openapi: '3.1.0',
29 paths: {
30 '/v1/messages': {
31 post: {
32 summary: 'Create a message',
33 requestBody: {
34 content: { 'application/json': { schema: ref('CreateMessage') } },
35 },
36 responses: {
37 '200': {
38 content: { 'application/json': { schema: ref('Message') } },
39 },
40 },
41 },
42 },
43 '/v1/admin/keys': {
44 post: { requestBody: { content: {} }, responses: {} },
45 },
46 },
47 components: {
48 schemas: {
49 CreateMessage: {
50 type: 'object',
51 properties: {
52 model: { type: 'string' },
53 ...(maxTokens ? { max_tokens: { type: 'integer' } } : {}),
54 },
55 },
56 Message: { type: 'object', properties: { id: { type: 'string' } } },
57 },
58 },
59 }
60}
61
62// D1 state persists across tests in the same isolate, so each test gets its
63// own provider id and filters its queries by it.
64const STUB_SOURCE = {
65 url: 'https://example.com/spec.json',
66 hash: 'stub-source-hash',
67}
68
69it('withdraws only explicitly rejected current sources after a successful native fetch', async () => {
70 const id = 'sync-withdraw-borrowed'
71 const deps = await freshDeps(id)
72 const provider = stubProvider(id, fixtureSpec(false))
73 await syncProvider(deps, provider)
74 await expect(
75 syncProvider(deps, {
76 ...provider,
77 fetchSpec: async () => {
78 throw new Error('native docs failed')
79 },
80 }),
81 ).rejects.toThrow('native docs failed')
82 expect(
83 await getEndpointSchema(deps.db, id, 'chat', 'v1/messages', 'input'),
84 ).not.toBeNull()
85 const otherId = 'sync-withdraw-other-provider'
86 const otherDeps = await freshDeps(otherId)
87 await syncProvider(otherDeps, stubProvider(otherId, fixtureSpec(false)))
88 const result = await syncProvider(deps, {
89 ...provider,
90 fetchSpec: async () => ({
91 specs: [],
92 sources: [],
93 outputStrategy: 'post-200',
94 withdrawnSchemaSources: [STUB_SOURCE.url],
95 skipped: 'own docs publish no schema',
96 }),
97 })
98 expect(result.warnings).toContain(
99 'Withdrew 2 schema versions from rejected former sources',
100 )
101 expect(
102 await getEndpointSchema(deps.db, id, 'chat', 'v1/messages', 'input'),
103 ).toBeNull()
104 expect(
105 await getEndpointSchema(deps.db, id, 'chat', 'v1/messages', 'output'),
106 ).toBeNull()
107 expect(
108 await getEndpointSchema(deps.db, otherId, 'chat', 'v1/messages', 'input'),
109 ).not.toBeNull()
110 const history = await deps.db
111 .select()
112 .from(schemaVersions)
113 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
114 .where(eq(endpoints.providerId, id))
115 expect(history).toHaveLength(2)
116 expect(
117 history.every((row) => row.schema_versions.supersededAt !== null),
118 ).toBe(true)
119})
120
121function stubProvider(id: string, spec: OpenApiDocument): ProviderConfig {
122 return {
123 id,
124 displayName: 'Stub',
125 defaultDerivation: 'upstream-spec',
126 fetchSpec: () =>
127 Promise.resolve({
128 specs: [spec],
129 sources: [STUB_SOURCE],
130 outputStrategy: 'post-200' as const,
131 }),
132 listModels: () => Promise.resolve({ models: [] }),
133 classify: (path) => (path === '/v1/messages' ? 'chat' : null),
134 }
135}
136
137async function freshDeps(providerId: string): Promise<SyncDeps> {
138 const db = getDb(env)
139 await db.insert(providers).values({
140 id: providerId,
141 displayName: 'Stub',
142 specSourceUrl: 'https://example.com/spec.json',
143 })
144 let tick = 1_781_150_000
145 return { db, kv: env.SCHEMA_CACHE, secrets: {}, now: () => tick++ }
146}
147
148const providerChanges = (db: SyncDeps['db'], id: string) =>
149 db.select().from(changes).where(eq(changes.providerId, id))
150const providerEndpoints = (db: SyncDeps['db'], id: string) =>
151 db.select().from(endpoints).where(eq(endpoints.providerId, id))
152
153describe('syncProvider', () => {
154 it('inserts on first run, no-ops on second, one schema.updated on mutation', async () => {
155 const id = 'stub-main'
156 const deps = await freshDeps(id)
157 const db = deps.db
158
159 // First run: endpoint + input/output versions inserted, KV warmed.
160 const first = await syncProvider(deps, stubProvider(id, fixtureSpec(false)))
161 expect(first.error).toBeUndefined()
162 expect(first.endpointsSeen).toBe(1) // admin endpoint classified to null
163 expect(first.versionsAdded).toBe(2)
164
165 const endpointRows = await providerEndpoints(db, id)
166 expect(endpointRows).toHaveLength(1)
167 expect(endpointRows[0]?.id).toBe(`${id}/v1/messages`)
168 expect(endpointRows[0]?.activity).toBe('chat')
169
170 const firstChanges = await providerChanges(db, id)
171 expect(firstChanges.map((c) => c.type).sort()).toEqual([
172 'endpoint.added',
173 'schema.added',
174 'schema.added',
175 ])
176
177 const versions = await db
178 .select()
179 .from(schemaVersions)
180 .where(eq(schemaVersions.endpointId, `${id}/v1/messages`))
181 expect(versions).toHaveLength(2)
182 const inputVersion = versions.find((v) => v.kind === 'input')
183 expect(
184 await getByHash(env.SCHEMA_CACHE, inputVersion?.contentHash ?? ''),
185 ).toEqual({ type: 'object', properties: { model: { type: 'string' } } })
186 // Provenance is recorded on every version.
187 expect(inputVersion?.sourceUrl).toBe(STUB_SOURCE.url)
188 expect(inputVersion?.sourceHash).toBe(STUB_SOURCE.hash)
189 expect(inputVersion?.extractorVersion).toBe(EXTRACTOR_VERSION)
190 // Derivation falls back to the provider default when an operation
191 // carries no marker of its own.
192 expect(inputVersion?.derivation).toBe('upstream-spec')
193 expect(inputVersion?.verifiedAt).toBeNull()
194
195 const providerRow = await db.query.providers.findFirst({
196 where: eq(providers.id, id),
197 })
198 expect(providerRow?.lastSyncedAt).not.toBeNull()
199 expect(providerRow?.status).toBe('active')
200
201 // Second run with the identical spec: fully idempotent.
202 const second = await syncProvider(
203 deps,
204 stubProvider(id, fixtureSpec(false)),
205 )
206 expect(second.versionsAdded).toBe(0)
207 expect(second.changesWritten).toBe(0)
208 expect(await providerChanges(db, id)).toHaveLength(3)
209
210 // Mutated input schema: exactly one schema.updated change, old version
211 // superseded, new one current.
212 const third = await syncProvider(deps, stubProvider(id, fixtureSpec(true)))
213 expect(third.versionsAdded).toBe(1)
214 expect(third.changesWritten).toBe(1)
215
216 const updated = (await providerChanges(db, id)).filter(
217 (c) => c.type === 'schema.updated',
218 )
219 expect(updated).toHaveLength(1)
220 expect(updated[0]?.subjectId).toBe(`${id}/v1/messages`)
221
222 const inputVersions = (
223 await db
224 .select()
225 .from(schemaVersions)
226 .where(eq(schemaVersions.endpointId, `${id}/v1/messages`))
227 ).filter((v) => v.kind === 'input')
228 expect(inputVersions).toHaveLength(2)
229 expect(inputVersions.filter((v) => v.supersededAt === null)).toHaveLength(1)
230 const payload = updated[0]?.payload as { previousHash: string }
231 expect(payload.previousHash).toBe(inputVersion?.contentHash)
232 })
233
234 it.each([
235 ['endpoint.added', false],
236 ['schema.added', false],
237 ['schema.updated', true],
238 ] as const)(
239 'rolls back the write whose %s change failed, so the next run records it',
240 async (type, mutate) => {
241 const id = `stub-atomic-${type.replace('.', '-')}`
242 const trigger = `fail_${id.replaceAll('-', '_')}`
243 const deps = await freshDeps(id)
244 const db = deps.db
245 if (mutate) await syncProvider(deps, stubProvider(id, fixtureSpec(false)))
246
247 // Fails only this change insert, as the D1 error on the grok sync did.
248 await env.DB.prepare(
249 `CREATE TRIGGER ${trigger} BEFORE INSERT ON changes
250 WHEN NEW.provider_id = '${id}' AND NEW.type = '${type}'
251 BEGIN SELECT RAISE(ABORT, 'injected'); END`,
252 ).run()
253 try {
254 await expect(
255 syncProvider(deps, stubProvider(id, fixtureSpec(mutate))),
256 ).rejects.toThrow('injected')
257 } finally {
258 await env.DB.prepare(`DROP TRIGGER IF EXISTS ${trigger}`).run()
259 }
260
261 // The next run still sees the change, so it is written exactly once.
262 await syncProvider(deps, stubProvider(id, fixtureSpec(mutate)))
263 const written = (await providerChanges(db, id)).filter(
264 (c) => c.type === type,
265 )
266 expect(written).toHaveLength(type === 'schema.added' ? 2 : 1)
267 },
268 )
269
270 it('revives the superseded version when upstream reverts to prior content', async () => {
271 const id = 'stub-revert'
272 const deps = await freshDeps(id)
273 const db = deps.db
274
275 // A → B → A: the third run re-derives version A's deterministic id.
276 await syncProvider(deps, stubProvider(id, fixtureSpec(false)))
277 const versionA = await db.query.schemaVersions.findFirst({
278 where: and(
279 eq(schemaVersions.endpointId, `${id}/v1/messages`),
280 eq(schemaVersions.kind, 'input'),
281 ),
282 })
283 await syncProvider(deps, stubProvider(id, fixtureSpec(true)))
284 const revert = await syncProvider(
285 deps,
286 stubProvider(id, fixtureSpec(false)),
287 )
288 expect(revert.error).toBeUndefined()
289 expect(revert.versionsAdded).toBe(1)
290 expect(revert.changesWritten).toBe(1)
291
292 const inputVersions = (
293 await db
294 .select()
295 .from(schemaVersions)
296 .where(eq(schemaVersions.endpointId, `${id}/v1/messages`))
297 ).filter((v) => v.kind === 'input')
298 // Still two distinct versions — A was revived, not duplicated.
299 expect(inputVersions).toHaveLength(2)
300 const current = inputVersions.filter((v) => v.supersededAt === null)
301 expect(current).toHaveLength(1)
302 expect(current[0]?.id).toBe(versionA?.id)
303 expect(current[0]?.contentHash).toBe(versionA?.contentHash)
304
305 // The revert is recorded as a regular schema.updated change.
306 const updated = (await providerChanges(db, id)).filter(
307 (c) => c.type === 'schema.updated',
308 )
309 expect(updated).toHaveLength(2)
310
311 const providerRow = await db.query.providers.findFirst({
312 where: eq(providers.id, id),
313 })
314 expect(providerRow?.status).toBe('active')
315 })
316
317 it('records endpoint.removed once when an endpoint vanishes from the spec', async () => {
318 const id = 'stub-removal'
319 const deps = await freshDeps(id)
320 await syncProvider(deps, stubProvider(id, fixtureSpec(false)))
321
322 const emptySpec: OpenApiDocument = {
323 paths: {},
324 components: { schemas: {} },
325 }
326 await syncProvider(deps, stubProvider(id, emptySpec))
327 await syncProvider(deps, stubProvider(id, emptySpec)) // no duplicate change
328
329 const removed = (await providerChanges(deps.db, id)).filter(
330 (c) => c.type === 'endpoint.removed',
331 )
332 expect(removed).toHaveLength(1)
333 // History rows survive removal.
334 expect(await providerEndpoints(deps.db, id)).toHaveLength(1)
335 expect(
336 await deps.db
337 .select()
338 .from(schemaVersions)
339 .where(eq(schemaVersions.endpointId, `${id}/v1/messages`)),
340 ).toHaveLength(2)
341 })
342
343 it('reports skipped providers without touching the database', async () => {
344 const id = 'stub-skipped'
345 const deps = await freshDeps(id)
346 const skippy: ProviderConfig = {
347 ...stubProvider(id, fixtureSpec(false)),
348 fetchSpec: () =>
349 Promise.resolve({
350 specs: [],
351 sources: [],
352 outputStrategy: 'post-200' as const,
353 skipped: 'stub: STUB_KEY not set — skipped',
354 }),
355 }
356 const outcome = await syncProvider(deps, skippy)
357 expect(outcome.skipped).toContain('STUB_KEY')
358 expect(await providerEndpoints(deps.db, id)).toHaveLength(0)
359 const providerRow = await deps.db.query.providers.findFirst({
360 where: eq(providers.id, id),
361 })
362 expect(providerRow?.lastSyncedAt).toBeNull()
363 })
364
365 it('restores active after a by-design skip and leaves a missing-key skip degraded', async () => {
366 const id = 'stub-skip-recovers'
367 const deps = await freshDeps(id)
368 const syncedAt = 1_700_000_000
369 await deps.db
370 .update(providers)
371 .set({ status: 'degraded', lastSyncedAt: syncedAt })
372 .where(eq(providers.id, id))
373 const skip = (skipped: string): ProviderConfig => ({
374 ...stubProvider(id, fixtureSpec(false)),
375 fetchSpec: () =>
376 Promise.resolve({
377 specs: [],
378 sources: [STUB_SOURCE],
379 outputStrategy: 'post-200' as const,
380 skipped,
381 }),
382 })
383
384 const recovered = await syncProvider(
385 deps,
386 skip('stub: docs publish no request schema — skipped'),
387 )
388 expect(recovered.skipped).toContain('no request schema')
389 const restored = await deps.db.query.providers.findFirst({
390 where: eq(providers.id, id),
391 })
392 expect(restored?.status).toBe('active')
393 expect(restored?.lastSyncedAt).toBe(syncedAt)
394
395 await deps.db
396 .update(providers)
397 .set({ status: 'degraded' })
398 .where(eq(providers.id, id))
399 const missed = await syncProvider(
400 deps,
401 skip('stub: STUB_KEY not set — skipped'),
402 )
403 expect(missed.skipped).toContain('STUB_KEY')
404 const stillDegraded = await deps.db.query.providers.findFirst({
405 where: eq(providers.id, id),
406 })
407 expect(stillDegraded?.status).toBe('degraded')
408 expect(stillDegraded?.lastSyncedAt).toBe(syncedAt)
409 })
410
411 it('drops schema versions sourced from models.dev on a skipped sync', async () => {
412 const id = 'stub-models-dev-schema'
413 const deps = await freshDeps(id)
414 await deps.db.insert(endpoints).values({
415 id: `${id}/chat/completions`,
416 providerId: id,
417 activity: 'chat',
418 method: 'POST',
419 path: '/chat/completions',
420 })
421 await deps.db.insert(schemaVersions).values([
422 {
423 id: `${id}/chat/completions:dev`,
424 endpointId: `${id}/chat/completions`,
425 kind: 'input',
426 contentHash: 'a'.repeat(64),
427 schema: JSON.stringify({ type: 'object' }),
428 sourceUrl: MODELS_DEV_API_URL,
429 createdAt: 1,
430 },
431 {
432 id: `${id}/chat/completions:docs`,
433 endpointId: `${id}/chat/completions`,
434 kind: 'output',
435 contentHash: 'b'.repeat(64),
436 schema: JSON.stringify({ type: 'object' }),
437 sourceUrl: 'https://example.com/openapi.json',
438 createdAt: 1,
439 },
440 ])
441 const outcome = await syncProvider(deps, {
442 ...stubProvider(id, fixtureSpec(false)),
443 fetchSpec: () =>
444 Promise.resolve({
445 specs: [],
446 sources: [],
447 outputStrategy: 'post-200' as const,
448 skipped: 'stub: no first-party spec — skipped',
449 }),
450 })
451 expect(outcome.skipped).toContain('no first-party spec')
452 const versions = await deps.db
453 .select()
454 .from(schemaVersions)
455 .where(eq(schemaVersions.endpointId, `${id}/chat/completions`))
456 expect(versions.map((row) => row.id)).toEqual([
457 `${id}/chat/completions:docs`,
458 ])
459 expect(await providerEndpoints(deps.db, id)).toHaveLength(1)
460 })
461})
462
463it('stores a verified schema-less route without manufacturing schema versions', async () => {
464 const id = 'sync-native-route-only'
465 const deps = await freshDeps(id)
466 const provider = stubProvider(id, {
467 paths: {
468 '/v1/messages': {
469 post: { 'x-modelschemas-route-only': true, responses: {} },
470 },
471 },
472 })
473 const outcome = await syncProvider(deps, provider)
474 expect(outcome).toMatchObject({ endpointsSeen: 1, versionsAdded: 0 })
475 expect(
476 (await getActivitySchemaMap(deps.db, id, 'chat')).endpoints['v1/messages'],
477 ).toEqual({ input: null, output: null })
478 expect(await getEndpointSchema(deps.db, id, 'chat', 'v1/messages')).toBeNull()
479 expect(
480 await deps.db.select().from(endpoints).where(eq(endpoints.providerId, id)),
481 ).toMatchObject([{ path: '/v1/messages', method: 'POST', activity: 'chat' }])
482 expect(
483 await deps.db
484 .select()
485 .from(schemaVersions)
486 .where(eq(schemaVersions.endpointId, `${id}/v1/messages`)),
487 ).toEqual([])
488})
489
490it('keeps per-model logical schema identities on one real multi-activity HTTP path', async () => {
491 const id = 'sync-shared-native-run'
492 const deps = await freshDeps(id)
493 const path = '/accounts/{account_id}/ai/run'
494 const provider: ProviderConfig = {
495 ...stubProvider(id, {}),
496 fetchSpec: async () => ({
497 specs: [],
498 sources: [],
499 outputStrategy: 'post-200',
500 bundledEndpoints: [
501 {
502 publicId: 'author/chat',
503 path,
504 activity: 'chat',
505 description: null,
506 source: STUB_SOURCE,
507 derivation: 'generated',
508 input: {
509 type: 'object',
510 properties: { model: { const: 'author/chat' } },
511 },
512 },
513 {
514 publicId: 'author/image',
515 path,
516 activity: 'image',
517 description: null,
518 source: STUB_SOURCE,
519 derivation: 'generated',
520 input: {
521 type: 'object',
522 properties: { model: { const: 'author/image' } },
523 },
524 },
525 ],
526 }),
527 }
528 const outcome = await syncProvider(deps, provider)
529 expect(outcome).toMatchObject({ endpointsSeen: 2, versionsAdded: 2 })
530 const rows = await deps.db
531 .select()
532 .from(endpoints)
533 .where(eq(endpoints.providerId, id))
534 expect(rows.map((row) => row.path)).toEqual([path, path])
535 expect(rows.map((row) => row.id).sort()).toEqual([
536 `${id}/author/chat`,
537 `${id}/author/image`,
538 ])
539 expect(
540 await getEndpointSchema(deps.db, id, 'chat', 'author/chat', 'output'),
541 ).toBeNull()
542 const configured = {
543 ...provider,
544 specGrain: gatewayProvider.specGrain,
545 connect: gatewayProvider.connect,
546 listModels: async () => ({
547 models: [
548 { rawId: 'author/chat', activity: 'chat' as const },
549 { rawId: 'author/image', activity: 'image' as const },
550 ],
551 }),
552 }
553 providerRegistry.push(configured)
554 try {
555 await pollProviderModels(deps, configured)
556 const assembled = await assembleProviderOpenApi(deps.db, id, {
557 model: 'author/chat',
558 })
559 expect(assembled.ok).toBe(true)
560 if (!assembled.ok) throw new Error(assembled.message)
561 expect(
562 Object.keys(assembled.document.paths as Record<string, unknown>),
563 ).toEqual([path])
564 expect(assembled.document.servers).toEqual([
565 { url: 'https://api.cloudflare.com/client/v4' },
566 ])
567 expect(assembled.document.paths).toMatchObject({
568 [path]: {
569 post: {
570 requestBody: {
571 content: {
572 'application/json': {
573 schema: { properties: { model: { enum: ['author/chat'] } } },
574 },
575 },
576 },
577 },
578 },
579 })
580 } finally {
581 providerRegistry.splice(providerRegistry.indexOf(configured), 1)
582 }
583})