Repository navigation
domain: implement node:domain on AsyncLocalStorage and port the upstream domain suite (+40 upstream tests) - #31828
cirospaciari wants to merge 96 commits into
Conversation
|
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:
WalkthroughThis pull request adds Node-compatible domains with async context propagation, EventEmitter integration, uncaught-exception routing, and abort-on-uncaught-exception support. It also updates exception-origin plumbing and adds domain and subprocess regression tests. ChangesDomain runtime and EventEmitter integration
Uncaught-exception handling
Possibly related PRs
Pre-merge checks:
|
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
d620847 to
e190cb5
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/js/node/process/process.test.js (1)
817-825: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick winAssert stderr before exitCode for better test failure diagnostics.
The current assertion order makes test failures less informative. If the exit code is wrong, you won't see what stderr actually contained. As per coding guidelines, subprocess tests should assert output before exit code.
♻️ Recommended fix
it("aborts when the uncaughtExceptionCaptureCallback throws", async () => { - const proc = Bun.spawn([bunExe(), join(import.meta.dir, "process-uncaughtExceptionCaptureCallbackAbort.js")], { + await using proc = Bun.spawn([bunExe(), join(import.meta.dir, "process-uncaughtExceptionCaptureCallbackAbort.js")], { stderr: "pipe", }); + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + expect(stderr).toContain("bar"); // An exception thrown from the capture callback exits with code 7 like // node (internal exception handler run-time failure). - expect(await proc.exited).toBe(7); - expect(await proc.stderr.text()).toContain("bar"); + expect(exitCode).toBe(7); });Based on learnings: applies to **/*.test.{ts,tsx}: assert stdout/stderr BEFORE exitCode; subprocess tests must drain pipes concurrently with
Promise.all.🤖 Prompt for 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. In `@test/js/node/process/process.test.js` around lines 817 - 825, The test currently checks proc.exited before reading proc.stderr, which hides stderr when the exit code assertion fails; change the assertions to drain pipes concurrently and assert output first by awaiting both with Promise.all (e.g., await Promise.all([proc.stderr.text(), proc.exited])) and then assert that the stderr string contains "bar" before asserting the exit code equals 7; update the test that uses Bun.spawn and variables proc, proc.stderr.text(), and proc.exited to use this pattern so stdout/stderr are read concurrently and checked prior to exit code assertion.
🤖 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 `@src/js/node/async_hooks.ts`:
- Line 283: Replace the explicit null and undefined check for the variable
`domain` with a combined loose equality check: locate the conditional `if
(domain !== null && domain !== undefined)` in src/js/node/async_hooks.ts and
change it to use `!= null` so it succinctly checks for both null and undefined
(keep the rest of the conditional block unchanged and ensure no other logic is
affected).
In `@src/js/node/domain.ts`:
- Around line 434-436: The code currently treats any falsy second argument as
missing when constructing the error payload (const er = args.length > 1 &&
args[1] ? args[1] : $ERR_UNHANDLED_ERROR()), which drops valid falsy values like
0/false/""/null/undefined; change the condition to only consider the absence of
a second argument (e.g. const er = args.length > 1 ? args[1] :
$ERR_UNHANDLED_ERROR()) so emit("error", <falsy>) is preserved; update the
assignment to variable er in src/js/node/domain.ts (the
EventEmitter.prototype.emit/error handling block) accordingly to preserve
provided values.
In `@src/jsc/bindings/BunProcess.cpp`:
- Around line 1252-1256: In the fatal branches inside
Bun__handleUncaughtException, after calling Bun__Process__exit(...) you must
return immediately so worker threads don't continue execution; add an immediate
return statement right after the Bun__Process__exit(lexicalGlobalObject, 7) call
in the branch following Bun__logUnhandledException and
Bun__Node__AbortOnUncaughtException, and do the same for the other identical
code path later (the branch around the second Bun__Process__exit call), so
neither path can fall through in worker contexts.
---
Outside diff comments:
In `@test/js/node/process/process.test.js`:
- Around line 817-825: The test currently checks proc.exited before reading
proc.stderr, which hides stderr when the exit code assertion fails; change the
assertions to drain pipes concurrently and assert output first by awaiting both
with Promise.all (e.g., await Promise.all([proc.stderr.text(), proc.exited]))
and then assert that the stderr string contains "bar" before asserting the exit
code equals 7; update the test that uses Bun.spawn and variables proc,
proc.stderr.text(), and proc.exited to use this pattern so stdout/stderr are
read concurrently and checked prior to exit code assertion.
🪄 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: c79a864b-3171-4931-903d-6fb8f19d82d8
📒 Files selected for processing (51)
src/js/node/async_hooks.tssrc/js/node/domain.tssrc/js/node/events.tssrc/jsc/VirtualMachine.rssrc/jsc/bindings/BunProcess.cppsrc/jsc/bindings/BunProcess.hsrc/jsc/bindings/ZigGlobalObject.cppsrc/runtime/cli/Arguments.rstest/js/node/process/process.test.jstest/js/node/test/parallel/test-domain-abort-on-uncaught.jstest/js/node/test/parallel/test-domain-add-remove.jstest/js/node/test/parallel/test-domain-async-id-map-leak.jstest/js/node/test/parallel/test-domain-bind-timeout.jstest/js/node/test/parallel/test-domain-ee-implicit.jstest/js/node/test/parallel/test-domain-ee.jstest/js/node/test/parallel/test-domain-emit-error-handler-stack.jstest/js/node/test/parallel/test-domain-enter-exit.jstest/js/node/test/parallel/test-domain-error-types.jstest/js/node/test/parallel/test-domain-from-timer.jstest/js/node/test/parallel/test-domain-fs-enoent-stream.jstest/js/node/test/parallel/test-domain-http-server.jstest/js/node/test/parallel/test-domain-intercept.jstest/js/node/test/parallel/test-domain-load-after-set-uncaught-exception-capture.jstest/js/node/test/parallel/test-domain-multiple-errors.jstest/js/node/test/parallel/test-domain-nested-throw.jstest/js/node/test/parallel/test-domain-nested.jstest/js/node/test/parallel/test-domain-nexttick.jstest/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-0.jstest/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.jstest/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.jstest/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.jstest/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.jstest/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.jstest/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.jstest/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.jstest/js/node/test/parallel/test-domain-promise.jstest/js/node/test/parallel/test-domain-run.jstest/js/node/test/parallel/test-domain-safe-exit.jstest/js/node/test/parallel/test-domain-set-uncaught-exception-capture-after-load.jstest/js/node/test/parallel/test-domain-stack-empty-in-process-uncaughtexception.jstest/js/node/test/parallel/test-domain-stack.jstest/js/node/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.jstest/js/node/test/parallel/test-domain-thrown-error-handler-stack.jstest/js/node/test/parallel/test-domain-timer.jstest/js/node/test/parallel/test-domain-timers-uncaught-exception.jstest/js/node/test/parallel/test-domain-timers.jstest/js/node/test/parallel/test-domain-top-level-error-handler-clears-stack.jstest/js/node/test/parallel/test-domain-top-level-error-handler-throw.jstest/js/node/test/parallel/test-domain-uncaught-exception.jstest/js/node/test/parallel/test-domain-vm-promise-isolation.jstest/js/node/test/parallel/test-domain-with-abort-on-uncaught-exception.js
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/js/node/test/parallel/test-domain-nested-throw.js (1)
46-48: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick winExit code assertion could be stricter for robustness.
The assertion
assert(!c)accepts any falsy exit code, includingnull(signal termination) in addition to0(normal successful exit). For a domain error-handling test, the child should exit normally with code0after handling the errors, not be terminated by a signal.🔒 Stricter exit assertion
- child.on('exit', common.mustCall((c) => { - assert(!c); + child.on('exit', common.mustCall((code, signal) => { + assert.strictEqual(code, 0); + assert.strictEqual(signal, null); }));This ensures the child exited normally with success code
0, not via signal or other abnormal termination.🤖 Prompt for 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. In `@test/js/node/test/parallel/test-domain-nested-throw.js` around lines 46 - 48, The exit assertion in the child process handler currently uses assert(!c) which allows any falsy value (including null for signal termination); update the assertion in the child.on('exit', common.mustCall(...)) callback to assert that the exit code is exactly 0 (e.g., use assert.strictEqual(c, 0)) so the test verifies the child exited normally with success rather than being terminated by a signal.
🤖 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 `@src/jsc/bindings/BunProcess.cpp`:
- Around line 1220-1223: Bun__Node__AbortOnUncaughtException is an AtomicBool in
Rust but is declared as extern "C" bool in C++, causing ABI/atomic mismatches;
add a C ABI accessor in Rust (e.g., a function named
Bun__Node__AbortOnUncaughtException_load that returns the result of
.load(Ordering::Relaxed)) and change shouldAbortOnUncaughtException() to call
that loader instead of reading Bun__Node__AbortOnUncaughtException directly so
the C++ side performs a proper atomic-safe load.
---
Outside diff comments:
In `@test/js/node/test/parallel/test-domain-nested-throw.js`:
- Around line 46-48: The exit assertion in the child process handler currently
uses assert(!c) which allows any falsy value (including null for signal
termination); update the assertion in the child.on('exit', common.mustCall(...))
callback to assert that the exit code is exactly 0 (e.g., use
assert.strictEqual(c, 0)) so the test verifies the child exited normally with
success rather than being terminated by a signal.
🪄 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: 0644b2fe-bfef-44d9-bcb4-11bf820acdd8
📒 Files selected for processing (6)
src/jsc/bindings/BunProcess.cpptest/js/node/test/parallel/test-domain-abort-on-uncaught.jstest/js/node/test/parallel/test-domain-nested-throw.jstest/js/node/test/parallel/test-domain-nested.jstest/js/node/test/parallel/test-domain-thrown-error-handler-stack.jstest/js/node/test/parallel/test-domain-top-level-error-handler-clears-stack.js
e8d4378 to
2b58181
Compare
297a234 to
0b243a8
Compare
…eam domain test suite
node:domain was a ~70-line stub (sync-only run/bind, no process.domain, no
uncaught-exception routing). This replaces it with a port of Node's
lib/domain.js and vendors the test-domain-* suite from the Node v26.3.0 tag.
- domain.ts: full port. Async pairing rides on AsyncLocalStorage (Bun has no
async_hooks.createHook): the active domain is carried in an ALS box that
AsyncContextFrame snapshots/restores around every callback. The box also
records a token identifying the synchronous execution that wrote it; when
a callback later observes domain state with a stale token, the paired
domain is entered on the module-global stack — the equivalent of Node's
before() hook. Synchronous throws that unwind to the native fatal path
lose the ALS box (the context frame pops with the unwind), so the
dispatcher falls back to the throw-surviving module-global stack/active.
- BunProcess.{h,cpp}: dedicated domain error-handler slot
(jsFunctionSetDomainErrorHandler) consulted by Bun__handleUncaughtException
before the capture callback and 'uncaughtException' listeners. Errors
thrown from the handler/capture callback now exit with code 7 (Node's
internal-exception-handler failure code). --abort-on-uncaught-exception
aborts before 'uncaughtException' listeners are consulted unless a capture
callback (or domain error handler) is installed, matching V8's throw-time
abort semantics.
- Arguments.rs: implement --abort-on-uncaught-exception, accepting both the
dashed and underscored spellings like V8.
- events.ts: extract the constructor body into a Node-compatible
EventEmitter.init static so domain can wrap it; remove the old
`init: EventEmitter` alias from the exports Object.assign — with the
constructor delegating through EventEmitter.init, the alias made the
constructor call itself.
- async_hooks.ts: AsyncResource instances created inside a domain get the
non-enumerable `domain` property like Node's init hook provides.
- ZigGlobalObject.cpp: fix a pre-existing bug where process.nextTick
callbacks queued alongside AsyncLocalStorage.enterWith() were dropped:
cleanupAsyncHooksData unhooked the microtask-tick callback without
draining the pending nextTick queue, so the process exited with ticks
still queued (reproduces on stock Bun with enterWith + nextTick at main
scope and no other event-loop work).
- process.test.js: the capture-callback-throw fixture now exits 7 (was 1).
Most of the suite is vendored verbatim; divergences are commented in-place:
- Tests throwing from fs callbacks (test-domain-implicit-binding/-fs, the
fs cases in the abort tests) are omitted: errors thrown from fs callbacks
surface through the unhandled rejection path in Bun, which does not yet
route rejections through the domain machinery (same reason the unhandled
rejection block of test-domain-promise is omitted).
- test-domain-dep0097 needs node:inspector; test-domain-multi needs raw
res.socket writes to corrupt the wire protocol mid-response.
- test-domain-with-abort-on-uncaught-exception's synchronous throw case is
omitted: Bun reports a main-module synchronous throw after the nextTick
queue has drained, so the nextTick error's domain cleanup runs first.
Follow-ups from CI on the node:domain port: - Workers: node only honors --abort-on-uncaught-exception on the main thread; an uncaught exception inside a Worker is forwarded to the parent's 'error' handler instead of aborting the process. Gate the abort paths in Bun__handleUncaughtException on Bun__isMainThreadVM(). Fixes test-worker-abort-on-uncaught-exception aborting the whole test process. - Windows: raising SIGABRT there terminates with an ambiguous exit code (observed as 9), which the node test harness does not recognize as an abort. Call _exit(134) in place of abort() like node does; common.nodeProcessAborted expects exactly that value. - Skip the four domain tests (and one case of test-domain-abort-on-uncaught) whose main module throws an uncaught exception that a domain then handles on Windows: that path leaves the process hanging there due to a pre-existing event loop bug, the same one tracked by the zeroExitWithUncaughtHandler windows-todo in test/js/node/process/process.test.js.
Three more entry points into the same pre-existing Windows hang: a handled uncaught exception thrown synchronously from the main module leaves the process hanging there (the bug tracked by the zeroExitWithUncaughtHandler windows-todo in test/js/node/process/process.test.js). - test-domain-abort-on-uncaught: the firstRunOnlyTopLevelErrorHandler and firstRunNestedWithErrorHandler cases throw synchronously from the main module like the already-skipped firstRun case; early-return them on Windows too. The async cases (nextTick/timer/immediate/netServer and the nested variants) are unaffected and keep running. - test-domain-stack-empty-in-process-uncaughtexception: the throw from d.run() is swallowed by the process 'uncaughtException' listener — the exact zeroExitWithUncaughtHandler scenario. - test-crypto-domain: d.run(cb) throws synchronously at module top level and the domain handles it. This passed on Windows before only because the old domain stub caught the error inside run() in JS instead of routing it through the native uncaught-exception path.
Review follow-ups on the node:domain port: - Bun's EventEmitter.init installs the capture-rejections emit variant as an own instance property, which shadows the domain-aware prototype emit, so emitters constructed with captureRejections (or while EventEmitter.captureRejections is enabled globally) bypassed domain error routing entirely. The domain emit override is now built by a factory and EventEmitter.init wraps an own emit with it too. - adopt() enters an async callback's paired domain on the module-global stack (node's before() hook equivalent), but nothing exited it when the callback returned, so the pairing leaked into unrelated callbacks (process.domain reported a stale domain) and repeated adoption grew the stack without bound. The next domain-state access from a different execution context now lazily undoes the previous adoption — the deferred equivalent of node's after() hook, which exits the paired domain along with anything entered above it that was never exited. - Bun__handleUncaughtException: return immediately after the two Bun__Process__exit(7) calls. Bun__Process__exit is only noreturn on the main thread; in a Worker it requests termination and returns, so these fatal branches could fall through into the capture-callback / 'uncaughtException' routing (and into toBoolean() on the call result, which is not meaningful when the call threw). - test-crypto-domain.js: document why this copy diverges from upstream's d.run(fn, cb) (errors thrown from crypto callbacks surface through the unhandled rejection path, which does not yet consult domains) instead of presenting the synchronous throw as upstream behavior. - Style: use `!= null` for the combined null/undefined checks.
When the main module's synchronous evaluation throws and a user 'uncaughtException' listener (or domain error handler) claims the error, the run command grouped that case with --hot/--watch and called tickPossiblyForever(). That arms a ref'd four-minute repeating "forever timer" whenever the loop looks inactive — which is exactly the watcher keep-alive semantics, not what a handled error needs. On Windows this hung the process: the libuv-backed tick is uv_run(UV_RUN_ONCE), which blocks until the next event — the four-minute timer — and the ref'd timer keeps uv_loop_alive() true, so the regular run-loop afterwards never sees the loop go idle and the process never exits. POSIX only escaped by accident: its tick (us_loop_run_bun_tick) happens to find the loop's wakeup eventfd already signaled and returns immediately, and the POSIX is_active() counter is Bun-managed and never incremented by the forever timer. Handled entry errors now just drain the event loop once and fall through to the regular run-loop, which finishes any work the handler scheduled and exits when the loop is empty — same observable behavior on POSIX, no hang on Windows. The --hot/--watch arm is unchanged. This removes the underlying reason for the Windows skips added earlier: - test-domain-nested, test-domain-nested-throw, test-domain-thrown-error-handler-stack, test-domain-top-level-error-handler-clears-stack, test-domain-stack-empty-in-process-uncaughtexception, test-crypto-domain: common.skip(isWindows) removed. - test-domain-abort-on-uncaught: the three firstRun* early-returns removed. - process.test.js: zeroExitWithUncaughtHandler and changeCodeInUncaughtHandler windows-todos flipped to regular tests; both exercise this exact path.
- event-emitter.test.ts: import the harness at module scope instead of
require() inside the describe block, and drain the subprocess stderr
pipes, asserting a combined { stdout, stderr, exitCode } object so
failure diffs show the child's diagnostics.
- test-domain-with-abort-on-uncaught-exception.js: drop the fs require
left behind when the fs.exists case was omitted.
--abort-on-uncaught-exception aborted before 'uncaughtException' listeners for every origin, but node only does that for synchronous throws (V8 aborts at throw time). Promise rejections that reach the uncaught-exception path (--unhandled-rejections=strict) go through process._fatalException first; node aborts only if it returns unhandled (TriggerUncaughtException in node_errors.cc). So a listener that swallowed a strict-mode rejection still SIGABRTed under the flag. Replace the boolean is_rejection with a three-valued origin (exception / rejection / entry-point rejection). True rejections now skip the pre-listener abort and instead abort in the nothing-handled branch at the bottom. The entry-point kind keeps abort-before-listeners semantics: a synchronous throw from the main module surfaces as the rejected entry promise and must abort like a throw (a rejected top-level await is indistinguishable at this layer and shares the behavior), while listeners still observe the 'unhandledRejection' origin string. Adds two regression tests: a strict-mode rejection swallowed by an 'uncaughtException' listener exits 0 under the flag, and one with no listeners still aborts.
The no-listener --abort-on-uncaught-exception regression test spawns a child that SIGABRTs by design. CI lanes that collect core files at teardown (alpine aarch64) found that child's core and flagged the test file as crashed even though every test passed. Wrap the child in `ulimit -c 0`, exactly like the upstream node abort tests (test-domain-abort-on-uncaught and friends) already do for their intentionally-aborting children.
…ters Two residual gaps in the domain-aware EventEmitter integration: - An emitter constructed with captureRejections before node:domain loads carries the un-wrapped capture emit as an own property; the wrapped EventEmitter.init only covers construction after load, so its 'error' events bypassed domain routing even after d.add(ee). add() — the only way such an emitter acquires a domain — now wraps an own emit too. - The process.domain / domain.active setters wrote the context box without entering the callback's scheduling-time pairing first, so a callback whose first domain operation is a write could observe a previous tick's adopted entry on domain._stack (the freshened token made the stale globals look current). Both setters now adopt() first. Adds a subprocess regression test for each.
9a76a62 to
2e035df
Compare
There was a problem hiding this comment.
All prior feedback has been addressed and this run found no new issues, but given the scope — a novel ALS-based domain implementation with the adopt/unadopt reconciliation mechanism, changes to the native uncaught-exception/abort path and exit-code semantics, and the EventEmitter.init/emit restructuring — this warrants a human pass before merging.
Extended reasoning...
Overview
This PR replaces the ~70-line node:domain stub with a full implementation (585 lines) built on AsyncLocalStorage rather than async_hooks.createHook, and wires it into the native uncaught-exception path. It touches 67 files: the core implementation in src/js/node/domain.ts, EventEmitter restructuring (events.ts now exposes a wrappable EventEmitter.init static and drops the init: EventEmitter alias), a new domain-error-handler slot on Process (BunProcess.{h,cpp}), --abort-on-uncaught-exception support, the bool isRejection → three-valued UncaughtExceptionOrigin enum threaded through ~15 Rust call sites, exit-code 1→7 for capture-callback failures, a nextTick-drain fix in ZigGlobalObject.cpp, and a run_command.rs change splitting the handled-entry-error path from the hot-reload path. Plus 48 vendored upstream tests and several Bun-specific regression tests.
Security risks
None identified. The new jsFunctionSetDomainErrorHandler is reachable only via $newCppFunction from the builtin module (not exposed on process), the abort path is gated on an init-time CLI flag, and the EventEmitter prototype mutation is the standard Node behavior being ported. No auth/crypto/permission surfaces touched.
Level of scrutiny
High. This is production-critical exception-handling code: Bun__handleUncaughtException ordering, abort semantics, process exit codes, and the entry-point error path in run_command.rs all affect how every Bun process behaves on error. The adopt()/unadopt() deferred-after-hook mechanism in domain.ts is a novel design (not a port — Node uses createHook) that went through two rounds of correctness fixes during review (the stack-leak and write-first-setter gaps), and the PR description itself notes 18 upstream tests still failing across four buckets. The EventEmitter.init restructuring and removal of the init export alias is a user-visible API surface change.
Other factors
The author has been highly responsive — every inline comment I and CodeRabbit left across five review rounds was addressed with targeted commits and regression tests, and the reasoning in each reply was sound (e.g., correctly pushing back on the AtomicBool ABI and ERR_UNHANDLED_ERROR truthiness suggestions as matching established patterns / upstream). Test coverage is substantial. But the combination of architectural novelty, critical-path changes, known-incomplete coverage, and behavior changes (exit code 7, the events.ts init export removal) puts this well outside auto-approval territory.
2e035df to
9658a11
Compare
|
Two more
Verified on a local debug build of 32c7a46 merged with No test in the PR asserts either case. The vendored test.concurrent("bind() and intercept() return the callback's value, add() accepts a timer", async () => {
const r = await run(`
const domain = require("domain");
const d = domain.create();
const twice = d.bind(x => x * 2);
const sum = d.intercept((a, b) => a + b);
const t = setTimeout(() => {}, 1);
d.add(t);
const added = [t.domain === d, d.members.length];
d.remove(t);
clearTimeout(t);
console.log(JSON.stringify([twice(21), twice.name, sum(null, 1, 2), sum.name, added, t.domain, d.members.length]));
`);
expect(r.stdout).toBe('[42,"runBound",3,"runIntercepted",[true,1],null,0]\n');
expect(r.exitCode).toBe(0);
});One note for the next merge of |
…rray emit() passed its rest array to emitError() as a plain argument. In `bun run` that call keeps the JIT from leaving the array out of an emit() that is not inlined, even when no "error" event is ever emitted: 10,003 arrays per 10,000 emits. emit() now applies the arguments to a wrapper. Compiled ahead of time, the plain call stays: there an array that goes to a function which keeps no reference to it costs nothing. Co-authored-by: SUZUKI Sosuke <sosuke@bun.com>
With captureRejections, the constructor stored a second function as an own `emit` property of the emitter. So `emitter.emit()` never called an emit() that a subclass defines, a replaced EventEmitter.prototype.emit was bypassed, and `emit` showed in Object.keys(emitter). Node has one emit(), on the prototype. emit() now reads this[kCapture] after a listener returns a promise, as addCatch does in node, and no constructor stores `emit`: not the one of node:events, not the ahead-of-time texts of node:http, not the browser polyfill. In `bun run`, emit() hands its arguments on only by $apply, so the JIT keeps the rest array out of the heap. Compiled ahead of time, emit() has a text of its own that is as small as it was.
The constructor stored EventEmitter.prototype[kCapture] twice when no option asked for capture. A Proxy below the emitter saw two sets, and the interpreter paid for two reads and two stores by a symbol: 4444 to 3472 instructions for `new EventEmitter()`.
node:domain replaces EventEmitter.init in node. Here the constructor of EventEmitter, and the ahead-of-time texts of node:http that construct a request or a response without it, call domainHooks.bindEmitter first. The hook that tells an AsyncResource its domain moves there too, so the export of node:async_hooks has no key of Bun's own.
A debug build read `this.constructor` for the log line of every emit(), so a Proxy saw one more `get` there than in a release build, and the stored traps of node:http and node:stream did not hold under `bun bd`. node-http-proxy-traps.test.ts expects one store of kCapture, as the constructor now makes.
`--trim` builds an executable without bun:jsc when the program never
names it. require("bun:jsc") throws there, and it threw out of emit()
at the first promise that a listener returned. The marks that keep
emit() small for the JIT are now skipped in such an executable.
…' into claude/port-node-domain-tests
…ter to run Its program constructs the class with captureRejections and calls emit(): the line that the override prints was missing from the expected output, as main does not call the override.
The table of built-ins gets the native function that keeps the two functions of node:domain. The two spellings of --abort-on-uncaught-exception get their rows of requirements. The Bun.ModuleGraph hook in uncaught_exception() reads the origin.
…' into claude/port-node-domain-tests
| function adopt() { | ||
| const box = AlsGetStore.$call(als); | ||
| if (isCurrentExecution(box)) return; | ||
| unadopt(); | ||
| if (isRestoredPairing(box)) { | ||
| adoptedDomain = box.d; | ||
| adoptedIndex = stack.length; | ||
| ArrayPrototypePush.$call(stack, box.d); | ||
| setActive(box.d); | ||
| } |
There was a problem hiding this comment.
🔴 After merging, a d.run() that emits on an EventEmitterAsyncResource (or runs any AsyncResource.runInAsyncScope / AsyncLocalStorage.snapshot scope that enters a domain) leaves d on the global stack forever, so every later uncaught exception in the process is swallowed by d's 'error' listener; node exits 1. runInAsyncScope restores the exact pre-scope frame, whose box token is now stale after the inner enter/exit bumped currentToken, and adopt() at domain.ts:126-131 reads that as node's before() hook and pushes a duplicate d; the outer exit() pops only one. Fix: adopt()/unadopt() must not treat a frame restored inside the same synchronous execution as a callback boundary; at minimum skip the push when box.d is already stack[stack.length-1], which closes the leak.
Why this was flagged
Trigger: const d = domain.create(); d.on('error', e => console.log('handled', e.message)); d.run(() => { const ee = new EventEmitterAsyncResource({name:'x'}); ee.on('x', () => {}); ee.emit('x'); }); setTimeout(() => { throw new Error('later') });. ee.emit runs super.emit under runInAsyncScope (async_hooks.ts:452-460), which in finally calls set(prev) with the exact old frame. The domain-aware emit (domain.ts:442-444) calls d.enter()/d.exit() there, so setActive (domain.ts:72-76) advances currentToken to 3; set(prev) then puts back the frame whose box is still {d, 1}. The outer d.run now calls this.exit() -> adopt() (domain.ts:122-132): isCurrentExecution is false (1 != 3), isRestoredPairing (domain.ts:82-84) is true, so d is pushed again and exit() splices only index 1, leaving stack [d] and globalActive d. The timer throw reaches fatalErrorDispatch (domain.ts:203-220): unadopt() cannot pop, stackClaims([d]) is true, and d._errorHandler handles it, exit 0; node (and the base branch, whose stub never routed uncaught exceptions) exits 1.
Verification: The finally { set(prev) } in runInAsyncScope (async_hooks.ts:452-460) reinstalls F1 whose box is still {d, token 1}. adopt() (domain.ts:122-132): isRestoredPairing (:82-84) is TRUE, so it pushes d again and exit() splices only the duplicate, leaving stack=[d], globalActive=d. Base branch's stub had no uncaught-exception routing. No test in the PR exercises runInAsyncScope under a domain.
There was a problem hiding this comment.
Reproduced, and not fixed yet. A fix at the scope layer is written and not pushed, because its review found it incomplete (a ReadableStream cancel and an http2 session.destroy() inside d.run() still leave the domain entered). State and the question that decides the next step: #31828 (comment)
| const activeDomain = domainHooks.active; | ||
| if (activeDomain !== undefined) { | ||
| const domain = activeDomain(); | ||
| if (domain != null) { | ||
| Object.defineProperty(this, "domain", { | ||
| __proto__: null, | ||
| configurable: true, | ||
| enumerable: false, | ||
| value: domain, | ||
| writable: true, | ||
| }); | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 (optional) Users whose domain callbacks run code through an AsyncResource created outside any domain lose domain error routing for work scheduled inside it: Node handles the error, Bun exits 1. runInAsyncScope (async_hooks.ts:452-460) replaces the whole async frame with the resource's snapshot, which carries no domain box, so timers/I/O scheduled inside pair with nothing (domain.ts:101-107, 122-132) and a later throw falls to uncaughtException. Node's before() hook leaves the active domain untouched for an unpaired resource. Fix: an unpaired resource (no .domain set here) must keep the caller frame's domain pairing inside runInAsyncScope/bind, e.g. re-bind the domain box from prev after set(this.#snapshot), while a paired resource still restores its own domain.
Why this was flagged
Trigger: const res = new AsyncResource('X') at module top level (no domain active, so #snapshot at async_hooks.ts:414 is a frame with no domain box), then inside a domain callback d.run(() => setTimeout(() => res.runInAsyncScope(() => setTimeout(() => { throw new Error('x') })))). runInAsyncScope at async_hooks.ts:452-460 does set(this.#snapshot), so the inner setTimeout snapshots a frame where AlsGetStore(als) is undefined. When that timer throws, fatalErrorDispatch (domain.ts:203-220) calls adopt() (domain.ts:122-132), which only pushes a domain when isRestoredPairing(box) is true; with no box it pushes nothing, stackClaims(stack) is false, and the error goes to uncaughtException and exit code 1. Node v26 pairs the inner timer with d because its init hook reads process.domain, which the before() hook of an unpaired resource never changes, so d handles the error and the process exits 0. On the base branch node:domain was a stub, so this is a divergence the new implementation introduces relative to its stated goal of matching Node's pairing.
Verification: async_hooks.ts:452-460 runInAsyncScope does set(this.#snapshot). Inside runInAsyncScope of a resource created outside any domain, the box is undefined, so a setTimeout scheduled there captures a frame with no pairing. fatalErrorDispatch (domain.ts:203-220): adopt() finds no pairing and the exception falls through to 'uncaughtException' → exit 1. No test in the PR covers runInAsyncScope under a domain.
There was a problem hiding this comment.
The same unpushed fix covers this case for node v26. Node main differs here (nodejs/node#61095): a scope made outside every domain runs with no domain there. Which node to follow is the open question: #31828 (comment)
`bun install`, `add`, `remove` and `update` ignore the flags of the runtime that take no value. `--abort-on-uncaught-exception` and `--abort_on_uncaught_exception` were not in that list, so `bun remove --abort-on-uncaught-exception` failed. Three lists of tests name what the port adds. `test/bundler/compile-trim-options.ts` has every option that a compiled executable reads: both flags work there as without `--trim`. `test/aot/builtins/native-contract.test.ts` loads every module, node:domain too, and from then on the EventEmitter constructor defines `domain` on the object, as node does.
A throw in the callback of `fs.exists` reaches the domain. `test-domain-abort-on-uncaught.js` is the text of node v26.3.0 again, `test-domain-with-abort-on-uncaught-exception.js` has its `fs.exists` case back, and `test-domain-no-error-handler-abort-on-uncaught-5.js` and `-9.js` are added as they are upstream.
There was a problem hiding this comment.
Still open from earlier reviews (2):
- 🔴
src/js/node/domain.ts:131—After merging, a d.run() that emits on an EventEmitterAsyncResource (or runs any AsyncResource.runInAsyncScope / AsyncL… - Also unresolved: 1 minor or pre-existing.
If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.
Two programs of `test/aot/trimmed-is-whole` reach `process` through an accessor named `domain` on `EventEmitter.prototype`. With node:domain loaded, `process.domain` is an own accessor of `process` and each emitter has an own `domain`, as in node. So the program that enters a domain reaches nothing now and ends with 0. The program of the http request keeps what it shows, because it no longer loads node:domain: only the program that needs the module imports it. The skip of `test-crypto-domain.js` names its cause: Bun reports a throw of a crypto callback after it put back the async context that was in place before the callback. `test-domain-implicit-fs.js`, `test-domain-implicit-binding.js` and `test-domain-multi.js` are added as they are in node v26.3.0. They pass.
…allback entered since Bun reports a throw of the entry module after the ticks that were queued before it, and a rejection of an ESM entry after the callbacks that ran before it. A callback that uses a domain leaves its pairing on the stack until the next callback looks: that is the stand-in for node's after() hook. The report of the entry module skipped that stand-in, so the domain of the callback took the error. With two domains, node printed `d1 sync` and Bun `d2 sync`. `fatalErrorDispatch` and `domainWouldClaim` now pop what a callback adopted before they read the stack.
There was a problem hiding this comment.
Code review completed
Nothing new to post: everything this review found is already covered by existing comments on this pull request or didn't merit a separate one.
Still open from earlier reviews (2):
- 🔴
src/js/node/domain.ts:131—After merging, a d.run() that emits on an EventEmitterAsyncResource (or runs any AsyncResource.runInAsyncScope / AsyncL… - Also unresolved: 1 minor or pre-existing.
If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.
|
@cirospaciari this is the state of the blocking review thread (a finished domain stays entered), and one question that decides what I build next. State. The report holds on this branch. With Express 5.3.0,
The repair is one rewrite of that commit. It exists as a model, and it is not built. Question. Which node does
If the answer is v26, I finish the rewrite of the scope commit and push it here. If the answer is node main, |
Implements
node:domain(previously a ~70-line stub) as a port of Node'slib/domain.js, and vendors the upstream domain test suite verbatim from Node v26.49 of the 50 upstream
test-domain-*tests now pass (45 newly vendored, plus 3 existing files re-synced to upstream). The one that does not pass is not in the tree: it is listed as a gap below rather than marked failing.test/expectations.txtis untouched by this PR. On linux-x64-musl,test-gc-http-client-connaborted.jsnow joinstest-net-connect-memleak.jsas a manifestation of open issue #33044 (one object not finalized in a gc+setImmediate loop; no JS-level retention found, 10/10 on glibc); it is left un-quarantined alongside its sibling pending that issue's fix.What this does
node:domainwas a stub, so any package depending on it silently did nothing. This implements it and proves it against Node's own test suite.node:domainimplemented:create()/Domain,run/bind/intercept/add/remove/enter/exit,domain.active/domain._stack, and Node's error decoration (err.domain,domainThrown,domainEmitter,domainBound).createHook: Node pairs each async resource with the active domain via the async-hooksinithook, then enters it inbefore(). Bun has nocreateHook, so the active domain rides Bun's AsyncLocalStorage/AsyncContextFrame machinery instead — snapshotted at schedule time, restored around every callback, which is the same pairing. The synchronous domain stack stays a module-global like Node's; the uncaught-exception dispatcher reconciles the two at async boundaries.Bun__handleUncaughtExceptionbefore the capture callback and'uncaughtException'listeners — where Node's domain hooks intoprocess._fatalException.process.domainbecomes an accessor reading the async-local active domain.EventEmitterintegration:node:domaintakes every emitter before its construction, through a hook ininternal/sharedthat theEventEmitterconstructor calls. The ahead-of-time texts ofnode:httpthat construct a request or a response without the constructor call it too. Node replacesEventEmitter.initfor this. Here the constructor does not go throughinit, soEventEmitter.initstays what it is on main. Emitters created inside a domain get.domainand route'error'into it with Node's stack pruning/restore semantics. The hook costs 105 interpreter instructions pernew EventEmitter()(3,480 to 3,585), and nothing in an executable compiled ahead of time that never loadsnode:domain.emiton the prototype: this comes from node:events: one emit() for emitters that capture rejections #47381, which this branch contains until it lands.node:domainneeds it: an ownemiton an emitter that captures rejections hides theemitthatnode:domainputs on the prototype. node:events: one emit() for emitters that capture rejections #47381 is a draft while its design is reviewed again, and this branch follows it.AsyncResourcecreated inside a domain gets the non-enumerable.domainproperty Node's init hook provides.async_hooksstays domain-agnostic: the hook ininternal/sharedis undefined untilnode:domainloads, so nothing touchesprocess.domainotherwise.--abort-on-uncaught-exception: implemented, including the--abort_on_uncaught_exceptionspelling V8 also accepts. Aborts after printing instead ofexit(1), and a throwing top-level domain'error'handler aborts rather than being swallowed. Ordering matches Node: exceptions abort before'uncaughtException'listeners are consulted (V8 aborts at throw time), while true promise rejections abort only after listeners decline.(An earlier revision also carried a drive-by fix for
enterWith()+process.nextTickdropping the tick at main-module scope, patched incleanupAsyncHooksData. #41190 removed that function and fixes the same case at the event-loop boundary, so the hunk is gone from this diff; the repro still passes on the merged branch.)How we know it works
Every vendored test is byte-identical to upstream v26 except two, each carrying an inline
Note for Buncomment explaining the omitted case (see gaps). All 47 fail on released Bun and pass on this branch. That is the 45 added files plus the two re-syncedtest-domain-*files; the third re-synced file,test-crypto-domain.js, is skipped (see gaps), andtest-domain-crypto.jsandtest-domain-ee-error-listener.js, the other two of the 49, were already on main and are untouched here. Also re-ran theevents,async-hooks, andasynclocalstorageupstream suites (29/29) and Bun's ownasync_hooks(111) andevent-emitter/process(184) tests, sinceEventEmitter.initand the nextTick drain are cross-cutting.Review round (a988724): four findings of the review are answered so far. A throw in an
fscallback reaches its domain, sotest-domain-abort-on-uncaught.jsis the upstream text again,test-domain-with-abort-on-uncaught-exception.jshas itsfs.existscase back, and five upstream files are added (test-domain-no-error-handler-abort-on-uncaught-5.jsand-9.js,test-domain-implicit-fs.js,test-domain-implicit-binding.js,test-domain-multi.js). A throw of the entry module is no longer given to a domain that a callback entered since: Bun reports that throw after the queued ticks ran, and the report skipped the stand-in for node'safter()hook (node printedd1 sync, this branchd2 sync). Three tests of other subjects name what the port changes: the install commands take both spellings of--abort-on-uncaught-exception, the lists ofcompile-trim-options.tsand ofnative-contract/known-changes.tshave the new names, and one program oftest/aot/trimmed-is-wholeends with 0 now, becauseprocess.domainis an own accessor ofprocessoncenode:domainis loaded, as in node. Still open from the review: a scope ofAsyncResourceor ofAsyncLocalStorage.snapshot()insidedomain.run()leaves the domain on the stack. The fix is in progress. Verified on the debug build:domain.test.ts16 pass, 83 upstream files exit 0 (the 49 domain files and theasync-hooks,async-local-storage,asyncresourceandprocess-exception-capturefiles),test/js/node/events136 pass.Merge note (0bb5272): merged main f7607a3 and #47381 (d2fb1eb). Eight files conflicted.
domain.tskeeps the port and declares$Node.Domain,events.tstakes the text of #47381, andBun__handleUncaughtExceptionkeeps main'sdefaultGlobalObjectwith this branch's origin and exit code 7. Main's new tables asked for three things: the native function that keeps the two functions ofnode:domainis declared innative-functions.builtins.ts, both spellings of--abort-on-uncaught-exceptionhave a row of requirements, and theBun.ModuleGraphhook reads the origin. The key thatnode:async_hooksexported fornode:domainis gone, becausevisible-surface.test.tslists every own key of that module. Verified on the debug build:domain.test.ts14 pass, the 45 vendored domain files exit 0,event-emitter.test.ts117 pass. On the release build:visible-surface.test.ts,AsyncLocalStorage.test.ts63 pass,test/aot/servers/budgets-of-node.test.tswith the counts of #47381, and a probe that binds emitters, streams, requests and responses to the active domain prints the same under node v26.3.0,bun runand--aot.Merge note (d38da28): main refactored several uncaught-exception reporting sites into shared helpers (
task::report_error_or_terminate,NapiEnv::surface_exception,run_callback_with_result). Those conflicts were resolved by taking main's structure and passingUncaughtExceptionOrigin::Exceptionat the three remaining direct calls (Task.rs, WebSocketServerContext.rs, socket Handlers.rs); the branch's now-redundantreport_active_exception_as_unhandledhelper was dropped with main. Verified by probing each path (timer throw, socketopenthrow without anerrorhandler, websocketopenthrow) for theuncaughtExceptionorigin, plus the cron, domain, events, and process suites.Merge note (7836e08 + 12ff462): #41190 keeps an
enterWith()frame alive through the uncaught-exception dispatch of the same synchronous execution (as node does), while Bun drains nextTicks before dispatching an entry-point throw. node:domain's tick-retired pairing token then misread the still-running entry execution as a restored pairing, soprocess.domain = d; throw ewas routed tod(node aborts under the flag, exits 1 without it, because the setter never putsdon the stack). Fix: a newUncaughtExceptionOrigin::EntryPointException(CJS entry throw; listeners still see'uncaughtException') joinsEntryPointRejectionin telling node:domain that no callback boundary preceded the dispatch, andfatalErrorDispatchnow follows node'supdateExceptionCapturerule exactly: route toprocess.domain._errorHandleronly while a domain on the stack has an'error'listener, never pushing the active domain at dispatch time. All four setter cases (sync throw with and without the flag, timer, nextTick) match node v26.3.0.Gaps
One upstream
test-domain-*test is not vendored, two vendored tests omit one case each, and one is skipped:promiseInfo.domain).test-domain-promise.jsomits its one case for that, and the.todocases oftest/js/node/domain/domain.test.tshold it.node:domain(anuncaughtExceptionlistener reads noAsyncLocalStoragestore there), and this PR does not change it.test-crypto-domain.jsis vendored byte-identical behind a documentedcommon.skip, and upstream'stest-crypto-domains.jsis not vendored.test-domain-with-abort-on-uncaught-exception.jsomits the synchronous throw from thedomain.runcallback for that.MakeCallbackequivalent, so the DEP0097 warning has no source. Blockstest-domain-dep0097.js.An earlier revision of this text said that a throw in an
fscallback does not reach its domain. It does: the five tests and two cases that were left out for it are in the tree now.no test proof · iteration 41 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/process/process.test.js