Repository navigation
Conversation
|
Updated 8:30 PM PT - Aug 20th, 2026
✅ @robobun, your commit f1897dcedec24853cbbbc5b6262212e59317a15c passed in 🧪 To try this PR locally: bunx bun-pr 30633That installs a local version of the PR into your bun-30633 --bun |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds a builtin reset identifier and stream helpers, implements a C++ orchestrator invoked during GlobalObject::reload(), and adds a regression test to ensure process stdin/stdout/stderr listeners do not accumulate across hot reloads. ChangesStdio listener reset on hot reload
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/cli/hot/hot.test.ts`:
- Around line 754-773: The fire-and-forget async IIFEs that iterate
runner.stdout and runner.stderr can raise unhandled rejections when
runner.kill() aborts the streams; wrap each invoked async IIFE (the ones reading
from runner.stdout and runner.stderr) with .catch(() => {}) so any stream-abort
errors are swallowed silently, e.g., the async () => { for await (const chunk of
runner.stdout) ... }() and the async () => { for await (const chunk of
runner.stderr) ... }() invocations should have .catch(() => {}) appended to
their returned promises to avoid unhandled rejections.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 5dac22a1-5f69-4ae3-b637-b956b95217d9
📒 Files selected for processing (7)
src/js/builtins/BunBuiltinNames.hsrc/js/builtins/ProcessObjectInternals.tssrc/jsc/bindings/BunProcess.cppsrc/jsc/bindings/BunProcess.hsrc/jsc/bindings/ZigGlobalObject.cpptest/cli/hot/hot-stdin-readline-fixture.jstest/cli/hot/hot.test.ts
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
StatusReady for review. Current head is f1897dc (rebased onto main @ 18bf288), CI is build 102120. All review threads are resolved. f1897dc picks up the two leftovers from the latest review pass: the stdin reset now also clears the flag left by a previous load's 973be94 replaces the python PTY driver with This rebase
Previous CIThe previous head (667ee41, build 98234) passed every job that ran (177/177). Its only red was the Fix summary
|
7f5f61f to
9c9e1f1
Compare
9c9e1f1 to
bc5513f
Compare
4e96927 to
d5bf791
Compare
d5bf791 to
200b431
Compare
There was a problem hiding this comment.
I reviewed this PR again after the rebase and comment-trimming pass — no bugs found. Because it introduces a new hot-reload/stdio coupling (private @resetStdioForHotReload on each stream, invoked from GlobalObject::reload()) with subtle interactions across readline internals, TTY raw mode, and Readable stream state, a human look at the overall approach would still be worthwhile.
What was reviewed:
- The new
tryClearException()loop inresetStdioForHotReload— returnsfalseonly on termination, so normal exceptions are swallowed per-stream and termination propagates;RETURN_IF_EXCEPTIONinreload()satisfies the exception-scope validator. - The
end=2baseline update — matches the new internalonStreamEndhandler, which the reset re-registers so the count stays fixed across reloads. - The remaining comment-cop flags on lines 343/351 — those are 2–3-line explanations of cross-module invariants (InternalModuleRegistry caching,
kDataListening), not workaround justifications; I don't think they need further trimming.
Extended reasoning...
Overview
This PR fixes #15027 by adding a private $resetStdioForHotReload builtin to each of process.stdin/stdout/stderr, invoked from GlobalObject::reload() before the module registry is cleared. For stdin the reset disowns the native reader, restores cooked TTY mode, deletes readline's keypress-decoder marker, unpipes, removes data listeners individually (to clear kDataListening), pauses, strips all listeners, and re-registers the four internal handlers. For stdout/stderr it just calls removeAllListeners(). Changes span ProcessObjectInternals.ts, BunProcess.{cpp,h}, ZigGlobalObject.cpp, BunBuiltinNames.h, plus a two-case test (pipe + PTY).
Since my last round on 2026-05-26 the branch was rebased and picked up two changes: (1) the pipe-mode test's expected end count moved from 1 to 2 to account for main's new internal auto-destroy end listener, and (2) the C++ side switched from CLEAR_IF_EXCEPTION + assertNoExceptionExceptTermination to a per-stream if (!scope.tryClearException()) return; with RETURN_IF_EXCEPTION in the caller — a strict improvement that lets termination stop the loop while normal exceptions on one stream don't block the others.
Security risks
None identified. The reset is only reachable from --hot reload on the main thread; it uses getDirect() on the process object so it never triggers user getters, and looks up the reset function via a private builtin name, so user code can't intercept or replace it. setRawMode(false) restoring cooked mode is a hardening step (keeps ^C alive), not an exposure.
Level of scrutiny
Medium-high. The change is not large in LOC but is dense in cross-cutting invariants: readline's module-local symbols surviving via InternalModuleRegistry, the Readable kDataListening/kFlowing state machine, TTY raw mode and ISIG, JSC exception-scope discipline, and --hot's partial-teardown semantics. Each of these produced a real bug during earlier review rounds (silent terminal after reload, escape-timer TypeError, PTY spin on macOS EOF, leaked --hot grandchild on test-runner timeout) — all now fixed and covered by the two tests. That history argues the mechanism deserves a maintainer's eye on whether @resetStdioForHotReload is the right layer for this cleanup versus, say, clearing more state in reload() itself.
Other factors
All ten prior inline threads from this reviewer are resolved with corresponding commits. No human reviewer has looked at the PR. The two unresolved comment-cop flags (github-actions) are heuristic style nags on comments that were already trimmed once in 667ee41; the surviving comments explain non-local invariants rather than justify workarounds, so I would not treat them as blocking. The tests are condition-driven (no arbitrary sleeps remain), skip on Windows for the PTY case, and reap the --hot grandchild on SIGTERM/SIGINT/SIGALRM.
In --hot mode the JSGlobalObject and its process.stdin/stdout/stderr streams survive module-registry reloads. User code (notably node:readline) that attached 'data'/'keypress'/'error'/'end' listeners on the previous evaluation remained attached, so after the entry point was re-run a second set of handlers stacked on the same stream. Every keystroke was then handled by both the old and new readline instances, producing doubled (then quadrupled, etc.) echo in the terminal. On reload, drop user-attached listeners from stdin/stdout/stderr and re-add the internal own()/disown() wiring so the stream is clean for the fresh evaluation. Fixes #15027.
hot.test.ts has a pre-existing timing-sensitive test that fails on debug builds; keep the stdin-listener coverage in a dedicated file so it can be run in isolation. Fixture is inlined via tempDir().
resetStdioForHotReload() declares a ThrowScope whose destructor simulates a throw on return; without an intervening check the next scope constructed by requireMap()->clear() trips validateExceptionChecks=1 on the asan lane.
removeAllListeners() leaves the Readable's kDataListening bit set and schedules updateReadableListening() on the next tick, which would call self.resume() → own() and undo the disown() in the reset. It also leaves kFlowing set, so a chunk pushed by an in-flight internalRead before the new load attaches its handler would be emitted to zero listeners instead of buffered. Remove 'data' listeners individually (clears kDataListening) and pause() (clears kFlowing) before removeAllListeners().
- unpipe() before removeAllListeners() so _readableState.pipes from the previous load isn't pinned across reloads. - The Windows file watcher can fire multiple events for a single writeFileSync, so one reload trigger may advance the load counter by more than one. Rework the test to assert the invariants (listener counts stay at 1; exactly one ECHO per input from a post-reset load) without pinning exact load numbers.
readline sets raw mode (ISIG cleared). Once the reset strips the keypress handler that translated ^C, Ctrl+C is dead if the new load doesn't re-enter raw mode itself. Restore cooked mode so the terminal behaves after a reload that stops using readline.
node:readline is cached in the InternalModuleRegistry and is not re-evaluated on --hot reload, so its module-local KEYPRESS_DECODER / ESCAPE_DECODER symbols keep pointing at properties left on process.stdin. emitKeypressEvents() early-returns when it sees them, so after the reset removed the data→keypress bridge it was never reinstalled and terminal-mode readline went silent after a reload. Delete those properties in the reset so the next createInterface() wires keypress events up again. Add a PTY-driven test covering the terminal path: asserts one data/keypress/resize listener on each load, exactly one echo of the pre-reload line, and exactly one echo of the post-reload line from a post-reload interface.
macOS/BSD report PTY EOF as an empty read instead of EIO; break out of the wait loop in that case so a failing run doesn't spin on the closed fd until the deadline.
The hand-rolled fork doesn't give the child a controlling TTY, so closing the PTY master won't SIGHUP it. Handle SIGTERM/SIGINT (test runner timeout, Ctrl+C) like SIGALRM and kill the child explicitly so a failing run doesn't leak a bun --hot process.
READY 2 is only printed after createInterface() has synchronously re-wired the data→keypress bridge, so waiting for it is sufficient; typed input is kernel-buffered regardless.
The emitKeypressEvents() idempotence guard checks only KEYPRESS_DECODER; ESCAPE_DECODER is overwritten unconditionally once the guard passes. Deleting the escape decoder was unnecessary and could turn a pending escape-sequence timer from the previous load into an uncaught TypeError if the next load doesn't re-enter terminal readline.
main now installs an auto-destroy 'end' handler on process.stdin, so the expected baseline is data=1 error=1 end=2 resize=0.
…sserting reload() now uses the ordinary RETURN_IF_EXCEPTION after the call, and the per-stream loop stops early on a termination exception. Trim the stdio reset comments down to the facts that are not visible from the code.
667ee41 to
826ee19
Compare
Replaces the python PTY driver, so the test no longer depends on a python interpreter being installed, and waits for the echo of a follow-up line instead of draining for a fixed second to catch a duplicated echo.
There was a problem hiding this comment.
I reviewed this PR and the latest revision found no bugs. The python-dependency concern from the last pass was addressed in 973be94 by rewriting the PTY test on Bun.Terminal, which is cleaner than a skipIf. Given the intricacy of the stdin reset ordering (readline's private symbol marker, kDataListening vs removeAllListeners, raw-mode restore) and that the Bun.Terminal test rewrite is fresh, a human look is still worthwhile.
What was reviewed:
resetStdioForHotReloadin BunProcess.cpp —getDirectavoids reifying untouched streams,tryClearExceptionlets one stream's failure skip to the next while a termination stops the loop.- The stdin reset step ordering against Readable's
removeListener/removeAllListenerssemantics andemitKeypressEvents' idempotence guard. - The rewritten terminal-mode test: filters PTY echo to READY/ECHO lines, races each wait against
proc.exited, and flushes with a follow-up line instead of a fixed drain.
Extended reasoning...
Overview
This PR fixes #15027 (bun --hot doubles readline input after each reload) by giving each stdio stream a private $resetStdioForHotReload method and calling it from GlobalObject::reload(). Touches: one builtin-name entry, ~45 lines in ProcessObjectInternals.ts (refactoring four inline handlers into named functions plus the new reset), a 35-line C++ helper in BunProcess.cpp with a one-line hook in ZigGlobalObject.cpp, and a new 268-line test file with pipe-mode and PTY-mode cases.
Security risks
None identified. The reset is only reachable from GlobalObject::reload(), which is only invoked by --hot on the main global. The private-name method is not user-callable. No new input parsing, no auth/crypto/permission surface.
Level of scrutiny
Moderate-to-high. The stdin reset interacts with several subtle invariants at once — Readable's kDataListening/kFlowing bits (only removeListener('data') clears the former; removeAllListeners() schedules an updateReadableListening that would otherwise resume()), readline's module-private keypress-decoder symbol (matched by description because requiring readline from the reset would load it into every --hot process), TTY raw mode (ISIG), and the native reader's own/disown lifecycle. Each of these was the subject of a prior review round on this PR, and the current ordering reflects those fixes. The C++ side is small and pattern-matching: getDirect to skip un-reified lazy properties, profiledCall under a ThrowScope, tryClearException to continue past a normal throw but stop on termination, and RETURN_IF_EXCEPTION at the call site.
Other factors
- The PR has been through roughly a dozen review rounds since May; every prior inline finding is marked resolved with a corresponding commit.
- The most recent commit (973be94) replaces the python PTY driver with
Bun.Terminaland reworks the duplicate-echo check to await a follow-up line rather than draining for a fixed interval — a substantive test rewrite whose CI run (#102089) is still in progress. - Two acknowledged non-blocking leftovers remain by author choice: the stale second sentence on
waitForLoadAfter's doc comment, andforceUnrefnot being reset (zero impact under--hot). - The stdout/stderr reset is a bare
removeAllListeners();getStdioWriteStreamattaches no listeners of its own to the stream (the SIGWINCH handler is onprocess, not the stream), so this only drops user listeners.
Not approving because the stdin reset is intricate enough — and the PTY test rewrite fresh enough — that a maintainer sign-off is warranted, but the automated review has nothing further to flag.
A previous load's process.stdin.unref() is per-load state like its listeners, so the next load starts out referenced again. Also drops a stale sentence from a test helper comment.
There was a problem hiding this comment.
I reviewed this PR and the bug-hunting pass found no issues this round; the earlier findings (kDataListening/kFlowing state, raw-mode restore, keypress-decoder marker, escape-decoder timer, python PTY driver → Bun.Terminal, forceUnref reset) have all been addressed. Because the fix touches process.stdin/stdout/stderr construction and GlobalObject::reload(), with an ordering-sensitive stdin reset that reaches into node:readline internals, a human look is still worthwhile before merge.
What was reviewed:
resetStdioForHotReload()in BunProcess.cpp —getDirect()avoids reifying untouched streams;tryClearException()lets one stream's failure not block the others while a termination stops the loop; caller inreload()usesRETURN_IF_EXCEPTION.- The stdin
$resetStdioForHotReloadsequence — per-listenerremoveListener('data')beforeremoveAllListeners()sokDataListeningclears;unpipe(); raw-mode restore; only thekeypress-decodersymbol deleted (escape-decoder kept for the pending ESC timer); internal resume/pause/end/close handlers re-added;forceUnrefcleared. - Tests — pipe-mode and
Bun.Terminal-driven terminal-mode; both wait on observable conditions (READY/ECHO lines) and wire early exit to fail the pending wait; no fixed sleeps; assertions avoid pinning exact load numbers for the Windows watcher's coalescing.
Extended reasoning...
Overview
The PR fixes #15027: under bun --hot, process.stdin/stdout/stderr outlive each reload, so node:readline listeners stack and every line is handled once per prior load. It adds a private @resetStdioForHotReload method to each stdio stream in ProcessObjectInternals.ts, a C++ Bun::resetStdioForHotReload() in BunProcess.cpp that invokes it on each already-reified stream, and a call from GlobalObject::reload() in ZigGlobalObject.cpp. A new builtin private name is registered in BunBuiltinNames.h. Two tests (pipe mode + Bun.Terminal-driven TTY mode) cover the regression.
Security risks
None identified. The reset method is stored under a private name (unreachable from user JS), runs only on the main global's --hot reload path, and only touches listener/state on the process's own stdio streams. No untrusted input parsing, auth, or crypto.
Level of scrutiny
Medium-high. The mechanical pieces (builtin name, header declaration, stdout/stderr removeAllListeners()) are simple, but the stdin reset is ordering-sensitive and encodes several non-obvious invariants about node:stream Readable internals (kDataListening only cleared by per-listener removeListener, updateReadableListening next-tick resume, state.pipes only cleared by unpipe()) and node:readline internals (the keypress-decoder idempotence marker vs. the escape-decoder that a pending ESC timer still dereferences). It also adds a call into JS from GlobalObject::reload(), a core path. These are the kinds of interactions where a maintainer familiar with the stdio/hot-reload machinery should sign off.
Other factors
The PR has been through ~16 iterations with every prior automated finding addressed (ThrowScope release, Windows CI failure, kFlowing/kDataListening, unpipe, raw-mode restore, keypress-decoder marker, escape-decoder timer safety, the python PTY driver replaced by Bun.Terminal, and the forceUnref reset added in f1897dc). The tests are condition-driven, wire process exit to reject pending waits, and were verified to fail on main. Given the touched files (ZigGlobalObject.cpp, BunProcess.cpp, stdio stream construction) and the subtlety of the reset ordering, I'm deferring rather than approving.
|
A note on order with #48174. #48174 makes So a load that destroys stdin leaves it dead for the next load: on main after a if (stream.destroyed && !stream_reachedEof) stream._undestroy();The case: load 1 adds a |
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-21. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Fixes #15027
Problem
bun --hot,node:readlineonprocess.stdinhandles every line twice after one reload, three times after two (thehheellllooecho in the issue).GlobalObject::reload()(src/jsc/bindings/ZigGlobalObject.cpp) only clears the module registries.processand its stdio streams are the same objects in every load, so each load stacks its'data','keypress'and'resize'listeners on the previous load's.node:readlineis not re-evaluated on reload, soemitKeypressEvents()still sees its marker onprocess.stdin, does nothing, and readline goes silent.Fix
ProcessObjectInternals.tsgets a private@resetStdioForHotReloadmethod.reload()callsBun::resetStdioForHotReload()(BunProcess.cpp), which runs it on each stream that already exists (getDirect(), so an untouched stream is not built only to be reset).stdoutandstderrremove their listeners.stdinalso releases the native reader, leaves raw mode, deletes readline's marker, unpipes, clears the flowing state, and re-adds its own four internal handlers.reload()returns throughRETURN_IF_EXCEPTION.test/cli/hot/hot-stdin.test.ts(pipe mode, and terminal mode throughBun.Terminal). On main both fail:LISTENERS 2 2 2 3 0, andREADY 2 data=1 keypress=2 resize=2. Alsohot.test.tsunderBUN_JSC_validateExceptionChecks=1andprocess-stdin.test.ts.Background
--hotreload:VirtualMachine.rscallsreload()on the main global and evaluates the entry point again in the sameJSGlobalObject. The reset lives inreload(), next to the cron detach hook, not inclearModuleRegistry(), which--isolateand worker teardown also call.node:readlinekeeps on a stream, such as itsSymbol("keypress-decoder"), survives a reload.Readable.removeListener('data')clears the data-listening flag.removeAllListeners()does not, and wouldresume()the stream next tick for a load that no longer exists. So the'data'listeners go first, one by one.tryClearException()clears normal exceptions and refuses terminations. That is how the loop knows to stop.Notes
stdin reset, in order.
disown()releases the native reader, and the flag set by a previous load'sstdin.unref()is cleared so the next load starts out referenced, as in a fresh process.setRawMode(false)runs if the old load entered raw mode: raw mode turns off ISIG, and readline's keypress handler was what turned Ctrl+C into SIGINT, so without this Ctrl+C stops working until the new load happens to enter raw mode too. Thekeypress-decodermarker is deleted so the nextcreateInterface()installs the keypress bridge again. Theescape-decodergenerator stays:emitKeypressEvents()replaces it once the marker is gone, and a pending escape timeout from the old load still calls into it.unpipe()is the only call that clearsstate.pipes. Then the'data'listeners are removed one by one,pause()clears the flowing flag so an in-flight chunk is buffered for the next load instead of emitted to nobody,removeAllListeners()removes the rest, theresume/pause/end/closehandlers are re-added, and_readableState.readingis cleared exactly as the existing pause handler does.Why the marker is found by description. The symbol is private to
internal/readline/emitKeypressEvents. Requiring that module from the stdin reset would load readline into every--hotprocess on its first reload.Workers.
reload()only runs on the main global. worker_threads workers get port-backed streams (#39536) that have no reset method; the C++ loop skips a stream without one.Test expectations. Pipe mode checks
data=1 error=1 end=2 resize=0after each reload: readline'serrorandendlisteners plus the stream's own internalendhandler, which the reset re-registers. Terminal mode checksdata=1 keypress=1 resize=1on every load and exactly oneECHO worldfrom a post-reload load; a follow-up line is typed and its echo awaited so a duplicateworldecho would have arrived first. The expectations avoid exact load numbers because the Windows watcher can deliver one write as two reload events.Rebase history. Onto 18bf288: #39818 split
clearModuleRegistry()out ofreload(); git placed the call in the shared helper and it was moved back intoreload(), leaving the helper identical to main. Earlier rebases (88a6398, 3e08719, 4324120) had mechanical conflicts only: neighbouring declarations inBunProcess.cpp/.h, thecellLock()guard, and main's internal'end'listener on stdin, which moved the expected count toend=2. The fail-before and pass-after runs above were repeated after each rebase.no test proof · iteration 16 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/cli/hot/hot-stdin.test.ts