1
0

boot-write-failure.spec.ts 4.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { EventEmitter } from 'node:events'
  2. import { readdirSync } from 'node:fs'
  3. import { PassThrough } from 'node:stream'
  4. import { tmpdir } from 'node:os'
  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. describe('PythonCodeRuntime — boot-write failure', () => {
  46. it('resolves a worker-exit when the fd-3 boot write throws (no TDZ ReferenceError)', async () => {
  47. // Before the fix, the boot-write block ran BEFORE `wallTimer`, `onAbort`,
  48. // and `live` were initialized, so its `finish()` (which clears `wallTimer`,
  49. // removes `onAbort`, and — through `settle` — deletes `live`) hit the
  50. // temporal dead zone and threw a ReferenceError. That escaped the Promise
  51. // executor and REJECTED run() instead of resolving the worker-exit the catch
  52. // constructs. This test would see that rejection; the fix makes it resolve.
  53. spawnMock.mockImplementation(() => fakeChildWithThrowingFd3())
  54. const ctx = new Context()
  55. const fiber = await ctx.plugin(PythonCodeRuntime)
  56. const runtime = ctx.codeRuntime as InstanceType<typeof PythonCodeRuntime>
  57. const result = await runtime.run({ program: 'return 1', bindings: [] })
  58. expect(result.error?.kind).toBe('worker-exit')
  59. expect(result.error?.message).toContain('failed to boot python subprocess')
  60. await fiber.dispose()
  61. })
  62. it('resolves a worker-exit and removes the staging dir when spawn throws synchronously', async () => {
  63. // `spawn` can throw same-tick — EMFILE on a descriptor-exhausted host, or a
  64. // libuv-level failure — before the Promise executor and its settlement path
  65. // exist. Left uncaught it rejected run() (the seam permits rejection only for
  66. // misuse) and stranded the staging directory materializePyScripts had just
  67. // written, which only settle() removes. The fix catches it, unlinks the
  68. // directory, and resolves the same `worker-exit` class as an async ENOENT.
  69. const before = readdirSync(tmpdir()).filter(name => name.startsWith('dsh-code-runtime-python-'))
  70. spawnMock.mockImplementation(() => { throw Object.assign(new Error('EMFILE: too many open files'), { code: 'EMFILE' }) })
  71. const ctx = new Context()
  72. const fiber = await ctx.plugin(PythonCodeRuntime)
  73. const runtime = ctx.codeRuntime as InstanceType<typeof PythonCodeRuntime>
  74. const result = await runtime.run({ program: 'return 1', bindings: [] })
  75. expect(result.error?.kind).toBe('worker-exit')
  76. expect(result.error?.message).toContain('python spawn error')
  77. const after = readdirSync(tmpdir()).filter(name => name.startsWith('dsh-code-runtime-python-'))
  78. expect(after).toEqual(before)
  79. await fiber.dispose()
  80. })
  81. })