Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { journalPaths } from '../src/journal'
3import {
4 DEFAULT_ATTACH_JOURNAL_WAIT_MS,
5 JournalAttachUnavailableError,
6} from '../src/attach-preflight'
7import {
8 DEFAULT_JOURNAL_POLL_MS,
9 journalReadStrategy,
10 readJournal,
11} from '../src/journal-reader'
12import type {
13 ExecResult,
14 ProcessOptions,
15 SandboxCapabilities,
16 SandboxHandle,
17 SpawnHandle,
18} from '../src/contracts'
19import type { JournalLine } from '../src/journal-bytes'
20
21function caps(
22 overrides: Partial<SandboxCapabilities> = {},
23): SandboxCapabilities {
24 return {
25 fs: true,
26 exec: true,
27 env: true,
28 ports: false,
29 backgroundProcesses: true,
30 writableStdin: true,
31 killableProcesses: true,
32 snapshots: false,
33 networkPolicy: false,
34 durableFilesystem: false,
35 fork: false,
36 ...overrides,
37 }
38}
39
40async function* fromValues(values: Array<string>): AsyncIterable<string> {
41 for (const value of values) {
42 await Promise.resolve()
43 yield value
44 }
45}
46
47/**
48 * Yield `values`, then hang forever. Models a provider whose `kill` fails to
49 * reach the process holding stdout open, so the stream is never closed.
50 */
51async function* neverEnding(values: Array<string>): AsyncIterable<string> {
52 yield* fromValues(values)
53 await new Promise<never>(() => {
54 // Never settles: that is the whole point.
55 })
56}
57
58function b64(text: string): string {
59 return Buffer.from(text, 'utf8').toString('base64')
60}
61
62async function collect<T>(it: AsyncIterable<T>): Promise<Array<T>> {
63 const out: Array<T> = []
64 for await (const value of it) out.push(value)
65 return out
66}
67
68interface FakeHandleInput {
69 capabilities?: Partial<SandboxCapabilities>
70 spawnStdout?: Array<string> | AsyncIterable<string>
71 exec?: (command: string) => Promise<ExecResult>
72 onSpawn?: (command: string, options?: ProcessOptions) => void
73 onKill?: () => void
74}
75
76function fakeHandle(input: FakeHandleInput = {}): SandboxHandle {
77 const spawnHandle: SpawnHandle = {
78 pid: -1,
79 stdout: Array.isArray(input.spawnStdout)
80 ? fromValues(input.spawnStdout)
81 : (input.spawnStdout ?? fromValues([])),
82 stderr: fromValues([]),
83 stdin: { write: () => Promise.resolve(), end: () => Promise.resolve() },
84 wait: () => Promise.resolve(0),
85 kill: () => {
86 input.onKill?.()
87 return Promise.resolve()
88 },
89 }
90 return {
91 id: 'fake',
92 provider: 'fake',
93 capabilities: caps(input.capabilities),
94 fs: {
95 read: () =>
96 Promise.reject(new Error('fs must not be used for the journal')),
97 readBytes: () =>
98 Promise.reject(new Error('fs must not be used for the journal')),
99 write: () =>
100 Promise.reject(new Error('fs must not be used for the journal')),
101 list: () => Promise.reject(new Error('unused')),
102 mkdir: () => Promise.reject(new Error('unused')),
103 remove: () => Promise.reject(new Error('unused')),
104 rename: () => Promise.reject(new Error('unused')),
105 exists: () =>
106 Promise.reject(new Error('fs.exists must not be used for the journal')),
107 },
108 git: {} as SandboxHandle['git'],
109 process: {
110 exec: (command) =>
111 input.exec
112 ? input.exec(command)
113 : Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }),
114 spawn: (command, options) => {
115 input.onSpawn?.(command, options)
116 return Promise.resolve(spawnHandle)
117 },
118 },
119 ports: { connect: () => Promise.reject(new Error('unused')) },
120 env: { set: () => Promise.resolve() },
121 destroy: () => Promise.resolve(),
122 }
123}
124
125describe('journalReadStrategy', () => {
126 it('follows when the provider can kill a spawned process', () => {
127 expect(journalReadStrategy(fakeHandle())).toBe('follow')
128 })
129
130 it('polls when kill is a no-op, so nothing unstoppable is ever spawned', () => {
131 expect(
132 journalReadStrategy(
133 fakeHandle({ capabilities: { killableProcesses: false } }),
134 ),
135 ).toBe('poll')
136 })
137
138 it('polls when the provider has no background processes at all', () => {
139 expect(
140 journalReadStrategy(
141 fakeHandle({ capabilities: { backgroundProcesses: false } }),
142 ),
143 ).toBe('poll')
144 })
145
146 it('polls when neither backgroundProcesses nor killableProcesses is supported', () => {
147 expect(
148 journalReadStrategy(
149 fakeHandle({
150 capabilities: {
151 backgroundProcesses: false,
152 killableProcesses: false,
153 },
154 }),
155 ),
156 ).toBe('poll')
157 })
158})
159
160describe('readJournal — follow strategy', () => {
161 it('spawns a following tail from the requested byte and yields positioned lines', async () => {
162 const commands: Array<string> = []
163 const handle = fakeHandle({
164 spawnStdout: ['{"a":1}\n{"b":2}\n'],
165 onSpawn: (command) => commands.push(command),
166 })
167 const lines = await collect(
168 readJournal(handle, { paths: journalPaths('r1'), fromByte: 0 }),
169 )
170 // Raw, unframed: a `| base64` here would buffer the whole stream.
171 expect(commands).toEqual([
172 `mkdir -p '/tmp/tanstack-runs' 2>/dev/null; ` +
173 `: >> '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null; ` +
174 `tail -c +1 -f '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null`,
175 ])
176 expect(lines).toEqual<Array<JournalLine>>([
177 { line: '{"a":1}', endPosition: 8 },
178 { line: '{"b":2}', endPosition: 16 },
179 ])
180 })
181
182 it('counts positions in BYTES, not characters, for a multi-byte line', async () => {
183 // '{"t":"café"}' is 13 bytes but 12 UTF-16 code units: a position counted
184 // over characters would desync every following `tail -c +N`.
185 const handle = fakeHandle({ spawnStdout: ['{"t":"café"}\n'] })
186 expect(
187 await collect(readJournal(handle, { paths: journalPaths('r1') })),
188 ).toEqual<Array<JournalLine>>([{ line: '{"t":"café"}', endPosition: 14 }])
189 })
190
191 it('reassembles a line the provider split across two stdout chunks', async () => {
192 const handle = fakeHandle({ spawnStdout: ['{"a":', '1}\n{"b":2}', '\n'] })
193 expect(
194 await collect(readJournal(handle, { paths: journalPaths('r1') })),
195 ).toEqual<Array<JournalLine>>([
196 { line: '{"a":1}', endPosition: 8 },
197 { line: '{"b":2}', endPosition: 16 },
198 ])
199 })
200
201 it('withholds a trailing line the agent has not finished writing', async () => {
202 const handle = fakeHandle({ spawnStdout: ['{"a":1}\n{"par'] })
203 expect(
204 await collect(readJournal(handle, { paths: journalPaths('r1') })),
205 ).toEqual<Array<JournalLine>>([{ line: '{"a":1}', endPosition: 8 }])
206 })
207
208 it('resumes from fromByte, keeping positions absolute', async () => {
209 const commands: Array<string> = []
210 const handle = fakeHandle({
211 spawnStdout: ['{"b":2}\n'],
212 onSpawn: (command) => commands.push(command),
213 })
214 const lines = await collect(
215 readJournal(handle, { paths: journalPaths('r1'), fromByte: 8 }),
216 )
217 expect(commands[0]).toContain('tail -c +9 -f')
218 expect(lines).toEqual<Array<JournalLine>>([
219 { line: '{"b":2}', endPosition: 16 },
220 ])
221 })
222
223 it('forwards the abort signal to spawn and kills the tail when the consumer stops early', async () => {
224 let killed = false
225 let forwarded: AbortSignal | undefined
226 const controller = new AbortController()
227 const handle = fakeHandle({
228 spawnStdout: ['{"a":1}\n{"b":2}\n'],
229 onSpawn: (_command, options) => {
230 forwarded = options?.signal
231 },
232 onKill: () => {
233 killed = true
234 },
235 })
236 const iterator = readJournal(handle, {
237 paths: journalPaths('r1'),
238 signal: controller.signal,
239 })[Symbol.asyncIterator]()
240 await iterator.next()
241 await iterator.return?.(undefined)
242 expect(forwarded).toBe(controller.signal)
243 expect(killed).toBe(true)
244 })
245
246 it('never touches handle.fs (the local-process /tmp aliasing trap)', async () => {
247 const handle = fakeHandle({ spawnStdout: ['{"a":1}\n'] })
248 await expect(
249 collect(readJournal(handle, { paths: journalPaths('r1') })),
250 ).resolves.toHaveLength(1)
251 })
252
253 it('ends on abort even when the provider never closes stdout', async () => {
254 // The reader must not depend on `kill` closing the pipe: local-process on
255 // Windows falls back to signalling only the `sh` wrapper when `taskkill` is
256 // unavailable, leaving the `tail` grandchild holding stdout open forever.
257 // `neverEnding` models exactly that provider.
258 let killed = false
259 const controller = new AbortController()
260 const handle = fakeHandle({
261 spawnStdout: neverEnding(['{"a":1}\n']),
262 onKill: () => {
263 killed = true
264 },
265 })
266 const lines: Array<JournalLine> = []
267 const done = (async () => {
268 for await (const line of readJournal(handle, {
269 paths: journalPaths('r1'),
270 signal: controller.signal,
271 })) {
272 lines.push(line)
273 }
274 })()
275 // Let the first line through, then abort with the stream still open.
276 await vi.waitFor(() => expect(lines).toHaveLength(1))
277 controller.abort()
278 await done
279 expect(lines).toEqual<Array<JournalLine>>([
280 { line: '{"a":1}', endPosition: 8 },
281 ])
282 expect(killed).toBe(true)
283 })
284
285 it('yields nothing and tears down at once when the signal is already aborted', async () => {
286 let killed = false
287 const controller = new AbortController()
288 controller.abort()
289 const handle = fakeHandle({
290 spawnStdout: neverEnding(['{"a":1}\n']),
291 onKill: () => {
292 killed = true
293 },
294 })
295 expect(
296 await collect(
297 readJournal(handle, {
298 paths: journalPaths('r1'),
299 signal: controller.signal,
300 }),
301 ),
302 ).toEqual([])
303 expect(killed).toBe(true)
304 })
305})
306
307describe('readJournal — poll strategy', () => {
308 it('issues bounded, non-following execs and advances the byte position', async () => {
309 const commands: Array<string> = []
310 const responses = [b64('{"a":1}\n'), '', b64('{"b":2}\n')]
311 let call = 0
312 const handle = fakeHandle({
313 capabilities: { killableProcesses: false },
314 exec: (command) => {
315 commands.push(command)
316 const stdout = responses[call] ?? ''
317 call += 1
318 return Promise.resolve({ stdout, stderr: '', exitCode: 0 })
319 },
320 })
321 const controller = new AbortController()
322 const lines: Array<JournalLine> = []
323 for await (const line of readJournal(handle, {
324 paths: journalPaths('r1'),
325 pollIntervalMs: 0,
326 signal: controller.signal,
327 })) {
328 lines.push(line)
329 if (lines.length === 2) controller.abort()
330 }
331 expect(lines).toEqual<Array<JournalLine>>([
332 { line: '{"a":1}', endPosition: 8 },
333 { line: '{"b":2}', endPosition: 16 },
334 ])
335 expect(commands[0]).toBe(
336 `tail -c +1 '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null | base64`,
337 )
338 expect(commands.every((command) => !command.includes('-f'))).toBe(true)
339 // The third poll must start after the bytes the first two consumed.
340 expect(commands[2]).toContain('tail -c +9 ')
341 })
342
343 it('re-polls from the same position when a line is still incomplete', async () => {
344 const commands: Array<string> = []
345 const responses = [b64('{"par'), b64('{"partial":1}\n')]
346 let call = 0
347 const handle = fakeHandle({
348 capabilities: { killableProcesses: false },
349 exec: (command) => {
350 commands.push(command)
351 const stdout = responses[call] ?? ''
352 call += 1
353 return Promise.resolve({ stdout, stderr: '', exitCode: 0 })
354 },
355 })
356 const controller = new AbortController()
357 const lines: Array<JournalLine> = []
358 for await (const line of readJournal(handle, {
359 paths: journalPaths('r1'),
360 pollIntervalMs: 0,
361 signal: controller.signal,
362 })) {
363 lines.push(line)
364 controller.abort()
365 }
366 expect(lines).toEqual<Array<JournalLine>>([
367 { line: '{"partial":1}', endPosition: 14 },
368 ])
369 // Both polls started at byte 0: a partial line advances nothing.
370 expect(commands[0]).toContain('tail -c +1 ')
371 expect(commands[1]).toContain('tail -c +1 ')
372 })
373
374 it('stops when the signal is already aborted, issuing no exec at all', async () => {
375 const exec = vi.fn(() =>
376 Promise.resolve<ExecResult>({ stdout: '', stderr: '', exitCode: 0 }),
377 )
378 const controller = new AbortController()
379 controller.abort()
380 const handle = fakeHandle({
381 capabilities: { killableProcesses: false },
382 exec,
383 })
384 expect(
385 await collect(
386 readJournal(handle, {
387 paths: journalPaths('r1'),
388 signal: controller.signal,
389 pollIntervalMs: 0,
390 }),
391 ),
392 ).toEqual([])
393 expect(exec).not.toHaveBeenCalled()
394 })
395
396 it('defaults the poll interval to 250ms, matching the cloudflare tail loop', () => {
397 expect(DEFAULT_JOURNAL_POLL_MS).toBe(250)
398 })
399})
400
401describe('readJournal — explicit strategy override', () => {
402 it('honors strategy: poll on a follow-capable provider', async () => {
403 const commands: Array<string> = []
404 const controller = new AbortController()
405 const handle = fakeHandle({
406 exec: (command) => {
407 commands.push(command)
408 controller.abort()
409 return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 })
410 },
411 })
412 await collect(
413 readJournal(handle, {
414 paths: journalPaths('r1'),
415 strategy: 'poll',
416 pollIntervalMs: 0,
417 signal: controller.signal,
418 }),
419 )
420 expect(commands[0]).toContain('tail -c +1 ')
421 })
422})
423
424describe('readJournal is bounded even when the journal exists', () => {
425 // The state this covers is one the reader MANUFACTURES: `journalFollowCommand`
426 // creates the journal before tailing it (`: >> file`), which it must, so a read
427 // for a runId with no journal produces an empty file and tails it forever — the
428 // e274a11fd defect verbatim. The same state is independently reachable by
429 // SIGKILL/OOM of the agent's shell before its sentinel `printf`. And
430 // `readJournal` is PUBLIC, with no RunStore in its signature, so the preflight
431 // cannot cover it: the bound has to live here.
432
433 it('fails a follow that receives no bytes at all, instead of tailing forever', async () => {
434 const handle = fakeHandle({ spawnStdout: neverEnding([]) })
435 const error = await collect(
436 readJournal(handle, {
437 paths: journalPaths('r-stalled'),
438 runId: 'r-stalled',
439 firstByteTimeoutMs: 60,
440 }),
441 ).then(
442 () => null,
443 (reason: unknown) => reason,
444 )
445 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
446 if (!(error instanceof JournalAttachUnavailableError)) return
447 expect(error.reason).toBe('journal-stalled')
448 expect(error.runId).toBe('r-stalled')
449 expect(error.message).toContain('no bytes within 60ms')
450 })
451
452 it('kills the tail on the stall path, so nothing is left running in the sandbox', async () => {
453 let killed = false
454 const handle = fakeHandle({
455 spawnStdout: neverEnding([]),
456 onKill: () => {
457 killed = true
458 },
459 })
460 await collect(
461 readJournal(handle, {
462 paths: journalPaths('r-stalled-kill'),
463 firstByteTimeoutMs: 30,
464 }),
465 ).catch(() => {})
466 expect(killed).toBe(true)
467 })
468
469 it('bounds the FIRST byte only — a slow agent is never cut off', async () => {
470 // A healthy run can think for minutes between lines. Once bytes are flowing,
471 // no deadline here may end the read.
472 async function* slowSecondLine(): AsyncIterable<string> {
473 yield '{"a":1}\n'
474 await new Promise((resolve) => setTimeout(resolve, 80))
475 yield '{"b":2}\n'
476 }
477 const handle = fakeHandle({ spawnStdout: slowSecondLine() })
478 expect(
479 await collect(
480 readJournal(handle, {
481 paths: journalPaths('r-slow'),
482 firstByteTimeoutMs: 40,
483 }),
484 ),
485 ).toEqual<Array<JournalLine>>([
486 { line: '{"a":1}', endPosition: 8 },
487 { line: '{"b":2}', endPosition: 16 },
488 ])
489 })
490
491 it('treats a consumer abort as an end, not a stall', async () => {
492 // An abort is the caller withdrawing; it is not a diagnosis about the run, so
493 // it must not be reported as `journal-stalled`.
494 const controller = new AbortController()
495 const handle = fakeHandle({ spawnStdout: neverEnding([]) })
496 setTimeout(() => controller.abort(), 20)
497 expect(
498 await collect(
499 readJournal(handle, {
500 paths: journalPaths('r-abort-not-stall'),
501 signal: controller.signal,
502 firstByteTimeoutMs: 5_000,
503 }),
504 ),
505 ).toEqual([])
506 })
507
508 it('bounds the POLL strategy the same way', async () => {
509 // Cloudflare's strategy has the identical defect: every `exec` answers with an
510 // empty frame and the loop never leaves.
511 const handle = fakeHandle({
512 capabilities: { killableProcesses: false },
513 exec: () => Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }),
514 })
515 const error = await collect(
516 readJournal(handle, {
517 paths: journalPaths('r-poll-stalled'),
518 runId: 'r-poll-stalled',
519 pollIntervalMs: 5,
520 firstByteTimeoutMs: 60,
521 }),
522 ).then(
523 () => null,
524 (reason: unknown) => reason,
525 )
526 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
527 if (!(error instanceof JournalAttachUnavailableError)) return
528 expect(error.reason).toBe('journal-stalled')
529 })
530
531 it('defaults the bound to the attach-preflight number, and names the run by path when no runId is given', async () => {
532 // Reused deliberately: the preflight bounds "the file does not exist", this
533 // bounds "the file exists but nothing writes to it" — one question, two sides.
534 expect(DEFAULT_ATTACH_JOURNAL_WAIT_MS).toBe(10_000)
535 const handle = fakeHandle({ spawnStdout: neverEnding([]) })
536 const paths = journalPaths('r-noid')
537 const error = await collect(
538 readJournal(handle, { paths, firstByteTimeoutMs: 20 }),
539 ).then(
540 () => null,
541 (reason: unknown) => reason,
542 )
543 expect(error).toBeInstanceOf(JournalAttachUnavailableError)
544 if (!(error instanceof JournalAttachUnavailableError)) return
545 expect(error.runId).toBe(paths.journal)
546 })
547
548 it('can be switched off explicitly, for a caller with its own deadline', async () => {
549 // `0` disables it. Asserted so the escape hatch is real rather than folklore —
550 // and it is opt-OUT, not opt-in, which is the whole point.
551 const controller = new AbortController()
552 const handle = fakeHandle({ spawnStdout: neverEnding([]) })
553 setTimeout(() => controller.abort(), 30)
554 expect(
555 await collect(
556 readJournal(handle, {
557 paths: journalPaths('r-unbounded'),
558 firstByteTimeoutMs: 0,
559 signal: controller.signal,
560 }),
561 ),
562 ).toEqual([])
563 })
564})
565
566describe('killableProcesses is a required capability', () => {
567 it('is declared on every capability literal the package builds', () => {
568 // A compile-time guarantee expressed as a runtime assertion so the intent
569 // survives a refactor that loosens the type.
570 expect(caps()).toHaveProperty('killableProcesses')
571 })
572})