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

attach-preflight.test.ts

535 lines18.2 KB

1/**
2 * The attach preflight: a hopeless attach must FAIL, not hang.
3 *
4 * Every test that could regress into a hang carries an explicit short bound
5 * (`attachWaitMs` / `waitMs` in the tens of milliseconds, plus a per-test
6 * timeout), so a regression fails the suite in under a second instead of
7 * stalling CI until Vitest's default timeout.
8 */
9import { describe, expect, it } from 'vitest'
10import { InMemoryRunStore } from '@tanstack/ai'
11import {
12 DEFAULT_ATTACH_JOURNAL_WAIT_MS,
13 JournalAttachUnavailableError,
14 awaitAttachableJournal,
15} from '../src/attach-preflight'
16import {
17 exitSentinelLine,
18 journalExistsCommand,
19 journalPaths,
20} from '../src/journal'
21import { readJournalNdjson } from '../src/runner'
22import type { RunStatus, RunStore } from '@tanstack/ai'
23import type { ExecResult, SandboxHandle, SpawnHandle } from '../src/contracts'
24​
25/**
26 * A run's real exit sentinel. Built, never hand-written: it carries a per-run
27 * nonce (`journal.ts`), so a literal `{"__exit":0}` in a fixture is agent output
28 * the reader must not stop at.
29 */
30function EXIT(runId: string, exitCode = 0): string {
31 return exitSentinelLine(journalPaths(runId), exitCode)
33​
34async function* fromChunks(chunks: Array<string>): AsyncIterable<string> {
35 for (const chunk of chunks) {
36 await Promise.resolve()
37 yield chunk
38 }
40​
41async function collect<T>(it: AsyncIterable<T>): Promise<Array<T>> {
42 const out: Array<T> = []
43 for await (const value of it) out.push(value)
44 return out
46​
47interface ProbeHandle {
48 handle: SandboxHandle
49 commands: Array<string>
50 /** Flip the `test -f` answer mid-test, to model a journal that appears late. */
51 setExists: (exists: boolean) => void
53​
54/**
55 * A handle whose `test -f` answers from a mutable flag and whose `spawn`
56 * replays one scripted journal.
57 *
58 * The existence answer is an EXIT CODE, not stdout: `journalExistsCommand` is a
59 * shell `test -f`, so a preflight that read stdout instead would pass this test
60 * while failing against every real provider.
61 */
62function probeHandle(
63 options: {
64 exists?: boolean
65 script?: Array<string>
66 execFails?: boolean
67 /** Run the default script's sentinel belongs to. */
68 runId?: string
69 } = {},
70): ProbeHandle {
71 let exists = options.exists ?? false
72 const commands: Array<string> = []
73 const spawnHandle: SpawnHandle = {
74 pid: -1,
75 stdout: fromChunks(
76 options.script ?? [`${EXIT(options.runId ?? 'probe-default')}\n`],
77 ),
78 stderr: fromChunks([]),
79 stdin: { write: () => Promise.resolve(), end: () => Promise.resolve() },
80 wait: () => Promise.resolve(0),
81 kill: () => Promise.resolve(),
82 }
83 const handle: SandboxHandle = {
84 id: 'probe',
85 provider: 'probe',
86 capabilities: {
87 fs: true,
88 exec: true,
89 env: true,
90 ports: false,
91 backgroundProcesses: true,
92 writableStdin: true,
93 killableProcesses: true,
94 snapshots: false,
95 networkPolicy: false,
96 durableFilesystem: false,
97 fork: false,
98 },
99 fs: {} as SandboxHandle['fs'],
100 git: {} as SandboxHandle['git'],
101 process: {
102 exec: (command): Promise<ExecResult> => {
103 commands.push(command)
104 if (options.execFails === true) {
105 return Promise.reject(
106 new Error('exec is unavailable on this provider'),
107 )
108 }
109 const isProbe = command.startsWith('test -f')
110 return Promise.resolve({
111 stdout: '',
112 stderr: '',
113 exitCode: isProbe && !exists ? 1 : 0,
114 })
115 },
116 spawn: (command) => {
117 commands.push(command)
118 return Promise.resolve(spawnHandle)
119 },
120 },
121 ports: { connect: () => Promise.reject(new Error('unused')) },
122 env: { set: () => Promise.resolve() },
123 destroy: () => Promise.resolve(),
124 }
125 return {
126 handle,
127 commands,
128 setExists: (value) => {
129 exists = value
130 },
131 }
133​
134/** A store holding exactly one record, in the given lifecycle state. */
135async function storeWith(
136 runId: string,
137 status: RunStatus,
138 extra: { detachedSince?: number } = {},
139): Promise<RunStore> {
140 const runs = new InMemoryRunStore()
141 await runs.createOrResume({ runId, threadId: `t-${runId}`, startedAt: 1 })
142 await runs.update(runId, {
143 status,
144 ...(extra.detachedSince === undefined
145 ? {}
146 : { detachedSince: extra.detachedSince }),
147 })
148 return runs
150​
151describe('awaitAttachableJournal: an existing journal', () => {
152 it('returns immediately without reading the run store at all', async () => {
153 const runId = 'pf-exists-1'
154 const probe = probeHandle({ exists: true })
155 let storeReads = 0
156 const runs: RunStore = {
157 createOrResume: () => Promise.reject(new Error('unused')),
158 update: () => Promise.resolve(),
159 get: () => {
160 storeReads += 1
161 return Promise.resolve(null)
162 },
163 findActiveRun: () => {
164 storeReads += 1
165 return Promise.resolve(null)
166 },
167 }
168 await awaitAttachableJournal(probe.handle, {
169 paths: journalPaths(runId),
170 runId,
171 runs,
172 waitMs: 50,
173 })
174 // A journal that exists either carries a sentinel or is still growing;
175 // neither hangs. Gating it on a record the store may have evicted would
176 // make a perfectly readable journal unreadable.
177 expect(storeReads).toBe(0)
178 expect(probe.commands).toEqual([journalExistsCommand(journalPaths(runId))])
179 })
180})
181​
182describe('awaitAttachableJournal: fails fast', () => {
183 it(
184 'rejects an unknown runId with reason unknown-run',
185 { timeout: 2_000 },
186 async () => {
187 const runId = 'pf-unknown-1'
188 const probe = probeHandle({ exists: false })
189 const error = await awaitAttachableJournal(probe.handle, {
190 paths: journalPaths(runId),
191 runId,
192 runs: new InMemoryRunStore(),
193 // Generous on purpose: if the store check were removed, this would take
194 // 5s and blow the 2s test timeout instead of passing by luck.
195 waitMs: 5_000,
196 }).then(
197 () => null,
198 (reason: unknown) => reason,
199 )
200 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
201 if (!(error instanceof JournalAttachUnavailableError)) return
202 expect(error.reason).toBe('unknown-run')
203 expect(error.runId).toBe(runId)
204 expect(error.message).toContain('no run record exists')
205 expect(error.message).toContain(journalPaths(runId).journal)
206 },
207 )
208​
209 it.each(['completed', 'failed', 'aborted'] as const)(
210 'rejects a %s run with no journal with reason terminal-run',
211 { timeout: 2_000 },
212 async (status) => {
213 const runId = `pf-terminal-${status}`
214 const probe = probeHandle({ exists: false })
215 const error = await awaitAttachableJournal(probe.handle, {
216 paths: journalPaths(runId),
217 runId,
218 runs: await storeWith(runId, status),
219 waitMs: 5_000,
220 }).then(
221 () => null,
222 (reason: unknown) => reason,
223 )
224 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
225 if (!(error instanceof JournalAttachUnavailableError)) return
226 expect(error.reason).toBe('terminal-run')
227 expect(error.message).toContain(`already '${status}'`)
228 expect(error.message).toContain('event log')
229 },
230 )
231​
232 it('still fails fast on an unknown runId when the probe itself is unusable', async () => {
233 // A provider whose `exec` rejects gives no existence answer, but the store
234 // needs none — so the two verdicts that are decidable without a probe stay
235 // decidable.
236 const runId = 'pf-unknown-noprobe'
237 await expect(
238 awaitAttachableJournal(probeHandle({ execFails: true }).handle, {
239 paths: journalPaths(runId),
240 runId,
241 runs: new InMemoryRunStore(),
242 waitMs: 5_000,
243 }),
244 ).rejects.toThrow(/unknown to the RunStore/)
245 })
246})
247​
248describe('awaitAttachableJournal: the legitimate race', () => {
249 it(
250 'waits for a live run whose journal appears after a short delay',
251 { timeout: 5_000 },
252 async () => {
253 const runId = 'pf-race-1'
254 const probe = probeHandle({ exists: false })
255 const runs = await storeWith(runId, 'running')
256 // The driver has claimed the run and writes its first line ~120ms later.
257 // This is the NORMAL case (`journalFollowCommand`'s `: >> file` exists for
258 // it), so failing fast here would reintroduce the defect that fix cured.
259 const timer = setTimeout(() => probe.setExists(true), 120)
260 try {
261 await awaitAttachableJournal(probe.handle, {
262 paths: journalPaths(runId),
263 runId,
264 runs,
265 waitMs: 3_000,
266 probeIntervalMs: 20,
267 })
268 } finally {
269 clearTimeout(timer)
270 }
271 // Resolving at all is the assertion; the probe count proves it polled
272 // rather than getting lucky on the first read.
273 expect(probe.commands.length).toBeGreaterThan(1)
274 },
275 )
276​
277 it(
278 'waits for an interrupted run too — a HITL pause is not terminal',
279 { timeout: 5_000 },
280 async () => {
281 const runId = 'pf-race-interrupted'
282 const probe = probeHandle({ exists: false })
283 const timer = setTimeout(() => probe.setExists(true), 60)
284 try {
285 await awaitAttachableJournal(probe.handle, {
286 paths: journalPaths(runId),
287 runId,
288 runs: await storeWith(runId, 'interrupted'),
289 waitMs: 3_000,
290 probeIntervalMs: 20,
291 })
292 } finally {
293 clearTimeout(timer)
294 }
295 expect(probe.commands.length).toBeGreaterThan(1)
296 },
297 )
298})
299​
300describe('awaitAttachableJournal: the bounded wait', () => {
301 it(
302 'rejects with journal-timeout when a live run never writes one',
303 { timeout: 2_000 },
304 async () => {
305 const runId = 'pf-timeout-1'
306 const probe = probeHandle({ exists: false })
307 const started = Date.now()
308 const error = await awaitAttachableJournal(probe.handle, {
309 paths: journalPaths(runId),
310 runId,
311 runs: await storeWith(runId, 'running'),
312 waitMs: 80,
313 probeIntervalMs: 20,
314 }).then(
315 () => null,
316 (reason: unknown) => reason,
317 )
318 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
319 if (!(error instanceof JournalAttachUnavailableError)) return
320 expect(error.reason).toBe('journal-timeout')
321 expect(error.message).toContain('80ms')
322 expect(error.message).toContain(journalPaths(runId).journal)
323 // The bound is real: an unbounded wait would never reach this line, and
324 // the 2s test timeout is what turns that into a failure.
325 expect(Date.now() - started).toBeLessThan(1_500)
326 },
327 )
328​
329 it(
330 'names the detached state in the timeout, since it points at a different cause',
331 { timeout: 2_000 },
332 async () => {
333 const runId = 'pf-timeout-detached'
334 const detachedSince = Date.UTC(2026, 0, 2, 3, 4, 5)
335 const error = await awaitAttachableJournal(
336 probeHandle({ exists: false }).handle,
337 {
338 paths: journalPaths(runId),
339 runId,
340 runs: await storeWith(runId, 'running', { detachedSince }),
341 waitMs: 40,
342 probeIntervalMs: 20,
343 },
344 ).then(
345 () => null,
346 (reason: unknown) => reason,
347 )
348 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
349 if (!(error instanceof JournalAttachUnavailableError)) return
350 expect(error.message).toContain('detached since')
351 expect(error.message).toContain(new Date(detachedSince).toISOString())
352 },
353 )
354​
355 it(
356 'bounds the wait even with no run store wired, rather than hanging',
357 { timeout: 2_000 },
358 async () => {
359 // No store means no unknown/terminal verdict is available, but a bound is
360 // still strictly better than an infinite wait.
361 const runId = 'pf-timeout-nostore'
362 const error = await awaitAttachableJournal(
363 probeHandle({ exists: false }).handle,
364 { paths: journalPaths(runId), runId, waitMs: 40, probeIntervalMs: 20 },
365 ).then(
366 () => null,
367 (reason: unknown) => reason,
368 )
369 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
370 if (!(error instanceof JournalAttachUnavailableError)) return
371 expect(error.reason).toBe('journal-timeout')
372 expect(error.message).toContain('no run store is wired')
373 },
374 )
375​
376 it('returns without throwing when the consumer aborts the wait', async () => {
377 // The caller stopped caring; that is not a diagnosis about the run, so the
378 // reader (whose own signal handling ends the read) gets control back.
379 const runId = 'pf-abort-1'
380 const controller = new AbortController()
381 controller.abort()
382 await awaitAttachableJournal(probeHandle({ exists: false }).handle, {
383 paths: journalPaths(runId),
384 runId,
385 runs: await storeWith(runId, 'running'),
386 // Would take 30s if the abort were ignored; the default test timeout
387 // would catch that.
388 waitMs: 30_000,
389 signal: controller.signal,
390 })
391 })
392​
393 it(
394 'does NOT fail open on an unusable probe — it bounds the wait instead',
395 { timeout: 3_000 },
396 async () => {
397 // The fail-open branch this replaces (`if (existence === 'unknown')
398 // return`) did not preserve a working attach: it handed control to a reader
399 // whose first act CREATES the journal (`journalFollowCommand`'s
400 // `: >> file`) and then tails it forever. And it was self-perpetuating —
401 // the file it created made `test -f` succeed from then on, so every later
402 // attach short-circuited on "the journal exists" and hung too, permanently,
403 // long after the transient exec failure had cleared.
404 const runId = 'pf-failopen-1'
405 const probe = probeHandle({ execFails: true })
406 const error = await awaitAttachableJournal(probe.handle, {
407 paths: journalPaths(runId),
408 runId,
409 runs: await storeWith(runId, 'running'),
410 waitMs: 120,
411 probeIntervalMs: 20,
412 }).then(
413 () => null,
414 (reason: unknown) => reason,
415 )
416 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
417 if (!(error instanceof JournalAttachUnavailableError)) return
418 expect(error.reason).toBe('journal-timeout')
419 // The message names the actual problem — the probe, not a missing file —
420 // because those point at different causes.
421 // No stopwatch assertion: the three assertions above already prove the
422 // bound was applied (an unbounded wait produces no error at all), and this
423 // case's own `{ timeout: 3_000 }` already turns an unbounded wait into a
424 // failure — with a better message than a `2000` vs elapsed diff.
425 expect(error.message).toContain('could not be probed at all')
426 // It really re-probed rather than answering from the first failure: an
427 // unusable probe may recover inside the window.
428 expect(probe.commands.length).toBeGreaterThan(1)
429 },
430 )
431​
432 it(
433 'still resolves if an unusable probe RECOVERS inside the window',
434 { timeout: 3_000 },
435 async () => {
436 // Bounding must not mean giving up: a provider whose `exec` blipped once is
437 // the case the old fail-open branch was written for, and it still attaches.
438 const runId = 'pf-failopen-recovers'
439 let calls = 0
440 const probe = probeHandle({ exists: false })
441 const inner = probe.handle.process.exec
442 probe.handle.process.exec = (command, options) => {
443 calls += 1
444 if (calls <= 2) return Promise.reject(new Error('exec blipped'))
445 probe.setExists(true)
446 return inner(command, options)
447 }
448 await awaitAttachableJournal(probe.handle, {
449 paths: journalPaths(runId),
450 runId,
451 runs: await storeWith(runId, 'running'),
452 waitMs: 2_000,
453 probeIntervalMs: 10,
454 })
455 expect(calls).toBeGreaterThan(2)
456 },
457 )
458​
459 it('defaults the bound to DEFAULT_ATTACH_JOURNAL_WAIT_MS', () => {
460 // Pinned because it bounds an attach REQUEST, so an app fronting the route
461 // with its own timeout has to be able to rely on the number.
462 expect(DEFAULT_ATTACH_JOURNAL_WAIT_MS).toBe(10_000)
463 })
464})
465​
466describe('readJournalNdjson runs the preflight on attach only', () => {
467 it(
468 'fails an attach to an unknown runId instead of tailing an empty journal forever',
469 { timeout: 3_000 },
470 async () => {
471 const runId = 'pf-wired-unknown'
472 // The script would never deliver a sentinel, so a missing preflight means
473 // this read never returns — which is exactly the defect.
474 const probe = probeHandle({ exists: false, script: [] })
475 await expect(
476 collect(
477 readJournalNdjson(probe.handle, {
478 journal: {
479 runId,
480 attach: true,
481 runs: new InMemoryRunStore(),
482 attachWaitMs: 5_000,
483 },
484 }),
485 ),
486 ).rejects.toBeInstanceOf(JournalAttachUnavailableError)
487 // It never even spawned a tail on a journal that cannot exist.
488 expect(probe.commands.some((c) => c.includes('tail'))).toBe(false)
489 },
490 )
491​
492 it(
493 'honors attachWaitMs as the bound for a live run with no journal',
494 { timeout: 3_000 },
495 async () => {
496 const runId = 'pf-wired-timeout'
497 const probe = probeHandle({ exists: false, script: [] })
498 const error = await collect(
499 readJournalNdjson(probe.handle, {
500 journal: {
501 runId,
502 attach: true,
503 runs: await storeWith(runId, 'running'),
504 attachWaitMs: 60,
505 },
506 }),
507 ).then(
508 () => null,
509 (reason: unknown) => reason,
510 )
511 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
512 if (!(error instanceof JournalAttachUnavailableError)) return
513 expect(error.reason).toBe('journal-timeout')
514 },
515 )
516​
517 it('does NOT gate a FRESH run, whose journal does not exist yet by design', async () => {
518 // A fresh run's journal is created by its own `journaledCommand` spawn. The
519 // store here is empty, so a preflight that ran on this path would reject it
520 // as an unknown run and break every new durable run.
521 const runId = 'pf-fresh-1'
522 const probe = probeHandle({
523 exists: false,
524 script: [`{"a":1}\n${EXIT(runId)}\n`],
525 })
526 expect(
527 await collect(
528 readJournalNdjson(probe.handle, {
529 journal: { runId, runs: new InMemoryRunStore() },
530 }),
531 ),
532 ).toEqual([{ a: 1 }])
533 expect(probe.commands.some((c) => c.startsWith('test -f'))).toBe(false)
534 })
535})