refactor(coding-agent): await the spawn event instead of a startup sleep - #1854
Open
snimu wants to merge 13 commits into
Open
refactor(coding-agent): await the spawn event instead of a startup sleep#1854snimu wants to merge 13 commits into
snimu wants to merge 13 commits into
Conversation
…es cannot hang shutdown stop() waited for the child 'close' event with no fallback: a grandchild inheriting the stdio pipes (or a child that never dies) kept 'close' from firing, hanging stop() forever and leaving this.process set so a later start() threw 'Client already started'. Wait on 'exit' instead, resolve after the SIGKILL escalation as a fallback, and clear this.process explicitly (guarded against a restarted child).
# Conflicts: # packages/coding-agent/test/rpc-client-timeout.test.ts
…hild Late error/stdout-close events from a replaced child could set transportError on a freshly restarted client, rejecting its pending work. Guard every child handler with this.process === child, fail pending operations on 'exit' so a grandchild holding stdout cannot leave requests and idle waiters hanging, and finalize on 'close' as well so a failed spawn (which emits 'error'/'close' but never 'exit') clears this.process and start() can be retried.
… start() can be retried once(child, 'spawn') rejects on the child 'error' event, which for a failed spawn fires before the 'close' event where the finalizer clears this.process; the rejection therefore won the race and a retried start() threw 'Client already started'. Clear this.process in the rejection path: an error before 'spawn' can only mean the child never came up, so no live process is abandoned, and the finalizer's process-identity guard makes the later 'close' a no-op.
…n child exit Node may emit 'exit' while a complete response is still buffered in the stdout pipe (docs guarantee only that 'close' runs after the streams drain), so the exit finalizer could reject a request whose answer was already in flight. Defer failPendingOperations until stdout closes, with a 1s unref'd fallback so pipes held open by a grandchild still fail promptly, and skip the deferred failure if the client was restarted.
…start If start() ran inside a dead child's stdout-drain window, the deferred failure skipped (anti-poisoning guard) and the old generation's pending requests and idle waiters hung forever; the old JSONL reader also stayed attached, so late output from the dead child's pipe could resolve the new session's waiters. start() now detaches the previous reader and fails any leftover pending operations synchronously before spawning.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 8c392f1. Configure here.
The ghost grandchild now also writes a sentinel to the inherited stderr, which still feeds the client's shared stderr accumulator after restart. The test awaits the sentinel before asserting the new session's waiter is untouched, so the still-pending assertion cannot pass vacuously if the stdin-EOF trigger ever stops firing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

What was wrong
RpcClient.start()guessed process readiness by sleeping 100ms and then sampling the exit code — a timer standing in for a real signal. Children that died at 150ms were "ready"; healthy children paid 100ms for nothing (audit: timeouts as synchronization, timeouts.md finding 6).The fix
The sleep and exit-code sampling are deleted.
start()awaits the child's OSspawnevent (node:events.once) — the readiness signal the child actually emits. Pre-spawn errors surface through the recorded transport error with the existing message format; fast post-spawn exits surface on first use via the stdout-close handler with captured stderr — strictly more honest than the old sample. +14/−6.How it's verified
Reviewer traced both failure orderings (error-before-spawn, exit-after-spawn), confirmed
events.oncecleans its listeners on both paths with no missed-event race, and validated the new fake-timer test is meaningful (old code hangs under fake timers, new code resolves). Focused RPC suites green; full CI-style failures match the stack base exactly (dist-build extras pass after building). Two-model implement/review loop, approved first pass.Stacked on #1743 (test the whole stack at the leaf; merge base-first).
Note: intentionally no Linear ticket for this cleanup stack, so that check stays red.
Note
Medium Risk
Public RpcClient API behavior changes (no default timeouts, removed export, prompt errors propagate), though failures are more explicit; lifecycle fixes reduce hang risk on restart/stop.
Overview
RpcClient no longer applies fixed client-side timeouts on
send,refine,waitForIdle,collectEvents, orpromptAndWait— work completes on a real response oragent_end, or fails when the transport dies. Callers can still pass an explicit timeout to the wait helpers.REFINE_REQUEST_TIMEOUT_MSis removed.Startup awaits the child
spawnevent instead of a 100ms sleep and immediate exit-code check.Process lifecycle is generation-scoped: restart/stop/error/exit/stdout-close call
failPendingOperationsso pending RPCs and event waiters reject with stderr context; late output from a replaced child cannot satisfy the new session.stop()fails in-flight work, uses SIGTERM with a 1s SIGKILL fallback, and can restart even when a grandchild keeps stdio pipes open.prompt()now surfaces server-side prompt failures via the response instead of returning after send only.Tests add a hanging-child fixture and
rpc-client-timeout.test.ts; the refine extended-timeout unit test is dropped.Reviewed by Cursor Bugbot for commit 2cccab2. Bugbot is set up for automated code reviews on this repo. Configure here.
Linear ticket: ENG-5662
(ticket linked above)
Note
Replace RPC client startup sleep with
spawnevent and remove blanket timeoutsRpcClient.start()now resolves when the child emitsspawninstead of after a fixed delay, and rejects cleanly on spawn errors so the client remains restartablesend(),refine(),waitForIdle(),collectEvents(), andpromptAndWait(); these now run indefinitely by default unless an explicit timeout is passedfailPendingOperations()which caches a terminaltransportErrorand rejects all pending requests and event waiters when the process errors, exits, or output closesprompt()now throws on unsuccessful responses viagetData<void>()instead of silently returningstop()tolerates grandchild-held stdio pipes, proactively rejects pending work, and SIGKILLs after a 1s fallbackREFINE_REQUEST_TIMEOUT_MS) must pass explicit timeouts or handle indefinite waitsMacroscope summarized 2cccab2.