subprocess.spec.ts 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. import { once } from 'node:events'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import {
  4. CommandExitError,
  5. FileNotFoundError,
  6. SandboxNotFoundError,
  7. type CommandHandle,
  8. type CommandResult,
  9. type Sandbox,
  10. } from '@deepseek-ai/dsh-e2b'
  11. import type E2BRuntime from '@deepseek-ai/dsh-e2b'
  12. import type { SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
  13. import E2BSubprocessRuntime from '@deepseek-ai/dsh-subprocess-e2b'
  14. import { E2BBase64Decoder, E2B_OUTPUT_COMPLETE_FRAME, E2BOutputReader } from '../src/output.ts'
  15. import { E2BSubprocessHandle } from '../src/process.ts'
  16. import { describe, expect, it, vi } from 'vitest'
  17. function commandError(exitCode: number): CommandExitError {
  18. return new CommandExitError({ exitCode, stdout: '', stderr: '', error: `exit ${exitCode}` })
  19. }
  20. interface StartOptions {
  21. background: true
  22. cwd: string
  23. stdin: boolean
  24. timeoutMs: number
  25. signal?: AbortSignal
  26. envs?: Record<string, string>
  27. onStdout?: (data: string) => void | Promise<void>
  28. onStderr?: (data: string) => void | Promise<void>
  29. }
  30. class FakeCommandHandle {
  31. pid = 4242
  32. readonly sent: Array<string | Uint8Array> = []
  33. closes = 0
  34. kills = 0
  35. disconnects = 0
  36. killError: unknown
  37. killResult = true
  38. disconnectError: unknown
  39. private readonly result = Promise.withResolvers<CommandResult>()
  40. private settled = false
  41. constructor(private readonly onKill: () => void = () => {}) {}
  42. wait(): Promise<CommandResult> {
  43. return this.result.promise
  44. }
  45. async sendStdin(data: string | Uint8Array): Promise<void> {
  46. this.sent.push(data)
  47. }
  48. async closeStdin(): Promise<void> {
  49. this.closes += 1
  50. }
  51. async kill(): Promise<boolean> {
  52. this.kills += 1
  53. if (this.killError !== undefined) throw this.killError
  54. this.onKill()
  55. return this.killResult
  56. }
  57. async disconnect(): Promise<void> {
  58. this.disconnects += 1
  59. if (this.disconnectError !== undefined) throw this.disconnectError
  60. }
  61. succeed(exitCode = 0): void {
  62. if (this.settled) return
  63. this.settled = true
  64. this.result.resolve({ exitCode, stdout: '', stderr: '' })
  65. }
  66. fail(exitCode: number): void {
  67. if (this.settled) return
  68. this.settled = true
  69. this.result.reject(commandError(exitCode))
  70. }
  71. crash(error: unknown): void {
  72. if (this.settled) return
  73. this.settled = true
  74. this.result.reject(error)
  75. }
  76. }
  77. class FakeSandbox {
  78. readonly handle: FakeCommandHandle
  79. readonly commandsSeen: string[] = []
  80. readonly writtenFiles: string[][] = []
  81. readonly writtenFileData = new Map<string, string>()
  82. readonly removed: string[] = []
  83. readonly directories: string[] = []
  84. startOptions: StartOptions | undefined
  85. backgroundError: unknown
  86. envError: unknown
  87. statusError: unknown
  88. nextRemoveError: unknown
  89. probeError: unknown
  90. signalError: unknown
  91. readonly signalErrors: unknown[] = []
  92. trapsTerm = false
  93. delaysKill = false
  94. delaysKillCompletion = false
  95. sdkKillStops = true
  96. alive = true
  97. zombieOnly = false
  98. ambient = 'PATH=/ambient/bin\0KEEP=safe\0UNICODE=你好\0NPM_TOKEN=secret\0DSH_STALE=old\0BROKEN\0=bad\0'
  99. environmentHome = '/home/user'
  100. environmentWire: string | undefined
  101. environmentRequest: ((signal: AbortSignal | undefined) => Promise<void>) | undefined
  102. processGroupId = '4242\n'
  103. exitStatus = ''
  104. statusReads = 0
  105. readonly processGroupReads: string[] = []
  106. afterStatusRead: (() => void) | undefined
  107. beforeProbe: (() => void) | undefined
  108. afterProbe: (() => void) | undefined
  109. private startGate: Promise<void> | undefined
  110. private openStart: (() => void) | undefined
  111. private processGroupReadGate: Promise<void> | undefined
  112. private openProcessGroupRead: (() => void) | undefined
  113. private signalGate: Promise<void> | undefined
  114. private openSignal: (() => void) | undefined
  115. constructor() {
  116. this.handle = new FakeCommandHandle(() => {
  117. if (this.sdkKillStops) {
  118. this.alive = false
  119. this.handle.fail(137)
  120. }
  121. })
  122. }
  123. deferStart(): void {
  124. const gate = Promise.withResolvers<undefined>()
  125. this.startGate = gate.promise
  126. this.openStart = () => { gate.resolve(undefined) }
  127. }
  128. releaseStart(): void {
  129. this.openStart?.()
  130. }
  131. deferProcessGroupRead(): void {
  132. const gate = Promise.withResolvers<undefined>()
  133. this.processGroupReadGate = gate.promise
  134. this.openProcessGroupRead = () => { gate.resolve(undefined) }
  135. }
  136. releaseProcessGroupRead(): void {
  137. this.openProcessGroupRead?.()
  138. }
  139. deferSignals(): void {
  140. const gate = Promise.withResolvers<undefined>()
  141. this.signalGate = gate.promise
  142. this.openSignal = () => { gate.resolve(undefined) }
  143. }
  144. releaseSignals(): void {
  145. this.openSignal?.()
  146. }
  147. finish(exitCode = 0): void {
  148. this.alive = false
  149. void this.completeOutput().then(
  150. () => {
  151. if (exitCode === 0) this.handle.succeed(0)
  152. else this.handle.fail(exitCode)
  153. },
  154. (error: unknown) => { this.handle.crash(error) },
  155. )
  156. }
  157. async completeOutput(): Promise<void> {
  158. await Promise.all([
  159. this.stdoutWire(`${E2B_OUTPUT_COMPLETE_FRAME}\n`),
  160. this.stderrWire(`${E2B_OUTPUT_COMPLETE_FRAME}\n`),
  161. ])
  162. }
  163. async stdout(data: string): Promise<void> {
  164. await this.stdoutWire(data.length === 0 ? '' : `${Buffer.from(data).toString('base64')}\n`)
  165. }
  166. async stderr(data: string): Promise<void> {
  167. await this.stderrWire(data.length === 0 ? '' : `${Buffer.from(data).toString('base64')}\n`)
  168. }
  169. async stdoutWire(data: string): Promise<void> {
  170. await this.startOptions?.onStdout?.(data)
  171. }
  172. async stderrWire(data: string): Promise<void> {
  173. await this.startOptions?.onStderr?.(data)
  174. }
  175. readonly sandbox = {
  176. sandboxId: 'fake',
  177. files: {
  178. makeDir: async (path: string): Promise<boolean> => {
  179. this.directories.push(path)
  180. return true
  181. },
  182. write: async (files: Array<{ path: string; data: string }>): Promise<object[]> => {
  183. this.writtenFiles.push(files.map(file => file.path))
  184. for (const file of files) this.writtenFileData.set(file.path, file.data)
  185. return files.map(() => ({}))
  186. },
  187. read: async (path: string): Promise<string> => {
  188. if (!path.endsWith('/exit-code')) {
  189. await this.processGroupReadGate
  190. return this.processGroupReads.shift() ?? this.processGroupId
  191. }
  192. if (this.statusError !== undefined) {
  193. const error = this.statusError
  194. this.statusError = undefined
  195. throw error
  196. }
  197. this.statusReads += 1
  198. this.afterStatusRead?.()
  199. return this.exitStatus
  200. },
  201. remove: async (path: string): Promise<void> => {
  202. this.removed.push(path)
  203. if (this.nextRemoveError !== undefined) {
  204. const error = this.nextRemoveError
  205. this.nextRemoveError = undefined
  206. throw error
  207. }
  208. },
  209. },
  210. commands: {
  211. run: async (command: string, options?: StartOptions | { signal?: AbortSignal }): Promise<CommandHandle | CommandResult> => {
  212. this.commandsSeen.push(command)
  213. if (command.includes('env -0 | base64')) {
  214. await this.environmentRequest?.(options?.signal)
  215. if (this.envError !== undefined) throw this.envError
  216. return {
  217. exitCode: 0,
  218. stdout: this.environmentWire ?? [this.environmentHome, this.ambient]
  219. .map(value => Buffer.from(value).toString('base64'))
  220. .join('\n'),
  221. stderr: '',
  222. }
  223. }
  224. if (command.startsWith('set -o pipefail; ps -eo pgid=,stat=')) {
  225. this.beforeProbe?.()
  226. if (options?.signal?.aborted === true) throw new DOMException('aborted', 'AbortError')
  227. if (this.probeError !== undefined) {
  228. const error = this.probeError
  229. this.probeError = undefined
  230. throw error
  231. }
  232. const stdout = this.alive && !this.zombieOnly ? 'live\n' : ''
  233. this.afterProbe?.()
  234. return { exitCode: 0, stdout, stderr: '' }
  235. }
  236. if (command.startsWith('kill -TERM ')) {
  237. await this.signalGate
  238. const error = this.signalErrors.shift() ?? this.signalError
  239. if (error !== undefined) {
  240. if (this.signalErrors.length === 0) this.signalError = undefined
  241. throw error
  242. }
  243. if (!this.trapsTerm) {
  244. this.alive = false
  245. this.handle.fail(143)
  246. }
  247. return { exitCode: 0, stdout: '', stderr: '' }
  248. }
  249. if (command.startsWith('kill -KILL ')) {
  250. await this.signalGate
  251. const error = this.signalErrors.shift() ?? this.signalError
  252. if (error !== undefined) {
  253. if (this.signalErrors.length === 0) this.signalError = undefined
  254. throw error
  255. }
  256. if (!this.delaysKill) this.alive = false
  257. if (!this.delaysKillCompletion) this.handle.fail(137)
  258. return { exitCode: 0, stdout: '', stderr: '' }
  259. }
  260. if ((options as StartOptions | undefined)?.background === true) {
  261. this.startOptions = options as StartOptions
  262. await this.startGate
  263. if (this.backgroundError !== undefined) throw this.backgroundError
  264. return this.handle as unknown as CommandHandle
  265. }
  266. return { exitCode: 0, stdout: '', stderr: '' }
  267. },
  268. },
  269. } as unknown as Sandbox
  270. }
  271. function spec(overrides: Partial<SubprocessSpawnSpec> = {}): SubprocessSpawnSpec {
  272. return {
  273. argv: ['bash', '-c', 'printf ok'],
  274. cwd: '/workspace',
  275. stdio: {
  276. stdin: 'ignore',
  277. stdout: { maxBytes: 4, spill: { maxBytes: 16 } },
  278. stderr: { maxBytes: 4 },
  279. },
  280. graceMs: 5,
  281. ...overrides,
  282. }
  283. }
  284. function runtime(fake: FakeSandbox, getSandbox: () => Promise<Sandbox> = async () => fake.sandbox): E2BRuntime {
  285. return {
  286. cwd: '/workspace',
  287. runtimeRoot: '/workspace/.dsh-e2b',
  288. getSandbox,
  289. } as unknown as E2BRuntime
  290. }
  291. async function flush(): Promise<void> {
  292. await new Promise(resolve => setTimeout(resolve, 0))
  293. }
  294. /** Construct the handle under test with the config default the service would pass. */
  295. function testHandle(
  296. runtime: ConstructorParameters<typeof E2BSubprocessHandle>[0],
  297. spec: ConstructorParameters<typeof E2BSubprocessHandle>[1],
  298. stateDir: string,
  299. pollMs = 20,
  300. ): E2BSubprocessHandle {
  301. return new E2BSubprocessHandle(runtime, spec, stateDir, pollMs)
  302. }
  303. describe('E2BOutputReader', () => {
  304. it('decodes base64 across arbitrary callback boundaries and rejects malformed framing', () => {
  305. const decoder = new E2BBase64Decoder()
  306. expect(decoder.push('')).toEqual(Buffer.alloc(0))
  307. expect(decoder.push('5')).toEqual(Buffer.alloc(0))
  308. expect(decoder.push('L2')).toEqual(Buffer.alloc(0))
  309. expect(decoder.push('g\n').toString()).toBe('你')
  310. expect(decoder.push('YQ==\nYg==\n').toString()).toBe('ab')
  311. expect(decoder.push(`${Buffer.from([0, 255]).toString('base64')}\n`)).toEqual(Buffer.from([0, 255]))
  312. expect(decoder.push(`${E2B_OUTPUT_COMPLETE_FRAME}\n`)).toEqual(Buffer.alloc(0))
  313. decoder.finish()
  314. expect(() => new E2BBase64Decoder().push('%\n')).toThrow('invalid base64')
  315. expect(() => new E2BBase64Decoder().push('AB==\n')).toThrow('invalid base64')
  316. expect(() => decoder.push(`${E2B_OUTPUT_COMPLETE_FRAME}\n`)).toThrow('duplicate output transport completion')
  317. expect(() => decoder.push('YQ==\n')).toThrow('continued after completion')
  318. const truncated = new E2BBase64Decoder()
  319. truncated.push('YQ')
  320. expect(() => { truncated.finish() }).toThrow('truncated base64')
  321. expect(() => { new E2BBase64Decoder().finish() }).toThrow('incomplete output transport')
  322. const interrupted = new E2BBase64Decoder()
  323. interrupted.push('YQ')
  324. expect(() => { interrupted.finish(false) }).not.toThrow()
  325. })
  326. it('keeps a byte-exact tail with independent whole-stream cursors', () => {
  327. const reader = new E2BOutputReader(4, 10, '/remote/spill')
  328. reader.push(Buffer.alloc(0))
  329. reader.push(Buffer.from('ab'))
  330. reader.push(Buffer.from('cdef'))
  331. expect(reader.size).toBe(6)
  332. expect(reader.readFrom(0)).toEqual({ text: 'cdef', nextOffset: 6, lossy: true, spillPath: '/remote/spill' })
  333. expect(reader.readFrom(2)).toEqual({ text: 'cdef', nextOffset: 6, lossy: false })
  334. expect(reader.readFrom(5)).toEqual({ text: 'f', nextOffset: 6, lossy: false })
  335. expect(reader.readFrom(99)).toEqual({ text: '', nextOffset: 6, lossy: false })
  336. reader.invalidateSpill()
  337. expect(reader.readFrom(0)).toEqual({ text: 'cdef', nextOffset: 6, lossy: true })
  338. })
  339. it('drops whole head chunks and withholds absent or over-cap spills', () => {
  340. const withoutSpill = new E2BOutputReader(2, undefined, '/unused')
  341. withoutSpill.push(Buffer.from('ab'))
  342. withoutSpill.push(Buffer.from('cd'))
  343. expect(withoutSpill.readFrom(0)).toEqual({ text: 'cd', nextOffset: 4, lossy: true })
  344. const overCap = new E2BOutputReader(2, 3, '/too-small')
  345. overCap.push(Buffer.from('abcd'))
  346. expect(overCap.readFrom(0)).toEqual({ text: 'cd', nextOffset: 4, lossy: true })
  347. })
  348. })
  349. describe('E2BSubprocessHandle', () => {
  350. it('starts asynchronously, keeps secrets out of the command, and supports deferred piped stdin/output', async () => {
  351. const fake = new FakeSandbox()
  352. fake.processGroupId = '4343\n'
  353. fake.deferStart()
  354. const handle = testHandle(runtime(fake), spec({
  355. argv: ['tool', 'argument with spaces'],
  356. stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 8, spill: { maxBytes: 32 } } },
  357. env: {
  358. PATH: '/bin',
  359. 'FOO-BAR': 'hyphen-value',
  360. '--split-string': 'literal-value',
  361. DEEPSEEK_API_KEY: 'explicit-secret',
  362. DSH_MODE: 'test',
  363. // The seam's tombstone: an explicit undefined removes the ambient entry.
  364. KEEP: undefined,
  365. },
  366. }), '/workspace/.dsh-e2b/processes/one')
  367. expect(handle.pid).toBe(-1)
  368. handle.stdin!.write('hello')
  369. handle.stdin!.end()
  370. fake.releaseStart()
  371. await flush()
  372. expect(handle.pid).toBe(4343)
  373. expect(fake.handle.sent.map(value => String(value))).toEqual(['hello'])
  374. expect(fake.handle.closes).toBe(1)
  375. const controlEnvs = fake.startOptions?.envs
  376. expect(controlEnvs?.HOME).toMatch(/^\/\.dsh-e2b-control-/)
  377. expect(controlEnvs).toEqual({
  378. TERM: 'dumb',
  379. NPM_TOKEN: '',
  380. DSH_STALE: '',
  381. HOME: controlEnvs?.HOME,
  382. })
  383. const command = fake.commandsSeen.find(value => value.includes('exec "$dsh_e2b_env_bin" -i'))!
  384. expect(command).toContain('"$dsh_e2b_setsid" --wait -- "$dsh_e2b_bash" -c')
  385. expect(command).not.toContain('DEEPSEEK_API_KEY')
  386. expect(command).not.toContain('DSH_MODE')
  387. expect(command).not.toContain('FOO-BAR')
  388. expect(command).not.toContain('explicit-secret')
  389. expect(command).not.toContain('hyphen-value')
  390. expect(command).not.toContain('${!dsh_e2b_name}')
  391. const environmentProbe = fake.commandsSeen.find(value => value.includes('env -0 | base64'))
  392. expect(environmentProbe).toContain('getent passwd "$(id -u)"')
  393. expect(environmentProbe).toContain('test -n "$dsh_e2b_home" -a -d "$dsh_e2b_home"')
  394. expect(environmentProbe).not.toContain('"$PWD"')
  395. expect(command).toContain('mapfile -d')
  396. expect(command).toContain('dsh_e2b_node="$(command -v node)"')
  397. expect(command).toContain('"$dsh_e2b_env_bin" -i "$dsh_e2b_node" -e')
  398. expect(command).toContain('"$dsh_e2b_env_bin" -i -- "${dsh_e2b_env[@]}" "$@"')
  399. expect(command).toContain('exec "$dsh_e2b_env_bin" -i -- "${dsh_e2b_env[@]}"')
  400. expect(command).toContain('>&2 2>/dev/null')
  401. expect(command).not.toContain('2>/dev/null >&2')
  402. expect(command).toContain('base64')
  403. expect(fake.writtenFiles[0]).toEqual([
  404. '/workspace/.dsh-e2b/processes/one/pid',
  405. '/workspace/.dsh-e2b/processes/one/exit-code',
  406. '/workspace/.dsh-e2b/processes/one/environment',
  407. '/workspace/.dsh-e2b/processes/one/stderr.log',
  408. ])
  409. expect(fake.writtenFileData.get('/workspace/.dsh-e2b/processes/one/environment')).toBe(
  410. 'PATH=/bin\0UNICODE=你好\0HOME=/home/user\0FOO-BAR=hyphen-value\0--split-string=literal-value\0DEEPSEEK_API_KEY=explicit-secret\0DSH_MODE=test\0',
  411. )
  412. let piped = ''
  413. handle.stdout!.on('data', (chunk) => { piped += String(chunk) })
  414. await fake.stdout('pipe-data')
  415. await fake.stderr('err')
  416. fake.finish()
  417. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  418. expect(piped).toBe('pipe-data')
  419. expect(handle.collected.stderr!.readFrom(0)).toMatchObject({ text: 'err', lossy: false })
  420. expect(fake.removed).toContain('/workspace/.dsh-e2b/processes/one/stderr.log')
  421. await expect(handle.waitForExit()).resolves.toBe(true)
  422. })
  423. it('rejects an unrepresentable graceMs before any remote work', () => {
  424. const ctx = new Context()
  425. const service = Object.create(E2BSubprocessRuntime.prototype) as E2BSubprocessRuntime
  426. Reflect.set(service, 'disposing', false)
  427. Reflect.set(service, 'ctx', ctx)
  428. for (const graceMs of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
  429. expect(() => service.spawn(spec({ graceMs }))).toThrow('graceMs must be a positive finite number')
  430. void expect(service.spawnTerminal({
  431. argv: ['bash'], cwd: '/w', rows: 24, cols: 80, graceMs,
  432. })).rejects.toThrow('graceMs must be a positive finite number')
  433. }
  434. })
  435. it('rejects malformed environment entries before command start', async () => {
  436. for (const env of [{ 'BAD=NAME': 'x' }, { BAD: 'x\0INJECTED=1' }]) {
  437. const fake = new FakeSandbox()
  438. const handle = testHandle(runtime(fake), spec({ env }), '/runtime/invalid-environment')
  439. await expect(handle.done).rejects.toThrow('environment entries')
  440. expect(fake.startOptions).toBeUndefined()
  441. expect(fake.removed).toContain('/runtime/invalid-environment')
  442. }
  443. })
  444. it('preserves UTF-8 bytes when the ASCII transport is split across callbacks', async () => {
  445. const fake = new FakeSandbox()
  446. const handle = testHandle(runtime(fake), spec({
  447. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: { maxBytes: 4 } },
  448. }), '/runtime/split-utf8')
  449. await flush()
  450. const chunks: Buffer[] = []
  451. handle.stdout!.on('data', (chunk: Buffer) => { chunks.push(chunk) })
  452. for (const character of `${Buffer.from('A你好B').toString('base64')}\n`) {
  453. await fake.stdoutWire(character)
  454. }
  455. fake.finish()
  456. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  457. expect(Buffer.concat(chunks).toString('utf8')).toBe('A你好B')
  458. })
  459. it('rejects malformed output transport without confusing it with a consumer sink failure', async () => {
  460. const fake = new FakeSandbox()
  461. const handle = testHandle(runtime(fake), spec(), '/runtime/malformed-output')
  462. await flush()
  463. await fake.stdoutWire('%\n')
  464. fake.finish()
  465. await expect(handle.done).rejects.toThrow('invalid base64 output transport')
  466. const stderrFake = new FakeSandbox()
  467. const stderrHandle = testHandle(runtime(stderrFake), spec(), '/runtime/malformed-stderr')
  468. await flush()
  469. await stderrFake.stderrWire('%\n')
  470. stderrFake.finish()
  471. await expect(stderrHandle.done).rejects.toThrow('invalid base64 output transport')
  472. })
  473. it('rejects a naturally completed command whose encoder omits its completion frame', async () => {
  474. const fake = new FakeSandbox()
  475. const handle = testHandle(runtime(fake), spec(), '/runtime/incomplete-output')
  476. await flush()
  477. fake.alive = false
  478. fake.handle.succeed(0)
  479. await expect(handle.done).rejects.toThrow('incomplete output transport')
  480. })
  481. it('bounds descendant-held output draining and withholds the incomplete spill', async () => {
  482. const fake = new FakeSandbox()
  483. const handle = testHandle(runtime(fake), spec({ graceMs: 5 }), '/runtime/drain-bound')
  484. await flush()
  485. await fake.stdout('leader-output')
  486. fake.exitStatus = '0\n'
  487. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  488. expect(fake.handle.disconnects).toBe(1)
  489. expect(handle.collected.stdout?.readFrom(0)).toEqual({
  490. text: 'tput',
  491. nextOffset: 13,
  492. lossy: true,
  493. })
  494. expect(fake.removed).toContain('/runtime/drain-bound/stdout.log')
  495. handle.terminate()
  496. await expect(handle.waitForExit()).resolves.toBe(true)
  497. })
  498. it('releases an inherited-output callback blocked on host backpressure at drain expiry', async () => {
  499. const fake = new FakeSandbox()
  500. const written: string[] = []
  501. const stdoutWrite = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: Uint8Array) => {
  502. written.push(Buffer.from(chunk).toString())
  503. return false
  504. }) as typeof process.stdout.write)
  505. try {
  506. const handle = testHandle(runtime(fake), spec({
  507. graceMs: 5,
  508. stdio: { stdin: 'ignore', stdout: 'inherit', stderr: { maxBytes: 4 } },
  509. }), '/runtime/inherit-backpressure')
  510. await flush()
  511. let callbackSettled = false
  512. const blocked = fake.stdout('blocked bytes').then(() => { callbackSettled = true })
  513. await flush()
  514. expect(callbackSettled).toBe(false)
  515. fake.exitStatus = '0\n'
  516. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  517. await blocked
  518. expect(callbackSettled).toBe(true)
  519. expect(written.join('')).toBe('blocked bytes')
  520. expect(fake.handle.disconnects).toBe(1)
  521. handle.terminate()
  522. await expect(handle.waitForExit()).resolves.toBe(true)
  523. } finally {
  524. stdoutWrite.mockRestore()
  525. }
  526. })
  527. it('waits for lossless raw-pipe output after the direct status is published', async () => {
  528. const fake = new FakeSandbox()
  529. const handle = testHandle(runtime(fake), spec({
  530. graceMs: 1,
  531. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: { maxBytes: 4 } },
  532. }), '/runtime/pipe-drain')
  533. let output = ''
  534. handle.stdout!.on('data', (chunk) => { output += String(chunk) })
  535. await flush()
  536. fake.exitStatus = '0\n'
  537. let settled = false
  538. void handle.done.then(() => { settled = true })
  539. await new Promise(resolve => setTimeout(resolve, 50))
  540. expect(settled).toBe(false)
  541. expect(fake.handle.disconnects).toBe(0)
  542. expect(fake.statusReads).toBe(0)
  543. await fake.stdout('complete protocol frame')
  544. fake.finish()
  545. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  546. expect(output).toBe('complete protocol frame')
  547. expect(fake.statusReads).toBe(1)
  548. })
  549. it('accepts clean encoder completion inside the output-drain grace', async () => {
  550. const fake = new FakeSandbox()
  551. const handle = testHandle(runtime(fake), spec({ graceMs: 100 }), '/runtime/drain-complete')
  552. await flush()
  553. fake.exitStatus = '0\n'
  554. fake.afterStatusRead = () => {
  555. fake.afterStatusRead = undefined
  556. setTimeout(() => { fake.finish() }, 0)
  557. }
  558. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  559. expect(fake.handle.disconnects).toBe(0)
  560. })
  561. it('preserves a published exit code when requested termination outlives output draining', async () => {
  562. const fake = new FakeSandbox()
  563. fake.trapsTerm = true
  564. fake.delaysKill = true
  565. fake.delaysKillCompletion = true
  566. fake.sdkKillStops = false
  567. const handle = testHandle(runtime(fake), spec({ graceMs: 5 }), '/runtime/drain-signal')
  568. await flush()
  569. handle.terminate()
  570. await vi.waitFor(() => { expect(fake.commandsSeen).toContain('kill -KILL -- -4242') })
  571. fake.exitStatus = '0\n'
  572. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  573. expect(fake.handle.disconnects).toBe(1)
  574. fake.alive = false
  575. handle.terminate()
  576. await expect(handle.waitForExit()).resolves.toBe(true)
  577. })
  578. it('preserves a published nonzero exit code when termination settles the SDK inside the drain grace', async () => {
  579. const fake = new FakeSandbox()
  580. const handle = testHandle(runtime(fake), spec({ graceMs: 100 }), '/runtime/drain-signal-settled')
  581. await flush()
  582. fake.exitStatus = '7\n'
  583. fake.afterStatusRead = () => {
  584. fake.afterStatusRead = undefined
  585. handle.terminate()
  586. }
  587. await expect(handle.done).resolves.toEqual({ exitCode: 7, signal: null })
  588. await expect(handle.waitForExit()).resolves.toBe(true)
  589. })
  590. it('rejects an invalid direct-command exit status', async () => {
  591. const fake = new FakeSandbox()
  592. const handle = testHandle(runtime(fake), spec(), '/runtime/invalid-status')
  593. await flush()
  594. fake.exitStatus = '999\n'
  595. await expect(handle.done).rejects.toThrow('invalid exit code')
  596. handle.terminate()
  597. await expect(handle.waitForExit()).resolves.toBe(true)
  598. })
  599. it('rolls back a published process group before rejecting a monitoring failure', async () => {
  600. const fake = new FakeSandbox()
  601. fake.statusError = new Error('status transport failed')
  602. const handle = testHandle(runtime(fake), spec(), '/runtime/status-failure')
  603. await expect(handle.done).rejects.toThrow('status transport failed')
  604. expect(fake.commandsSeen).toContain('kill -TERM -- -4242')
  605. expect(fake.alive).toBe(false)
  606. await expect(handle.waitForExit()).resolves.toBe(true)
  607. const failed = new FakeSandbox()
  608. failed.statusError = new Error('status transport failed')
  609. failed.signalErrors.push(new Error('TERM transport failed'), new Error('KILL transport failed'))
  610. failed.handle.killError = new Error('SDK kill failed')
  611. const retained = testHandle(runtime(failed), spec({ graceMs: 1 }), '/runtime/status-cleanup-failure')
  612. await expect(retained.done).rejects.toThrow(
  613. 'command monitoring failed and process-group rollback did not reach quiescence',
  614. )
  615. expect(failed.alive).toBe(true)
  616. failed.handle.killError = undefined
  617. retained.terminate()
  618. await expect(retained.waitForExit()).resolves.toBe(true)
  619. // A state-cleanup failure on top preserves the rollback failure instead of
  620. // re-aggregating only the original monitoring error.
  621. const triple = new FakeSandbox()
  622. triple.statusError = new Error('status transport failed')
  623. triple.signalErrors.push(new Error('TERM transport failed'), new Error('KILL transport failed'))
  624. triple.handle.killError = new Error('SDK kill failed')
  625. triple.nextRemoveError = new Error('state cleanup failed')
  626. const tripleHandle = testHandle(runtime(triple), spec({ graceMs: 1 }), '/runtime/triple-failure')
  627. const failure = await tripleHandle.done.catch((error: unknown) => error as AggregateError)
  628. expect(failure).toBeInstanceOf(AggregateError)
  629. expect((failure as AggregateError).message).toContain('private state cleanup failed')
  630. const nested = (failure as AggregateError).errors[0] as AggregateError
  631. expect(nested.message).toContain('rollback did not reach quiescence')
  632. triple.handle.killError = undefined
  633. tripleHandle.terminate()
  634. await expect(tripleHandle.waitForExit()).resolves.toBe(true)
  635. })
  636. it('surfaces deferred piped-stdin write and close failures as stream errors', async () => {
  637. const writeFake = new FakeSandbox()
  638. writeFake.deferStart()
  639. vi.spyOn(writeFake.handle, 'sendStdin').mockRejectedValueOnce('stdin rejected')
  640. const writeHandle = testHandle(runtime(writeFake), spec({
  641. stdio: { stdin: 'pipe', stdout: { maxBytes: 4 }, stderr: { maxBytes: 4 } },
  642. }), '/runtime/stdin-write-error')
  643. const writeError = once(writeHandle.stdin!, 'error')
  644. writeHandle.stdin!.write('input')
  645. writeFake.releaseStart()
  646. await expect(writeError).resolves.toMatchObject([{ message: 'stdin rejected' }])
  647. writeFake.finish()
  648. await writeHandle.done
  649. const closeFake = new FakeSandbox()
  650. vi.spyOn(closeFake.handle, 'closeStdin').mockRejectedValueOnce(new Error('close rejected'))
  651. const closeHandle = testHandle(runtime(closeFake), spec({
  652. stdio: { stdin: 'pipe', stdout: { maxBytes: 4 }, stderr: { maxBytes: 4 } },
  653. }), '/runtime/stdin-close-error')
  654. await flush()
  655. const closeError = once(closeHandle.stdin!, 'error')
  656. closeHandle.stdin!.end()
  657. await expect(closeError).resolves.toMatchObject([{ message: 'close rejected' }])
  658. closeFake.finish()
  659. await closeHandle.done
  660. })
  661. it('collects bounded tails, retains valid spills, and maps natural nonzero exits', async () => {
  662. const fake = new FakeSandbox()
  663. const handle = testHandle(runtime(fake), spec({
  664. stdio: {
  665. stdin: { data: 'batch' },
  666. stdout: { maxBytes: 4, spill: { maxBytes: 16 } },
  667. stderr: { maxBytes: 3 },
  668. },
  669. }), '/runtime/two')
  670. await flush()
  671. await fake.stdout('abcdef')
  672. await fake.stderr('12345')
  673. fake.finish(7)
  674. await expect(handle.done).resolves.toEqual({ exitCode: 7, signal: null })
  675. expect(fake.handle.sent).toEqual(['batch'])
  676. expect(fake.handle.closes).toBe(1)
  677. expect(handle.collected.stdout!.readFrom(0)).toEqual({
  678. text: 'cdef',
  679. nextOffset: 6,
  680. lossy: true,
  681. spillPath: '/runtime/two/stdout.log',
  682. })
  683. expect(handle.collected.stderr!.readFrom(0)).toEqual({ text: '345', nextOffset: 5, lossy: true })
  684. expect(fake.removed).not.toContain('/runtime/two/stdout.log')
  685. })
  686. it('removes a spill once the complete stream exceeds its cap', async () => {
  687. const fake = new FakeSandbox()
  688. const handle = testHandle(runtime(fake), spec({
  689. stdio: { stdin: 'ignore', stdout: { maxBytes: 2, spill: { maxBytes: 3 } }, stderr: 'inherit' },
  690. }), '/runtime/oversize')
  691. await flush()
  692. await fake.stdout('abcd')
  693. await fake.stderr('')
  694. fake.finish()
  695. await handle.done
  696. expect(handle.collected.stdout!.readFrom(0)).toEqual({ text: 'cd', nextOffset: 4, lossy: true })
  697. expect(fake.removed).toContain('/runtime/oversize/stdout.log')
  698. const command = fake.commandsSeen.find(value => value.includes('dsh_e2b_tee='))!
  699. expect(command).toContain('"$dsh_e2b_head" -c 3')
  700. expect(command).toContain('/runtime/oversize/stdout.log')
  701. expect(command).toContain('"$dsh_e2b_tee" --output-error=warn-nopipe')
  702. expect(command).not.toContain('tee -a')
  703. })
  704. it('contains remote spill-removal failures and routes empty inherited output', async () => {
  705. const fake = new FakeSandbox()
  706. fake.nextRemoveError = new Error('already removed')
  707. const handle = testHandle(runtime(fake), spec({
  708. stdio: { stdin: 'ignore', stdout: 'inherit', stderr: { maxBytes: 4, spill: { maxBytes: 8 } } },
  709. }), '/runtime/remove-error')
  710. await flush()
  711. await fake.stdout('')
  712. await fake.stderr('')
  713. fake.finish()
  714. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  715. expect(fake.removed).toContain('/runtime/remove-error/stderr.log')
  716. })
  717. it('terminates a process group with TERM and reports the signal outcome', async () => {
  718. const fake = new FakeSandbox()
  719. const handle = testHandle(runtime(fake), spec(), '/runtime/term')
  720. await flush()
  721. handle.terminate()
  722. handle.terminate()
  723. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  724. await expect(handle.waitForExit()).resolves.toBe(true)
  725. expect(fake.commandsSeen).toContain('kill -TERM -- -4242')
  726. expect(fake.commandsSeen).not.toContain('kill -KILL -- -4242')
  727. const signals = fake.commandsSeen.filter(command => command.startsWith('kill -')).length
  728. fake.alive = true
  729. handle.terminate()
  730. await flush()
  731. expect(fake.alive).toBe(true)
  732. expect(fake.commandsSeen.filter(command => command.startsWith('kill -'))).toHaveLength(signals)
  733. })
  734. it('makes termination a permanent no-op after natural quiescence is observed', async () => {
  735. const fake = new FakeSandbox()
  736. const handle = testHandle(runtime(fake), spec(), '/runtime/natural-quiescence')
  737. await flush()
  738. fake.finish()
  739. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  740. await expect(handle.waitForExit()).resolves.toBe(true)
  741. const signals = fake.commandsSeen.filter(command => command.startsWith('kill -')).length
  742. fake.alive = true
  743. handle.terminate()
  744. await flush()
  745. expect(fake.alive).toBe(true)
  746. expect(fake.commandsSeen.filter(command => command.startsWith('kill -'))).toHaveLength(signals)
  747. })
  748. it('treats a zombie-only process group as quiescent', async () => {
  749. const fake = new FakeSandbox()
  750. fake.zombieOnly = true
  751. const handle = testHandle(runtime(fake), spec(), '/runtime/zombie-quiescence')
  752. await flush()
  753. await expect(handle.waitForExit()).resolves.toBe(true)
  754. expect(fake.commandsSeen).toContain(
  755. 'set -o pipefail; ps -eo pgid=,stat= | awk \'$1 == 4242 && $2 !~ /^[ZXx]/ { live=1 } END { if (live) print "live" }\'',
  756. )
  757. fake.finish()
  758. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  759. })
  760. it('keeps proven quiescence after a concurrent termination transport fails', async () => {
  761. const fake = new FakeSandbox()
  762. fake.signalErrors.push(new Error('TERM transport failed'), new Error('KILL transport failed'))
  763. fake.handle.killError = new Error('SDK kill failed')
  764. fake.deferSignals()
  765. const handle = testHandle(runtime(fake), spec(), '/runtime/quiescent-race')
  766. await flush()
  767. handle.terminate()
  768. await vi.waitFor(() => { expect(fake.commandsSeen).toContain('kill -TERM -- -4242') })
  769. fake.alive = false
  770. await expect(handle.waitForExit()).resolves.toBe(true)
  771. fake.probeError = new Error('post-quiescence probe failed')
  772. fake.releaseSignals()
  773. await vi.waitFor(() => { expect(fake.handle.kills).toBe(1) })
  774. fake.finish()
  775. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  776. const signals = fake.commandsSeen.filter(command => command.startsWith('kill -')).length
  777. handle.terminate()
  778. await expect(handle.waitForExit()).resolves.toBe(true)
  779. expect(fake.commandsSeen.filter(command => command.startsWith('kill -'))).toHaveLength(signals)
  780. })
  781. it('escalates a TERM-trapping process group to KILL and uses the SDK kill as fallback', async () => {
  782. const fake = new FakeSandbox()
  783. fake.trapsTerm = true
  784. fake.handle.killError = new Error('already gone')
  785. const handle = testHandle(runtime(fake), spec({ graceMs: 1 }), '/runtime/kill')
  786. await flush()
  787. handle.terminate()
  788. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  789. await expect(handle.waitForExit()).resolves.toBe(true)
  790. expect(fake.commandsSeen).toContain('kill -KILL -- -4242')
  791. expect(fake.handle.kills).toBe(1)
  792. })
  793. it('keeps force cleanup retryable until quiescence is proven', async () => {
  794. const fake = new FakeSandbox()
  795. fake.trapsTerm = true
  796. fake.delaysKill = true
  797. fake.delaysKillCompletion = true
  798. fake.sdkKillStops = false
  799. const handle = testHandle(runtime(fake), spec({ graceMs: 1 }), '/runtime/termination-fence')
  800. await flush()
  801. handle.terminate()
  802. await vi.waitFor(() => { expect(fake.handle.kills).toBe(1) })
  803. await expect(handle.waitForExit()).rejects.toThrow('remained live after force termination')
  804. expect(fake.alive).toBe(true)
  805. fake.delaysKill = false
  806. fake.delaysKillCompletion = false
  807. fake.sdkKillStops = true
  808. handle.terminate()
  809. await expect(handle.waitForExit()).resolves.toBe(true)
  810. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  811. })
  812. it('honors termination requested before asynchronous startup finishes', async () => {
  813. const fake = new FakeSandbox()
  814. fake.deferStart()
  815. const handle = testHandle(runtime(fake), spec(), '/runtime/deferred-kill')
  816. handle.terminate()
  817. fake.releaseStart()
  818. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  819. })
  820. it('aborts a stalled preparation request before reporting startup quiescence', async () => {
  821. const fake = new FakeSandbox()
  822. let preparationSignal: AbortSignal | undefined
  823. fake.environmentRequest = async (signal) => {
  824. preparationSignal = signal
  825. await new Promise<never>((_resolve, reject) => {
  826. const rejectAbort = (): void => {
  827. const reason: unknown = signal?.reason
  828. reject(reason instanceof Error ? reason : new Error(String(reason)))
  829. }
  830. if (signal?.aborted === true) {
  831. rejectAbort()
  832. return
  833. }
  834. signal?.addEventListener('abort', rejectAbort, { once: true })
  835. })
  836. }
  837. const handle = testHandle(runtime(fake), spec(), '/runtime/stalled-preparation')
  838. await vi.waitFor(() => { expect(preparationSignal).toBeDefined() })
  839. handle.terminate()
  840. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  841. await expect(handle.waitForExit()).resolves.toBe(true)
  842. expect(preparationSignal?.aborted).toBe(true)
  843. expect(fake.startOptions).toBeUndefined()
  844. })
  845. it('kills through the provisional SDK handle before process-group publication', async () => {
  846. const fake = new FakeSandbox()
  847. fake.deferProcessGroupRead()
  848. fake.signalErrors.push(commandError(1), commandError(1))
  849. const handle = testHandle(runtime(fake), spec(), '/runtime/pre-publication-kill')
  850. await vi.waitFor(() => { expect(fake.startOptions).toBeDefined() })
  851. handle.terminate()
  852. await vi.waitFor(() => { expect(fake.handle.kills).toBe(1) })
  853. expect(fake.alive).toBe(false)
  854. await expect(handle.waitForExit()).resolves.toBe(true)
  855. fake.releaseProcessGroupRead()
  856. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  857. })
  858. it('does not treat an unsuccessful SDK fallback as provisional group quiescence', async () => {
  859. const fake = new FakeSandbox()
  860. fake.deferProcessGroupRead()
  861. fake.trapsTerm = true
  862. fake.delaysKill = true
  863. fake.delaysKillCompletion = true
  864. fake.sdkKillStops = false
  865. fake.handle.killResult = false
  866. const handle = testHandle(runtime(fake), spec({ graceMs: 1 }), '/runtime/provisional-sdk-false')
  867. await vi.waitFor(() => { expect(fake.startOptions).toBeDefined() })
  868. handle.terminate()
  869. await vi.waitFor(() => { expect(fake.handle.kills).toBe(1) })
  870. await expect(handle.waitForExit()).rejects.toThrow('remained live after force termination')
  871. fake.alive = false
  872. handle.terminate()
  873. await expect(handle.waitForExit()).resolves.toBe(true)
  874. fake.releaseProcessGroupRead()
  875. fake.finish()
  876. await handle.done
  877. })
  878. it('bounds a quiescence observer while provisional termination is awaiting the controller', async () => {
  879. const fake = new FakeSandbox()
  880. fake.deferProcessGroupRead()
  881. const reconnect = Promise.withResolvers<Sandbox>()
  882. let calls = 0
  883. const delayedRuntime = runtime(fake, async () => {
  884. calls += 1
  885. return calls === 1 ? fake.sandbox : await reconnect.promise
  886. })
  887. const handle = testHandle(delayedRuntime, spec(), '/runtime/pre-publication-observer')
  888. await vi.waitFor(() => { expect(fake.startOptions).toBeDefined() })
  889. handle.terminate()
  890. const controller = new AbortController()
  891. const waiting = handle.waitForExit(controller.signal)
  892. await flush()
  893. controller.abort()
  894. await expect(waiting).resolves.toBe(false)
  895. reconnect.resolve(fake.sandbox)
  896. await expect(handle.waitForExit()).resolves.toBe(true)
  897. fake.releaseProcessGroupRead()
  898. await handle.done
  899. })
  900. it('proves a provisional group exit when the SDK kill fallback fails', async () => {
  901. const fake = new FakeSandbox()
  902. fake.deferProcessGroupRead()
  903. fake.trapsTerm = true
  904. fake.handle.killError = new Error('SDK kill unavailable')
  905. const handle = testHandle(runtime(fake), spec({ graceMs: 1 }), '/runtime/pre-publication-group-kill')
  906. await vi.waitFor(() => { expect(fake.startOptions).toBeDefined() })
  907. handle.terminate()
  908. await expect(handle.waitForExit()).resolves.toBe(true)
  909. fake.releaseProcessGroupRead()
  910. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  911. })
  912. it('reports failed provisional group and SDK force transports', async () => {
  913. const fake = new FakeSandbox()
  914. fake.deferProcessGroupRead()
  915. fake.signalErrors.push(new Error('TERM transport failed'), new Error('KILL transport failed'))
  916. fake.handle.killError = new Error('SDK kill failed')
  917. const handle = testHandle(runtime(fake), spec({ graceMs: 1 }), '/runtime/pre-publication-failure')
  918. await vi.waitFor(() => { expect(fake.startOptions).toBeDefined() })
  919. handle.terminate()
  920. await expect(handle.waitForExit()).rejects.toThrow('remained live after force termination')
  921. fake.handle.killError = undefined
  922. handle.terminate()
  923. await expect(handle.waitForExit()).resolves.toBe(true)
  924. fake.releaseProcessGroupRead()
  925. await handle.done
  926. const absentGroup = new FakeSandbox()
  927. absentGroup.deferProcessGroupRead()
  928. absentGroup.signalErrors.push(commandError(1), commandError(1))
  929. absentGroup.handle.killError = new Error('SDK kill failed without a provisional group')
  930. const absentHandle = testHandle(
  931. runtime(absentGroup),
  932. spec({ graceMs: 1 }),
  933. '/runtime/pre-publication-absent-group',
  934. )
  935. await vi.waitFor(() => { expect(absentGroup.startOptions).toBeDefined() })
  936. absentHandle.terminate()
  937. await expect(absentHandle.waitForExit()).rejects.toThrow('remained live after force termination')
  938. absentGroup.handle.killError = undefined
  939. absentHandle.terminate()
  940. await expect(absentHandle.waitForExit()).resolves.toBe(true)
  941. absentGroup.releaseProcessGroupRead()
  942. await absentHandle.done
  943. const optimisticSdk = new FakeSandbox()
  944. optimisticSdk.deferProcessGroupRead()
  945. optimisticSdk.signalErrors.push(commandError(1), commandError(1))
  946. optimisticSdk.sdkKillStops = false
  947. const optimisticHandle = testHandle(
  948. runtime(optimisticSdk),
  949. spec({ graceMs: 1 }),
  950. '/runtime/pre-publication-optimistic-sdk',
  951. )
  952. await vi.waitFor(() => { expect(optimisticSdk.startOptions).toBeDefined() })
  953. optimisticHandle.terminate()
  954. await expect(optimisticHandle.waitForExit()).rejects.toThrow('remained live after force termination')
  955. optimisticHandle.terminate()
  956. await expect(optimisticHandle.waitForExit()).resolves.toBe(true)
  957. optimisticSdk.releaseProcessGroupRead()
  958. await optimisticHandle.done
  959. })
  960. it('honors an already-aborted signal when constructing the asynchronous handle directly', async () => {
  961. const fake = new FakeSandbox()
  962. const handle = testHandle(runtime(fake), spec({ signal: AbortSignal.abort('stop') }), '/runtime/pre-aborted')
  963. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  964. })
  965. it('reacts to a signal that aborts after the remote command has started', async () => {
  966. const fake = new FakeSandbox()
  967. const controller = new AbortController()
  968. const handle = testHandle(runtime(fake), spec({ signal: controller.signal }), '/runtime/live-abort')
  969. await flush()
  970. controller.abort('stop')
  971. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  972. })
  973. it('can terminate a surviving process group after the command leader settles', async () => {
  974. const fake = new FakeSandbox()
  975. const handle = testHandle(runtime(fake), spec(), '/runtime/surviving-group')
  976. await flush()
  977. await fake.completeOutput()
  978. fake.handle.succeed(0)
  979. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  980. expect(fake.alive).toBe(true)
  981. handle.terminate()
  982. await flush()
  983. const signaled = fake.commandsSeen.includes('kill -TERM -- -4242')
  984. if (!signaled) fake.finish()
  985. await expect(handle.waitForExit()).resolves.toBe(true)
  986. expect(signaled).toBe(true)
  987. })
  988. it('bounds waitForExit while startup or a live group is pending', async () => {
  989. const fake = new FakeSandbox()
  990. fake.deferStart()
  991. const handle = testHandle(runtime(fake), spec(), '/runtime/wait')
  992. const beforeStart = new AbortController()
  993. const pending = handle.waitForExit(beforeStart.signal)
  994. beforeStart.abort()
  995. await expect(pending).resolves.toBe(false)
  996. await expect(handle.waitForExit(AbortSignal.abort())).resolves.toBe(false)
  997. fake.releaseStart()
  998. await flush()
  999. const live = new AbortController()
  1000. const liveWait = handle.waitForExit(live.signal)
  1001. live.abort()
  1002. await expect(liveWait).resolves.toBe(false)
  1003. fake.finish()
  1004. await handle.done
  1005. const terminatingFake = new FakeSandbox()
  1006. terminatingFake.deferStart()
  1007. const terminating = testHandle(runtime(terminatingFake), spec(), '/runtime/wait-termination-start')
  1008. terminating.terminate()
  1009. const beforeHandle = new AbortController()
  1010. const handlePending = terminating.waitForExit(beforeHandle.signal)
  1011. beforeHandle.abort()
  1012. await expect(handlePending).resolves.toBe(false)
  1013. terminatingFake.releaseStart()
  1014. await terminating.done
  1015. })
  1016. it('bounds both sides of the liveness-poll abort race', async () => {
  1017. const fake = new FakeSandbox()
  1018. const handle = testHandle(runtime(fake), spec(), '/runtime/poll-abort')
  1019. await flush()
  1020. const beforeTick = new AbortController()
  1021. fake.afterProbe = () => { beforeTick.abort(); fake.afterProbe = undefined }
  1022. await expect(handle.waitForExit(beforeTick.signal)).resolves.toBe(false)
  1023. const duringTick = new AbortController()
  1024. fake.afterProbe = () => {
  1025. fake.afterProbe = undefined
  1026. setTimeout(() => { duringTick.abort() }, 0)
  1027. }
  1028. await expect(handle.waitForExit(duringTick.signal)).resolves.toBe(false)
  1029. const duringProbe = new AbortController()
  1030. fake.beforeProbe = () => { duringProbe.abort(); fake.beforeProbe = undefined }
  1031. await expect(handle.waitForExit(duringProbe.signal)).resolves.toBe(false)
  1032. let racedAbort = false
  1033. const raceSignal = {
  1034. get aborted() { return racedAbort },
  1035. addEventListener: () => { racedAbort = true },
  1036. removeEventListener: () => {},
  1037. } as unknown as AbortSignal
  1038. await expect(handle.waitForExit(raceSignal)).resolves.toBe(false)
  1039. fake.finish()
  1040. await handle.done
  1041. })
  1042. it('observes a live group across one successful bounded poll', async () => {
  1043. const fake = new FakeSandbox()
  1044. const handle = testHandle(runtime(fake), spec(), '/runtime/poll-success')
  1045. await flush()
  1046. setTimeout(() => { fake.finish() }, 1)
  1047. await expect(handle.waitForExit(new AbortController().signal)).resolves.toBe(true)
  1048. await handle.done
  1049. })
  1050. it('treats startup failure as no live tree and contains readiness rejection', async () => {
  1051. const fake = new FakeSandbox()
  1052. fake.backgroundError = new Error('start failed')
  1053. const handle = testHandle(runtime(fake), spec(), '/runtime/fail')
  1054. await expect(handle.done).rejects.toThrow('start failed')
  1055. expect(handle.pid).toBe(-1)
  1056. expect(fake.removed).toContain('/runtime/fail/environment')
  1057. expect(fake.removed).toContain('/runtime/fail')
  1058. await expect(handle.waitForExit()).resolves.toBe(true)
  1059. handle.terminate()
  1060. const unavailableHandle = testHandle(
  1061. runtime(new FakeSandbox(), async () => { throw new Error('sandbox unavailable') }),
  1062. spec(),
  1063. '/runtime/unavailable-start',
  1064. )
  1065. await expect(unavailableHandle.done).rejects.toThrow('sandbox unavailable')
  1066. await expect(unavailableHandle.waitForExit()).resolves.toBe(true)
  1067. const envFailure = new FakeSandbox()
  1068. envFailure.envError = new Error('ambient lookup failed')
  1069. const envHandle = testHandle(runtime(envFailure), spec(), '/runtime/env-failure')
  1070. await expect(envHandle.done).rejects.toThrow('ambient lookup failed')
  1071. expect(envFailure.removed).toEqual([])
  1072. const expectEnvironmentFailure = async (name: string, wire: string, message: string): Promise<void> => {
  1073. const fake = new FakeSandbox()
  1074. fake.environmentWire = wire
  1075. const failed = testHandle(runtime(fake), spec(), `/runtime/${name}`)
  1076. await expect(failed.done).rejects.toThrow(message)
  1077. }
  1078. const encodedEnvironment = Buffer.from('PATH=/bin\0').toString('base64')
  1079. const encodedHome = Buffer.from('/home/user').toString('base64')
  1080. await expectEnvironmentFailure('malformed-frame', '%', 'invalid base64')
  1081. await expectEnvironmentFailure('malformed-base64', `${encodedHome}\n%`, 'invalid base64')
  1082. await expectEnvironmentFailure(
  1083. 'invalid-utf8-home',
  1084. `${Buffer.from([0xff]).toString('base64')}\n${encodedEnvironment}`,
  1085. 'not valid UTF-8',
  1086. )
  1087. await expectEnvironmentFailure(
  1088. 'invalid-utf8-environment',
  1089. `${encodedHome}\n${Buffer.from([0xff]).toString('base64')}`,
  1090. 'not valid UTF-8',
  1091. )
  1092. await expectEnvironmentFailure(
  1093. 'relative-home',
  1094. `${Buffer.from('home/user').toString('base64')}\n${encodedEnvironment}`,
  1095. 'remote login home is invalid',
  1096. )
  1097. await expectEnvironmentFailure(
  1098. 'nul-home',
  1099. `${Buffer.from('/home/user\0tail').toString('base64')}\n${encodedEnvironment}`,
  1100. 'remote login home is invalid',
  1101. )
  1102. const cleanupFailure = new FakeSandbox()
  1103. cleanupFailure.backgroundError = new Error('start failed before credential consumption')
  1104. cleanupFailure.nextRemoveError = new Error('credential cleanup failed')
  1105. const cleanupHandle = testHandle(runtime(cleanupFailure), spec(), '/runtime/cleanup-failure')
  1106. await expect(cleanupHandle.done).rejects.toThrow('command failed and private state cleanup failed')
  1107. const absentState = new FakeSandbox()
  1108. absentState.backgroundError = new Error('start failed after external cleanup')
  1109. absentState.nextRemoveError = new FileNotFoundError('already removed')
  1110. const absentHandle = testHandle(runtime(absentState), spec(), '/runtime/absent-state')
  1111. await expect(absentHandle.done).rejects.toThrow('start failed after external cleanup')
  1112. })
  1113. it('bounds a readiness rejection with a still-live caller signal', async () => {
  1114. const fake = new FakeSandbox()
  1115. fake.deferStart()
  1116. fake.backgroundError = new Error('start failed')
  1117. const handle = testHandle(runtime(fake), spec(), '/runtime/fail-with-signal')
  1118. const waiting = handle.waitForExit(new AbortController().signal)
  1119. fake.releaseStart()
  1120. await expect(handle.done).rejects.toThrow('start failed')
  1121. await expect(waiting).resolves.toBe(true)
  1122. })
  1123. it('propagates an unavailable sandbox unless the caller aborts the wait', async () => {
  1124. const fake = new FakeSandbox()
  1125. let calls = 0
  1126. const unavailable = runtime(fake, async () => {
  1127. calls += 1
  1128. if (calls === 1) return fake.sandbox
  1129. throw new Error('connection unavailable')
  1130. })
  1131. const handle = testHandle(unavailable, spec(), '/runtime/unavailable')
  1132. await flush()
  1133. await expect(handle.waitForExit()).rejects.toThrow('connection unavailable')
  1134. fake.finish()
  1135. await handle.done
  1136. })
  1137. it('returns false when the caller aborts while reconnecting for liveness', async () => {
  1138. const fake = new FakeSandbox()
  1139. const reconnect = Promise.withResolvers<Sandbox>()
  1140. let calls = 0
  1141. const unavailable = runtime(fake, async () => {
  1142. calls += 1
  1143. return calls === 1 ? fake.sandbox : await reconnect.promise
  1144. })
  1145. const handle = testHandle(unavailable, spec(), '/runtime/reconnect-abort')
  1146. await flush()
  1147. const controller = new AbortController()
  1148. const waiting = handle.waitForExit(controller.signal)
  1149. await flush()
  1150. controller.abort()
  1151. reconnect.reject(new Error('connection unavailable'))
  1152. await expect(waiting).resolves.toBe(false)
  1153. fake.finish()
  1154. await handle.done
  1155. })
  1156. it('returns false when a liveness request itself is aborted and surfaces other probe failures', async () => {
  1157. const fake = new FakeSandbox()
  1158. const handle = testHandle(runtime(fake), spec(), '/runtime/probe')
  1159. await flush()
  1160. const controller = new AbortController()
  1161. controller.abort()
  1162. await expect(handle.waitForExit(controller.signal)).resolves.toBe(false)
  1163. fake.probeError = new Error('probe failed')
  1164. await expect(handle.waitForExit()).rejects.toThrow('probe failed')
  1165. fake.finish()
  1166. await handle.done
  1167. })
  1168. it('treats a timeout-killed sandbox as quiescent during liveness probing', async () => {
  1169. const fake = new FakeSandbox()
  1170. const handle = testHandle(runtime(fake), spec(), '/runtime/expired-sandbox')
  1171. await flush()
  1172. fake.finish()
  1173. await handle.done
  1174. fake.probeError = new SandboxNotFoundError('sandbox expired')
  1175. await expect(handle.waitForExit()).resolves.toBe(true)
  1176. })
  1177. it('treats a missing sandbox handle as quiescent during liveness acquisition', async () => {
  1178. const fake = new FakeSandbox()
  1179. let calls = 0
  1180. const handle = testHandle(runtime(fake, async () => {
  1181. calls += 1
  1182. if (calls === 1) return fake.sandbox
  1183. throw new SandboxNotFoundError('sandbox expired')
  1184. }), spec(), '/runtime/expired-acquisition')
  1185. await flush()
  1186. await expect(handle.waitForExit()).resolves.toBe(true)
  1187. await fake.completeOutput()
  1188. fake.alive = false
  1189. fake.handle.succeed(0)
  1190. await handle.done
  1191. })
  1192. it('treats sandbox loss during termination as quiescent', async () => {
  1193. const fake = new FakeSandbox()
  1194. let calls = 0
  1195. const handle = testHandle(runtime(fake, async () => {
  1196. calls += 1
  1197. if (calls === 1) return fake.sandbox
  1198. throw new SandboxNotFoundError('sandbox expired')
  1199. }), spec(), '/runtime/expired-termination')
  1200. await flush()
  1201. await fake.completeOutput()
  1202. handle.terminate()
  1203. await expect(handle.waitForExit()).resolves.toBe(true)
  1204. fake.alive = false
  1205. fake.handle.succeed(0)
  1206. await handle.done
  1207. })
  1208. it('makes batch stdin close failures best-effort', async () => {
  1209. const fake = new FakeSandbox()
  1210. vi.spyOn(fake.handle, 'sendStdin').mockRejectedValueOnce(new Error('closed'))
  1211. const handle = testHandle(runtime(fake), spec({
  1212. stdio: { stdin: { data: 'ignored' }, stdout: { maxBytes: 4 }, stderr: { maxBytes: 4 } },
  1213. }), '/runtime/stdin-closed')
  1214. await flush()
  1215. fake.finish()
  1216. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  1217. })
  1218. it('rejects malformed SDK process ids and non-command settlement failures', async () => {
  1219. const invalidPid = new FakeSandbox()
  1220. invalidPid.handle.pid = 0
  1221. const invalid = testHandle(runtime(invalidPid), spec(), '/runtime/invalid-pid')
  1222. await expect(invalid.done).rejects.toThrow(/invalid command pid 0/)
  1223. expect(invalidPid.handle.kills).toBe(1)
  1224. expect(invalidPid.removed).toContain('/runtime/invalid-pid/environment')
  1225. await expect(invalid.waitForExit()).resolves.toBe(true)
  1226. const failedRollback = new FakeSandbox()
  1227. failedRollback.handle.pid = 0
  1228. failedRollback.handle.killError = new Error('invalid handle kill failed')
  1229. const retained = testHandle(runtime(failedRollback), spec(), '/runtime/invalid-pid-retained')
  1230. await expect(retained.done).rejects.toThrow('invalid command pid rollback did not reach quiescence')
  1231. await expect(retained.waitForExit()).rejects.toThrow('invalid handle kill failed')
  1232. failedRollback.handle.killError = undefined
  1233. retained.terminate()
  1234. await expect(retained.waitForExit()).resolves.toBe(true)
  1235. const crashedFake = new FakeSandbox()
  1236. const crashed = testHandle(runtime(crashedFake), spec(), '/runtime/crashed')
  1237. await flush()
  1238. crashedFake.alive = false
  1239. crashedFake.handle.crash(new Error('command transport failed'))
  1240. await expect(crashed.done).rejects.toThrow('command transport failed')
  1241. })
  1242. it('rejects invalid or absent process-group publication', async () => {
  1243. const invalidGroup = new FakeSandbox()
  1244. invalidGroup.processGroupId = 'not-a-pid\n'
  1245. invalidGroup.delaysKill = true
  1246. invalidGroup.sdkKillStops = false
  1247. invalidGroup.afterProbe = () => { invalidGroup.alive = false }
  1248. const invalid = testHandle(runtime(invalidGroup), spec(), '/runtime/invalid-group')
  1249. await expect(invalid.done).rejects.toThrow(/invalid process-group id/)
  1250. expect(invalidGroup.handle.kills).toBe(1)
  1251. expect(invalidGroup.commandsSeen).toContain('kill -KILL -- -4242')
  1252. await expect(invalid.waitForExit()).resolves.toBe(true)
  1253. // A rewritten pid file must not aim the kill at every process (`-- -1`).
  1254. const unsafeGroup = new FakeSandbox()
  1255. unsafeGroup.processGroupId = '1\n'
  1256. unsafeGroup.delaysKill = true
  1257. unsafeGroup.sdkKillStops = false
  1258. unsafeGroup.afterProbe = () => { unsafeGroup.alive = false }
  1259. const unsafe = testHandle(runtime(unsafeGroup), spec(), '/runtime/unsafe-group')
  1260. await expect(unsafe.done).rejects.toThrow(/unsafe published process-group id 1/)
  1261. expect(unsafeGroup.commandsSeen).not.toContain('kill -KILL -- -1')
  1262. await expect(unsafe.waitForExit()).resolves.toBe(true)
  1263. const absentGroup = new FakeSandbox()
  1264. absentGroup.processGroupId = ''
  1265. const absent = testHandle(runtime(absentGroup), spec(), '/runtime/absent-group')
  1266. await flush()
  1267. absentGroup.finish()
  1268. await expect(absent.done).rejects.toThrow(/exited before publishing/)
  1269. expect(absentGroup.handle.kills).toBe(1)
  1270. expect(absentGroup.commandsSeen).toContain('kill -KILL -- -4242')
  1271. await expect(absent.waitForExit()).resolves.toBe(true)
  1272. })
  1273. it('preserves publication failure and reports cleanup that cannot be verified', async () => {
  1274. const fake = new FakeSandbox()
  1275. fake.processGroupId = 'not-a-pid\n'
  1276. fake.signalError = new Error('rollback signal failed')
  1277. fake.handle.killError = new Error('SDK kill failed')
  1278. const handle = testHandle(runtime(fake), spec(), '/runtime/failed-rollback')
  1279. let failure: unknown
  1280. try {
  1281. await handle.done
  1282. } catch (error: unknown) {
  1283. failure = error
  1284. }
  1285. expect(failure).toBeInstanceOf(AggregateError)
  1286. if (!(failure instanceof AggregateError)) throw new Error('expected AggregateError')
  1287. expect(failure.message).toBe('subprocess-e2b: process-group publication failed and rollback did not reach quiescence')
  1288. const failures = Array.from(failure.errors as Iterable<unknown>)
  1289. expect(failures).toHaveLength(2)
  1290. expect(failures[0]).toBeInstanceOf(Error)
  1291. expect(failures[1]).toBeInstanceOf(Error)
  1292. if (!(failures[0] instanceof Error) || !(failures[1] instanceof Error)) throw new Error('expected nested errors')
  1293. expect(failures[0].message).toContain('invalid process-group id')
  1294. expect(failures[1].message).toContain('remained live after force termination')
  1295. expect(fake.handle.kills).toBe(1)
  1296. const bounded = new AbortController()
  1297. const waiting = handle.waitForExit(bounded.signal)
  1298. bounded.abort()
  1299. await expect(waiting).resolves.toBe(false)
  1300. handle.terminate()
  1301. await expect(handle.waitForExit()).resolves.toBe(true)
  1302. expect(fake.commandsSeen).toContain('kill -TERM -- -4242')
  1303. const naturallyGone = new FakeSandbox()
  1304. naturallyGone.processGroupId = 'not-a-pid\n'
  1305. naturallyGone.signalError = new Error('rollback signal failed')
  1306. naturallyGone.handle.killError = new Error('SDK kill failed')
  1307. const observed = testHandle(runtime(naturallyGone), spec(), '/runtime/failed-rollback-observed')
  1308. await expect(observed.done).rejects.toThrow('process-group publication failed')
  1309. naturallyGone.alive = false
  1310. await expect(observed.waitForExit()).resolves.toBe(true)
  1311. })
  1312. it('waits for delayed process-group publication', async () => {
  1313. const fake = new FakeSandbox()
  1314. fake.processGroupReads.push('', '4242\n')
  1315. const handle = testHandle(runtime(fake), spec(), '/runtime/delayed-group')
  1316. await vi.waitFor(() => { expect(handle.pid).toBe(4242) })
  1317. fake.finish()
  1318. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  1319. })
  1320. it('handles output backpressure and contains a stderr sink failure', async () => {
  1321. const fake = new FakeSandbox()
  1322. const handle = testHandle(runtime(fake), spec({
  1323. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' },
  1324. }), '/runtime/backpressure')
  1325. await flush()
  1326. handle.stdout!.on('error', () => {})
  1327. const stdoutWrite = vi.spyOn(handle.stdout!, 'write').mockReturnValueOnce(false)
  1328. const stdoutPending = fake.stdout('blocked')
  1329. queueMicrotask(() => { handle.stdout!.emit('drain') })
  1330. await stdoutPending
  1331. stdoutWrite.mockRestore()
  1332. handle.stderr!.on('error', () => {})
  1333. const stderrWrite = vi.spyOn(handle.stderr!, 'write').mockReturnValueOnce(false)
  1334. const stderrPending = fake.stderr('broken')
  1335. queueMicrotask(() => { handle.stderr!.emit('error', new Error('sink failed')) })
  1336. await stderrPending
  1337. stderrWrite.mockRestore()
  1338. fake.finish()
  1339. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  1340. })
  1341. it('settles output backpressure when the consumer closes the pipe', async () => {
  1342. const fake = new FakeSandbox()
  1343. const handle = testHandle(runtime(fake), spec({
  1344. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: { maxBytes: 4 } },
  1345. }), '/runtime/backpressure-close')
  1346. await flush()
  1347. const stdoutWrite = vi.spyOn(handle.stdout!, 'write').mockReturnValueOnce(false)
  1348. const pending = fake.stdout('discarded')
  1349. queueMicrotask(() => { handle.stdout!.destroy() })
  1350. await pending
  1351. stdoutWrite.mockRestore()
  1352. fake.finish()
  1353. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  1354. })
  1355. it('breaks output backpressure when termination owns the command', async () => {
  1356. const fake = new FakeSandbox()
  1357. const handle = testHandle(runtime(fake), spec({
  1358. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: { maxBytes: 4 } },
  1359. }), '/runtime/backpressure-termination')
  1360. await flush()
  1361. const stdoutWrite = vi.spyOn(handle.stdout!, 'write').mockReturnValueOnce(false)
  1362. let released = false
  1363. const pending = fake.stdout('blocked').then(() => { released = true })
  1364. await Promise.resolve()
  1365. handle.terminate()
  1366. await flush()
  1367. const releasedByTermination = released
  1368. if (!released) handle.stdout!.emit('drain')
  1369. await pending
  1370. stdoutWrite.mockRestore()
  1371. await handle.done
  1372. expect(releasedByTermination).toBe(true)
  1373. })
  1374. it('settles backpressure when a synchronous pipe write starts termination', async () => {
  1375. const fake = new FakeSandbox()
  1376. const handle = testHandle(runtime(fake), spec({
  1377. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: { maxBytes: 4 } },
  1378. }), '/runtime/backpressure-synchronous-termination')
  1379. await flush()
  1380. const stdoutWrite = vi.spyOn(handle.stdout!, 'write').mockImplementationOnce(() => {
  1381. handle.terminate()
  1382. return false
  1383. })
  1384. await expect(fake.stdout('blocked')).resolves.toBeUndefined()
  1385. stdoutWrite.mockRestore()
  1386. await handle.done
  1387. })
  1388. it('contains a pipe callback failure instead of rejecting command settlement', async () => {
  1389. const fake = new FakeSandbox()
  1390. const handle = testHandle(runtime(fake), spec({
  1391. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: { maxBytes: 4 } },
  1392. }), '/runtime/pipe-error')
  1393. await flush()
  1394. const emitted = once(handle.stdout!, 'error')
  1395. handle.stdout!.destroy(new Error('consumer failed'))
  1396. await emitted
  1397. await fake.stdout('late output')
  1398. fake.finish()
  1399. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  1400. })
  1401. it('contains an already-gone group signal and escalates after a TERM transport failure', async () => {
  1402. const gone = new FakeSandbox()
  1403. gone.trapsTerm = true
  1404. gone.signalError = commandError(1)
  1405. const goneHandle = testHandle(runtime(gone), spec({ graceMs: 1 }), '/runtime/gone-signal')
  1406. await flush()
  1407. goneHandle.terminate()
  1408. await expect(goneHandle.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  1409. const failed = new FakeSandbox()
  1410. failed.signalError = new Error('signal transport failed')
  1411. const failedHandle = testHandle(runtime(failed), spec(), '/runtime/failed-signal')
  1412. await flush()
  1413. failedHandle.terminate()
  1414. await expect(failedHandle.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  1415. expect(failed.commandsSeen).toContain('kill -KILL -- -4242')
  1416. })
  1417. it('allows termination retry after both force transports fail', async () => {
  1418. const fake = new FakeSandbox()
  1419. fake.signalErrors.push(new Error('TERM transport failed'), new Error('KILL transport failed'))
  1420. fake.handle.killError = new Error('SDK kill failed')
  1421. const handle = testHandle(runtime(fake), spec({ graceMs: 1 }), '/runtime/retry-signal')
  1422. await flush()
  1423. handle.terminate()
  1424. await expect(handle.waitForExit()).rejects.toThrow('remained live after force termination')
  1425. fake.handle.killError = undefined
  1426. handle.terminate()
  1427. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  1428. expect(fake.commandsSeen.filter(command => command.startsWith('kill -TERM '))).toHaveLength(2)
  1429. const missingGroup = new FakeSandbox()
  1430. missingGroup.trapsTerm = true
  1431. missingGroup.signalErrors.push(undefined, commandError(1))
  1432. missingGroup.handle.killError = new Error('SDK kill failed after group exit race')
  1433. const raced = testHandle(runtime(missingGroup), spec({ graceMs: 1 }), '/runtime/group-exit-race')
  1434. await flush()
  1435. raced.terminate()
  1436. await expect(raced.waitForExit()).rejects.toThrow('remained live after force termination')
  1437. missingGroup.handle.killError = undefined
  1438. raced.terminate()
  1439. await expect(raced.waitForExit()).resolves.toBe(true)
  1440. })
  1441. it('rejects an optimistic SDK kill while descendants survive a failed group KILL', async () => {
  1442. const fake = new FakeSandbox()
  1443. fake.trapsTerm = true
  1444. fake.sdkKillStops = false
  1445. fake.signalErrors.push(undefined, new Error('KILL transport failed'))
  1446. const handle = testHandle(runtime(fake), spec({ graceMs: 1 }), '/runtime/optimistic-sdk-kill')
  1447. await flush()
  1448. handle.terminate()
  1449. await expect(handle.waitForExit()).rejects.toThrow('remained live after force termination')
  1450. expect(fake.alive).toBe(true)
  1451. fake.sdkKillStops = true
  1452. handle.terminate()
  1453. await expect(handle.waitForExit()).resolves.toBe(true)
  1454. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  1455. })
  1456. })
  1457. describe('E2BSubprocessRuntime', () => {
  1458. async function service(
  1459. fake = new FakeSandbox(),
  1460. providedRuntime: E2BRuntime = runtime(fake),
  1461. ): Promise<{ ctx: Context; fiber: Awaited<ReturnType<Context['plugin']>> }> {
  1462. const ctx = new Context()
  1463. ctx.provide('e2b', providedRuntime)
  1464. const fiber = await ctx.plugin(E2BSubprocessRuntime)
  1465. return { ctx, fiber }
  1466. }
  1467. it('registers handles and disposal terminates and joins live remote groups regardless of sandbox policy', async () => {
  1468. const fake = new FakeSandbox()
  1469. fake.trapsTerm = true
  1470. const { ctx, fiber } = await service(fake)
  1471. const handle = ctx.subprocess.spawn(spec({ graceMs: 1 }))
  1472. await flush()
  1473. await fiber.dispose()
  1474. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  1475. expect(fake.alive).toBe(false)
  1476. })
  1477. it('awaits SDK settlement after the remote process group becomes quiescent', async () => {
  1478. const fake = new FakeSandbox()
  1479. fake.trapsTerm = true
  1480. const { ctx, fiber } = await service(fake)
  1481. const handle = ctx.subprocess.spawn(spec())
  1482. await flush()
  1483. fake.alive = false
  1484. let disposed = false
  1485. const disposing = fiber.dispose().then(() => { disposed = true })
  1486. await flush()
  1487. expect(disposed).toBe(false)
  1488. fake.finish()
  1489. await disposing
  1490. await expect(handle.done).resolves.toEqual({ exitCode: 0, signal: null })
  1491. })
  1492. it('reports a failed termination transaction from disposal instead of waiting on done', async () => {
  1493. const fake = new FakeSandbox()
  1494. fake.signalErrors.push(new Error('TERM transport failed'), new Error('KILL transport failed'))
  1495. fake.handle.killError = new Error('SDK kill failed')
  1496. const { ctx, fiber } = await service(fake)
  1497. const handle = ctx.subprocess.spawn(spec({ graceMs: 1 }))
  1498. await flush()
  1499. await expect(fiber.dispose()).resolves.toBeUndefined()
  1500. await expect(handle.waitForExit()).rejects.toThrow('remained live after force termination')
  1501. fake.handle.killError = undefined
  1502. handle.terminate()
  1503. await expect(handle.waitForExit()).resolves.toBe(true)
  1504. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  1505. })
  1506. it('aggregates sibling cleanup failures instead of reporting only the first', async () => {
  1507. const { ctx, fiber } = await service()
  1508. const disposalErrors: unknown[] = []
  1509. ctx.logger.error = ((error: unknown) => { disposalErrors.push(error) }) as typeof ctx.logger.error
  1510. const first = {
  1511. terminate: vi.fn(),
  1512. waitForExit: vi.fn(async () => { throw new Error('first cleanup failed') }),
  1513. done: Promise.resolve({ exitCode: 0, signal: null }),
  1514. } as unknown as E2BSubprocessHandle
  1515. const second = {
  1516. terminate: vi.fn(),
  1517. waitForExit: vi.fn(async () => { throw new Error('second cleanup failed') }),
  1518. done: Promise.resolve({ exitCode: 0, signal: null }),
  1519. } as unknown as E2BSubprocessHandle
  1520. const live = (ctx.subprocess as unknown as { live: Set<E2BSubprocessHandle> }).live
  1521. live.add(first)
  1522. live.add(second)
  1523. await fiber.dispose()
  1524. const failure = disposalErrors[0]
  1525. expect(failure).toBeInstanceOf(AggregateError)
  1526. if (!(failure instanceof AggregateError)) throw new Error('expected AggregateError')
  1527. expect(failure.errors.map(error => (error as Error).message).sort()).toEqual([
  1528. 'first cleanup failed',
  1529. 'second cleanup failed',
  1530. ])
  1531. })
  1532. it('waits for every owned cleanup before reporting a disposal failure', async () => {
  1533. const { ctx, fiber } = await service()
  1534. const failed = {
  1535. terminate: vi.fn(),
  1536. waitForExit: vi.fn(async () => { throw new Error('cleanup failed') }),
  1537. done: Promise.resolve({ exitCode: 0, signal: null }),
  1538. } as unknown as E2BSubprocessHandle
  1539. let finishCleanup!: () => void
  1540. const cleanup = new Promise<boolean>((resolve) => {
  1541. finishCleanup = () => { resolve(true) }
  1542. })
  1543. const draining = {
  1544. terminate: vi.fn(),
  1545. waitForExit: vi.fn(() => cleanup),
  1546. done: Promise.resolve({ exitCode: 0, signal: null }),
  1547. } as unknown as E2BSubprocessHandle
  1548. const live = (ctx.subprocess as unknown as { live: Set<E2BSubprocessHandle> }).live
  1549. live.add(failed)
  1550. live.add(draining)
  1551. let disposed = false
  1552. const disposing = fiber.dispose().then(() => { disposed = true })
  1553. await flush()
  1554. expect(disposed).toBe(false)
  1555. finishCleanup()
  1556. await disposing
  1557. expect(live).toEqual(new Set([failed]))
  1558. })
  1559. it('releases naturally settled handles before later service disposal', async () => {
  1560. const fake = new FakeSandbox()
  1561. const { ctx, fiber } = await service(fake)
  1562. const handle = ctx.subprocess.spawn(spec())
  1563. await flush()
  1564. fake.finish()
  1565. await handle.done
  1566. await flush()
  1567. const signalsBefore = fake.commandsSeen.filter(command => command.startsWith('kill -')).length
  1568. await fiber.dispose()
  1569. expect(fake.commandsSeen.filter(command => command.startsWith('kill -')).length).toBe(signalsBefore)
  1570. })
  1571. it('contains a release liveness failure and retries quiescence during disposal', async () => {
  1572. const fake = new FakeSandbox()
  1573. let calls = 0
  1574. const reconnecting = runtime(fake, async () => {
  1575. calls += 1
  1576. if (calls === 2) throw new Error('transient liveness failure')
  1577. return fake.sandbox
  1578. })
  1579. const { ctx, fiber } = await service(fake, reconnecting)
  1580. const handle = ctx.subprocess.spawn(spec())
  1581. await flush()
  1582. fake.finish()
  1583. await handle.done
  1584. await flush()
  1585. await fiber.dispose()
  1586. expect(calls).toBeGreaterThanOrEqual(3)
  1587. })
  1588. it('contains spawn rejection while disposal is joining the pending handle', async () => {
  1589. const fake = new FakeSandbox()
  1590. fake.deferStart()
  1591. fake.backgroundError = new Error('start failed during disposal')
  1592. const { ctx, fiber } = await service(fake)
  1593. const subprocess = ctx.subprocess
  1594. const handle = subprocess.spawn(spec())
  1595. await vi.waitFor(() => { expect(fake.startOptions).toBeDefined() })
  1596. const disposing = fiber.dispose()
  1597. await flush()
  1598. expect(() => subprocess.spawn(spec())).toThrow('service is disposing')
  1599. fake.releaseStart()
  1600. await expect(disposing).resolves.toBeUndefined()
  1601. await expect(handle.done).rejects.toThrow('start failed during disposal')
  1602. })
  1603. it('validates synchronous spawn preconditions', async () => {
  1604. const { ctx } = await service()
  1605. expect(() => ctx.subprocess.spawn(spec({ argv: [] }))).toThrow(/non-empty program/)
  1606. expect(() => ctx.subprocess.spawn(spec({ signal: AbortSignal.abort('stop') }))).toThrow(/aborted before spawn/)
  1607. })
  1608. })