Skip to content

domain: implement node:domain on AsyncLocalStorage and port the upstream domain suite (+40 upstream tests) - #31828

Open
cirospaciari wants to merge 96 commits into
mainfrom
claude/port-node-domain-tests
Open

cirospaciari wants to merge 96 commits into
mainfrom
claude/port-node-domain-tests

Conversation

@cirospaciari

@cirospaciari cirospaciari commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Implements node:domain (previously a ~70-line stub) as a port of Node's lib/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.txt is untouched by this PR. On linux-x64-musl, test-gc-http-client-connaborted.js now joins test-net-connect-memleak.js as 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:domain was a stub, so any package depending on it silently did nothing. This implements it and proves it against Node's own test suite.

  • node:domain implemented: create()/Domain, run/bind/intercept/add/remove/enter/exit, domain.active/domain._stack, and Node's error decoration (err.domain, domainThrown, domainEmitter, domainBound).
  • Async propagation without createHook: Node pairs each async resource with the active domain via the async-hooks init hook, then enters it in before(). Bun has no createHook, 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.
  • Uncaught-exception routing: a dedicated native dispatch slot consulted by Bun__handleUncaughtException before the capture callback and 'uncaughtException' listeners — where Node's domain hooks into process._fatalException. process.domain becomes an accessor reading the async-local active domain.
  • EventEmitter integration: node:domain takes every emitter before its construction, through a hook in internal/shared that the EventEmitter constructor calls. The ahead-of-time texts of node:http that construct a request or a response without the constructor call it too. Node replaces EventEmitter.init for this. Here the constructor does not go through init, so EventEmitter.init stays what it is on main. Emitters created inside a domain get .domain and route 'error' into it with Node's stack pruning/restore semantics. The hook costs 105 interpreter instructions per new EventEmitter() (3,480 to 3,585), and nothing in an executable compiled ahead of time that never loads node:domain.
  • One emit on the prototype: this comes from node:events: one emit() for emitters that capture rejections #47381, which this branch contains until it lands. node:domain needs it: an own emit on an emitter that captures rejections hides the emit that node:domain puts 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.
  • AsyncResource created inside a domain gets the non-enumerable .domain property Node's init hook provides. async_hooks stays domain-agnostic: the hook in internal/shared is undefined until node:domain loads, so nothing touches process.domain otherwise.
  • --abort-on-uncaught-exception: implemented, including the --abort_on_uncaught_exception spelling V8 also accepts. Aborts after printing instead of exit(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.
  • Exit code 7 when an error is thrown from the capture callback or a top-level domain error handler (Node's internal-exception-handler run-time failure code; was exit 1).

(An earlier revision also carried a drive-by fix for enterWith() + process.nextTick dropping the tick at main-module scope, patched in cleanupAsyncHooksData. #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 Bun comment 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-synced test-domain-* files; the third re-synced file, test-crypto-domain.js, is skipped (see gaps), and test-domain-crypto.js and test-domain-ee-error-listener.js, the other two of the 49, were already on main and are untouched here. Also re-ran the events, async-hooks, and asynclocalstorage upstream suites (29/29) and Bun's own async_hooks (111) and event-emitter/process (184) tests, since EventEmitter.init and the nextTick drain are cross-cutting.

Review round (a988724): four findings of the review are answered so far. A throw in an fs callback reaches its domain, so test-domain-abort-on-uncaught.js is the upstream text again, test-domain-with-abort-on-uncaught-exception.js has its fs.exists case back, and five upstream files are added (test-domain-no-error-handler-abort-on-uncaught-5.js and -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's after() hook (node printed d1 sync, this branch d2 sync). Three tests of other subjects name what the port changes: the install commands take both spellings of --abort-on-uncaught-exception, the lists of compile-trim-options.ts and of native-contract/known-changes.ts have the new names, and one program of test/aot/trimmed-is-whole ends with 0 now, because process.domain is an own accessor of process once node:domain is loaded, as in node. Still open from the review: a scope of AsyncResource or of AsyncLocalStorage.snapshot() inside domain.run() leaves the domain on the stack. The fix is in progress. Verified on the debug build: domain.test.ts 16 pass, 83 upstream files exit 0 (the 49 domain files and the async-hooks, async-local-storage, asyncresource and process-exception-capture files), test/js/node/events 136 pass.

Merge note (0bb5272): merged main f7607a3 and #47381 (d2fb1eb). Eight files conflicted. domain.ts keeps the port and declares $Node.Domain, events.ts takes the text of #47381, and Bun__handleUncaughtException keeps main's defaultGlobalObject with this branch's origin and exit code 7. Main's new tables asked for three things: the native function that keeps the two functions of node:domain is declared in native-functions.builtins.ts, both spellings of --abort-on-uncaught-exception have a row of requirements, and the Bun.ModuleGraph hook reads the origin. The key that node:async_hooks exported for node:domain is gone, because visible-surface.test.ts lists every own key of that module. Verified on the debug build: domain.test.ts 14 pass, the 45 vendored domain files exit 0, event-emitter.test.ts 117 pass. On the release build: visible-surface.test.ts, AsyncLocalStorage.test.ts 63 pass, test/aot/servers/budgets-of-node.test.ts with 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 run and --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 passing UncaughtExceptionOrigin::Exception at the three remaining direct calls (Task.rs, WebSocketServerContext.rs, socket Handlers.rs); the branch's now-redundant report_active_exception_as_unhandled helper was dropped with main. Verified by probing each path (timer throw, socket open throw without an error handler, websocket open throw) for the uncaughtException origin, 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, so process.domain = d; throw e was routed to d (node aborts under the flag, exits 1 without it, because the setter never puts d on the stack). Fix: a new UncaughtExceptionOrigin::EntryPointException (CJS entry throw; listeners still see 'uncaughtException') joins EntryPointRejection in telling node:domain that no callback boundary preceded the dispatch, and fatalErrorDispatch now follows node's updateExceptionCapture rule exactly: route to process.domain._errorHandler only 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:

  • Unhandled rejections are not routed through the domain machinery (node's promiseInfo.domain). test-domain-promise.js omits its one case for that, and the .todo cases of test/js/node/domain/domain.test.ts hold it.
  • A throw in the callback of an async crypto call is reported after Bun put back the async context that was in place before the callback, so the domain of the call is not found. Main has the same order without node:domain (an uncaughtException listener reads no AsyncLocalStorage store there), and this PR does not change it. test-crypto-domain.js is vendored byte-identical behind a documented common.skip, and upstream's test-crypto-domains.js is not vendored.
  • Bun reports a synchronous throw of the entry module after the ticks that were queued before it, on main too. test-domain-with-abort-on-uncaught-exception.js omits the synchronous throw from the domain.run callback for that.
  • No MakeCallback equivalent, so the DEP0097 warning has no source. Blocks test-domain-dep0097.js.

An earlier revision of this text said that a throw in an fs callback 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

@coderabbitai

coderabbitai Bot commented Jun 4, 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

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

Changes

Domain runtime and EventEmitter integration

Layer / File(s) Summary
Domain state, APIs, and EventEmitter integration
src/js/node/domain.ts, src/js/node/async_hooks.ts, src/js/node/events.ts, src/js/node/http2.ts, src/jsc/bindings/ZigGlobalObject.cpp
Implements async-aware domain state, lifecycle APIs, callback binding, error routing, EventEmitter association, AsyncResource domain tagging, and centralized rejection capture.
Domain lifecycle and async integration tests
test/js/node/domain/*, test/js/node/async_hooks/*, test/js/node/events/*, test/js/node/test/parallel/*
Adds coverage for domain stacks, async propagation, EventEmitter routing, Promise behavior, metadata, cleanup, garbage collection, and compatibility gaps.

Uncaught-exception handling

Layer / File(s) Summary
Exception origins and abort handling
src/jsc/VirtualMachine.rs, src/jsc/bindings/BunProcess.*, src/runtime/cli/Arguments.rs, src/jsc/*, src/runtime/*
Adds explicit exception origins, domain-handler storage, abort flag parsing, handler ordering, worker substitution, exit-code handling, and updated exception-reporting call sites.
Abort regression suites
test/js/node/process/process.test.js, test/js/node/test/common/index.js, test/js/node/test/parallel/test-domain-*-abort-on-uncaught*.js
Adds subprocess coverage for abort behavior, domain handlers, capture callbacks, handler failures, crash-report suppression, and platform-specific results.

Possibly related PRs

  • oven-sh/bun#31831: Shares uncaught-exception origin and exit handling across the VM and process runtime.
  • oven-sh/bun#34121: Overlaps in async-hooks and nextTick queue cleanup.
  • oven-sh/bun#36579: Also changes uncaught-exception and rejection handling in BunProcess.cpp.
Pre-merge checks: Passed 4
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly identifies the primary change: implementing node:domain with AsyncLocalStorage and porting the upstream domain test suite.
Description check Passed The description is complete and relevant. It explains the PR purpose, implementation details, known gaps, platform differences, and extensive verification results. The section headings differ from the…
Full details: Description check

Explanation

The description is complete and relevant. It explains the PR purpose, implementation details, known gaps, platform differences, and extensive verification results. The section headings differ from the repository template, but the required information is present.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions github-actions Bot added the claude label Jun 4, 2026
@robobun

robobun commented Jun 4, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 2:51 AM PT - Oct 30th, 2026

❌ @autofix-ci[bot], your commit 90aa792 has 5 failures in Build #135662 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 31828

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

bun-31828 --bun

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Found 2 issues this PR may fix:

  1. Missing functionality of 'domain' API: control of async unhandled exceptions #6045 - PR's full node:domain reimplementation directly fixes the reported inability to catch async exceptions via domain.on('error')
  2. domain does not catch exceptions thrown inside setTimeout() callbacks #30672 - PR's AsyncLocalStorage-based domain implementation directly fixes the exact setTimeout + domain error-catching scenario reported

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

Fixes #6045
Fixes #30672

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. Implement process._fatalException with domain error routing #28665 - Implements process._fatalException with domain error routing in BunProcess.cpp and fixes domain.enter()/exit() in domain.ts — a subset of this PR's domain rewrite.
  2. domain: catch exceptions thrown inside setTimeout/setInterval/setImmediate callbacks #30675 - Rewrites domain.ts to maintain a real domain stack with timer callback wrapping and uncaught exception routing — also a subset of this PR's comprehensive AsyncLocalStorage-based implementation.

🤖 Generated with Claude Code

@cirospaciari
cirospaciari force-pushed the claude/port-node-domain-tests branch from d620847 to e190cb5 Compare June 5, 2026 01:52

@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: 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 win

Assert 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

📥 Commits

Reviewing files that changed from the base of the PR and between 91270aa and e190cb5.

📒 Files selected for processing (51)
  • src/js/node/async_hooks.ts
  • src/js/node/domain.ts
  • src/js/node/events.ts
  • src/jsc/VirtualMachine.rs
  • src/jsc/bindings/BunProcess.cpp
  • src/jsc/bindings/BunProcess.h
  • src/jsc/bindings/ZigGlobalObject.cpp
  • src/runtime/cli/Arguments.rs
  • test/js/node/process/process.test.js
  • test/js/node/test/parallel/test-domain-abort-on-uncaught.js
  • test/js/node/test/parallel/test-domain-add-remove.js
  • test/js/node/test/parallel/test-domain-async-id-map-leak.js
  • test/js/node/test/parallel/test-domain-bind-timeout.js
  • test/js/node/test/parallel/test-domain-ee-implicit.js
  • test/js/node/test/parallel/test-domain-ee.js
  • test/js/node/test/parallel/test-domain-emit-error-handler-stack.js
  • test/js/node/test/parallel/test-domain-enter-exit.js
  • test/js/node/test/parallel/test-domain-error-types.js
  • test/js/node/test/parallel/test-domain-from-timer.js
  • test/js/node/test/parallel/test-domain-fs-enoent-stream.js
  • test/js/node/test/parallel/test-domain-http-server.js
  • test/js/node/test/parallel/test-domain-intercept.js
  • test/js/node/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js
  • test/js/node/test/parallel/test-domain-multiple-errors.js
  • test/js/node/test/parallel/test-domain-nested-throw.js
  • test/js/node/test/parallel/test-domain-nested.js
  • test/js/node/test/parallel/test-domain-nexttick.js
  • test/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-0.js
  • test/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.js
  • test/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.js
  • test/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.js
  • test/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.js
  • test/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.js
  • test/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.js
  • test/js/node/test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.js
  • test/js/node/test/parallel/test-domain-promise.js
  • test/js/node/test/parallel/test-domain-run.js
  • test/js/node/test/parallel/test-domain-safe-exit.js
  • test/js/node/test/parallel/test-domain-set-uncaught-exception-capture-after-load.js
  • test/js/node/test/parallel/test-domain-stack-empty-in-process-uncaughtexception.js
  • test/js/node/test/parallel/test-domain-stack.js
  • test/js/node/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js
  • test/js/node/test/parallel/test-domain-thrown-error-handler-stack.js
  • test/js/node/test/parallel/test-domain-timer.js
  • test/js/node/test/parallel/test-domain-timers-uncaught-exception.js
  • test/js/node/test/parallel/test-domain-timers.js
  • test/js/node/test/parallel/test-domain-top-level-error-handler-clears-stack.js
  • test/js/node/test/parallel/test-domain-top-level-error-handler-throw.js
  • test/js/node/test/parallel/test-domain-uncaught-exception.js
  • test/js/node/test/parallel/test-domain-vm-promise-isolation.js
  • test/js/node/test/parallel/test-domain-with-abort-on-uncaught-exception.js

Comment thread src/js/node/async_hooks.ts Resolved
Comment thread src/js/node/domain.ts Resolved
Comment thread src/jsc/bindings/BunProcess.cpp Resolved
Comment thread src/js/node/domain.ts Resolved
Comment thread src/js/node/domain.ts Resolved

@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

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 win

Exit code assertion could be stricter for robustness.

The assertion assert(!c) accepts any falsy exit code, including null (signal termination) in addition to 0 (normal successful exit). For a domain error-handling test, the child should exit normally with code 0 after 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

📥 Commits

Reviewing files that changed from the base of the PR and between e190cb5 and a8004f8.

📒 Files selected for processing (6)
  • src/jsc/bindings/BunProcess.cpp
  • test/js/node/test/parallel/test-domain-abort-on-uncaught.js
  • test/js/node/test/parallel/test-domain-nested-throw.js
  • test/js/node/test/parallel/test-domain-nested.js
  • test/js/node/test/parallel/test-domain-thrown-error-handler-stack.js
  • test/js/node/test/parallel/test-domain-top-level-error-handler-clears-stack.js

Comment thread src/jsc/bindings/BunProcess.cpp Resolved
Comment thread src/jsc/bindings/BunProcess.cpp Resolved
Comment thread src/js/node/domain.ts Resolved
@cirospaciari
cirospaciari force-pushed the claude/port-node-domain-tests branch from e8d4378 to 2b58181 Compare June 5, 2026 20:22
@cirospaciari
cirospaciari force-pushed the claude/port-node-domain-tests branch from 297a234 to 0b243a8 Compare June 5, 2026 23:05
Comment thread src/jsc/bindings/BunProcess.cpp Resolved
Comment thread src/js/node/domain.ts Resolved
Comment thread src/js/node/domain.ts Resolved
…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.
@cirospaciari
cirospaciari force-pushed the claude/port-node-domain-tests branch from 9a76a62 to 2e035df Compare June 6, 2026 02:51

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

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.

@cirospaciari
cirospaciari force-pushed the claude/port-node-domain-tests branch from 2e035df to 9658a11 Compare June 8, 2026 18:59

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

Code review found no issues

No high-confidence issues detected in this change.

@robobun

robobun commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

Two more node:domain differences against node v26.3.0 are still on main (511ddb3, the 96-line shim). This PR fixes both, because bind(), intercept() and add() here are node's.

  • The wrappers from d.bind(fn) and d.intercept(fn) drop the return value of fn. d.bind(x => x * 2)(21) is undefined (node: 42). d.intercept((a, b) => a + b)(null, 1, 2) is undefined (node: 3). The wrapper names are "" (node: runBound, runIntercepted).
  • d.add(timer) throws TypeError: emitter.on is not a function. Node accepts a timer, sets timer.domain and adds it to d.members.

Verified on a local debug build of 32c7a46 merged with main: both cases print the same output as node v26.3.0, and so do remove(), moving a timer between two domains, a truthy non-Error first argument to an intercept() wrapper, and this forwarding.

No test in the PR asserts either case. The vendored test-domain-intercept.js and test-domain-bind-timeout.js do not check return values, and nothing calls add() with a timer. This block fits the run() helper in test/js/node/domain/domain.test.ts. The script prints the expected line on that build and on node v26.3.0, and throws on main:

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 main: it merges without textual conflicts but does not compile. main added a Bun__ModuleGraph__handleUncaughtException guard in VirtualMachine::uncaught_exception that reads is_rejection, which this PR replaced with origin. !matches!(origin, UncaughtExceptionOrigin::Rejection) in that condition builds. Whether the two entry-point origins belong in that check is your call.

robobun and others added 3 commits October 29, 2026 06:36
…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.
…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.

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

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread src/js/node/domain.ts
Comment on lines +122 to +131
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);
}

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.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)

Comment on lines +417 to +429
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,
});
}
}

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.

🟡 (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.

@robobun robobun Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

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

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.

Comment thread src/js/node/domain.ts Resolved
robobun and others added 3 commits October 30, 2026 05:22
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.

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

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.

@robobun

robobun commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator

@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, express.json() and one domain for each request, the domain of request 1 takes a later throw of an unrelated interval, and the process continues. Node v26.3.0 and main end with the uncaught error. I wrote a fix at the scope layer and did not push it: runInAsyncScope, AsyncResource.bind, AsyncLocalStorage.snapshot() and AsyncLocalStorage.bind enter the domain and leave it, as the before and after hooks of node v26 do. It brings 88 probe rows from 49 that differ from node v26.3.0 to 3, and 1,902 scope programs from 1,356 to 44. A review of it found two faults:

  • It closes the four public routes only. A ReadableStream whose cancel() runs inside d.run(), and an http2 session.destroy() there, still leave the domain entered.
  • It is wrong in new cases where the head is right. A scope made in domain A that cancels a stream made in domain B leaves B entered. A vm timeout inside a scope leaves the domain of the caller entered.

The repair is one rewrite of that commit. It exists as a model, and it is not built.

Question. Which node does node:domain follow: v26, which Bun reports as its node version, or node main? nodejs/node#61095 (semver-major, merged into main on 2026-06-21) replaced lib/domain.js with a port to AsyncLocalStorage. I ran that file as it is on the build of this PR's head, as a module with node's primordials supplied. It needs one addition, the bindEmitter hook of this PR, because Bun's EventEmitter does not call EventEmitter.init.

  • It prints what node main prints in 88 of 88 probe rows and in 1,902 of 1,902 scope programs. It keeps no pairing in the frame, so the fault of this thread cannot occur there.
  • Against node v26.3.0 it differs in 51 of the 88 rows. Three of the 55 vendored test-domain-* files fail with it: test-domain-async-id-map-leak.js, test-domain-emit-error-handler-stack.js and test-domain-stack-empty-in-process-uncaughtexception.js. #61095 changed all three.
  • The head of this PR differs from node v26.3.0 in 49 of the 88 rows, and from node main in 46.

If the answer is v26, I finish the rewrite of the scope commit and push it here. If the answer is node main, src/js/node/domain.ts becomes the text of node main with that hook, and the scope commit is not needed.

This branch has not been deployed

No deployments
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.

4 participants