boot-write-failure.spec.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. 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. //
  70. // Capture THIS run's exact staging dir from the argv the mocked spawn
  71. // received (`['-I', <dir>/bootstrap.py]`) and assert only that path is gone.
  72. // A tmpdir scan — even a set difference against a pre-run snapshot — would
  73. // flake under vitest's forks pool: a sibling worker creating its own
  74. // `dsh-code-runtime-python-*` dir in the window reads as a leak here. Keying
  75. // off our own argv is fully isolated from concurrent staging.
  76. let stagedBootstrap: string | undefined
  77. spawnMock.mockImplementation((_bin: string, args: string[]) => {
  78. stagedBootstrap = args[args.length - 1]
  79. throw Object.assign(new Error('EMFILE: too many open files'), { code: 'EMFILE' })
  80. })
  81. const ctx = new Context()
  82. const fiber = await ctx.plugin(PythonCodeRuntime)
  83. const runtime = ctx.codeRuntime as InstanceType<typeof PythonCodeRuntime>
  84. const result = await runtime.run({ program: 'return 1', bindings: [] })
  85. expect(result.error?.kind).toBe('worker-exit')
  86. expect(result.error?.message).toContain('python spawn error')
  87. expect(stagedBootstrap).toBeDefined()
  88. expect(existsSync(dirname(stagedBootstrap as string))).toBe(false)
  89. await fiber.dispose()
  90. })
  91. })