fix(engine): wait for a crashed engine server's exit before its connection closes

Merged
SA
8d ago
+131-11
  • spawnTransport handed the child's stdout straight to the connection (packages/core/src/engine/protocol/transport.ts).
  • When a server exits during a request, its stdout can end before Node delivers the exit and the rest of its stderr. The connection reads both for its message the moment it closes, so the request failed with only the peer closed the connection.
  • That made engine protocol over a child process > fails a request with the server stderr when the process dies mid-call flaky. It failed on Node 22 in CI on #1810 (job) with exactly that message.
  • Now the connection reads stdout through untilClosed, an async generator that ends once the child has closed, or 2 s after stdout ended. The cap covers a server that closes stdout and keeps running, or one whose own child holds its stderr.
  • A stdout error still reaches the connection: the generator rethrows it as the stream's error.
  • close() is unchanged: it still waits for exit, not close.
yield* stdout;
await Promise.race([closed, delay(EXIT_AFTER_STDOUT_MS, undefined, { ref: false })]);

Issue

None filed. Found as a CI flake on #1810.

Verified

Ran it locally: yes

Built CLI against a scratch project whose target is connectEngine with spawnTransport on the protocol tests' toy server, made to crash during the test:

Crashmain (25bde7a7)this branch
Closes stdout, then 300 ms later writes stderr and exits 7closed the connection: the peer closed the connectionclosed the connection: the peer closed the connection; exited with code 7; stderr:
Writes stderr, then SIGKILLs itself...the peer closed the connection; stderr:...the peer closed the connection; killed by SIGKILL; stderr:
  • Cells are the CLI's Cleanup summary line, which ends at stderr: on both builds and hides the stderr text that follows. That is a separate display issue, not changed here. The unit tests check that the stderr text is in the message.
  • New tests in tests/unit/engine-protocol.test.ts, each failing on main's transport:
    • stdout closes before the exit
    • the server's child writes stderr after the server exited
    • the server closes stdout and stays up (fails between 1.9 s and 3 s)
    • the server is stopped by a signal
  • Mutations each fail a test: waiting for exit instead of close, the cap alone, no cap, a 7 s cap, ending at once, a 1 s or 3.5 s cap, and the signal status dropped.
  • The child-process tests pass 10 of 10 runs under 32 busy loops pinned to one CPU.
  • pnpm check passes. e2e unit tests: 3822 passed, 2 skipped.

🤖 Generated with Claude Code