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

driver.test.ts

342 lines12.6 KB

1/**
2 * Coverage for `sandboxRunDriver` (`src/driver.ts`) — the wiring that fills in
3 * core's injected `claim`/`pipe` seams with this package's real ones.
4 *
5 * This file is written adversarially against the three ways the wiring can be
6 * wrong while still *looking* right (a test that only asserted "pipe was
7 * called" would pass against all three):
8 *
9 * 1. **The epoch actually carried into the fence.** `pipe` gets no epoch from
10 * core, so the wiring must carry the acquired claim across. A hardcoded
11 * epoch (`0`) is not a weak fence, it is a permanently tripped one:
12 * `withRunClaim` bumps `driverEpoch` to `1` before `fn` runs, so
13 * `observed > claim.epoch` holds on the first append and every takeover
14 * fails. Hence the paired assertions: the fence must PERMIT an append at the
15 * acquired epoch and REFUSE one at a superseded epoch, with the refused path
16 * proven by `snapshot()` — the driven chunk must not be in it.
17 * 2. **`close()` must not be fenced.** It runs on the very teardown caused by
18 * losing the claim, so fencing it wedges the record at `'running'` with every
19 * tailer parked forever. The `'close'` op is asserted on the refused path,
20 * which is exactly where a fenced close would throw.
21 * 3. **Quiescence before the first append.** Asserted by op ORDER, not by a spy
22 * count: dropping the gate makes the first recorded op an `append`.
23 *
24 * Every assertion about stored events goes through `(await log.snapshot())` and
25 * never through an array handed to `fakeLog` — `fakeLog` COPIES its seed, so
26 * asserting on the seed array is vacuous.
27 */
28import { describe, expect, it } from 'vitest'
29import { EventType, InMemoryRunStore } from '@tanstack/ai'
30import { InMemoryLockStore } from '@tanstack/ai/locks'
31import { fakeLog } from './fakes'
32import { RunDriverPipeOutsideClaimError, sandboxRunDriver } from '../src/driver'
33import type { LockStore } from '@tanstack/ai/locks'
34import type {
35 RunDriverOptions,
36 StreamChunk,
37 StreamDurability,
38} from '@tanstack/ai'
39​
40function chunk(runId: string, delta: string): StreamChunk {
41 return {
42 type: EventType.TEXT_MESSAGE_CONTENT,
43 messageId: `${runId}-m`,
44 delta,
45 timestamp: 1,
46 }
48​
49type LogOp = 'append' | 'close' | 'snapshot'
50​
51/**
52 * A {@link fakeLog} that records the ORDER of the calls made against it. Order
53 * is what proves quiescence ran before the first append and that `close()` still
54 * ran after a refused one; a plain call counter proves neither.
55 */
56function recordingLog(): { log: StreamDurability; ops: Array<LogOp> } {
57 const inner = fakeLog()
58 const ops: Array<LogOp> = []
59 const log: StreamDurability = {
60 resumeFrom: () => inner.resumeFrom(),
61 append: (chunks) => {
62 ops.push('append')
63 return inner.append(chunks)
64 },
65 read: (offset, signal) => inner.read(offset, signal),
66 close: () => {
67 ops.push('close')
68 return inner.close()
69 },
70 snapshot: () => {
71 ops.push('snapshot')
72 return inner.snapshot()
73 },
74 }
75 return { log, ops }
77​
78/**
79 * A {@link LockStore} whose lease can be revoked mid-drive. `InMemoryLockStore`
80 * hands out a fresh `AbortController().signal` it never aborts, so it cannot
81 * exercise the fence's lease branch at all.
82 */
83function leaseLock(): { locks: LockStore; lose: () => void } {
84 let controller: AbortController | undefined
85 return {
86 locks: {
87 withLock: (_key, fn) => {
88 controller = new AbortController()
89 return fn(controller.signal)
90 },
91 },
92 lose: () => controller?.abort(new Error('lease lost')),
93 }
95​
96/** A run record in `'running'` state, ready to be claimed. */
97async function runningRun(runId: string): Promise<InMemoryRunStore> {
98 const runs = new InMemoryRunStore()
99 await runs.createOrResume({ runId, threadId: `${runId}-t`, startedAt: 1 })
100 return runs
102​
103interface Harness {
104 runId: string
105 runs: InMemoryRunStore
106 driver: RunDriverOptions
107 ops: Array<LogOp>
108 log: StreamDurability
110​
111/**
112 * Build a driver over one run. `fenceQuietMs: 0` keeps the quiescence gate in
113 * the path (it still takes its two snapshots) without a real sleep.
114 */
115async function harness(
116 runId: string,
117 options: {
118 chunks?: Array<StreamChunk>
119 locks?: LockStore
120 beforeYield?: () => Promise<void>
121 } = {},
122): Promise<Harness> {
123 const runs = await runningRun(runId)
124 const { log, ops } = recordingLog()
125 const chunks = options.chunks ?? [chunk(runId, 'hello')]
126 const driver = sandboxRunDriver({
127 request: new Request(`http://test.local/attach?runId=${runId}&offset=-1`),
128 runs,
129 locks: options.locks ?? new InMemoryLockStore(),
130 durability: () => log,
131 fenceQuietMs: 0,
132 drive: () => ({
133 async *[Symbol.asyncIterator]() {
134 await options.beforeYield?.()
135 for (const c of chunks) yield c
136 },
137 }),
138 })
139 return { runId, runs, driver, ops, log }
141​
142/** Exactly what core's `startRunDriver` does: claim, then pipe the drive. */
143function takeOver(h: Harness): Promise<unknown> {
144 const { runId, runs, driver } = h
145 const threadId = `${runId}-t`
146 return driver.claim({ runs, locks: driver.locks, runId }, (claim) =>
147 driver.pipe(driver.drive({ runId, threadId, signal: claim.signal }), {
148 runId,
149 threadId,
150 signal: claim.signal,
151 }),
152 )
154​
155describe('sandboxRunDriver — the acquired epoch reaches the fence', () => {
156 it('PERMITS appends at the epoch the claim acquired', async () => {
157 const h = await harness('drv-permit')
158 await takeOver(h)
159​
160 // Asserted from the log itself, never from an array passed to `fakeLog`.
161 const stored = await h.log.snapshot()
162 expect(stored.map((entry) => entry.chunk)).toEqual([
163 chunk('drv-permit', 'hello'),
164 ])
165 // A hardcoded `epoch: 0` fences this out: the claim bumped driverEpoch to 1.
166 expect((await h.runs.get('drv-permit'))?.driverEpoch).toBe(1)
167 expect((await h.runs.get('drv-permit'))?.status).toBe('completed')
168 })
169​
170 it('REFUSES appends once a higher epoch exists, and nothing lands', async () => {
171 const h = await harness('drv-superseded', {
172 // Supersede us between the claim and the first append, exactly as a
173 // successor host claiming the run would.
174 beforeYield: () => h.runs.update('drv-superseded', { driverEpoch: 99 }),
175 })
176 await takeOver(h)
177​
178 // FIRST: the harm the fence exists to prevent — a superseded host writing
179 // the run's events a second time. If the refused append had landed, a later
180 // status assertion would have tripped first and masked it.
181 const stored = (await h.log.snapshot()).map((entry) => entry.chunk)
182 expect(stored).not.toContainEqual(chunk('drv-superseded', 'hello'))
183 // NOTHING lands — not even `pipeToRunLog`'s recovery `RUN_ERROR`. That log
184 // belongs to the SUCCESSOR, and a terminal `RUN_ERROR` written by a host
185 // that has already lost its claim would fail the stream for every client
186 // attached to the live, healthy run. `fenceDurability` latches shut on the
187 // first refusal (`claim.ts`), so the recovery append refuses too instead of
188 // riding a fresh epoch-recheck throttle window.
189 expect(stored).toEqual([])
190 // And nothing lands on the RECORD either. `pipeToRunLog` answers the refused
191 // append by calling `finish(ctx, 'failed', …)`, so fencing only the log would
192 // leave this superseded host marking a run the successor is healthily
193 // streaming as terminal — `isTerminalRunStatus` would then answer `true` for
194 // a live run, which is what `findActiveRun` and the Phase 4 reaper branch on.
195 // `fenceRunStore` (`claim.ts`) suppresses that write.
196 const record = await h.runs.get('drv-superseded')
197 expect(record?.status).toBe('running')
198 expect(record?.finishedAt).toBeUndefined()
199 expect(record?.error).toBeUndefined()
200 })
201​
202 it('closes the log on the refused path', async () => {
203 const h = await harness('drv-close', {
204 beforeYield: () => h.runs.update('drv-close', { driverEpoch: 99 }),
205 })
206 await takeOver(h)
207​
208 expect(h.ops.filter((op) => op === 'close')).toEqual(['close'])
209 })
210​
211 it('closes the log when the LEASE is lost — close() must NOT be fenced', async () => {
212 const lease = leaseLock()
213 const h = await harness('drv-close-lease', {
214 locks: lease.locks,
215 beforeYield: () => {
216 lease.lose()
217 return Promise.resolve()
218 },
219 })
220 await takeOver(h)
221​
222 // The lease branch of the fence is synchronous and UNTHROTTLED (unlike the
223 // epoch re-read), so this is the case that actually proves `close()` is
224 // outside the fence: route it through and it throws, the underlying log
225 // never closes, the record stays wedged at 'running', and every live tailer
226 // parks forever — a durability `read` only ends when the log closes.
227 expect(h.ops.filter((op) => op === 'close')).toEqual(['close'])
228 // The status the abort WOULD have written is `'aborted'`, and it is suppressed
229 // for the same reason the `'failed'` one above is: the only thing that aborts
230 // `claim.signal` on this path is losing the lease, so this host no longer owns
231 // the run and must not declare it over. `close()` still ran — the assertion
232 // above is what proves the suppression did not take the teardown with it.
233 expect((await h.runs.get('drv-close-lease'))?.status).toBe('running')
234 })
235})
236​
237describe('sandboxRunDriver — quiescence gate', () => {
238 it('waits for the log to quiesce BEFORE the first append', async () => {
239 const h = await harness('drv-quiesce')
240 await takeOver(h)
241​
242 const firstAppend = h.ops.indexOf('append')
243 expect(firstAppend).toBeGreaterThan(0)
244 // `awaitLogQuiescence` compares two snapshots, so at least two precede it.
245 expect(
246 h.ops.slice(0, firstAppend).filter((op) => op === 'snapshot').length,
247 ).toBeGreaterThanOrEqual(2)
248 expect(h.ops[0]).toBe('snapshot')
249 })
250})
251​
252describe('sandboxRunDriver — pipe outside a claim', () => {
253 it('throws rather than appending unfenced at an unknown epoch', async () => {
254 const h = await harness('drv-unclaimed')
255 const threadId = 'drv-unclaimed-t'
256​
257 await expect(
258 h.driver.pipe(
259 h.driver.drive({
260 runId: 'drv-unclaimed',
261 threadId,
262 signal: new AbortController().signal,
263 }),
264 {
265 runId: 'drv-unclaimed',
266 threadId,
267 signal: new AbortController().signal,
268 },
269 ),
270 ).rejects.toBeInstanceOf(RunDriverPipeOutsideClaimError)
271​
272 // Nothing may reach the log without a claim: an unfenced append is the
273 // duplicate-write bug the claim exists to prevent.
274 expect(await h.log.snapshot()).toEqual([])
275 expect(h.ops).not.toContain('append')
276 })
277​
278 it('releases the claim slot when the claim callback returns', async () => {
279 const h = await harness('drv-released')
280 await takeOver(h)
281​
282 const threadId = 'drv-released-t'
283 await expect(
284 h.driver.pipe(
285 h.driver.drive({
286 runId: 'drv-released',
287 threadId,
288 signal: new AbortController().signal,
289 }),
290 {
291 runId: 'drv-released',
292 threadId,
293 signal: new AbortController().signal,
294 },
295 ),
296 ).rejects.toBeInstanceOf(RunDriverPipeOutsideClaimError)
297 })
298})
299​
300describe('sandboxRunDriver — pass-through wiring', () => {
301 it('forwards request/runs/locks/drive and the optional waitUntil', async () => {
302 const runs = await runningRun('drv-wiring')
303 const locks = new InMemoryLockStore()
304 const request = new Request('http://test.local/attach?runId=drv-wiring')
305 const kept: Array<Promise<unknown>> = []
306 const driver = sandboxRunDriver({
307 request,
308 runs,
309 locks,
310 durability: () => fakeLog(),
311 drive: () => ({ async *[Symbol.asyncIterator]() {} }),
312 waitUntil: (promise) => kept.push(promise),
313 })
314​
315 expect(driver.request).toBe(request)
316 expect(driver.runs).toBe(runs)
317 expect(driver.locks).toBe(locks)
318 expect(typeof driver.waitUntil).toBe('function')
319 driver.waitUntil?.(Promise.resolve())
320 expect(kept).toHaveLength(1)
321 })
322​
323 it('omits waitUntil entirely when none is supplied', async () => {
324 const runs = await runningRun('drv-no-waituntil')
325 const driver = sandboxRunDriver({
326 request: new Request('http://test.local/attach?runId=drv-no-waituntil'),
327 runs,
328 locks: new InMemoryLockStore(),
329 durability: () => fakeLog(),
330 drive: () => ({ async *[Symbol.asyncIterator]() {} }),
331 })
332 expect('waitUntil' in driver).toBe(false)
333 })
334​
335 it('refuses the claim on a terminal run, so pipe never runs', async () => {
336 const h = await harness('drv-terminal')
337 await h.runs.update('drv-terminal', { status: 'completed', finishedAt: 2 })
338​
339 await expect(takeOver(h)).rejects.toThrow('driver claim not acquired')
340 expect(h.ops).not.toContain('append')
341 })
342})