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

run-driver.test.ts

704 lines23.6 KB

1/**
2 * Coverage for the retargeted run driver (`src/run.ts`): `pipeToRunLog` and
3 * `RunController` now drive core's `RunStore` + `StreamDurability` pair instead
4 * of the package-local event log.
5 *
6 * Two things this file asserts deliberately and directly, because both used to
7 * be observable only as a 4-second Playwright-style hang or as a stray
8 * "Unhandled Rejection" note in the runner's output:
9 *
10 * 1. `durability.close()` is called EXACTLY ONCE on every terminal path.
11 * Deleting the close previously failed five tests purely via timeouts (the
12 * already-aborted test passed, so one path's log terminalization had no
13 * coverage at all). The `closes` counter turns that into an instant,
14 * legible failure.
15 * 2. `pipeToRunLog` RESOLVES on every store/event-log failure and reports the
16 * failure through its logger. It is consumed fire-and-forget, so a rejection
17 * has no caller to reach and a silently absorbed failure is invisible.
18 */
19import { describe, expect, it } from 'vitest'
20import { EventType, InMemoryRunStore, memoryStream } from '@tanstack/ai'
21import { captureLogger } from './fakes'
22import { RunController, pipeToRunLog } from '../src'
23import type {
24 RunRecord,
25 RunStore,
26 StreamChunk,
27 StreamDurability,
28} from '@tanstack/ai'
29​
30function producerRequest(runId: string): Request {
31 return new Request(`http://test.local/api/chat?runId=${runId}`, {
32 method: 'POST',
33 })
35​
36function joinRequest(runId: string): Request {
37 return new Request(`http://test.local/api/chat?runId=${runId}&offset=-1`, {
38 method: 'GET',
39 })
41​
42function textChunk(delta: string): StreamChunk {
43 return {
44 type: EventType.TEXT_MESSAGE_CONTENT,
45 messageId: 'm1',
46 delta,
47 content: delta,
48 timestamp: 1,
49 } as unknown as StreamChunk
51​
52async function* twoChunks(): AsyncGenerator<StreamChunk> {
53 yield textChunk('hello ')
54 yield textChunk('world')
56​
57async function* throwing(): AsyncGenerator<StreamChunk> {
58 yield textChunk('partial')
59 throw new Error('provider exploded')
61​
62/** Build a `RUN_ERROR` chunk, mirroring `syntheticRunError` in `src/run.ts`. */
63function runErrorChunk(message: string, code?: string): StreamChunk {
64 const chunk: { type: EventType.RUN_ERROR; message: string; code?: string } = {
65 type: EventType.RUN_ERROR,
66 message,
67 ...(code === undefined ? {} : { code }),
68 }
69 return chunk
71​
72async function* chunkThenRunError(code?: string): AsyncGenerator<StreamChunk> {
73 yield textChunk('partial')
74 yield runErrorChunk('provider rejected the request', code)
76​
77/** Aborts `controller` between the first and second yielded chunk. */
78async function* abortAfterFirstChunk(
79 controller: AbortController,
80): AsyncGenerator<StreamChunk> {
81 yield textChunk('before-abort')
82 controller.abort()
83 yield textChunk('after-abort')
85​
86/**
87 * The producer shape a well-behaved signal-aware stream actually has, and the
88 * one that made an aborted run be recorded as `'completed'`: it observes the
89 * abort and simply ENDS ITS STREAM. `chat()` does exactly this. The consuming
90 * `for await` loop then exits NORMALLY, so the per-chunk abort check is never
91 * reached again and control used to fall through to the success path.
92 *
93 * Distinct from {@link abortAfterFirstChunk} on purpose: that one yields once
94 * MORE after aborting, so the in-loop check catches it. Only a producer that
95 * stops — or an abort that lands between two chunks — reaches the gap.
96 */
97async function* returnsOnAbort(
98 controller: AbortController,
99): AsyncGenerator<StreamChunk> {
100 yield textChunk('before-abort')
101 controller.abort()
103​
104/** Reacts to its own abort by throwing, the way an `AbortError` producer does. */
105async function* throwsOnAbort(
106 controller: AbortController,
107): AsyncGenerator<StreamChunk> {
108 yield textChunk('before-abort')
109 controller.abort()
110 throw new DOMException('The operation was aborted', 'AbortError')
112​
113/**
114 * A `memoryStream` durability that counts `close()` calls (so terminalization
115 * is asserted directly rather than inferred from a hang) and can be made to
116 * fail a chosen `append` or its `close`.
117 */
118function recordingDurability(
119 runId: string,
120 faults: {
121 append?: (chunks: Array<StreamChunk>) => void
122 close?: () => void
123 } = {},
124): {
125 durability: StreamDurability
126 calls: { appends: number; closes: number }
127} {
128 const inner = memoryStream(producerRequest(runId))
129 const calls = { appends: 0, closes: 0 }
130 const durability: StreamDurability = {
131 resumeFrom: () => inner.resumeFrom(),
132 read: (offset, signal) => inner.read(offset, signal),
133 append: (chunks) => {
134 calls.appends++
135 faults.append?.(chunks)
136 return inner.append(chunks)
137 },
138 close: () => {
139 calls.closes++
140 faults.close?.()
141 return inner.close()
142 },
143 // Delegate to the wrapped `memoryStream`, which is the actual store of
144 // record for this fake.
145 snapshot: () => inner.snapshot(),
146 }
147 return { durability, calls }
149​
150/**
151 * An `InMemoryRunStore` whose three required methods can be made to fail, or
152 * (for `get`) to answer `null` the way an eventually-consistent / read-replica
153 * backend can for a run that was just driven.
154 */
155function faultyRunStore(faults: {
156 createOrResume?: () => void
157 update?: () => void
158 get?: 'throw' | 'null'
159}): RunStore {
160 const inner = new InMemoryRunStore()
161 return {
162 createOrResume: (input) => {
163 faults.createOrResume?.()
164 return inner.createOrResume(input)
165 },
166 update: (runId, patch) => {
167 faults.update?.()
168 return inner.update(runId, patch)
169 },
170 get: (runId) => {
171 if (faults.get === 'throw') throw new Error('run store read failed')
172 if (faults.get === 'null') return Promise.resolve(null)
173 return inner.get(runId)
174 },
175 findActiveRun: (threadId) => inner.findActiveRun(threadId),
176 }
178​
179/** Whether an `errors`-level log line matching `fragment` was emitted. */
180function loggedError(
181 calls: Array<{ level: string; msg: string }>,
182 fragment: string,
183): boolean {
184 return calls.some(
185 (call) => call.level === 'error' && call.msg.includes(fragment),
186 )
188​
189/** Replay a finished run's log from the start and collect every chunk. */
190async function replay(runId: string): Promise<Array<StreamChunk>> {
191 const chunks: Array<StreamChunk> = []
192 for await (const event of memoryStream(joinRequest(runId)).read('-1')) {
193 chunks.push(event.chunk)
194 }
195 return chunks
197​
198/**
199 * Let Node's unhandled-rejection bookkeeping run. A rejection is reported only
200 * after the microtask queue drains, so a macrotask hop is required before
201 * asserting that none was reported.
202 */
203async function settleUnhandledRejections(): Promise<void> {
204 await new Promise((resolve) => setTimeout(resolve, 0))
205 await new Promise((resolve) => setTimeout(resolve, 0))
207​
208describe('pipeToRunLog', () => {
209 it('records a completed run, appends every chunk, and closes the log once', async () => {
210 const runs = new InMemoryRunStore()
211 const { durability, calls } = recordingDurability('r1')
212 const record = await pipeToRunLog(twoChunks(), {
213 runs,
214 durability: () => durability,
215 runId: 'r1',
216 threadId: 't1',
217 })
218​
219 expect(record.status).toBe('completed')
220 expect(record.threadId).toBe('t1')
221 expect((await runs.get('r1'))?.status).toBe('completed')
222 expect(calls.closes).toBe(1)
223​
224 const deltas: Array<string> = []
225 for (const chunk of await replay('r1')) {
226 if (chunk.type === EventType.TEXT_MESSAGE_CONTENT)
227 deltas.push(chunk.delta)
228 }
229 expect(deltas).toEqual(['hello ', 'world'])
230 })
231​
232 it('never rejects on a stream error: records failed plus a RUN_ERROR event, closing the log once', async () => {
233 const runs = new InMemoryRunStore()
234 const { durability, calls } = recordingDurability('r2')
235 const record = await pipeToRunLog(throwing(), {
236 runs,
237 durability: () => durability,
238 runId: 'r2',
239 threadId: 't1',
240 })
241​
242 expect(record.status).toBe('failed')
243 expect(record.error?.message).toContain('provider exploded')
244 expect(calls.closes).toBe(1)
245​
246 const types = (await replay('r2')).map((chunk) => chunk.type)
247 expect(types).toContain(EventType.RUN_ERROR)
248 })
249​
250 it('finishes as aborted when the signal is already aborted, still closing the log once', async () => {
251 const runs = new InMemoryRunStore()
252 const { durability, calls } = recordingDurability('r3')
253 const controller = new AbortController()
254 controller.abort()
255 const record = await pipeToRunLog(twoChunks(), {
256 runs,
257 durability: () => durability,
258 runId: 'r3',
259 threadId: 't1',
260 signal: controller.signal,
261 })
262 expect(record.status).toBe('aborted')
263 expect(calls.closes).toBe(1)
264 })
265​
266 it('finishes failed on a RUN_ERROR chunk, capturing its message and logging the event', async () => {
267 const runs = new InMemoryRunStore()
268 const { durability, calls } = recordingDurability('r6')
269 const record = await pipeToRunLog(chunkThenRunError(), {
270 runs,
271 durability: () => durability,
272 runId: 'r6',
273 threadId: 't1',
274 })
275​
276 expect(record.status).toBe('failed')
277 expect(record.error?.message).toBe('provider rejected the request')
278 expect(calls.closes).toBe(1)
279​
280 const events = await replay('r6')
281 expect(events.some((chunk) => chunk.type === EventType.RUN_ERROR)).toBe(
282 true,
283 )
284 })
285​
286 it("keeps a RUN_ERROR chunk's machine-branchable code on the record", async () => {
287 const runs = new InMemoryRunStore()
288 const { durability } = recordingDurability('r9')
289 const record = await pipeToRunLog(chunkThenRunError('rate_limited'), {
290 runs,
291 durability: () => durability,
292 runId: 'r9',
293 threadId: 't1',
294 })
295​
296 expect(record.error).toEqual({
297 message: 'provider rejected the request',
298 code: 'rate_limited',
299 })
300 })
301​
302 it('finishes aborted mid-stream, keeping chunks appended before the abort replayable', async () => {
303 const runs = new InMemoryRunStore()
304 const { durability, calls } = recordingDurability('r7')
305 const controller = new AbortController()
306 const record = await pipeToRunLog(abortAfterFirstChunk(controller), {
307 runs,
308 durability: () => durability,
309 runId: 'r7',
310 threadId: 't1',
311 signal: controller.signal,
312 })
313​
314 expect(record.status).toBe('aborted')
315 expect(calls.closes).toBe(1)
316​
317 const deltas: Array<string> = []
318 for (const chunk of await replay('r7')) {
319 if (chunk.type === EventType.TEXT_MESSAGE_CONTENT)
320 deltas.push(chunk.delta)
321 }
322 expect(deltas).toEqual(['before-abort'])
323 })
324})
325​
326/**
327 * The four producer reactions to an abort signal, asserted as EXACT terminal
328 * statuses rather than as "terminal".
329 *
330 * "Terminal" is the weak assertion that let the defect ship: an aborted run
331 * recorded as `'completed'` is terminal too, so a test that only checked
332 * terminality passed against the bug. The status string is the whole fact.
333 *
334 * The first case is the one that was broken and the reason this block exists.
335 * It was measured on the reaper's TTL-expiry path, where a run the reaper had
336 * force-expired — and whose sandbox it had already destroyed — came back as
337 * `{"status":"completed"}`. It is not a reaper quirk: any caller whose producer
338 * ends its stream on abort got a false `'completed'`, a takeover that loses its
339 * claim mid-drive included.
340 */
341describe('pipeToRunLog abort classification', () => {
342 it('records aborted when the producer reacts to the abort by ENDING its stream', async () => {
343 const runs = new InMemoryRunStore()
344 const { durability, calls } = recordingDurability('a1')
345 const controller = new AbortController()
346​
347 const record = await pipeToRunLog(returnsOnAbort(controller), {
348 runs,
349 durability: () => durability,
350 runId: 'a1',
351 threadId: 't1',
352 signal: controller.signal,
353 })
354​
355 // NOT `'completed'`: an aborted run did not complete, whatever the producer
356 // did on its way out.
357 expect(record.status).toBe('aborted')
358 expect((await runs.get('a1'))?.status).toBe('aborted')
359 expect(record.error).toBeUndefined()
360 expect(calls.closes).toBe(1)
361 // What the producer really delivered is still replayable.
362 const deltas: Array<string> = []
363 for (const chunk of await replay('a1')) {
364 if (chunk.type === EventType.TEXT_MESSAGE_CONTENT)
365 deltas.push(chunk.delta)
366 }
367 expect(deltas).toEqual(['before-abort'])
368 })
369​
370 it('still records failed when the producer THROWS on the abort', async () => {
371 const runs = new InMemoryRunStore()
372 const { durability, calls } = recordingDurability('a2')
373 const controller = new AbortController()
374​
375 const record = await pipeToRunLog(throwsOnAbort(controller), {
376 runs,
377 durability: () => durability,
378 runId: 'a2',
379 threadId: 't1',
380 signal: controller.signal,
381 })
382​
383 // Unchanged by the abort re-check: a producer that threw reported a failure,
384 // and the thrown value is what a tailing client must be shown. The
385 // synthesized `RUN_ERROR` is the only channel it has.
386 expect(record.status).toBe('failed')
387 expect(record.error?.message).toContain('aborted')
388 expect(calls.closes).toBe(1)
389 const types = (await replay('a2')).map((chunk) => chunk.type)
390 expect(types).toContain(EventType.RUN_ERROR)
391 })
392​
393 it('records completed when the stream ends normally and the signal never fired', async () => {
394 const runs = new InMemoryRunStore()
395 const { durability, calls } = recordingDurability('a3')
396 const controller = new AbortController()
397​
398 const record = await pipeToRunLog(twoChunks(), {
399 runs,
400 durability: () => durability,
401 runId: 'a3',
402 threadId: 't1',
403 // A live, never-fired signal: the re-check must not turn a genuine
404 // completion into an abort just because a signal was supplied.
405 signal: controller.signal,
406 })
407​
408 expect(record.status).toBe('completed')
409 expect((await runs.get('a3'))?.status).toBe('completed')
410 expect(calls.closes).toBe(1)
411 })
412​
413 it('records failed on a provider error even with a live signal attached', async () => {
414 const runs = new InMemoryRunStore()
415 const { durability, calls } = recordingDurability('a4')
416 const controller = new AbortController()
417​
418 const record = await pipeToRunLog(throwing(), {
419 runs,
420 durability: () => durability,
421 runId: 'a4',
422 threadId: 't1',
423 signal: controller.signal,
424 })
425​
426 expect(record.status).toBe('failed')
427 expect(record.error?.message).toContain('provider exploded')
428 expect(calls.closes).toBe(1)
429 })
430})
431​
432describe('pipeToRunLog failure absorption', () => {
433 it('still closes the log (and logs) when the terminal runs.update throws', async () => {
434 const runs = faultyRunStore({
435 update: () => {
436 throw new Error('store update failed')
437 },
438 })
439 const { durability, calls } = recordingDurability('f1')
440 const { logger, calls: logs } = captureLogger()
441​
442 const record = await pipeToRunLog(twoChunks(), {
443 runs,
444 durability: () => durability,
445 logger,
446 runId: 'f1',
447 threadId: 't1',
448 })
449​
450 // Without a guaranteed close the record would be wedged at `running` and
451 // every live tailer would park forever, since `read` ends only on close.
452 expect(calls.closes).toBe(1)
453 expect(record.status).toBe('completed')
454 expect(record.runId).toBe('f1')
455 expect(record.threadId).toBe('t1')
456 expect(loggedError(logs, 'recording the terminal run record failed')).toBe(
457 true,
458 )
459 })
460​
461 it('still terminalizes when the logger itself throws', async () => {
462 // The logger is consumer-supplied and is handed arbitrary thrown values, so
463 // a sink that cannot serialize one would throw from inside a `catch` body
464 // and escape it. That would skip `durability.close()` and wedge the record
465 // at `running`, defeating the totality the logger exists to report on.
466 const runs = new InMemoryRunStore()
467 runs.update = () => {
468 throw new Error('store update failed')
469 }
470 const { durability, calls } = recordingDurability('f-log')
471 const exploding = {
472 errors: () => {
473 throw new Error('logger sink exploded')
474 },
475 } as unknown as Parameters<typeof pipeToRunLog>[1]['logger']
476​
477 const record = await pipeToRunLog(twoChunks(), {
478 runs,
479 durability: () => durability,
480 logger: exploding,
481 runId: 'f-log',
482 threadId: 't1',
483 })
484​
485 expect(calls.closes).toBe(1)
486 expect(record.status).toBe('completed')
487 })
488​
489 it('resolves and logs when durability.close() itself throws', async () => {
490 const runs = new InMemoryRunStore()
491 const { durability, calls } = recordingDurability('f2', {
492 close: () => {
493 throw new Error('close failed')
494 },
495 })
496 const { logger, calls: logs } = captureLogger()
497​
498 const record = await pipeToRunLog(twoChunks(), {
499 runs,
500 durability: () => durability,
501 logger,
502 runId: 'f2',
503 threadId: 't1',
504 })
505​
506 expect(record.status).toBe('completed')
507 expect(calls.closes).toBe(1)
508 expect(loggedError(logs, 'closing the run event log failed')).toBe(true)
509 })
510​
511 it('records the ORIGINAL provider error when the recovery append throws', async () => {
512 const runs = new InMemoryRunStore()
513 const { durability, calls } = recordingDurability('f3', {
514 append: (chunks) => {
515 if (chunks.some((chunk) => chunk.type === EventType.RUN_ERROR)) {
516 throw new Error('log write failed')
517 }
518 },
519 })
520 const { logger, calls: logs } = captureLogger()
521​
522 const record = await pipeToRunLog(throwing(), {
523 runs,
524 durability: () => durability,
525 logger,
526 runId: 'f3',
527 threadId: 't1',
528 })
529​
530 expect(record.status).toBe('failed')
531 // The secondary failure must be merged in, never substituted for the cause.
532 expect(record.error?.message).toContain('provider exploded')
533 expect(record.error?.message).toContain('log write failed')
534 expect(calls.closes).toBe(1)
535 expect(
536 loggedError(logs, 'appending the synthesized RUN_ERROR failed'),
537 ).toBe(true)
538 })
539​
540 it('handles a throwing runs.createOrResume as a failed run rather than rejecting', async () => {
541 const runs = faultyRunStore({
542 createOrResume: () => {
543 throw new Error('store create failed')
544 },
545 })
546 const { durability, calls } = recordingDurability('f4')
547 const { logger, calls: logs } = captureLogger()
548​
549 const record = await pipeToRunLog(twoChunks(), {
550 runs,
551 durability: () => durability,
552 logger,
553 runId: 'f4',
554 threadId: 't1',
555 })
556​
557 expect(record.status).toBe('failed')
558 expect(record.error?.message).toContain('store create failed')
559 expect(calls.closes).toBe(1)
560 // Not "the stream failed": createOrResume threw, so the stream never ran.
561 expect(loggedError(logs, 'the run failed before completing')).toBe(true)
562​
563 // The synthesized RUN_ERROR still reached the log, so a tailer sees why.
564 const types = (await replay('f4')).map((chunk) => chunk.type)
565 expect(types).toContain(EventType.RUN_ERROR)
566 })
567​
568 it('rebuilds the terminal record when runs.get answers null on the re-read', async () => {
569 const runs = faultyRunStore({ get: 'null' })
570 const { durability, calls } = recordingDurability('f5')
571 const { logger, calls: logs } = captureLogger()
572​
573 const record = await pipeToRunLog(twoChunks(), {
574 runs,
575 durability: () => durability,
576 logger,
577 runId: 'f5',
578 threadId: 't1',
579 })
580​
581 // An eventually-consistent read must not turn a successful run into a
582 // rejection ("record vanished mid-run").
583 expect(record.status).toBe('completed')
584 expect(record.runId).toBe('f5')
585 expect(record.threadId).toBe('t1')
586 expect(record.finishedAt).toBeTypeOf('number')
587 expect(calls.closes).toBe(1)
588 expect(
589 loggedError(logs, 'record vanished before the terminal re-read'),
590 ).toBe(true)
591 })
592​
593 it('resolves and logs when runs.get throws on the re-read', async () => {
594 const runs = faultyRunStore({ get: 'throw' })
595 const { durability, calls } = recordingDurability('f6')
596 const { logger, calls: logs } = captureLogger()
597​
598 const record = await pipeToRunLog(twoChunks(), {
599 runs,
600 durability: () => durability,
601 logger,
602 runId: 'f6',
603 threadId: 't1',
604 })
605​
606 expect(record.status).toBe('completed')
607 expect(calls.closes).toBe(1)
608 expect(loggedError(logs, 're-reading the terminal run record failed')).toBe(
609 true,
610 )
611 })
612})
613​
614describe('RunController', () => {
615 it('start returns immediately and done resolves with the terminal record', async () => {
616 const runs = new InMemoryRunStore()
617 const durability = memoryStream(producerRequest('r4'))
618 const controller = new RunController({ runs, durability: () => durability })
619 const handle = controller.start({
620 runId: 'r4',
621 threadId: 't1',
622 stream: twoChunks(),
623 })
624 expect(handle.runId).toBe('r4')
625 const record = await handle.done
626 expect(record.status).toBe('completed')
627 })
628​
629 it('status reads the record and drain awaits in-flight runs', async () => {
630 const runs = new InMemoryRunStore()
631 const durability = memoryStream(producerRequest('r5'))
632 const controller = new RunController({ runs, durability: () => durability })
633 controller.start({ runId: 'r5', threadId: 't1', stream: twoChunks() })
634 await controller.drain()
635 expect((await controller.status('r5'))?.status).toBe('completed')
636 })
637​
638 it("attach replays from an opaque offset (memoryStream's '-1' from-start sentinel)", async () => {
639 const runs = new InMemoryRunStore()
640 const durability = memoryStream(producerRequest('r8'))
641 const controller = new RunController({ runs, durability: () => durability })
642 const handle = controller.start({
643 runId: 'r8',
644 threadId: 't1',
645 stream: twoChunks(),
646 })
647 await handle.done
648​
649 const deltas: Array<string> = []
650 for await (const event of controller.attach('r8', '-1')) {
651 if (event.chunk.type === EventType.TEXT_MESSAGE_CONTENT)
652 deltas.push(event.chunk.delta)
653 }
654 expect(deltas).toEqual(['hello ', 'world'])
655 })
656​
657 it('leaves no unhandled rejection behind when a run hits store failures', async () => {
658 // `start()`'s in-flight bookkeeping used `void done.finally(...)`, whose NEW
659 // promise adopts any rejection with nobody left to handle it: fatal on
660 // modern Node defaults, and it kills the instance inside a Durable Object.
661 // Drive a fault-injected run (the shape that used to reject) and assert
662 // both halves separately: the process saw nothing unhandled, AND the run
663 // settled fulfilled. Settling `done` without `await`ing it directly keeps
664 // the two assertions independent, so a reintroduced rejection is reported
665 // as an unhandled-rejection failure rather than as a thrown await.
666 const rejections: Array<unknown> = []
667 const onUnhandled = (reason: unknown): void => void rejections.push(reason)
668 process.on('unhandledRejection', onUnhandled)
669 try {
670 const runs = faultyRunStore({
671 update: () => {
672 throw new Error('store update failed')
673 },
674 })
675 const { durability } = recordingDurability('f7')
676 const { logger } = captureLogger()
677 const controller = new RunController({
678 runs,
679 durability: () => durability,
680 logger,
681 })
682​
683 const handle = controller.start({
684 runId: 'f7',
685 threadId: 't1',
686 stream: throwing(),
687 })
688 const outcome = await handle.done.then(
689 (record: RunRecord) => ({ rejected: false, record }),
690 (error: unknown) => ({ rejected: true, error }),
691 )
692 await controller.drain()
693 await settleUnhandledRejections()
694​
695 expect(rejections).toEqual([])
696 expect(outcome).toMatchObject({
697 rejected: false,
698 record: { status: 'failed' },
699 })
700 } finally {
701 process.off('unhandledRejection', onUnhandled)
702 }
703 })
704})