boot-write-failure.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import { EventEmitter } from 'node:events'
  2. import { existsSync } from 'node:fs'
  3. import { dirname } from 'node:path'
  4. import { PassThrough } from 'node:stream'
  5. import { afterEach, describe, expect, it, vi } from 'vitest'
  6. import { Context } from 'cordis'
  7. /**
  8. * A synchronous `proto.write` throw on the fd-3 pipe is the one boot path a real
  9. * subprocess cannot be coerced into from a test: the pipe accepts queued bytes
  10. * until the kernel buffer fills, and a same-tick EPIPE needs fd 3 already closed
  11. * before the first write. `spawn` is mocked so fd 3 throws on the boot frame,
  12. * which is exactly the branch that regressed. The mock is confined to this file
  13. * so the real-subprocess suite in runtime.spec.ts is untouched.
  14. */
  15. const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }))
  16. vi.mock('node:child_process', async importOriginal => ({
  17. ...(await importOriginal<typeof import('node:child_process')>()),
  18. spawn: spawnMock,
  19. }))
  20. const { PythonCodeRuntime } = await import('../src/index.ts')
  21. /** A `child_process.ChildProcess` stand-in whose fd-3 pipe rejects every write. */
  22. function fakeChildWithThrowingFd3(): EventEmitter {
  23. const child = new EventEmitter() as EventEmitter & {
  24. pid?: number
  25. stdout: PassThrough
  26. stderr: PassThrough
  27. stdio: unknown[]
  28. }
  29. // Leave `pid` absent: `finish()` still runs its `clearTimeout(wallTimer)` /
  30. // `removeEventListener(onAbort)` prologue (the TDZ site) before short-
  31. // circuiting on `child.pid === undefined` to `settle` instead of waiting on a
  32. // `close` this fake never emits, so the run resolves promptly.
  33. child.stdout = new PassThrough()
  34. child.stderr = new PassThrough()
  35. // A duplex whose `write` throws synchronously, standing in for an fd-3 pipe
  36. // that fails the moment the boot frame is issued.
  37. const proto = new PassThrough()
  38. proto.write = () => { throw Object.assign(new Error('EPIPE: broken pipe, write'), { code: 'EPIPE' }) }
  39. child.stdio = [new PassThrough(), child.stdout, child.stderr, proto]
  40. return child
  41. }
  42. afterEach(() => {
  43. spawnMock.mockReset()
  44. })
  45. /** A child that emits an async `error` (an ENOENT-style spawn failure). */
  46. function fakeChildWithAsyncSpawnError(): EventEmitter {
  47. const child = new EventEmitter() as EventEmitter & {
  48. pid?: number
  49. stdout: PassThrough
  50. stderr: PassThrough
  51. stdio: unknown[]
  52. }
  53. child.stdout = new PassThrough()
  54. child.stderr = new PassThrough()
  55. const proto = new PassThrough()
  56. child.stdio = [new PassThrough(), child.stdout, child.stderr, proto]
  57. // `spawn` reports an async failure via the child's `error` event; the run
  58. // settles on it as a worker-exit without waiting for `close`.
  59. setImmediate(() => {
  60. child.emit('error', Object.assign(new Error('ENOENT: no such file or directory, spawn python3'), { code: 'ENOENT' }))
  61. })
  62. return child
  63. }
  64. /** A child whose fd-3 pipe accepts the boot write, then rejects the run write. */
  65. function fakeChildWithAckThenThrowingFd3(): EventEmitter {
  66. const child = new EventEmitter() as EventEmitter & {
  67. pid?: number
  68. stdout: PassThrough
  69. stderr: PassThrough
  70. stdio: unknown[]
  71. }
  72. child.stdout = new PassThrough()
  73. child.stderr = new PassThrough()
  74. const proto = new PassThrough()
  75. let writes = 0
  76. proto.write = () => {
  77. writes += 1
  78. if (writes === 1) return true // The boot frame goes out.
  79. throw Object.assign(new Error('EPIPE: broken pipe, write'), { code: 'EPIPE' })
  80. }
  81. child.stdio = [new PassThrough(), child.stdout, child.stderr, proto]
  82. // Emit the boot-ack after the boot write, so the run-frame write fires and
  83. // hits the throwing pipe.
  84. setImmediate(() => proto.emit('data', Buffer.from('{"type":"boot-ack"}\n')))
  85. return child
  86. }
  87. /**
  88. * A child whose fd-3 pipe backpressures every write and is then destroyed
  89. * while the host waits for `drain`. The reply-drain loop must settle on the
  90. * pipe's `close` (or destroyed state) rather than hanging forever waiting for
  91. * a `drain` that can never arrive. Returns the pipe as well so the test can
  92. * assert the drain wait left no listener behind.
  93. */
  94. function fakeChildBackpressuredThenDestroyed(): { child: EventEmitter; proto: PassThrough } {
  95. const child = new EventEmitter() as EventEmitter & {
  96. pid?: number
  97. stdout: PassThrough
  98. stderr: PassThrough
  99. stdio: unknown[]
  100. }
  101. child.stdout = new PassThrough()
  102. child.stderr = new PassThrough()
  103. const proto = new PassThrough()
  104. // Every write reports backpressure (never a `drain` event): the only way the
  105. // reply drain can proceed is the pipe being destroyed under it.
  106. proto.write = () => false
  107. child.stdio = [new PassThrough(), child.stdout, child.stderr, proto]
  108. // Boot-ack → run frame → two binding calls whose replies backpressure, then
  109. // destroy the pipe while the host still waits for `drain`: the drain loop
  110. // resumes with a queued reply left and must break on the destroyed pipe.
  111. setImmediate(() => {
  112. proto.emit('data', Buffer.from('{"type":"boot-ack"}\n'))
  113. setImmediate(() => {
  114. proto.emit('data', Buffer.from('{"type":"call","id":0,"global":"tools","name":"f","args":[]}\n'))
  115. proto.emit('data', Buffer.from('{"type":"call","id":1,"global":"tools","name":"f","args":[]}\n'))
  116. setImmediate(() => proto.destroy())
  117. })
  118. })
  119. return { child, proto }
  120. }
  121. describe('PythonCodeRuntime — boot-write failure', () => {
  122. it('resolves a worker-exit when the fd-3 boot write throws (no TDZ ReferenceError)', async () => {
  123. // Before the fix, the boot-write block ran BEFORE `wallTimer`, `onAbort`,
  124. // and `live` were initialized, so its `finish()` (which clears `wallTimer`,
  125. // removes `onAbort`, and — through `settle` — deletes `live`) hit the
  126. // temporal dead zone and threw a ReferenceError. That escaped the Promise
  127. // executor and REJECTED run() instead of resolving the worker-exit the catch
  128. // constructs. This test would see that rejection; the fix makes it resolve.
  129. spawnMock.mockImplementation(() => fakeChildWithThrowingFd3())
  130. const ctx = new Context()
  131. const fiber = await ctx.plugin(PythonCodeRuntime)
  132. const runtime = ctx.codeRuntime as InstanceType<typeof PythonCodeRuntime>
  133. const result = await runtime.run({ program: 'return 1', bindings: [] })
  134. expect(result.error?.kind).toBe('worker-exit')
  135. expect(result.error?.message).toContain('failed to boot python subprocess')
  136. await fiber.dispose()
  137. })
  138. it('resolves a worker-exit and removes the staging dir when spawn throws synchronously', async () => {
  139. // `spawn` can throw same-tick — EMFILE on a descriptor-exhausted host, or a
  140. // libuv-level failure — before the Promise executor and its settlement path
  141. // exist. Left uncaught it rejected run() (the seam permits rejection only for
  142. // misuse) and stranded the staging directory materializePyScripts had just
  143. // written, which only settle() removes. The fix catches it, unlinks the
  144. // directory, and resolves the same `worker-exit` class as an async ENOENT.
  145. //
  146. // Capture THIS run's exact staging dir from the argv the mocked spawn
  147. // received (`['-I', <dir>/bootstrap.py]`) and assert only that path is gone.
  148. // A tmpdir scan — even a set difference against a pre-run snapshot — would
  149. // flake under vitest's forks pool: a sibling worker creating its own
  150. // `dsh-code-runtime-python-*` dir in the window reads as a leak here. Keying
  151. // off our own argv is fully isolated from concurrent staging.
  152. let stagedBootstrap: string | undefined
  153. spawnMock.mockImplementation((_bin: string, args: string[]) => {
  154. stagedBootstrap = args[args.length - 1]
  155. throw Object.assign(new Error('EMFILE: too many open files'), { code: 'EMFILE' })
  156. })
  157. const ctx = new Context()
  158. const fiber = await ctx.plugin(PythonCodeRuntime)
  159. const runtime = ctx.codeRuntime as InstanceType<typeof PythonCodeRuntime>
  160. const result = await runtime.run({ program: 'return 1', bindings: [] })
  161. expect(result.error?.kind).toBe('worker-exit')
  162. expect(result.error?.message).toContain('python spawn error')
  163. expect(stagedBootstrap).toBeDefined()
  164. expect(existsSync(dirname(stagedBootstrap as string))).toBe(false)
  165. await fiber.dispose()
  166. })
  167. it('resolves a worker-exit when the run write after boot-ack throws', async () => {
  168. // The run frame goes out from the boot-ack handler; a pipe that accepts
  169. // the boot frame but rejects the run write must settle the run as a
  170. // worker-exit rather than reject run() or leave it hanging.
  171. spawnMock.mockImplementation(() => fakeChildWithAckThenThrowingFd3())
  172. const ctx = new Context()
  173. const fiber = await ctx.plugin(PythonCodeRuntime)
  174. const runtime = ctx.codeRuntime as InstanceType<typeof PythonCodeRuntime>
  175. const result = await runtime.run({ program: 'return 1', bindings: [] })
  176. expect(result.error?.kind).toBe('worker-exit')
  177. expect(result.error?.message).toContain('failed to boot python subprocess')
  178. await fiber.dispose()
  179. })
  180. it('resolves a worker-exit when spawn reports an async error', async () => {
  181. // A spawn that fails asynchronously (ENOENT for an interpreter removed
  182. // after load, or a libuv-level failure) surfaces through the child's
  183. // `error` event, not a synchronous throw. The run must settle as a
  184. // worker-exit from that event.
  185. spawnMock.mockImplementation(() => fakeChildWithAsyncSpawnError())
  186. const ctx = new Context()
  187. const fiber = await ctx.plugin(PythonCodeRuntime)
  188. const runtime = ctx.codeRuntime as InstanceType<typeof PythonCodeRuntime>
  189. const result = await runtime.run({ program: 'return 1', bindings: [] })
  190. expect(result.error?.kind).toBe('worker-exit')
  191. expect(result.error?.message).toContain('python spawn error')
  192. await fiber.dispose()
  193. })
  194. it('does not hang the reply drain when the pipe is destroyed mid-backpressure', async () => {
  195. // The reply drain waits for `drain` when fd 3's buffer is full. A pipe
  196. // destroyed under that wait never emits `drain` again; the drain must
  197. // settle on `close` instead, or `draining` stays true and the queued reply
  198. // (here a 4 MiB string) is pinned with the closure forever. The fake child
  199. // backpressures every write and destroys fd 3 right after the binding
  200. // call, so the host is mid-drain when the pipe dies. No `done` frame ever
  201. // arrives, so the run settles on the wall clock — the drain wait must have
  202. // removed its listeners by then (a `once('drain')` wait would leave one
  203. // attached to the destroyed pipe forever).
  204. let proto: PassThrough | undefined
  205. spawnMock.mockImplementation(() => {
  206. const fake = fakeChildBackpressuredThenDestroyed()
  207. proto = fake.proto
  208. return fake.child
  209. })
  210. const ctx = new Context()
  211. const fiber = await ctx.plugin(PythonCodeRuntime, { maxWallMs: 3000 })
  212. const runtime = ctx.codeRuntime as InstanceType<typeof PythonCodeRuntime>
  213. const result = await runtime.run({
  214. program: 'return 1',
  215. bindings: [{ global: 'tools', functions: { f: async () => 'x'.repeat(4 * 1024 * 1024) } }],
  216. })
  217. expect(result.error?.kind).toBe('timeout')
  218. // The drain wait settled on `close` and cleaned up after itself. The
  219. // discriminating listener is `drain`: a `once('drain')` wait would leave
  220. // its wrapper attached to the destroyed pipe forever (the event never
  221. // fires again), while the fixed wait removes it. (`error` is not asserted:
  222. // the runtime's own `silenceStreamError` occupies one slot.)
  223. expect(proto).toBeDefined()
  224. expect(proto?.listenerCount('drain')).toBe(0)
  225. expect(proto?.listenerCount('close')).toBe(0)
  226. await fiber.dispose()
  227. })
  228. })