Skip to content

hot: reset process.stdin/stdout/stderr listeners on reload - #30633

Closed
robobun wants to merge 18 commits into
mainfrom
farm/5f7289a3/hot-reload-stdin-listeners
Closed

robobun wants to merge 18 commits into
mainfrom
farm/5f7289a3/hot-reload-stdin-listeners

Conversation

@robobun

@robobun robobun commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #15027

Problem

  • Under bun --hot, node:readline on process.stdin handles every line twice after one reload, three times after two (the hheelllloo echo in the issue).
  • GlobalObject::reload() (src/jsc/bindings/ZigGlobalObject.cpp) only clears the module registries. process and 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.
  • In a terminal, removing listeners is not enough. node:readline is not re-evaluated on reload, so emitKeypressEvents() still sees its marker on process.stdin, does nothing, and readline goes silent.

Fix

  • Each stdio stream built by ProcessObjectInternals.ts gets a private @resetStdioForHotReload method. reload() calls Bun::resetStdioForHotReload() (BunProcess.cpp), which runs it on each stream that already exists (getDirect(), so an untouched stream is not built only to be reset).
  • stdout and stderr remove their listeners. stdin also releases the native reader, leaves raw mode, deletes readline's marker, unpipes, clears the flowing state, and re-adds its own four internal handlers.
  • A stream whose reset throws does not stop the others. A termination stops the loop, and reload() returns through RETURN_IF_EXCEPTION.
  • Verified: test/cli/hot/hot-stdin.test.ts (pipe mode, and terminal mode through Bun.Terminal). On main both fail: LISTENERS 2 2 2 3 0, and READY 2 data=1 keypress=2 resize=2. Also hot.test.ts under BUN_JSC_validateExceptionChecks=1 and process-stdin.test.ts.

Background

  • --hot reload: VirtualMachine.rs calls reload() on the main global and evaluates the entry point again in the same JSGlobalObject. The reset lives in reload(), next to the cron detach hook, not in clearModuleRegistry(), which --isolate and worker teardown also call.
  • Internal modules are evaluated once per process, so state node:readline keeps on a stream, such as its Symbol("keypress-decoder"), survives a reload.
  • Readable.removeListener('data') clears the data-listening flag. removeAllListeners() does not, and would resume() 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's stdin.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. The keypress-decoder marker is deleted so the next createInterface() installs the keypress bridge again. The escape-decoder generator 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 clears state.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, the resume/pause/end/close handlers are re-added, and _readableState.reading is 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 --hot process 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=0 after each reload: readline's error and end listeners plus the stream's own internal end handler, which the reset re-registers. Terminal mode checks data=1 keypress=1 resize=1 on every load and exactly one ECHO world from a post-reload load; a follow-up line is typed and its echo awaited so a duplicate world echo 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 of reload(); git placed the call in the shared helper and it was moved back into reload(), leaving the helper identical to main. Earlier rebases (88a6398, 3e08719, 4324120) had mechanical conflicts only: neighbouring declarations in BunProcess.cpp/.h, the cellLock() guard, and main's internal 'end' listener on stdin, which moved the expected count to end=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

@robobun

robobun commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 8:30 PM PT - Aug 20th, 2026

✅ @robobun, your commit f1897dcedec24853cbbbc5b6262212e59317a15c passed in Build #102120! 🎉


🧪   To try this PR locally:

bunx bun-pr 30633

That installs a local version of the PR into your bun-30633 executable, so you can run:

bun-30633 --bun

@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds 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.

Changes

Stdio listener reset on hot reload

Layer / File(s) Summary
Builtin identifier and C++ declaration
src/js/builtins/BunBuiltinNames.h, src/jsc/bindings/BunProcess.h
Registers builtin private identifier resetStdioForHotReload and declares the C++ bridge function resetStdioForHotReload.
Stdio stream reset implementations
src/js/builtins/ProcessObjectInternals.ts
Adds $resetStdioForHotReload() to write streams and refactors stdin handling to use named handlers, remove accumulated listeners, and reset _readableState.reading.
C++ reset orchestrator
src/jsc/bindings/BunProcess.cpp
Implements Bun::resetStdioForHotReload that calls each stdio stream's reset callback via getDirect() and clears exceptions.
Hot reload integration
src/jsc/bindings/ZigGlobalObject.cpp
Invokes Bun::resetStdioForHotReload(this) early in GlobalObject::reload() before clearing module loader and require map.
Regression test for listener cleanup
test/cli/hot/hot-stdin.test.ts
Adds an end-to-end test running a readline fixture under --hot, triggering reloads and asserting listener counts and single-echo behavior to prevent regression.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR fully addresses issue #15027 by resetting stdio listeners on hot reload. Changes to stdin/stdout/stderr stream handling in ProcessObjectInternals.ts and the resetStdioForHotReload function in BunProcess.cpp prevent listener accumulation, eliminating the double-echo problem described in the issue.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing listener accumulation across hot reloads. Modifications span builtin names, stream handling, process bindings, hot reload entry point, and a targeted test—all necessary to implement and validate the stdio reset mechanism.
Title check ✅ Passed The title clearly and concisely describes the main change: resetting process stdio listeners during hot reload.
Description check ✅ Passed The description explains the problem, fix, implementation details, background, and verification, although it does not use the template headings exactly.

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between b9c757b and 434372f.

📒 Files selected for processing (7)
  • src/js/builtins/BunBuiltinNames.h
  • src/js/builtins/ProcessObjectInternals.ts
  • src/jsc/bindings/BunProcess.cpp
  • src/jsc/bindings/BunProcess.h
  • src/jsc/bindings/ZigGlobalObject.cpp
  • test/cli/hot/hot-stdin-readline-fixture.js
  • test/cli/hot/hot.test.ts

Comment thread test/cli/hot/hot.test.ts Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. Duplicate Output Issue After Repeated Saves with bun --hot #13511 - Duplicate output after repeated saves with bun --hot is caused by the same stdio listener accumulation this PR fixes

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #13511

🤖 Generated with Claude Code

Comment thread src/jsc/bindings/BunProcess.cpp Resolved
Comment thread test/cli/hot/hot-stdin.test.ts Resolved
@robobun

robobun commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

Ready 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 stdin.unref(), and a stale sentence in a test helper comment is gone. hot-stdin.test.ts and process-stdin.test.ts pass on it.

973be94 replaces the python PTY driver with Bun.Terminal (review nit about skipping when python is missing), so the terminal-mode test has no system dependency and hot-stdin-pty.py is gone. It still fails on main at READY 2 data=1 keypress=2 resize=2; with the fix it passed 10/10 alone and 12/12 under 4x concurrent load on the debug build. The previous build (102050) had one unrelated failure, test/cli/test/test-changed.test.ts aborting in WTF::Thread::create on alpine, reported separately.

This rebase

  • One conflict needed a decision: bun test --isolate: stop finished files from pinning their global via mocks and plugins #39818 split the registry clearing out of GlobalObject::reload() into clearModuleRegistry(), which the bun test --isolate global swap and worker forbidExecution() also call. Git placed the resetStdioForHotReload() call inside that shared helper; it now lives in reload() only, and clearModuleRegistry() is identical to main. Those other two callers tear a global down and must not run stream JS on it.
  • worker_threads: don't build fd stdio or reify all of process at worker startup #39536 (worker_threads stdio) needed no changes: workers get port-backed streams without the reset method, reload() only runs on the main global, and the C++ loop skips a stream without the method anyway.
  • Re-verified on the rebased tree: both test/cli/hot/hot-stdin.test.ts cases pass with the fix and fail with src/ at main (LISTENERS 2 2 2 3 0, wwoorrlldd); hot.test.ts and hot-stdin.test.ts pass under BUN_JSC_validateExceptionChecks=1; process-stdin.test.ts passes.

Previous CI

The previous head (667ee41, build 98234) passed every job that ran (177/177). Its only red was the darwin 14 aarch64 shards expiring in the queue behind a CI-wide backlog for that agent pool; no test failed there. Its predecessor passed both darwin 14 lanes on build 67314.

Fix summary

GlobalObject::reload() invokes a per-stream @resetStdioForHotReload on any already-created process.stdin/stdout/stderr. For stdin it releases the native reader, leaves raw mode, clears readline's keypress-decoder marker, unpipes, clears the flowing state, removes all listeners and re-adds the stream's own handlers; for stdout/stderr it removes listeners. Details are in the PR description.

Comment thread test/cli/hot/hot-stdin.test.ts Resolved
@robobun
robobun force-pushed the farm/5f7289a3/hot-reload-stdin-listeners branch from 7f5f61f to 9c9e1f1 Compare May 14, 2026 17:30
@robobun
robobun force-pushed the farm/5f7289a3/hot-reload-stdin-listeners branch from 9c9e1f1 to bc5513f Compare May 26, 2026 05:05
Comment thread test/cli/hot/hot-stdin.test.ts Resolved
Comment thread test/cli/hot/hot-stdin-pty.py Resolved
Comment thread test/cli/hot/hot-stdin-pty.py Resolved
Comment thread test/cli/hot/hot-stdin-pty.py Resolved
@robobun
robobun force-pushed the farm/5f7289a3/hot-reload-stdin-listeners branch from 4e96927 to d5bf791 Compare June 30, 2026 20:40
@robobun
robobun force-pushed the farm/5f7289a3/hot-reload-stdin-listeners branch from d5bf791 to 200b431 Compare August 15, 2026 14:37
Comment thread src/jsc/bindings/BunProcess.cpp Resolved
Comment thread src/jsc/bindings/BunProcess.cpp Resolved
Comment thread src/jsc/bindings/ZigGlobalObject.cpp Resolved
Comment thread src/jsc/bindings/ZigGlobalObject.cpp Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 in resetStdioForHotReload — returns false only on termination, so normal exceptions are swallowed per-stream and termination propagates; RETURN_IF_EXCEPTION in reload() satisfies the exception-scope validator.
  • The end=2 baseline update — matches the new internal onStreamEnd handler, 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.

robobun added 16 commits August 21, 2026 01:31
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.
@robobun
robobun force-pushed the farm/5f7289a3/hot-reload-stdin-listeners branch from 667ee41 to 826ee19 Compare August 21, 2026 01:41
Comment thread test/cli/hot/hot-stdin.test.ts Resolved
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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • resetStdioForHotReload in BunProcess.cpp — getDirect avoids reifying untouched streams, tryClearException lets one stream's failure skip to the next while a termination stops the loop.
  • The stdin reset step ordering against Readable's removeListener/removeAllListeners semantics and emitKeypressEvents' 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.Terminal and 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, and forceUnref not being reset (zero impact under --hot).
  • The stdout/stderr reset is a bare removeAllListeners(); getStdioWriteStream attaches no listeners of its own to the stream (the SIGWINCH handler is on process, 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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 in reload() uses RETURN_IF_EXCEPTION.
  • The stdin $resetStdioForHotReload sequence — per-listener removeListener('data') before removeAllListeners() so kDataListening clears; unpipe(); raw-mode restore; only the keypress-decoder symbol deleted (escape-decoder kept for the pending ESC timer); internal resume/pause/end/close handlers re-added; forceUnref cleared.
  • 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.

@robobun

robobun commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

A note on order with #48174.

#48174 makes process.stdin.destroy() final in every case. On main it is final only when destroy() runs in a later turn than the first touch of stdin. A destroy() in that first turn is undone by the next resume().

So a load that destroys stdin leaves it dead for the next load: on main after a destroy() in a later turn, and after #48174 in both cases. The stdin reset of this PR is the place to revive it. One line is enough:

if (stream.destroyed && !stream_reachedEof) stream._undestroy();

The case: load 1 adds a 'data' listener and calls process.stdin.destroy() after 50 ms. Load 2 adds a 'data' listener and calls resume(). Release builds of main and of #48174 both print nothing for the input that comes in load 2. I did not build the line above.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@robobun robobun closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

--hot mode caused double echo in console

1 participant