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

nvidia-build-spec.test.ts

392 lines15.3 KB

1import { expect, it, afterEach, vi } from 'vitest'
2import native from './fixtures/nvidia-native-build-spec.json'
3import reference from './fixtures/nvidia-native-reasoning-discovery.json'
4import { NVIDIA_REFERENCE_INDEXES, nvidiaWireFacts } from './nvidia-openapi.ts'
5import {
6 parseNvidiaBuildSpec,
7 validateNvidiaBuildFacts,
8} from './nvidia-build-spec.ts'
9​
10import { provider, NVIDIA_MODELS_URL } from './adapters/nvidia.ts'
11import { sha256Text } from './types.ts'
12​
13const rawId = 'nvidia/nemotron-3.5-content-safety'
14const html = native[rawId].html
15it('reads the actual hosted Build spec independently of the incorrect ReadMe Nano schema', () => {
16 const facts = parseNvidiaBuildSpec(html, rawId)
17 expect(facts?.document.info?.title).toBe('NVIDIA NIM API for ' + rawId)
18 expect(facts?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
19 expect(facts?.maxOutput).toBe(4096)
20 expect(facts?.activity).toBe('chat')
21 expect(facts?.document.servers).toContainEqual({
22 url: 'https://integrate.api.nvidia.com/v1',
23 })
24 expect(Object.keys(facts?.document.paths ?? {})).toContain(
25 '/chat/completions',
26 )
27})
28it('binds actual native request selectors independently of API display titles', () => {
29 for (const id of [
30 'nvidia/llama-3.1-nemotron-safety-guard-8b-v3',
31 'nvidia/nemotron-parse-2.0',
32 ] as const) {
33 expect(
34 parseNvidiaBuildSpec(native[id].html, id)?.document.info?.title,
35 ).not.toContain(id)
36 }
37})
38it('fails on malformed published primary schema data', () => {
39 expect(() =>
40 parseNvidiaBuildSpec(
41 html.replaceAll('openAPISpec', 'openAPISpecBROKEN'),
42 rawId,
43 ),
44 ).toThrow('marker is unreadable')
45 expect(() => parseNvidiaBuildSpec('<html>Challenge</html>', rawId)).toThrow(
46 'no native Flight',
47 )
48 expect(parseNvidiaBuildSpec('NEXT_HTTP_ERROR_FALLBACK;404', rawId)).toBeNull()
49 expect(() => parseNvidiaBuildSpec(html, 'nvidia/another-model')).toThrow(
50 'identity conflict',
51 )
52})
53it('only a healthy native page without a schema can report absence', () => {
54 expect(
55 parseNvidiaBuildSpec(
56 '<script>self.__next_f.push([1,"1:{\\"model\\":\\"nvidia/example\\"}"])</script>',
57 'nvidia/example',
58 ),
59 ).toBeNull()
60})
61const originalFetch = globalThis.fetch
62afterEach(() => {
63 globalThis.fetch = originalFetch
64 vi.restoreAllMocks()
65})
66function ownSources(page: string) {
67 const requested: string[] = []
68 const url = native[rawId].sourceUrl
69 globalThis.fetch = async (input) => {
70 const source = String(input)
71 requested.push(source)
72 if (source === NVIDIA_MODELS_URL)
73 return new Response(JSON.stringify({ data: [{ id: rawId }] }))
74 if (source === url + '.md') return new Response(native[rawId].markdown)
75 if (source === url) return new Response(page)
76 if ((reference as Record<string, string>)[source])
77 return new Response((reference as Record<string, string>)[source])
78 if (NVIDIA_REFERENCE_INDEXES.includes(source))
79 return new Response('---\n---\n# No relevant models\n')
80 throw new Error('Unselected secondary source requested: ' + source)
81 }
82 return requested
84it('syncs the native primary before secondary discovery and keeps real path separate from model identity', async () => {
85 const requested = ownSources(html)
86 const rows = await provider.listModels({})
87 expect(requested).toContain(native[rawId].sourceUrl)
88 expect(requested).toContain(
89 'https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3-5-content-safety-infer.md',
90 )
91 const model = rows.models[0]
92 expect(rows.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
93 expect(model?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
94 expect(model?.capabilities).toContain('reasoning')
95 expect(model?.factSources?.reasoning).toMatchObject({
96 sourceUrl: native[rawId].sourceUrl,
97 sourceHash: await sha256Text(html),
98 path: 'chat_template_kwargs.enable_thinking',
99 })
100 expect(model?.factSources?.schemaEndpointId?.sourceUrl).toBe(
101 native[rawId].sourceUrl,
102 )
103 const synced = await provider.fetchSpec({})
104 expect(synced.specs).toEqual([])
105 expect(synced.bundledEndpoints).toHaveLength(1)
106 const endpoint = synced.bundledEndpoints?.[0]
107 expect(endpoint).toMatchObject({
108 publicId: rawId,
109 path: '/chat/completions',
110 source: { url: native[rawId].sourceUrl, hash: await sha256Text(html) },
111 })
112 expect(endpoint?.input).toBeDefined()
113 expect(endpoint?.output).toBeDefined()
114 expect(provider.specGrain).toBe('model')
115 expect(
116 synced.warnings?.some((warning) =>
117 warning.includes('rejected competing reference identity'),
118 ),
119 ).toBe(true)
120})
121it('never recovers an erroneous primary with another provider body', async () => {
122 const requested = ownSources(
123 html.replaceAll(
124 'nvidia/nemotron-3.5-content-safety',
125 'nvidia/incorrect-model',
126 ),
127 )
128 const rows = await provider.listModels({})
129 expect(rows.docsFailures?.failed).toBe(1)
130 expect(rows.docsFailures?.first[0]?.source).toBe(native[rawId].sourceUrl)
131 expect(rows.docsFailures?.first[0]?.error).toContain('identity conflict')
132 expect(rows.models[0]?.reasoning).toBeUndefined()
133 expect(rows.models[0]?.absent?.reasoning).toBe('unavailable')
134 await expect(provider.fetchSpec({})).rejects.toThrow('identity conflict')
135 expect(
136 requested.filter((url) => url === native[rawId].sourceUrl),
137 ).toHaveLength(2)
138})
139​
140it('revalidates cached primary identity and derives controls from its document', () => {
141 const facts = parseNvidiaBuildSpec(html, rawId)
142 if (!facts) throw new Error('Missing native fixture contract')
143 expect(
144 validateNvidiaBuildFacts(
145 {
146 ...facts,
147 reasoning: { mode: 'effort', mandatory: true, efforts: ['invented'] },
148 },
149 rawId,
150 ).reasoning,
151 ).toEqual({ mode: 'toggle', mandatory: false })
152 expect(() =>
153 validateNvidiaBuildFacts(facts, 'nvidia/unrelated-model'),
154 ).toThrow('identity conflict')
155})
156​
157it('reads published native JSON even when its response examples contain Markdown fences', () => {
158 const id = 'microsoft/phi-3-vision-128k-instruct'
159 const facts = parseNvidiaBuildSpec(native[id].html, id)
160 expect(facts?.document.info?.title).toBe('NVIDIA NIM API for ' + id)
161 expect(
162 facts?.document.paths?.['/vlm/microsoft/phi-3-vision-128k-instruct']?.post,
163 ).toBeDefined()
164 expect(facts?.activity).toBeNull()
165})
166​
167it('records local native identity failures without charging successful fetch time to the network failure budget', async () => {
168 ownSources(html.replaceAll(rawId, 'nvidia/unrelated-model'))
169 const fetchSource = globalThis.fetch
170 let now = 100_000
171 vi.spyOn(Date, 'now').mockImplementation(() => now)
172 globalThis.fetch = async (...args) => {
173 if (String(args[0]) === native[rawId].sourceUrl) now += 20_000
174 return fetchSource(...args)
175 }
176 const listing = await provider.listModels({})
177 expect(listing.docsFailures?.failed).toBe(1)
178 expect(listing.docsFailures?.skipped).toBe(0)
179 expect(listing.docsFailures?.first[0]?.elapsedMs).toBe(0)
180 expect(listing.docsFailures?.first[0]?.error).toContain('identity conflict')
181})
182​
183it('never caches a malformed primary and rejects cached wrong identities without requesting secondary sources', async () => {
184 const values = new Map<string, string>()
185 const kv = {
186 get: async (key: string) => values.get(key) ?? null,
187 put: async (key: string, value: string) => {
188 values.set(key, value)
189 },
190 } as unknown as KVNamespace
191 const key = 'nvidia-build-contract:v1:' + native[rawId].sourceUrl
192 ownSources(html.replaceAll(rawId, 'nvidia/unrelated-model'))
193 const invalid = await provider.listModels({}, kv)
194 expect(invalid.docsFailures?.failed).toBe(1)
195 expect(values.has(key)).toBe(false)
196 ownSources(html)
197 expect((await provider.listModels({}, kv)).docsFailures).toEqual({
198 failed: 0,
199 skipped: 0,
200 first: [],
201 })
202 expect(values.has(key)).toBe(true)
203 const contract = values.get(key)
204 if (!contract) throw new Error('Missing healthy native cached contract')
205 values.set(key, contract.replaceAll(rawId, 'nvidia/unrelated-model'))
206 const requested = ownSources(html)
207 const badCache = await provider.listModels({}, kv)
208 expect(badCache.docsFailures?.first[0]?.error).toContain('identity conflict')
209 expect(requested).not.toContain(native[rawId].sourceUrl)
210})
211​
212it('keeps an exact healthy ReadMe contract primary when the competing Build body omits its native thinking control', async () => {
213 const id = 'google/gemma-4-31b-it'
214 expect(parseNvidiaBuildSpec(native[id].html, id)?.reasoning).toBeUndefined()
215 const requested: string[] = []
216 globalThis.fetch = async (input) => {
217 const url = String(input)
218 requested.push(url)
219 if (url === NVIDIA_MODELS_URL) return Response.json({ data: [{ id }] })
220 if (url === native[id].sourceUrl) return new Response(native[id].html)
221 const body = (reference as Record<string, string>)[url]
222 if (body) return new Response(body)
223 if (NVIDIA_REFERENCE_INDEXES.includes(url))
224 return new Response('---\n---\n# No relevant models\n')
225 throw new Error('Unexpected native source ' + url)
226 }
227 const result = await provider.listModels({})
228 expect(result.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
229 expect(result.models[0]?.reasoning).toEqual({
230 mode: 'toggle',
231 mandatory: false,
232 })
233 expect(result.models[0]?.factSources?.reasoning?.sourceUrl).toBe(
234 'https://docs.api.nvidia.com/nim/reference/google-gemma-4-31b-it-infer.md',
235 )
236 expect(requested).not.toContain(native[id].sourceUrl)
237})
238​
239it('never uses a healthy Build body to recover a ReadMe network or malformed-content error', async () => {
240 for (const bad of [
241 new Response('Unavailable', { status: 503 }),
242 new Response('not a provider schema'),
243 ]) {
244 const requested = ownSources(html)
245 const nativeFetch = globalThis.fetch
246 globalThis.fetch = async (...args) =>
247 String(args[0]) ===
248 'https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3-5-content-safety-infer.md'
249 ? bad
250 : nativeFetch(...args)
251 const result = await provider.listModels({})
252 expect(result.docsFailures?.failed).toBe(1)
253 expect(result.models[0]?.absent?.reasoning).toBe('unavailable')
254 expect(result.models[0]?.schemaEndpointId).toBeUndefined()
255 expect(requested).not.toContain(native[rawId].sourceUrl)
256 }
257})
258​
259it('never converts failed complete or partial ReadMe index discovery into unpublished-source Build selection', async () => {
260 for (const allFailed of [true, false]) {
261 const requested = ownSources(html)
262 const ownFetch = globalThis.fetch
263 globalThis.fetch = async (...args) => {
264 const url = String(args[0])
265 if (NVIDIA_REFERENCE_INDEXES.includes(url)) {
266 if (allFailed || url === NVIDIA_REFERENCE_INDEXES[0])
267 return new Response('unavailable', { status: 503 })
268 return new Response('---\n---\n# No relevant models\n')
269 }
270 if (url === 'https://docs.api.nvidia.com/sitemap.xml')
271 return new Response(
272 '<urlset><url><loc>https://docs.api.nvidia.com/nim/reference/google-gemma-4-31b-it-infer</loc></url></urlset>',
273 )
274 return ownFetch(...args)
275 }
276 const result = await provider.listModels({})
277 expect(result.docsFailures?.failed).toBeGreaterThan(0)
278 expect(result.models[0]?.absent?.reasoning).toBe('unavailable')
279 expect(result.models[0]?.schemaEndpointId).toBeUndefined()
280 expect(requested).not.toContain(native[rawId].sourceUrl)
281 }
282})
283​
284it('retains native explicit capability negatives and surfaces a contradictory selected schema', async () => {
285 const requested = ownSources(html)
286 const nativeFetch = globalThis.fetch
287 globalThis.fetch = async (...args) =>
288 String(args[0]) === native[rawId].sourceUrl + '.md'
289 ? new Response(
290 native[rawId].markdown.replace(
291 '**Reasoning:** Supported',
292 '**Reasoning:** Not supported',
293 ),
294 )
295 : nativeFetch(...args)
296 const result = await provider.listModels({})
297 expect(result.docsFailures?.first[0]?.error).toContain(
298 'explicitly rejects reasoning',
299 )
300 expect(result.models[0]?.unsupportedCapabilities).toContain('reasoning')
301 expect(
302 result.models[0]?.factSources?.capabilities?.reasoning?.sourceUrl,
303 ).toBe(native[rawId].sourceUrl)
304 expect(
305 result.models[0]?.factSources?.capabilities?.reasoning?.sourceHash,
306 ).toBe(
307 await sha256Text(
308 native[rawId].markdown.replace(
309 '**Reasoning:** Supported',
310 '**Reasoning:** Not supported',
311 ),
312 ),
313 )
314 expect(result.models[0]?.capabilities).not.toContain('reasoning')
315 expect(result.models[0]?.requestMap).toBeNull()
316 expect(result.models[0]?.schemaEndpointId).toBeUndefined()
317 expect(requested).toContain(native[rawId].sourceUrl)
318})
319​
320it('does not turn an absent capability label into an unsupported fact', async () => {
321 ownSources(html)
322 const nativeFetch = globalThis.fetch
323 globalThis.fetch = async (...args) =>
324 String(args[0]) === native[rawId].sourceUrl + '.md'
325 ? new Response(
326 native[rawId].markdown.replace('- **Reasoning:** Supported\n', ''),
327 )
328 : nativeFetch(...args)
329 const result = await provider.listModels({})
330 expect(result.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
331 expect(result.models[0]?.unsupportedCapabilities).not.toContain('reasoning')
332 expect(result.models[0]?.capabilities).toContain('reasoning')
333})
334​
335it('derives wire fields from the exact native request members and preserves unknown leaves', async () => {
336 ownSources(html)
337 const model = (await provider.listModels({})).models[0]
338 expect(model?.requestMap?.maxTokensField).toBe('max_tokens')
339 expect(model?.requestMap?.thinking).toEqual({
340 on: { chat_template_kwargs: { enable_thinking: true } },
341 off: { chat_template_kwargs: { enable_thinking: false } },
342 levels: null,
343 })
344 expect(model?.requestMap?.store).toBeNull()
345 expect(model?.factSources?.requestMapFields?.maxTokensField?.sourceUrl).toBe(
346 native[rawId].sourceUrl,
347 )
348 expect(model?.factSources?.requestMapFields?.thinking?.sourceHash).toBe(
349 await sha256Text(html),
350 )
351})
352​
353it('responds to native role-enum and token-member changes without static per-provider flags', () => {
354 const facts = parseNvidiaBuildSpec(html, rawId)
355 if (!facts) throw new Error('Missing native fixture')
356 const doc = structuredClone(facts.document)
357 expect(nvidiaWireFacts(doc).fields.developerRole).toBe(false)
358 const role = doc.components?.schemas?.Role
359 if (
360 !role ||
361 typeof role !== 'object' ||
362 Array.isArray(role) ||
363 !('enum' in role)
364 )
365 throw new Error('Missing native role enum')
366 const nativeRoles: unknown = role.enum
367 role.enum = [
368 ...(Array.isArray(nativeRoles) ? (nativeRoles as unknown[]) : []),
369 'developer',
370 ]
371 expect(nvidiaWireFacts(doc).fields.developerRole).toBe(true)
372 delete role.enum
373 expect(nvidiaWireFacts(doc).fields.developerRole).toBeUndefined()
374 const request = doc.components?.schemas?.NIMLLMChatCompletionRequest
375 if (
376 !request ||
377 typeof request !== 'object' ||
378 !('properties' in request) ||
379 !request.properties ||
380 typeof request.properties !== 'object' ||
381 Array.isArray(request.properties)
382 )
383 throw new Error('Missing native request properties')
384 const props = request.properties as Record<string, unknown>
385 props.max_completion_tokens = props.max_tokens
386 delete props.max_tokens
387 expect(nvidiaWireFacts(doc).fields.maxTokensField).toBe(
388 'max_completion_tokens',
389 )
390 delete props.max_completion_tokens
391 expect(nvidiaWireFacts(doc).fields.maxTokensField).toBeUndefined()
392})