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('revives the superseded version when upstream reverts to prior content', async () => {
235 const id = 'stub-revert'
236 const deps = await freshDeps(id)
237 const db = deps.db
238
239 // A → B → A: the third run re-derives version A's deterministic id.
240 await syncProvider(deps, stubProvider(id, fixtureSpec(false)))
241 const versionA = await db.query.schemaVersions.findFirst({
242 where: and(
243 eq(schemaVersions.endpointId, `${id}/v1/messages`),
244 eq(schemaVersions.kind, 'input'),
245 ),
246 })
247 await syncProvider(deps, stubProvider(id, fixtureSpec(true)))
248 const revert = await syncProvider(
249 deps,
250 stubProvider(id, fixtureSpec(false)),
251 )
252 expect(revert.error).toBeUndefined()
253 expect(revert.versionsAdded).toBe(1)
254 expect(revert.changesWritten).toBe(1)
255
256 const inputVersions = (
257 await db
258 .select()
259 .from(schemaVersions)
260 .where(eq(schemaVersions.endpointId, `${id}/v1/messages`))
261 ).filter((v) => v.kind === 'input')
262 // Still two distinct versions — A was revived, not duplicated.
263 expect(inputVersions).toHaveLength(2)
264 const current = inputVersions.filter((v) => v.supersededAt === null)
265 expect(current).toHaveLength(1)
266 expect(current[0]?.id).toBe(versionA?.id)
267 expect(current[0]?.contentHash).toBe(versionA?.contentHash)
268
269 // The revert is recorded as a regular schema.updated change.
270 const updated = (await providerChanges(db, id)).filter(
271 (c) => c.type === 'schema.updated',
272 )
273 expect(updated).toHaveLength(2)
274
275 const providerRow = await db.query.providers.findFirst({
276 where: eq(providers.id, id),
277 })
278 expect(providerRow?.status).toBe('active')
279 })
280
281 it('records endpoint.removed once when an endpoint vanishes from the spec', async () => {
282 const id = 'stub-removal'
283 const deps = await freshDeps(id)
284 await syncProvider(deps, stubProvider(id, fixtureSpec(false)))
285
286 const emptySpec: OpenApiDocument = {
287 paths: {},
288 components: { schemas: {} },
289 }
290 await syncProvider(deps, stubProvider(id, emptySpec))
291 await syncProvider(deps, stubProvider(id, emptySpec)) // no duplicate change
292
293 const removed = (await providerChanges(deps.db, id)).filter(
294 (c) => c.type === 'endpoint.removed',
295 )
296 expect(removed).toHaveLength(1)
297 // History rows survive removal.
298 expect(await providerEndpoints(deps.db, id)).toHaveLength(1)
299 expect(
300 await deps.db
301 .select()
302 .from(schemaVersions)
303 .where(eq(schemaVersions.endpointId, `${id}/v1/messages`)),
304 ).toHaveLength(2)
305 })
306
307 it('reports skipped providers without touching the database', async () => {
308 const id = 'stub-skipped'
309 const deps = await freshDeps(id)
310 const skippy: ProviderConfig = {
311 ...stubProvider(id, fixtureSpec(false)),
312 fetchSpec: () =>
313 Promise.resolve({
314 specs: [],
315 sources: [],
316 outputStrategy: 'post-200' as const,
317 skipped: 'stub: STUB_KEY not set — skipped',
318 }),
319 }
320 const outcome = await syncProvider(deps, skippy)
321 expect(outcome.skipped).toContain('STUB_KEY')
322 expect(await providerEndpoints(deps.db, id)).toHaveLength(0)
323 const providerRow = await deps.db.query.providers.findFirst({
324 where: eq(providers.id, id),
325 })
326 expect(providerRow?.lastSyncedAt).toBeNull()
327 })
328
329 it('drops schema versions sourced from models.dev on a skipped sync', async () => {
330 const id = 'stub-models-dev-schema'
331 const deps = await freshDeps(id)
332 await deps.db.insert(endpoints).values({
333 id: `${id}/chat/completions`,
334 providerId: id,
335 activity: 'chat',
336 method: 'POST',
337 path: '/chat/completions',
338 })
339 await deps.db.insert(schemaVersions).values([
340 {
341 id: `${id}/chat/completions:dev`,
342 endpointId: `${id}/chat/completions`,
343 kind: 'input',
344 contentHash: 'a'.repeat(64),
345 schema: JSON.stringify({ type: 'object' }),
346 sourceUrl: MODELS_DEV_API_URL,
347 createdAt: 1,
348 },
349 {
350 id: `${id}/chat/completions:docs`,
351 endpointId: `${id}/chat/completions`,
352 kind: 'output',
353 contentHash: 'b'.repeat(64),
354 schema: JSON.stringify({ type: 'object' }),
355 sourceUrl: 'https://example.com/openapi.json',
356 createdAt: 1,
357 },
358 ])
359 const outcome = await syncProvider(deps, {
360 ...stubProvider(id, fixtureSpec(false)),
361 fetchSpec: () =>
362 Promise.resolve({
363 specs: [],
364 sources: [],
365 outputStrategy: 'post-200' as const,
366 skipped: 'stub: no first-party spec — skipped',
367 }),
368 })
369 expect(outcome.skipped).toContain('no first-party spec')
370 const versions = await deps.db
371 .select()
372 .from(schemaVersions)
373 .where(eq(schemaVersions.endpointId, `${id}/chat/completions`))
374 expect(versions.map((row) => row.id)).toEqual([
375 `${id}/chat/completions:docs`,
376 ])
377 expect(await providerEndpoints(deps.db, id)).toHaveLength(1)
378 })
379})
380
381it('stores a verified schema-less route without manufacturing schema versions', async () => {
382 const id = 'sync-native-route-only'
383 const deps = await freshDeps(id)
384 const provider = stubProvider(id, {
385 paths: {
386 '/v1/messages': {
387 post: { 'x-modelschemas-route-only': true, responses: {} },
388 },
389 },
390 })
391 const outcome = await syncProvider(deps, provider)
392 expect(outcome).toMatchObject({ endpointsSeen: 1, versionsAdded: 0 })
393 expect(
394 (await getActivitySchemaMap(deps.db, id, 'chat')).endpoints['v1/messages'],
395 ).toEqual({ input: null, output: null })
396 expect(await getEndpointSchema(deps.db, id, 'chat', 'v1/messages')).toBeNull()
397 expect(
398 await deps.db.select().from(endpoints).where(eq(endpoints.providerId, id)),
399 ).toMatchObject([{ path: '/v1/messages', method: 'POST', activity: 'chat' }])
400 expect(
401 await deps.db
402 .select()
403 .from(schemaVersions)
404 .where(eq(schemaVersions.endpointId, `${id}/v1/messages`)),
405 ).toEqual([])
406})
407
408it('keeps per-model logical schema identities on one real multi-activity HTTP path', async () => {
409 const id = 'sync-shared-native-run'
410 const deps = await freshDeps(id)
411 const path = '/accounts/{account_id}/ai/run'
412 const provider: ProviderConfig = {
413 ...stubProvider(id, {}),
414 fetchSpec: async () => ({
415 specs: [],
416 sources: [],
417 outputStrategy: 'post-200',
418 bundledEndpoints: [
419 {
420 publicId: 'author/chat',
421 path,
422 activity: 'chat',
423 description: null,
424 source: STUB_SOURCE,
425 derivation: 'generated',
426 input: {
427 type: 'object',
428 properties: { model: { const: 'author/chat' } },
429 },
430 },
431 {
432 publicId: 'author/image',
433 path,
434 activity: 'image',
435 description: null,
436 source: STUB_SOURCE,
437 derivation: 'generated',
438 input: {
439 type: 'object',
440 properties: { model: { const: 'author/image' } },
441 },
442 },
443 ],
444 }),
445 }
446 const outcome = await syncProvider(deps, provider)
447 expect(outcome).toMatchObject({ endpointsSeen: 2, versionsAdded: 2 })
448 const rows = await deps.db
449 .select()
450 .from(endpoints)
451 .where(eq(endpoints.providerId, id))
452 expect(rows.map((row) => row.path)).toEqual([path, path])
453 expect(rows.map((row) => row.id).sort()).toEqual([
454 `${id}/author/chat`,
455 `${id}/author/image`,
456 ])
457 expect(
458 await getEndpointSchema(deps.db, id, 'chat', 'author/chat', 'output'),
459 ).toBeNull()
460 const configured = {
461 ...provider,
462 specGrain: gatewayProvider.specGrain,
463 connect: gatewayProvider.connect,
464 listModels: async () => ({
465 models: [
466 { rawId: 'author/chat', activity: 'chat' as const },
467 { rawId: 'author/image', activity: 'image' as const },
468 ],
469 }),
470 }
471 providerRegistry.push(configured)
472 try {
473 await pollProviderModels(deps, configured)
474 const assembled = await assembleProviderOpenApi(deps.db, id, {
475 model: 'author/chat',
476 })
477 expect(assembled.ok).toBe(true)
478 if (!assembled.ok) throw new Error(assembled.message)
479 expect(
480 Object.keys(assembled.document.paths as Record<string, unknown>),
481 ).toEqual([path])
482 expect(assembled.document.servers).toEqual([
483 { url: 'https://api.cloudflare.com/client/v4' },
484 ])
485 expect(assembled.document.paths).toMatchObject({
486 [path]: {
487 post: {
488 requestBody: {
489 content: {
490 'application/json': {
491 schema: { properties: { model: { enum: ['author/chat'] } } },
492 },
493 },
494 },
495 },
496 },
497 })
498 } finally {
499 providerRegistry.splice(providerRegistry.indexOf(configured), 1)
500 }
501})