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

docker.test.ts

535 lines22.4 KB

1import { execFileSync } from 'node:child_process'
2import { mkdtemp, rm, writeFile } from 'node:fs/promises'
3import { tmpdir } from 'node:os'
4import { join } from 'node:path'
5import { describe, expect, it } from 'vitest'
6import Dockerode from 'dockerode'
7import {
8 defineSandbox,
9 defineWorkspace,
10 localSource,
11} from '@tanstack/ai-sandbox'
12import { dockerSandbox } from '../src/index'
13import { dockerDaemonAvailable } from './docker-daemon'
14import type { SandboxHandle } from '@tanstack/ai-sandbox'
15​
16// Auto-gate: only run when a Docker daemon is reachable. See `./docker-daemon.ts`
17// for what this matrix is the authority on.
18const dockerAvailable = await dockerDaemonAvailable('docker provider')
19​
20/** For the image-inspection assertions below, which read the daemon directly. */
21const docker = new Dockerode()
22​
23const IMAGE = 'alpine:3'
24​
25/**
26 * A command line no other process on the machine will match, so a `ps` sweep
27 * inside the container attributes a survivor to THIS test and nothing else. The
28 * bracket in the grep pattern below keeps the grep from matching its own
29 * command line.
30 */
31const KILL_PROBE_SLEEP = '987654321'
32const KILL_PROBE_GREP = '98765[4]321'
33​
34describe.skipIf(!dockerAvailable)(
35 'docker provider (gated on a reachable daemon)',
36 () => {
37 it('creates a container, runs exec, fs round-trip, snapshot + destroy', async () => {
38 const provider = dockerSandbox({ image: IMAGE })
39 let sbx: SandboxHandle | undefined
40 let snapshotTag: string | undefined
41 try {
42 sbx = await provider.create({})
43​
44 const echo = await sbx.process.exec('echo hello-docker')
45 expect(echo.stdout.trim()).toBe('hello-docker')
46 expect(echo.exitCode).toBe(0)
47​
48 await sbx.fs.write('/workspace/note.txt', 'inside the container')
49 expect(await sbx.fs.exists('/workspace/note.txt')).toBe(true)
50 expect(await sbx.fs.read('/workspace/note.txt')).toBe(
51 'inside the container',
52 )
53​
54 const bytes = new Uint8Array([0, 1, 2, 250])
55 await sbx.fs.write('/workspace/bin', bytes)
56 expect(Array.from(await sbx.fs.readBytes('/workspace/bin'))).toEqual([
57 0, 1, 2, 250,
58 ])
59​
60 // Larger than one `sh -c` argv (Linux MAX_ARG_STRLEN is 128 KiB).
61 const large = Buffer.alloc(180_000, 0x62)
62 await sbx.fs.write('/workspace/large.bin', large)
63 expect(await sbx.fs.readBytes('/workspace/large.bin')).toEqual(
64 new Uint8Array(large),
65 )
66​
67 const snap = await sbx.snapshot?.('test')
68 expect(snap?.id).toMatch(/tanstack-ai-sandbox-snapshot/)
69 snapshotTag = snap?.id
70​
71 // The returned id is a template string composed BEFORE the commit runs,
72 // so asserting its shape proves nothing about whether a snapshot exists
73 // — delete the `container.commit()` call and a shape assertion still
74 // passes. Inspect the image instead: this is the package's only snapshot
75 // coverage, so it has to fail when no image was actually committed.
76 const inspected = await docker.getImage(snapshotTag!).inspect()
77 expect(inspected.RepoTags).toContain(snapshotTag)
78 // ...and the snapshot really captured this container's filesystem.
79 expect(inspected.Id).not.toBe('')
80 } finally {
81 if (snapshotTag !== undefined) {
82 await docker
83 .getImage(snapshotTag)
84 .remove({ force: true })
85 .catch(() => {
86 // Best effort: never mask the real assertion failure.
87 })
88 }
89 await sbx?.destroy()
90 }
91 }, 120_000)
92​
93 it('kill() actually terminates the container-side process, not just the client stream', async () => {
94 const provider = dockerSandbox({ image: IMAGE })
95 let sbx: SandboxHandle | undefined
96 try {
97 sbx = await provider.create({})
98 const handle = sbx
99​
100 /** The probe process's rows in the container's own process table. */
101 const probeRows = async (): Promise<string> =>
102 (
103 await handle.process.exec(
104 `ps | grep ${KILL_PROBE_GREP} | grep -v grep || true`,
105 )
106 ).stdout.trim()
107​
108 const proc = await handle.process.spawn(
109 `echo up; sleep ${KILL_PROBE_SLEEP}`,
110 )
111 for await (const chunk of proc.stdout) {
112 if (chunk.includes('up')) break
113 }
114​
115 // Guard the guard: if the probe were never visible here, its absence
116 // after kill() would prove nothing.
117 expect(await probeRows()).toContain(KILL_PROBE_SLEEP)
118​
119 await proc.kill()
120​
121 // `killableProcesses: true` claims the process is FORCIBLY terminated,
122 // so ask the container — do not take the handle's word for it. Reading
123 // `capabilities.killableProcesses` here would only re-read a module
124 // constant, and passed even when kill() was a no-op that left this
125 // `sleep` running until the container was removed.
126 let survivors = await probeRows()
127 for (let i = 0; i < 20 && survivors !== ''; i += 1) {
128 await new Promise((resolve) => setTimeout(resolve, 250))
129 survivors = await probeRows()
130 }
131 expect(survivors).toBe('')
132 } finally {
133 await sbx?.destroy()
134 }
135 }, 120_000)
136​
137 // Three properties that together are what makes `killableProcesses: true`
138 // more than an assertion. Each fails on its own if the corresponding half of
139 // the fix is reverted.
140 it('kill() awaits the in-container kill instead of firing it and forgetting', async () => {
141 const provider = dockerSandbox({ image: IMAGE })
142 let sbx: SandboxHandle | undefined
143 try {
144 sbx = await provider.create({})
145 const handle = sbx
146 const probeRows = async (): Promise<string> =>
147 (
148 await handle.process.exec(
149 `ps | grep ${KILL_PROBE_GREP} | grep -v grep || true`,
150 )
151 ).stdout.trim()
152​
153 const proc = await handle.process.spawn(
154 `echo up; sleep ${KILL_PROBE_SLEEP}`,
155 )
156 for await (const chunk of proc.stdout) {
157 if (chunk.includes('up')) break
158 }
159 expect(await probeRows()).toContain(KILL_PROBE_SLEEP)
160​
161 const started = Date.now()
162 await proc.kill()
163 const elapsed = Date.now() - started
164​
165 // THE DISCRIMINATOR IS THE CLOCK, not the process table. The kill shell
166 // signals, then sleeps `KILL_ESCALATION_DELAY_MS` (200ms) before
167 // escalating to SIGKILL and verifying with `kill -0`, so a `kill()` that
168 // genuinely awaits it CANNOT resolve faster than that grace period. One
169 // that fires and forgets (`void this.exec(...)` then
170 // `Promise.resolve()`) resolves in ~1ms without a single round trip.
171 //
172 // Asserting on the process table instead does NOT distinguish the two:
173 // measured, a fire-and-forget kill still beats the `ps` probe, because
174 // the probe needs its own `container.exec()` + `exec.start()` round
175 // trips (~5ms each) and the kill was dispatched first. The sibling test
176 // above already covers "it dies"; this one covers "we waited for it".
177 expect(elapsed).toBeGreaterThanOrEqual(150)
178​
179 // …and having waited, the ordering `await proc.kill(); <next step>`
180 // really does hold: no polling, no retry loop, gone right now.
181 expect(await probeRows()).toBe('')
182 } finally {
183 await sbx?.destroy()
184 }
185 }, 120_000)
186​
187 it('treats a cleanly-exited process as nothing to kill: no wait, no warning', async () => {
188 const warnings: Array<string> = []
189 const provider = dockerSandbox({
190 image: IMAGE,
191 logger: {
192 warn: (message) => {
193 warnings.push(message)
194 },
195 },
196 })
197 let sbx: SandboxHandle | undefined
198 try {
199 sbx = await provider.create({})
200​
201 // `journal-reader`'s `followJournal` calls `proc.kill()` from a `finally`
202 // on EVERY exit path, so this — a container-side command that ended on
203 // its own, then a kill — is the NORMAL teardown, not an edge case.
204 const proc = await sbx.process.spawn('echo done')
205 for await (const _chunk of proc.stdout) {
206 // drain to EOF, so the wrapper has exited and its pid file is gone
207 }
208 expect(await proc.wait()).toBe(0)
209 // Let the fire-and-forget `rm -f` land, so the kill below really does
210 // face an absent pid file.
211 await new Promise((resolve) => setTimeout(resolve, 500))
212​
213 const started = Date.now()
214 await proc.kill()
215 const elapsed = Date.now() - started
216​
217 // BOTH harms, because either one regresses on its own.
218 //
219 // THE CLOCK. The pid read is a bounded retry — `PID_WAIT_TIMEOUT_MS`
220 // (2s) at `PID_WAIT_INTERVAL_MS` — and it exists for the fast-abort race
221 // covered below, so it must stay. But "absent" also means "the owner
222 // exited and we removed it", and inferring the first from the second
223 // made every ordinary teardown block ~2s inside `await proc.kill()`.
224 // Measured at 2083ms before the `exited` state; a round trip that skips
225 // the loop is tens of milliseconds. 1s separates them with room to
226 // spare on a loaded machine.
227 expect(elapsed).toBeLessThan(1000)
228​
229 // THE CHANNEL. That warning is the only in-band evidence for
230 // `killableProcesses: true` — the kill shell is built never to fail, so
231 // its exit code carries nothing. A channel that fires on every clean
232 // teardown cannot support the claim, so silence here is load-bearing,
233 // not cosmetic.
234 expect(warnings).toEqual([])
235 } finally {
236 await sbx?.destroy()
237 }
238 }, 120_000)
239​
240 it('reports a kill it could not perform instead of resolving as if it worked', async () => {
241 const warnings: Array<{
242 message: string
243 meta?: Record<string, unknown>
244 }> = []
245 const provider = dockerSandbox({
246 image: IMAGE,
247 logger: {
248 warn: (message, meta) => {
249 warnings.push({ message, meta })
250 },
251 },
252 })
253 let sbx: SandboxHandle | undefined
254 try {
255 sbx = await provider.create({})
256 const handle = sbx
257 const probeRows = async (): Promise<string> =>
258 (
259 await handle.process.exec(
260 `ps | grep ${KILL_PROBE_GREP} | grep -v grep || true`,
261 )
262 ).stdout.trim()
263 // Drive the unperformable case: delete the pid file out from under a
264 // STILL-RUNNING spawn, which is exactly the shape of "this process never
265 // recorded a pid" (its exec never started, or it died before its
266 // `echo $$`). The kill shell then waits, finds nothing, and sends NO
267 // signal — and the process really does survive, which is what makes this
268 // a genuine refusal rather than a modelled one.
269 //
270 // THAT "STILL-RUNNING" IS THE WHOLE DISTINCTION, and the reason this test
271 // keeps its shape after the `exited` fix. An absent pid file means two
272 // different things: "not written yet / never written" (here — nothing can
273 // be signalled, so warn) and "the owner exited and we cleaned up" (the
274 // sibling test above — nothing NEEDS signalling, so stay silent). The
275 // handle no longer infers either from the file alone; it tracks which
276 // happened. This case is the first, so the warning is earned. The
277 // assertions below prove that from the container's own process table
278 // rather than trusting the shape of the setup.
279 //
280 // Asserting only that `kill()` RESOLVED would pass against a kill that
281 // did nothing at all — the shell is built never to fail, so its exit
282 // code carries no information by design. The logger is the only channel
283 // that can carry it, which is why the assertion is on the logger.
284 const proc = await handle.process.spawn(
285 `echo up; sleep ${KILL_PROBE_SLEEP}`,
286 )
287 for await (const chunk of proc.stdout) {
288 if (chunk.includes('up')) break
289 }
290 // Guard the guard: there WAS a pid file, so its absence below is our
291 // doing and not a mechanism that never wrote one.
292 const listed = await handle.process.exec(
293 'ls -1 /tmp/.tanstack-sandbox-spawn-*.pid',
294 )
295 expect(listed.stdout.trim()).not.toBe('')
296 await handle.process.exec('rm -f /tmp/.tanstack-sandbox-spawn-*.pid')
297 // Guard the guard, part two: the probe is alive going in, so its presence
298 // afterwards is a survival and not a process that was never there.
299 expect(await probeRows()).toContain(KILL_PROBE_SLEEP)
300​
301 await proc.kill()
302​
303 // The kill could not be performed, and that fact is VISIBLE.
304 expect(
305 warnings.some((w) => /no pid was recorded/.test(w.message)),
306 ).toBe(true)
307​
308 // …and the refusal it reports is REAL. Without this the test would pass
309 // against a handle that warned about a process it had in fact killed —
310 // i.e. against the cried-wolf channel the sibling test forbids. The
311 // container's own `ps` is the arbiter: the probe is still running,
312 // because no signal was ever sent to it.
313 expect(await probeRows()).toContain(KILL_PROBE_SLEEP)
314 } finally {
315 // The probe outlives the un-performable kill by construction; removing
316 // the container is what actually ends it.
317 await sbx?.destroy()
318 }
319 }, 120_000)
320​
321 it('kills a process that is killed before its pid file can exist (the fast-abort race)', async () => {
322 const provider = dockerSandbox({ image: IMAGE })
323 let sbx: SandboxHandle | undefined
324 try {
325 sbx = await provider.create({})
326 const handle = sbx
327 const probeRows = async (): Promise<string> =>
328 (
329 await handle.process.exec(
330 `ps | grep ${KILL_PROBE_GREP} | grep -v grep || true`,
331 )
332 ).stdout.trim()
333​
334 // NO waiting for output this time — that is the whole test.
335 // `container.exec()`/`exec.start()` resolve once the DAEMON accepts the
336 // exec; the container-side shell has not necessarily run its `echo $$`
337 // yet. `journal-reader` kills its follower this promptly on abort.
338 //
339 // With a bare `cat` on the pid file, `$pid` is empty here, `[ -n "$pid" ]`
340 // is false, NO signal is sent, and `stream.destroy()` only detaches the
341 // client — the exact pre-fix orphan. The bounded retry in
342 // `killRecordedPidCommand` is what closes it.
343 const proc = await handle.process.spawn(
344 `echo up; sleep ${KILL_PROBE_SLEEP}`,
345 )
346 await proc.kill()
347​
348 // BusyBox `ps` prints argv, so a survivor is attributable to this test
349 // by its unique sleep duration. Poll until the probe is EMPTY, then
350 // assert once — do not assert inside the loop. `kill()` resolves when the
351 // daemon accepted the signal, not when the container-side process has
352 // finished dying, so a per-poll assertion turns a few milliseconds of
353 // teardown into a failure. The bound is the real assertion: the orphan
354 // this test exists to catch (`stream.destroy()` detaching only the
355 // client) leaves `sleep` running indefinitely, so it never empties and
356 // still fails here.
357 let rows = await probeRows()
358 for (let i = 0; i < 12 && rows !== ''; i += 1) {
359 await new Promise((resolve) => setTimeout(resolve, 250))
360 rows = await probeRows()
361 }
362 expect(rows).toBe('')
363 } finally {
364 await sbx?.destroy()
365 }
366 }, 120_000)
367​
368 it('does not leak a pid file per spawn / per signal-bearing exec', async () => {
369 const provider = dockerSandbox({ image: IMAGE })
370 let sbx: SandboxHandle | undefined
371 try {
372 sbx = await provider.create({})
373 const handle = sbx
374 /** Every pid file the wrapper mechanism could have left in /tmp. */
375 const pidFiles = async (): Promise<string> =>
376 (
377 await handle.process.exec(
378 'ls -1 /tmp/.tanstack-sandbox-*.pid 2>/dev/null || true',
379 )
380 ).stdout.trim()
381​
382 // `rm -f` used to run ONLY on the kill path, so a normally-exiting
383 // process left its file behind for the life of the container. The
384 // dot-prefix means `journalListCommand`'s `ls -1` never surfaced them,
385 // making the accumulation silent and unbounded.
386 const proc = await handle.process.spawn('echo done')
387 for await (const _chunk of proc.stdout) {
388 // drain to EOF — the cleanup hangs off the stream's `end`
389 }
390 expect(await proc.wait()).toBe(0)
391​
392 // A signal-bearing exec writes one too (a plain fs-backing exec does
393 // not, and must not start paying for a kill path it never uses).
394 const ac = new AbortController()
395 const ran = await handle.process.exec('echo ok', { signal: ac.signal })
396 expect(ran.stdout.trim()).toBe('ok')
397​
398 // The removals are dispatched fire-and-forget from stream completion,
399 // so allow them a beat to land before asserting.
400 let leftovers = await pidFiles()
401 for (let i = 0; i < 20 && leftovers !== ''; i += 1) {
402 await new Promise((resolve) => setTimeout(resolve, 250))
403 leftovers = await pidFiles()
404 }
405 expect(leftovers).toBe('')
406 } finally {
407 await sbx?.destroy()
408 }
409 }, 120_000)
410​
411 it('resumes a running container by id and streams a spawned process', async () => {
412 const provider = dockerSandbox({ image: IMAGE })
413 let sbx: SandboxHandle | undefined
414 try {
415 sbx = await provider.create({})
416 await sbx.fs.write('/workspace/keep.txt', 'persisted')
417​
418 const resumed = await provider.resume({ id: sbx.id })
419 expect(resumed?.id).toBe(sbx.id)
420 expect(await resumed!.fs.read('/workspace/keep.txt')).toBe('persisted')
421​
422 const proc = await resumed!.process.spawn('echo streamed-line')
423 let out = ''
424 for await (const chunk of proc.stdout) out += chunk
425 expect(out).toContain('streamed-line')
426 expect(await proc.wait()).toBe(0)
427 } finally {
428 await sbx?.destroy()
429 }
430 }, 120_000)
431​
432 it('ensure() bootstraps a workspace (setup command runs)', async () => {
433 const provider = dockerSandbox({ image: IMAGE })
434 const def = defineSandbox({
435 id: 'docker-ensure',
436 provider,
437 workspace: defineWorkspace({
438 source: { type: 'none' },
439 setup: ['echo bootstrapped > /workspace/setup-marker'],
440 }),
441 })
442 const ctx = { threadId: 'docker-t', runId: 'r1' }
443 try {
444 const sbx = await def.ensure(ctx)
445 expect((await sbx.fs.read('/workspace/setup-marker')).trim()).toBe(
446 'bootstrapped',
447 )
448 } finally {
449 await def.destroy(ctx)
450 }
451 }, 120_000)
452​
453 it('copies a localSource repository, so git status in the container matches the host', async () => {
454 const repo = await mkdtemp(join(tmpdir(), 'docker-local-source-'))
455 const git = (...args: Array<string>) =>
456 execFileSync('git', args, { cwd: repo, encoding: 'utf8' })
457 // The copy sets up git in the container, so the image needs git.
458 const provider = dockerSandbox({ image: 'node:24' })
459 let sbx: SandboxHandle | undefined
460 try {
461 git('init', '-q', '-b', 'main')
462 git('config', 'user.email', 't@t.test')
463 git('config', 'user.name', 't')
464 await writeFile(join(repo, '.gitignore'), 'secret.env\n')
465 await writeFile(join(repo, 'README.md'), 'hi\n')
466 await writeFile(join(repo, 'gone.txt'), 'x\n')
467 git('add', '.')
468 git('commit', '-q', '-m', 'init')
469 await writeFile(join(repo, 'README.md'), 'changed\n')
470 await rm(join(repo, 'gone.txt'))
471 await writeFile(join(repo, 'notes.txt'), 'untracked\n')
472 await writeFile(join(repo, 'secret.env'), 'TOKEN=1\n')
473 // Guard the guard: the host has the changes that the copy must keep.
474 expect(git('status', '--porcelain')).toBe(
475 ' M README.md\n D gone.txt\n?? notes.txt\n',
476 )
477​
478 sbx = await provider.create({
479 workspace: defineWorkspace({ source: localSource(repo) }),
480 })
481​
482 const status = await sbx.process.exec('git status --porcelain')
483 expect(status.exitCode).toBe(0)
484 expect(status.stdout).toBe(git('status', '--porcelain'))
485 const head = await sbx.process.exec('git rev-parse HEAD')
486 expect(head.stdout).toBe(git('rev-parse', 'HEAD'))
487 // The ignored file stays on the host.
488 expect(await sbx.fs.exists('/workspace/secret.env')).toBe(false)
489 } finally {
490 await sbx?.destroy()
491 await rm(repo, { recursive: true, force: true })
492 }
493 }, 300_000)
494​
495 it('reassembles a multi-byte character split across spawn stdout chunk boundaries', async () => {
496 const provider = dockerSandbox({ image: IMAGE })
497 let sbx: SandboxHandle | undefined
498 try {
499 sbx = await provider.create({})
500 // '€' = 0xE2 0x82 0xAC (octal \342 \202 \254). Emit the first byte,
501 // sleep, then the remaining bytes — forcing the container's exec
502 // stream to deliver them as separate chunks, reproducing a
503 // multi-byte character split across a chunk boundary.
504 const proc = await sbx.process.spawn(
505 `printf '\\342'; sleep 0.3; printf '\\202\\254lo'`,
506 )
507 let out = ''
508 for await (const chunk of proc.stdout) out += chunk
509 await proc.wait()
510 expect(out).toBe('€lo')
511 expect(out).not.toContain('�')
512 } finally {
513 await sbx?.destroy()
514 }
515 }, 120_000)
516​
517 it('flushes a genuinely truncated trailing UTF-8 sequence at end of stream (as U+FFFD, not silently dropped)', async () => {
518 const provider = dockerSandbox({ image: IMAGE })
519 let sbx: SandboxHandle | undefined
520 try {
521 sbx = await provider.create({})
522 // Only the first byte of a 3-byte sequence is ever written.
523 const proc = await sbx.process.spawn(`printf '\\342'`)
524 let out = ''
525 for await (const chunk of proc.stdout) out += chunk
526 await proc.wait()
527 // Decision: flush at end-of-stream surfaces the truncated sequence
528 // as the replacement character, rather than silently dropping it.
529 expect(out).toBe('�')
530 } finally {
531 await sbx?.destroy()
532 }
533 }, 120_000)
534 },