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

error-abort.test.ts

529 lines15.5 KB

1import { describe, expect, it, vi } from 'vitest'
2import {
3 EventType,
4 chat,
5 defineChatMiddleware,
6 defineInterrupt,
7 generateImage,
8} from '@tanstack/ai'
9import type {
10 AdapterYieldChunk,
11 AnyTextAdapter,
12 GenerationAbortInfo,
13 GenerationErrorInfo,
14 GenerationMiddlewareContext,
15 ImageAdapter,
16 StreamChunk,
17} from '@tanstack/ai'
18import { memoryPersistence } from '../src/memory'
19import { withPersistence, withGenerationPersistence } from '../src/middleware'
20import { composePersistence } from '../src/types'
21​
22function mockAdapter(iterations: Array<Array<AdapterYieldChunk>>) {
23 const calls: Array<unknown> = []
24 let i = 0
25 const adapter = {
26 kind: 'text',
27 name: 'mock',
28 model: 'test-model',
29 '~types': {},
30 chatStream: (opts: unknown) => {
31 calls.push(opts)
32 const chunks = iterations[i] ?? []
33 i++
34 return (async function* () {
35 for (const c of chunks) yield c
36 })()
37 },
38 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
39 } as unknown as AnyTextAdapter
40 return { adapter, calls }
42​
43const runStarted = (): StreamChunk => ({
44 type: EventType.RUN_STARTED,
45 runId: 'r1',
46 threadId: 't1',
47 timestamp: 1,
48})
49​
50const interruptFinished = (): StreamChunk => ({
51 type: EventType.RUN_FINISHED,
52 runId: 'r1',
53 threadId: 't1',
54 finishReason: 'tool_calls',
55 timestamp: 1,
56 outcome: {
57 type: 'interrupt',
58 interrupts: [{ id: 'interrupt-1', reason: 'tool_call', toolCallId: 'tc1' }],
59 },
60})
61​
62const booleanResponseSchema = {
63 '~standard': {
64 version: 1,
65 vendor: 'test',
66 validate(value: unknown) {
67 return typeof value === 'boolean'
68 ? { value }
69 : { issues: [{ message: 'response must be a boolean' }] }
70 },
71 jsonSchema: {
72 input() {
73 return { type: 'boolean' }
74 },
75 },
76 },
77} as const
78​
79async function collect(stream: AsyncIterable<StreamChunk>) {
80 const out: Array<StreamChunk> = []
81 for await (const c of stream) out.push(c)
82 return out
84​
85function throwingChatAdapter(thrown: unknown): AnyTextAdapter {
86 return {
87 kind: 'text',
88 name: 'mock',
89 model: 'test-model',
90 '~types': {},
91 chatStream: () =>
92 (async function* () {
93 yield runStarted()
94 throw thrown
95 })(),
96 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
97 } as unknown as AnyTextAdapter
99​
100describe('chat persistence error/abort hooks', () => {
101 it('marks the run failed when the provider throws mid-stream', async () => {
102 const persistence = memoryPersistence()
103​
104 await expect(
105 collect(
106 chat({
107 adapter: throwingChatAdapter(new Error('provider exploded')),
108 messages: [{ role: 'user', content: 'hi' }],
109 runId: 'r1',
110 threadId: 't1',
111 middleware: [withPersistence(persistence)],
112 }) as AsyncIterable<StreamChunk>,
113 ),
114 ).rejects.toThrow('provider exploded')
115​
116 const run = await persistence.stores.runs!.get('r1')
117 expect(run?.status).toBe('failed')
118 expect(run?.error).toEqual({ message: 'provider exploded' })
119 })
120​
121 it('marks the run failed when the adapter emits RUN_ERROR', async () => {
122 const persistence = memoryPersistence()
123 const review = defineInterrupt({
124 id: 'review',
125 responseSchema: booleanResponseSchema,
126 })
127 const { adapter } = mockAdapter([
128 [
129 runStarted(),
130 {
131 type: EventType.RUN_ERROR,
132 message: 'provider failed',
133 code: 'provider_error',
134 timestamp: 1,
135 },
136 ],
137 ])
138​
139 const chunks = await collect(
140 chat({
141 adapter,
142 interrupts: [review],
143 messages: [{ role: 'user', content: 'hi' }],
144 runId: 'r1',
145 threadId: 't1',
146 middleware: [
147 defineChatMiddleware({
148 onInterruptBoundary(ctx) {
149 if (ctx.phase !== 'afterModel') return
150 return {
151 interrupts: [
152 review.interrupt({
153 key: 'review',
154 reason: 'review',
155 message: 'Review the response',
156 }),
157 ],
158 }
159 },
160 }),
161 withPersistence(persistence),
162 ],
163 }) as AsyncIterable<StreamChunk>,
164 )
165​
166 expect(chunks).toContainEqual(
167 expect.objectContaining({
168 type: EventType.RUN_ERROR,
169 message: 'provider failed',
170 code: 'provider_error',
171 }),
172 )
173 expect(chunks).not.toContainEqual(
174 expect.objectContaining({
175 type: EventType.RUN_FINISHED,
176 outcome: expect.objectContaining({ type: 'interrupt' }),
177 }),
178 )
179 expect(await persistence.stores.runs!.get('r1')).toMatchObject({
180 status: 'failed',
181 error: { message: 'provider failed', code: 'provider_error' },
182 })
183 })
184​
185 it('preserves known usage when structured-output finalization fails', async () => {
186 const persistence = memoryPersistence()
187 const usage = {
188 promptTokens: 12,
189 completionTokens: 4,
190 totalTokens: 16,
191 }
192 const { adapter } = mockAdapter([
193 [
194 runStarted(),
195 {
196 type: EventType.TEXT_MESSAGE_CONTENT,
197 messageId: 'm1',
198 delta: 'draft',
199 timestamp: 1,
200 },
201 {
202 type: EventType.RUN_FINISHED,
203 runId: 'r1',
204 threadId: 't1',
205 finishReason: 'stop',
206 timestamp: 1,
207 usage,
208 },
209 ],
210 ])
211 adapter.structuredOutput = () =>
212 Promise.reject(new Error('finalization failed'))
213​
214 const chunks = await collect(
215 chat({
216 adapter,
217 messages: [{ role: 'user', content: 'hi' }],
218 tools: [
219 {
220 name: 'search',
221 description: 'Search',
222 execute: () => ({ hits: [] }),
223 },
224 ],
225 outputSchema: {
226 type: 'object',
227 properties: { answer: { type: 'string' } },
228 },
229 stream: true,
230 runId: 'r1',
231 threadId: 't1',
232 middleware: [withPersistence(persistence)],
233 }) as AsyncIterable<StreamChunk>,
234 )
235 expect(chunks).toContainEqual(
236 expect.objectContaining({
237 type: EventType.RUN_ERROR,
238 message: 'finalization failed',
239 }),
240 )
241​
242 expect(await persistence.stores.runs!.get('r1')).toMatchObject({
243 status: 'failed',
244 usage,
245 })
246 })
247​
248 it('coerces a non-Error thrown value into the run error message', async () => {
249 const persistence = memoryPersistence()
250​
251 await expect(
252 collect(
253 chat({
254 adapter: throwingChatAdapter('string failure'),
255 messages: [{ role: 'user', content: 'hi' }],
256 runId: 'r1',
257 threadId: 't1',
258 middleware: [withPersistence(persistence)],
259 }) as AsyncIterable<StreamChunk>,
260 ),
261 ).rejects.toBeDefined()
262​
263 const run = await persistence.stores.runs!.get('r1')
264 expect(run?.status).toBe('failed')
265 expect(run?.error).toEqual({ message: 'string failure' })
266 })
267​
268 it('propagates and does not swallow a store error thrown while recording an interrupt', async () => {
269 const base = memoryPersistence()
270 const real = base.stores.interrupts!
271 const createError = new Error('interrupts.create failed')
272 const persistence = composePersistence(base, {
273 overrides: {
274 interrupts: {
275 create: () => Promise.reject(createError),
276 resolve: (id, r) => real.resolve(id, r),
277 cancel: (id) => real.cancel(id),
278 get: (id) => real.get(id),
279 list: (t) => real.list(t),
280 listPending: (t) => real.listPending(t),
281 listByRun: (r) => real.listByRun(r),
282 listPendingByRun: (r) => real.listPendingByRun(r),
283 },
284 },
285 })
286​
287 await expect(
288 collect(
289 chat({
290 adapter: mockAdapter([[runStarted(), interruptFinished()]]).adapter,
291 messages: [{ role: 'user', content: 'hi' }],
292 runId: 'r1',
293 threadId: 't1',
294 middleware: [withPersistence(persistence)],
295 }) as AsyncIterable<StreamChunk>,
296 ),
297 ).rejects.toThrow('interrupts.create failed')
298 })
299​
300 it('leaves the interrupt persisted when the follow-up thread snapshot fails (partial write)', async () => {
301 const base = memoryPersistence()
302 const realMessages = base.stores.messages!
303 const saveError = new Error('saveThread failed')
304 const persistence = composePersistence(base, {
305 overrides: {
306 messages: {
307 loadThread: (t) => realMessages.loadThread(t),
308 saveThread: () => Promise.reject(saveError),
309 },
310 },
311 })
312​
313 await expect(
314 collect(
315 chat({
316 adapter: mockAdapter([[runStarted(), interruptFinished()]]).adapter,
317 messages: [{ role: 'user', content: 'hi' }],
318 runId: 'r1',
319 threadId: 't1',
320 middleware: [withPersistence(persistence)],
321 }) as AsyncIterable<StreamChunk>,
322 ),
323 ).rejects.toThrow('saveThread failed')
324​
325 // The interrupt was created before the failing snapshot, so it survives:
326 // recovery/retry can still see the pending interrupt.
327 const pending = await base.stores.interrupts!.listPending('t1')
328 expect(pending.map((p) => p.interruptId)).toEqual(['interrupt-1'])
329 })
330​
331 it('marks the run aborted when the chat is aborted', async () => {
332 const persistence = memoryPersistence()
333 const controller = new AbortController()
334 // Adapter that hangs after RUN_STARTED so we can abort mid-stream.
335 const adapter = {
336 kind: 'text',
337 name: 'mock',
338 model: 'test-model',
339 '~types': {},
340 chatStream: () =>
341 (async function* () {
342 yield runStarted()
343 await new Promise<void>((resolve) => {
344 controller.signal.addEventListener('abort', () => resolve(), {
345 once: true,
346 })
347 })
348 })(),
349 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
350 } as unknown as AnyTextAdapter
351​
352 const stream = chat({
353 adapter,
354 messages: [{ role: 'user', content: 'hi' }],
355 runId: 'abort-run',
356 threadId: 't1',
357 abortController: controller,
358 middleware: [withPersistence(persistence)],
359 }) as AsyncIterable<StreamChunk>
360​
361 const reader = (async () => {
362 try {
363 for await (const _ of stream) {
364 // drain until abort
365 }
366 } catch {
367 // abort may reject the stream
368 }
369 })()
370​
371 // Let onConfig/onStart establish the run row, then abort.
372 await vi.waitFor(async () => {
373 const run = await persistence.stores.runs!.get('abort-run')
374 expect(run?.status).toBe('running')
375 })
376 controller.abort()
377 await reader
378​
379 // Phase 3 Task 6: this used to assert 'interrupted'. That was asserting the
380 // bug — 'interrupted' is a human-in-the-loop PAUSE and is NOT terminal, so a
381 // cancelled run never reached a terminal status. No durability is wired here,
382 // so the run is not detachable and the abort is terminal: 'aborted'.
383 const run = await persistence.stores.runs!.get('abort-run')
384 expect(run?.status).toBe('aborted')
385 expect(run?.finishedAt).toBeTypeOf('number')
386 })
387})
388​
389function imageAdapterThatThrows(thrown: unknown): ImageAdapter<string> {
390 return {
391 kind: 'image',
392 name: 'test-image-provider',
393 model: 'test-image-model',
394 '~types': {
395 providerOptions: {},
396 modelProviderOptionsByName: {},
397 modelSizeByName: {},
398 modelInputModalitiesByName: {},
399 },
400 generateImages: vi.fn(() => Promise.reject(thrown)),
401 }
403​
404// A generation run is keyed on `runId` (`ctx.runId ?? ctx.requestId`). With no
405// runId supplied the auto-generated `requestId` is the runId, so the integration
406// tests capture it via a probe middleware, and the direct-drive tests set
407// `requestId` to the pre-created job's id.
408function generationContext(requestId: string): GenerationMiddlewareContext {
409 return {
410 requestId,
411 activity: 'image',
412 provider: 'test',
413 model: 'test-model',
414 source: 'server',
415 createId: (prefix) => `${prefix}-1`,
416 context: undefined,
417 // Required on the context: middleware registers result transforms by
418 // pushing onto it, so a context without the array would silently no-op
419 // both the artifact capture and the run-record result write.
420 resultTransforms: [],
421 }
423​
424describe('generation persistence error/abort hooks', () => {
425 it('marks the job errored when generation throws', async () => {
426 const persistence = memoryPersistence()
427 let requestId = ''
428​
429 await expect(
430 generateImage({
431 threadId: 'thread-1',
432 adapter: imageAdapterThatThrows(new Error('image boom')),
433 prompt: 'make an image',
434 middleware: [
435 {
436 onStart: (ctx) => {
437 requestId = ctx.requestId
438 },
439 },
440 withGenerationPersistence(persistence, { threadId: 'thread-test' }),
441 ],
442 }),
443 ).rejects.toThrow('image boom')
444​
445 const job = await persistence.stores.generationRuns.get(requestId)
446 expect(job?.status).toBe('failed')
447 expect(job?.error).toEqual({ message: 'image boom' })
448 })
449​
450 it('coerces a non-Error generation failure into the job error message', async () => {
451 const persistence = memoryPersistence()
452 let requestId = ''
453​
454 await expect(
455 generateImage({
456 threadId: 'thread-1',
457 adapter: imageAdapterThatThrows('image string failure'),
458 prompt: 'make an image',
459 middleware: [
460 {
461 onStart: (ctx) => {
462 requestId = ctx.requestId
463 },
464 },
465 withGenerationPersistence(persistence, { threadId: 'thread-test' }),
466 ],
467 }),
468 ).rejects.toBeDefined()
469​
470 const job = await persistence.stores.generationRuns.get(requestId)
471 expect(job?.status).toBe('failed')
472 expect(job?.error).toEqual({ message: 'image string failure' })
473 })
474​
475 it('marks the job aborted on generation abort', async () => {
476 const persistence = memoryPersistence()
477 const middleware = withGenerationPersistence(persistence, {
478 threadId: 'thread-test',
479 })
480​
481 await persistence.stores.generationRuns.createOrResume({
482 runId: 'req-abort',
483 threadId: 'thread-test',
484 activity: 'image',
485 provider: 'test',
486 model: 'test-model',
487 startedAt: 1,
488 })
489​
490 // Drive the abort hook directly: only long-poll activities (video) route
491 // through onAbort at runtime, so exercise the handler in isolation.
492 const abortInfo: GenerationAbortInfo = {
493 duration: 1,
494 reason: 'client cancelled',
495 }
496 await middleware.onAbort?.(generationContext('req-abort'), abortInfo)
497​
498 // Phase 3 Task 6: this used to assert 'interrupted', which was asserting the
499 // bug. A generation job has no journal to reattach to, so an abort is always
500 // terminal for it.
501 expect(
502 (await persistence.stores.generationRuns.get('req-abort'))?.status,
503 ).toBe('aborted')
504 })
505​
506 it('coerces a non-Error into the job error message via the onError handler', async () => {
507 const persistence = memoryPersistence()
508 const middleware = withGenerationPersistence(persistence, {
509 threadId: 'thread-test',
510 })
511 await persistence.stores.generationRuns.createOrResume({
512 runId: 'req-err',
513 threadId: 'thread-test',
514 activity: 'image',
515 provider: 'test',
516 model: 'test-model',
517 startedAt: 1,
518 })
519 const errorInfo: GenerationErrorInfo = {
520 error: { code: 500 },
521 duration: 1,
522 }
523 await middleware.onError?.(generationContext('req-err'), errorInfo)
524​
525 const job = await persistence.stores.generationRuns.get('req-err')
526 expect(job?.status).toBe('failed')
527 expect(job?.error).toEqual({ message: '[object Object]' })
528 })
529})