Skip to content

error printer: one render per error, [Circular] under the key that closes the cycle - #37270

Open
robobun wants to merge 2 commits into
farm/6002b032/formatter-visited-helpersfrom
farm/6002b032/error-printer-cyclic-cause-errors
Open

robobun wants to merge 2 commits into
farm/6002b032/formatter-visited-helpersfrom
farm/6002b032/error-printer-cyclic-cause-errors

Conversation

@robobun

@robobun robobun commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #44139.

Problem

  • bun crashes when it prints an Error that reaches itself through two properties. const e = new Error('cyc'); e.cause = e; e.errors = [e]; throw e; prints about 2,100 lines, then SIGSEGV (rc 139).
  • Cause: the callers of the error printer kept the record "this error is being rendered". Formatter::print_error (src/jsc/ConsoleObject.rs) removed it before the call. The uncaught entries made none.

Fix

  • print_error_instance_js (src/jsc/VirtualMachine.rs) prints [Circular] for an error that a caller is rendering. Every render passes it.
  • The body records the error before the first render that it nests. A property that closes a cycle prints in place: cause: [Circular],.
  • The console formatter no longer records errors, but keeps its stack check.
  • Verified: test/js/bun/util/inspect-error.test.js (15 new, 14 fail on main), test/js/node/worker_threads/worker_threads.test.ts (1 new).

Background

  • The visited set holds the values that the formatter is rendering. A value found in it prints [Circular].
  • Considered: a patch per caller, as in the first revision. One thrown cyclic error then renders 3 times.

Downsides

Notes

Status. #44268 covers this PR and lists it under Fixes. This PR stays open as the small fallback until that one lands. I do not push to it any more.

All numbers: linux x64, main a4f1429 and this branch.

Pool takes / hash inserts / hash lookups per print (release build, gdb hit counts of LocalKey::with for the pool, HashMap<JSValue, ()>::get_or_put_slot and ::get_index, difference of 80 and 40 prints):

print main this PR
Bun.inspect(new Error("x")), console.log of it 1 / 2 / 2 0 / 0 / 0
Bun.inspect of an Error with primitive properties 1 / 2 / 2 0 / 0 / 0
Bun.inspect of an Error with an object property 1 / 3 / 3 1 / 2 / 2
Bun.inspect of an Error with a cause 1 / 3 / 3 1 / 1 / 3
Bun.inspect of an AggregateError of 2 1 / 2 / 2 0 / 0 / 0
Bun.inspect({ a: 1, b: [1, { c: 2 }] }) 1 / 3 / 3 1 / 3 / 3
reportError(new Error("x")), also with primitive properties 0 / 0 / 0 0 / 0 / 0
reportError of an Error with an object property 1 / 1 / 1 1 / 2 / 2
reportError of an Error with a cause 1 / 1 / 1 1 / 1 / 3
reportError of an AggregateError of 2 0 / 0 / 0 0 / 0 / 0

reportError and throw use the same printer entry.

Syscalls (gdb catch syscall, entries plus returns, release): throw new Error('x') 477 -> 477. With an object property 477 -> 477. With a cause 477 -> 477. For e.cause = e; e.errors = [e] 510 -> 477 (write 38 -> 4).

Binary. size of the release binary: .text 80660492 -> 80659212 bytes (the same as #44139). Code of the printer functions (nm -S): 18958 -> 18744 bytes. Formatter has no new field. Instructions were not measured: perf and valgrind are not installed.

Stack reserved per function (sub ...,%rsp). Release: Formatter::print_error 40 -> 32 B, print_error_instance_js 5176 -> 5176 B, print_error_instance_body 376 -> 376 B, agg_iter 0 -> 24 B. Debug+ASAN: Formatter::print_error 736 -> 448 B, print_error_instance_js 3488 -> 3616 B, print_error_instance_body 10816 -> 10752 B, agg_iter 704 -> 800 B. One nested render through the cause loop, debug+ASAN: 14304 -> 14368 B. Through the formatter: 20576 -> 20352 B.

Output. Debug+ASAN build, one process per output. 38 values through 10 entries (console.log, console.error, console.log(v, v), Bun.inspect at depth 2, 0 and Infinity, util.inspect, throw, Promise.reject, reportError): 380 outputs.

  • 300 are byte-identical to main: every value without a cycle, and every AggregateError at depth 2 and 0.
  • 79 differ: the 9 values where an Error reaches itself, on the entries of the native printer. Main ends in an abort on 12 of them and in SIGSEGV on 6. This PR crashes on none.
  • 1 differs by the stack depth: Bun.inspect at depth Infinity of an AggregateError that lists itself prints 1001 levels before the stack check stops it, main 1013.
value main this PR
e.self = e at throw 2 renders 1 render, self: [Circular],
e.cause = e; e.errors = [e] at throw 392 renders, SIGSEGV 1 render
a.x = [b]; b.y = b at throw 392 renders, SIGSEGV 2 renders
a.cause = b; b.cause = a at console.log 4 renders 2 renders
new Error("b", { cause: a }) with a.cause = b 3 renders, bare [Circular] 2 renders, cause: [Circular],
Worker throws e.cause = e; e.errors = [e] debug: abort. release: message is the rendered text parent gets Error: cyc

What the first revision of this PR had, and why it is gone. The first revision removed the un-record in Formatter::print_error and made that function return Err when the printer left an exception pending. A check of deep chains found that a node:worker_threads Worker then reported null to its parent when the render of its uncaught error failed: on_unhandled_rejection (src/jsc/web_worker.rs) takes the JSC::Exception cell for the value on Err. #38560 fixes that reporter. The Err change is not part of this PR now. It can follow #38560 as its own change. The debug-build aborts that it fixed (comments of 2026-09-11 and 2026-09-13 on this PR) are not fixed by this revision.

Also not fixed here. An AggregateError that lists itself still renders once per level, to the depth cap (#36602). An assigned cause is still rendered twice at each nested level.

Suites run (debug+ASAN): inspect-error.test.js, inspect.test.js, bun-inspect.test.ts, reportError.test.ts, console-log.test.ts, circular-error-stack.test.ts, circular-error-stack-edge-cases.test.ts, test/js/bun/test/stack.test.ts.

Self-review. 9 concerns raised, 9 addressed. Addressed by a smaller diff: the AggregateError walk keeps its shape (a self-listing AggregateError lost its header in a larger draft), no change to web_worker.rs (#38560 owns it) or to the REPL, the groundwork is its own PR, fewer tests that spawn a process, the console formatter keeps its stack check for errors, release numbers are in this description.


[human-review] gate passed · iteration 2 · 4 files touched

fails on main (without fix)
ASAN without fix: 15 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/util/inspect-error.test.js test/js/node/worker_threads/worker_threads.test.ts
bun test v1.4.3 (367d939d9)

test/js/bun/util/inspect-error.test.js:
(pass) error.cause [11.56ms]
(pass) Error [7.01ms]
(pass) BuildMessage [20.02ms]
(pass) Error inside minified file (no color)  [821.29ms]
(pass) Error inside minified file (color)  [94.74ms]
(pass) Inserted originalLine and originalColumn do not appear in node:util.inspect [263.54ms]
(pass) observable properties > sourceURL is observable [12.18ms]
(pass) observable properties > line is observable [4.26ms]
(pass) observable properties > column is observable [3.54ms]
(pass) error.code is a String object that has no primitive value > no prototype > an uncaught throw prints the error [438.12ms]
(pass) error.code is a String object that has no primitive value > no prototype > Bun.inspect and console.error return to the caller [488.44ms]
(pass) error.code is a String object that has no primitive value > toString throws > Bun.inspect and console.error return to the caller [836.54ms]
(pas
... (truncated)

release without fix: 15 FAILED
bun test v1.4.3-canary.1 (367d939d9)

test/js/bun/util/inspect-error.test.js:
(pass) error.cause [0.36ms]
(pass) Error [0.11ms]
(pass) BuildMessage [1.13ms]
(pass) Error inside minified file (no color)  [4.06ms]
(pass) Error inside minified file (color)  [0.52ms]
(pass) Inserted originalLine and originalColumn do not appear in node:util.inspect [3.45ms]
(pass) observable properties > sourceURL is observable [0.24ms]
(pass) observable properties > line is observable [0.07ms]
(pass) observable properties > column is observable [0.05ms]
(pass) error.code is a String object that has no primitive value > toString throws > Bun.inspect and console.error return to the caller [1176.43ms]
(pass) error.code is a String object that has no primitive value > toString throws > an uncaught throw prints the error [1107.34ms]
(pass) error.code is a String object that has no primitive value > toString throws > an unhandled rejection prints the error [733.73ms]
(pass) error.code is a String object that has no primitive value > no prototype > Bun.inspect and console.error return to the caller [570.96ms]
(pass) error.code is a String object that has no primitive value > no prototype > an
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/bun/util/inspect-error.test.js test/js/node/worker_threads/worker_threads.test.ts
bun test v1.4.3 (367d939d9)

test/js/bun/util/inspect-error.test.js:
(pass) error.cause [10.80ms]
(pass) Error [7.17ms]
(pass) BuildMessage [25.07ms]
(pass) Error inside minified file (no color)  [144.38ms]
(pass) Error inside minified file (color)  [92.62ms]
(pass) Inserted originalLine and originalColumn do not appear in node:util.inspect [235.56ms]
(pass) observable properties > sourceURL is observable [9.84ms]
(pass) observable properties > line is observable [3.94ms]
(pass) observable properties > column is observable [3.29ms]
(pass) error.code is a String object that has no primitive value > toString throws > an uncaught throw prints the error [1248.40ms]
(pass) error.code is a String object that has no primitive value > toString throws > an unhandled rejection prints the error [1233.60ms]
(pass) error.code is a String object that has no primitive value > toString throws > Bun.inspect and console.error return to the caller [1400.08ms]
(pass) 
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     f2c583d456
  features     lto, baseline

23 deps, 136 codegen, 1176 objects in 6593ms

ninja: Entering directory `/workspace/bun/build/release'
[1/4] fetch lolhtml
[lolhtml] up to date
[2/4] fetch rust-argon2
[rust-argon2] up to date
[2/4] cargo plan → /workspace/bun/build/release/rust-target/plan.json
244 units: 172 lib, 16 proc-macro (host), 19 custom-build (host), 15 run custom-build, 17 lib (host), 4 run custom-build (host), 1 rlib
[3/4] reconfigure
[1/1499] mkdir stamps
[2/1499] mkdir codegen
[3/1499] install /workspace/bun
bun install v1.4.3-canary.1 (367d939d9)

Checked 26 installs across 65 packages (no changes) [203.00ms]
[4/1499] install /workspace/bun/packages/bun-error
bun install v1.4.3-canary.1 (367d939d9)

Checked 1 install across 2 packages (no changes) [11.00ms]
[5/1499] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[6/1499] rustc unicode_ident 
[7/1499] rustc build_script_build 
[8/1499] rustc build_script_build 
[9/1499] rustc bu
... (truncated)
diff hotspot
src/jsc/ConsoleObject.rs                           |  38 +++---
 src/jsc/VirtualMachine.rs                          |  82 +++++++++---
 test/js/bun/util/inspect-error.test.js             | 147 +++++++++++++++++++++
 test/js/node/worker_threads/worker_threads.test.ts |  28 ++++
 4 files changed, 256 insertions(+), 39 deletions(-)

gate history · 5 passed · 0 rejected · iteration 2

evidence per changed file
file                                                reads  edits  tests
src/jsc/ConsoleObject.rs                               13     11     42
src/jsc/VirtualMachine.rs                              16     20     42
test/js/bun/util/inspect-error.test.js                  0      0     34
test/js/node/worker_threads/worker_threads.test.ts      1      1     19

@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The formatter now retains visited errors during rendering and propagates pending JavaScript exceptions. Regression tests cover cyclic errors in uncaught output, console.log, and worker-thread error events.

Changes

Circular error formatting

Layer / File(s) Summary
Preserve circular tracking during error rendering
src/jsc/ConsoleObject.rs
print_error keeps the value in the visited map during formatting and returns JsError::Thrown when a pending exception exists.
Validate cyclic error output and worker handling
test/regression/issue/circular-error-stack.test.ts
Tests verify circular markers, exit codes, continued execution, and worker error messages for self-referential cause and errors values.

Possibly related PRs

  • oven-sh/bun#36912: Both changes update Formatter error propagation in src/jsc/ConsoleObject.rs.
  • oven-sh/bun#35039: Both changes cover nested or circular error rendering.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
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.
Description check ✅ Passed The description explains the problem, root cause, fix, limitations, verification steps, and test results. It does not use the template headings exactly, but it provides the required information in equ…
Title check ✅ Passed The title clearly identifies the error-printer change and the circular-reference behavior. It is specific, concise, and related to the primary change.

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

@github-actions github-actions Bot added the claude label Aug 9, 2026
@robobun

robobun commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Comment thread src/jsc/ConsoleObject.rs Outdated
Comment thread src/jsc/ConsoleObject.rs Outdated
Comment thread src/jsc/VirtualMachine.rs Outdated
Comment thread src/jsc/ConsoleObject.rs Outdated
Comment thread src/jsc/ConsoleObject.rs Outdated
Comment thread src/jsc/VirtualMachine.rs Outdated
Comment thread src/jsc/ConsoleObject.rs Outdated
@github-actions

github-actions Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. Guard AggregateError .errors printing against self-reference #35820 - Adds the same visited-map [Circular] guard around the error printer's .errors recursion and seats StackCheck::init() on both uncaught-print paths, which bounds the same self-referencing-error crash.
  2. console: guard AggregateError .errors recursion (cycle, depth, tampered property) #35825 - Near-identical to Guard AggregateError .errors printing against self-reference #35820 (visited-map [Circular] guard plus StackCheck seating on both uncaught-print entry points), targeting the same unbounded error-printer recursion.
  3. Guard print_errorlike_object against unbounded AggregateError recursion #34892 - Seats StackCheck on the same two uncaught-print entry points and bails early in print_errorlike_object, stopping the same unbounded recursion/SIGSEGV.
  4. error printer: clear the pending exception when formatting a non-Error uncaught value throws #36921 - Fixes the identical pending-exception-leak contract in print_error_instance_body (returning success with an exception still pending), the same change as this PR's second half.
  5. Guard the console and test-runner formatters against native stack overflow on deeply nested values #34884 - Changes Formatter::new() to StackCheck::init(), seating the check for the uncaught error printer so the existing recursion guard fires instead of crashing on the same repro.

🤖 Generated with Claude Code

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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/regression/issue/circular-error-stack.test.ts`:
- Around line 86-88: In test/regression/issue/circular-error-stack.test.ts,
replace the rationale comment at lines 86-88 with the confirmed GitHub issue URL
comment, and remove the duplicate rationale block at lines 123-127; retain only
the single issue-URL comment required for regression tests.
- Around line 90-97: Drain both configured subprocess pipes concurrently in both
test cases: at test/regression/issue/circular-error-stack.test.ts lines 90-97,
include stdout alongside stderr and proc.exited in the Promise.all call; at
lines 105-116, include stderr alongside stdout and proc.exited. No other changes
are needed.
🪄 Autofix

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: 88ddf1fa-210d-4104-a2e0-20f71eb8947d

📥 Commits

Reviewing files that changed from the base of the PR and between d2f48c6 and a63cab1.

📒 Files selected for processing (2)
  • src/jsc/ConsoleObject.rs
  • test/regression/issue/circular-error-stack.test.ts

Comment thread test/regression/issue/circular-error-stack.test.ts Outdated
Comment thread test/regression/issue/circular-error-stack.test.ts Outdated
@robobun

robobun commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Checked all five; same printer, different bugs, and this PR was deliberately narrowed to not overlap them.

All five can land independently of this one.

Comment thread test/regression/issue/circular-error-stack.test.ts Outdated

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

LGTM — the fix removes the visited-map removal/re-insertion dance in print_error and adds the same has_exception() propagation already used in print_as_prelude.

What was reviewed:

  • Traced the visited-map lifecycle: print_as_prelude inserts, VisitedRemove guard removes on exit, and keeping the value in the map during print_errorlike_object correctly bounds both the inline-property re-entry (errors: [e] → print_as) and the cause-chain loop at VirtualMachine.rs:6438.
  • Confirmed the top-level error still prints (the map is only consulted for child re-entries, not the initial render).
  • Tests drain both pipes, use test.concurrent, and the author verified fail-without-fix on both ASAN and release.
Extended reasoning...

Overview

The PR fixes a SIGSEGV in the error printer when an Error is both its own cause and an entry in its own errors array. The change is a net -14 lines in src/jsc/ConsoleObject.rs plus three regression tests.

The production change has two parts:

  1. Delete the 18-line block in Formatter::print_error that temporarily removed the value from the visited map (via raw pointer + scopeguard::defer! with an unsafe re-insertion) before calling print_errorlike_object. The value now stays in the map, so re-entrant formatting of cause/errors hits the existing [Circular] guard in print_as_prelude and the cause-chain loop in print_error_instance_body.
  2. Add a 3-line has_exception() check after print_errorlike_object returns, converting a pending exception into Err(JsError::Thrown) — the identical pattern already used at ConsoleObject.rs:3299 in print_as_prelude.

Security risks

None. This is error-formatting output logic; no auth, crypto, filesystem, or network surface. The change removes an unsafe block rather than adding one.

Level of scrutiny

Medium. The error printer is subtle and this file has several other open PRs targeting adjacent shapes (#35820, #35825, #34892, #34884, #36921), but the author analyzed each and this change is deliberately scoped not to overlap — it fixes only the Formatter::print_error visited-map handling, not the AggregateError branch or StackCheck seating those PRs cover. The removed code was demonstrably wrong (caused a crash), and the replacement is strictly simpler. I traced the map lifecycle through print_as → print_as_prelude (insert) → print_error → print_errorlike_object → property iteration → re-entrant print_as (finds existing → [Circular]) → cause-chain loop at VirtualMachine.rs:6427-6454 (finds existing → [Circular]) → VisitedRemove guard (remove on exit). The top-level error still renders because the map is only consulted for children.

Other factors

  • All prior review feedback (my pipe-draining note, CodeRabbit's identical finding, and the comment-cop bot's comment-length flags) was addressed in cf12347/a63cab1/796adb2; every thread is resolved.
  • The gate evidence in the description shows all three new tests fail on both ASAN-debug and release without the fix (SIGSEGV / mangled worker message) and pass with it.
  • The removed code included a raw-pointer capture inside scopeguard::defer! with an unsafe re-insertion — deleting it is a clear safety improvement.
  • The added has_exception() check does not clear the exception, so Bun.inspect's stack-overflow rethrow (pinned by bun-inspect.test.ts) is preserved.

@robobun

robobun commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI status: 195 of 196 jobs passed on 796adb2. The one red lane (darwin 14 x64 test-bun) is test/cli/test/parallel.test.ts, which the CI helper marks as pre-existing (same failure on main) and which this diff does not touch; it has been reported for main-break triage. The remaining entries in the annotation passed alone or on retry. The previously red bun-inspect.test.ts stack-overflow test passes on this revision.

@robobun

robobun commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:28 PM PT - Sep 28th, 2026

✅ @robobun, your commit 9638e773baf4a0dc7b1253d00df04e5772caf3b6 passed in Build #121399! 🎉


🧪   To try this PR locally:

bunx bun-pr 37270

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

bun-37270 --bun

Comment thread test/regression/issue/circular-error-stack.test.ts Outdated

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I reviewed this PR and the bug-hunting pass found no issues. The fix itself is small and looks correct — dropping the visited-map removal so the [Circular] guard fires, plus the has_exception() → Err(Thrown) check that mirrors print_as_prelude a few lines up. Given it adjusts the error-printer's exception-return contract (an earlier revision here broke bun-inspect.test.ts) and there are five open PRs touching adjacent guards in the same printer (#35820, #35825, #34892, #34884, #36921), a maintainer glance at the landing order would still be worthwhile.

What was reviewed:

  • Traced print_as → print_as_prelude → print_error: the value now stays in self.map across print_errorlike_object, so re-entry for cause/errors hits the existing get_or_put → [Circular] path; top-level name/message rendering doesn't go through the formatter, so it isn't shadowed.
  • Confirmed the new has_exception() guard matches the pattern at ConsoleObject.rs:3289 and leaves the exception pending (no clearException).
  • Tests: pipes drained concurrently, positive assertions only, test.concurrent for the subprocess cases; the vacuous ASSERTION FAILED check from the previous revision is gone.
Extended reasoning...

Overview

Two files: src/jsc/ConsoleObject.rs (net −14 lines in Formatter::print_error) and three new tests appended to test/regression/issue/circular-error-stack.test.ts. The source change (1) deletes the block that temporarily removed the current error from the formatter's visited map before calling vm.print_errorlike_object, and (2) adds a self.global_this.has_exception() check after that call to convert a pending exception into Err(JsError::Thrown) instead of Ok(()).

Security risks

None. This is diagnostic-output formatting for already-thrown errors; no auth, crypto, parsing of untrusted input, or resource acquisition. The change removes an unsafe scopeguard::defer! block with a raw-pointer write and replaces it with nothing, which is a net safety improvement.

Level of scrutiny

Medium. The diff is small and the mechanism is well-argued, but the error printer's recursion and exception-propagation contract is subtle: the original removed code carried a rationale comment ("circular check already done in print_as"), an earlier revision of this PR broke bun-inspect.test.ts and had to be narrowed, and five open PRs (#35820/#35825/#34892/#34884/#36921) touch adjacent guards in the same call graph. A maintainer should confirm this is the one to land and that keeping the value in the visited set has no unintended effect on non-cyclic error rendering that the existing suites don't cover.

Other factors

  • All prior review feedback (comment-cop, CodeRabbit, my two inline nits on pipe draining and the vacuous ASSERTION FAILED assertion) is addressed; every thread is resolved.
  • CI on 796adb2 was 195/196 with the one red job flagged as pre-existing on main; the latest push (60f95cd) only removes one test assertion.
  • The PR's evidence block shows the three new tests failing on unfixed debug/ASAN and release builds and passing with the fix, satisfying the fails-for-the-right-reason bar.
  • The added exception check follows the exact pattern already used at ConsoleObject.rs:3289-3290 in print_as_prelude, and per the PR description the pending exception is intentionally not cleared so Bun.inspect still rethrows genuine stack overflows (pinned by bun-inspect.test.ts).

@robobun

robobun commented Sep 11, 2026

Copy link
Copy Markdown
Collaborator Author

Two facts from work on a related crash path: an Error that holds another Error in an array own property (e.errors = [err] on a plain Error), 300 levels deep or more. All numbers are from debug+ASAN builds on linux x64.

The print_error check in this PR also fixes that path. On main, console.error, Bun.inspect, an uncaught throw and an unhandled rejection of such a chain all abort at 300 levels:

ASSERTION FAILED: Unexpected exception observed on thread ...
!exception() || m_vm.hasPendingTerminationException()
JavaScriptCore/ExceptionScope.h(63) : void JSC::ExceptionScope::assertNoExceptionExceptTermination()

JSC's property walk (JSC__JSValue__forEachPropertyImpl) throws Maximum call stack size exceeded. print_errorlike_object returns (), so print_error returned Ok(()) and the array walk called JSC again with the exception pending. On this branch, and on main plus this PR's ConsoleObject.rs change, all four sinks are clean at 300 levels. #34884 and #36602 do not stop it on their own (I built both). They fix the direct e.inner = err chain on the uncaught sinks.

One case still aborts on current main with this PR's change applied. It does not reproduce on this branch's older base.

let deep = new Error("leaf");
for (let i = 0; i < 1000; i++) {
  const next = new Error("level " + i);
  next.inner = deep;
  deep = next;
}
const top = new Error("top");
top.a = deep;
top.b = new Error("sibling");
try { console.error(top); } catch {}

The depth guard in print_error_instance_js throws and returns Ok(()). The errors_to_append loop in print_error_instance_body then starts the block for top.b with the exception pending.

Branch robobun/d0e947b4/printer-pending-exception has three test cells for both cases in test/js/bun/util/inspect-error.test.js (an error the printer cannot finish), and an 11-line check at the head of that loop. I did not open it as a PR, because its first hunk is the same check as the one here. The cleaner fix for the second case is at the producer: return Err from the depth guard in print_error_instance_js, and let print_errorlike_object return JsResult<()> so that print_error can use ?.

Both cases need an assert build. A release build does not crash on them through console.error or Bun.inspect.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

A separate report reached me: console.log([err]) aborts a debug or ASAN build when an own property of err throws while it prints. The print_error check in this PR fixes it. I applied the ConsoleObject.rs change of this PR to main (09bb546) and tested a debug build.

const e = new Error("boom");
e.when = Object.assign(new Date(0), { toJSON() { throw new Error("toJSON threw"); } });
try { console.log([e]); } catch (err) { console.log("threw", err.message); }
console.log("survived");
  • main: ASSERTION FAILED: Unexpected exception observed ... !exception() || m_vm.hasPendingTerminationException() ... JSC::ExceptionScope::assertNoExceptionExceptTermination(), exit 134. print_error returns Ok, then print_array calls for_each_property_non_indexed with the exception pending.
  • main with this PR: prints up to when:, then threw toJSON threw and survived, exit 0. A release build already does this.
  • The same is true for [1, e], [[e]], { wrapped: [e] }, [new Error("outer", { cause: e })], new Map([["k", e]]).entries(), console.table(new Map([[e, 1]])) (there collect_row reads the Map value next), Bun.inspect([e]) and the REPL. A Number, String or RegExp object with a throwing toString as the property value is another trigger.

One sibling is not covered by this PR. MapIteratorCtx::for_each ignores a Map key that failed to print. It then reads the tag of the value with the exception pending. Custom inspect is off inside an Error own property, so Tag::get_advanced goes straight to getOwn("$$typeof"), which asserts.

const e = new Error("boom");
e.entries = new Map([[Object.assign(new Date(0), { toJSON() { throw new Error("toJSON threw"); } }), {}]]);
console.log(e); // same assertion on a debug build, with or without this PR
Change that fixes the sibling, and a test for all of the shapes above
--- a/src/jsc/ConsoleObject.rs
+++ b/src/jsc/ConsoleObject.rs
@@ pub mod formatter { (MapIteratorCtx::for_each)
                 let Ok(key_tag) = Tag::get_advanced(key, global_object, opts) else {
                     return;
                 };
 
-                let _ = this.formatter.format::<C>(
-                    key_tag,
-                    this.writer,
-                    key,
-                    this.formatter.global_this,
-                );
+                if this
+                    .formatter
+                    .format::<C>(key_tag, this.writer, key, this.formatter.global_this)
+                    .is_err()
+                {
+                    return;
+                }
                 this.writer.write_all(b": ").expect("unreachable");

The C++ iteration stops at the pending exception after the callback returns, so print_map_like returns Err.

Test for test/js/bun/util/inspect-error.test.js. On a debug build of main it fails at the second call. With this PR it fails only at the last call. With this PR and the change above it passes.

test("an own property of an Error that throws while it is printed", async () => {
  const calls = [
    "console.log(e)",
    "console.log([e])",
    "console.log([1, e])",
    "console.log([[e]])",
    "console.log({ wrapped: [e] })",
    'console.log([new Error("outer", { cause: e })])',
    'console.log(new Map([["key", e]]).entries())',
    "console.table(new Map([[e, 1]]))",
    "Bun.inspect([e])",
    "console.log(hostileMapKey)",
  ];
  await using proc = Bun.spawn({
    cmd: [
      bunExe(),
      "-e",
      `
      const hostile = () => Object.assign(new Date(0), { toJSON() { throw new Error("toJSON threw"); } });
      const e = new Error("boom");
      e.when = hostile();
      const hostileMapKey = new Error("boom");
      hostileMapKey.entries = new Map([[hostile(), {}]]);
      const attempt = (name, call) => {
        try {
          call();
          console.error(name + ": returned");
        } catch (err) {
          console.error(name + ": threw " + err.message);
        }
      };
      ${calls.map(call => `attempt(${JSON.stringify(call)}, () => ${call});`).join("\n")}
      `,
    ],
    env: bunEnv,
    stdout: "pipe",
    stderr: "pipe",
  });
  const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
  expect(stderr).toBe(calls.map(call => `${call}: threw toJSON threw\n`).join(""));
  expect(exitCode).toBe(0);
});

One interaction to know about. on_unhandled_rejection in src/jsc/web_worker.rs replaces the reported error with the exception that format2 returns. With the print_error check, an uncaught worker Error that has such a property now takes that path, and the parent 'error' listener receives null (before: an Error whose message was the cut-off rendered text). #38560 fixes that path for every formatter throw.

@robobun

robobun commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator Author

A scope note, from a measurement of the open error-printer PRs against four native stack overflows (table in #36602 (comment)).

@robobun

robobun commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Do not merge this revision yet. A check of deep error chains found a regression in this diff.

  • Input: a node:worker_threads Worker throws an error that carries a chain of 500 errors linked by an assigned cause, by errors, or by an own property. The chain has no cycle.
  • main: the 'error' event of the parent gets an Error. Its message is the rendered text of the printer.
  • This PR: the parent gets null. Node gives the Error with its own message (l499).
  • Cause: Formatter::print_error now returns Err when the printer left an exception pending. on_unhandled_rejection (src/jsc/web_worker.rs:1209) then replaces the error of the worker with the result of take_exception(). That result is the JSC::Exception cell, not the Error. The structured clone of the cell arrives as null.

Repro:

const { Worker } = require("node:worker_threads");
const w = new Worker(
  `let e = new Error("leaf"); for (let i = 0; i < 500; i++) { const x = new Error("l" + i); x.cause = e; e = x; } throw e;`,
  { eval: true },
);
w.on("error", x => console.log(x === null ? "null" : x.message));

A fix is in progress: the Worker must deliver the error of the user when only the rendering fails.

@robobun robobun changed the title error printer: fix infinite recursion when an error reaches itself through cause and errors error printer: one render per error, [Circular] under the key that closes the cycle Sep 27, 2026
@robobun
robobun force-pushed the farm/6002b032/error-printer-cyclic-cause-errors branch from 60f95cd to 8d69b30 Compare September 27, 2026 17:48
@robobun
robobun changed the base branch from main to farm/6002b032/formatter-visited-helpers September 27, 2026 17:48
@robobun
robobun marked this pull request as draft September 27, 2026 17:48
Comment thread src/jsc/ConsoleObject.rs Outdated
Comment thread src/jsc/ConsoleObject.rs Outdated
Comment thread src/jsc/VirtualMachine.rs Outdated
Comment thread src/jsc/VirtualMachine.rs Outdated
Comment thread src/jsc/VirtualMachine.rs Outdated

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked the new VisitedRemove::new guard in print_error_instance_body for aliasing problems — it takes &raw mut formatter.map (no reference is created) and mirrors the existing guard in print_as, so it is not a new pattern — and the expect("unreachable") on get_or_put in visited_enter, which is the same call moved out of print_as and the old errors_to_append loop rather than a new panic path. The double render of a self-listing AggregateError is pre-existing (the member walk is untouched here).

Extended reasoning...

The change moves visited-set ownership for Error rendering from the console formatter into the native error printer in src/jsc/ConsoleObject.rs and src/jsc/VirtualMachine.rs, adds a raw-pointer RAII guard armed by a Cell, and adds subprocess tests; it touches no security-sensitive surface. Six confirmed findings are posted inline (exception-propagation change at the stack bound, output nits, a stale SAFETY comment, and a test-coverage gap), so a human look is already signalled; this note only records the memory-safety candidates that were examined and ruled out as pre-existing patterns.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟡 src/jsc/VirtualMachine.rs — Minor: an error whose cycle closes through a non-enumerable cause (the new Error(msg, { cause }) form) prints a bare [Circular] line after the stack trace instead of cause: [Circular], under the key. The fallback at src/jsc/VirtualMachine.rs:7205-7208 pushes cause into errors_to_append without the circular check the enumerable loop applies at src/jsc/VirtualMachine.rs:7096. Fix: apply the same in-place [Circular] rendering to the non-enumerable cause (compare against error_instance and visited_contains) so both spellings of cause print under the key, and add that shape to the test matrix. [also at: src/jsc/VirtualMachine.rs:7250 - nit: A cycle closed by a non-enumerable cause (the new Error(msg, { cause }) form) prints a bare [Circular] after the stack trace with no cause: key, unlike the enumerable case.]

    Why this was flagged

    Input: const e = new Error("x", { cause: undefined }); e.cause = e; throw e; (the constructor option makes cause a non-enumerable own property, and assignment keeps that attribute), or const a = new Error("a"); const b = new Error("b", { cause: a }); a.cause = b; throw a;. Any printer entry reaches print_error_instance_body. The property iterator at src/jsc/VirtualMachine.rs:7070 is created with DontEnumPropertiesMode::Exclude (src/jsc/bindings/JSPropertyIterator.cpp:87), so the loop with the new circular check at src/jsc/VirtualMachine.rs:7096 never sees cause. The fallback at src/jsc/VirtualMachine.rs:7203-7211 pushes the cyclic cause into errors_to_append unconditionally. At src/jsc/VirtualMachine.rs:7239 the error is recorded, and the loop at 7244 writes "\n" then print_error_instance_js writes [Circular] at src/jsc/VirtualMachine.rs:6676 with no key and no trailing comma. The user sees error: x followed by the frames and then a lone [Circular] line, while the enumerable spelling of the same cycle prints…

    Verification: nit — triggered whenever a cyclic error's cycle closes through a non-enumerable cause (the new Error(msg, { cause }) form, which per spec InstallErrorCause creates cause via CreateNonEnumerableDataProperty, and a later e.cause = e assignment keeps the DontEnum attribute). Mechanism verified in /home/claude/bun/src/jsc/VirtualMachine.rs: the own-property iterator at 7070-7081 is built on…

  • 🟡 src/jsc/ConsoleObject.rs — Maintainers reading the VisitedRemove Drop get a SAFETY comment that no longer describes its callers. src/jsc/ConsoleObject.rs:1562-1563 says map/armed "were taken via addr_of! on locals", but the new VisitedRemove::new caller at src/jsc/VirtualMachine.rs:7060-7061 passes a field of a &mut Formatter parameter and Cell::as_ptr(), and the # Safety clause on new (src/jsc/ConsoleObject.rs:1548) omits the no-live-borrow condition the Drop comment relies on. Fix: state the real contract once on VisitedRemove::new (pointers outlive the guard and no other borrow of the map is live at drop) and make the Drop comment reference it, so both the print_as literal site and the new site are covered.

    Why this was flagged

    REVIEW.md and the root CLAUDE.md require SAFETY comments above unsafe to be accurate. After this PR the Drop at src/jsc/ConsoleObject.rs:1562-1566 is reached from two constructors: the struct literal in print_as (src/jsc/ConsoleObject.rs:3324, &raw mut self.map, a field of &mut self, not a local) and the new unsafe fn new call at src/jsc/VirtualMachine.rs:7058-7064 (&raw mut formatter.map and recorded.as_ptr() from a Cell<bool>). Neither matches "addr_of! on locals". The # Safety doc on new (src/jsc/ConsoleObject.rs:1548-1549) only requires the pointers to stay valid, while the Drop's second clause ("no other borrow is live at drop") is what actually makes the dereference sound, so a future caller can satisfy the documented contract and still violate the real one. The dismissal accepted that the invariant happens to hold today; the finding is that the documented contract is wrong for a newly added public unsafe API. Remedy: rewrite the # Safety clause on new to include both conditions and correct the Drop comment.

    Verification: nit. Triggering condition: any maintainer reading or auditing the unsafe block in VisitedRemove::drop after this PR. The Drop SAFETY comment at /home/claude/bun/src/jsc/ConsoleObject.rs:1562-1563 is unchanged from base and still reads "map/armed were taken via addr_of! on locals that outlive this guard; no other borrow is live at drop." After this PR the struct becomes pub(crate)…

Comment thread src/jsc/ConsoleObject.rs
Comment thread src/jsc/VirtualMachine.rs
Comment thread test/js/bun/util/inspect-error.test.js
Comment thread src/jsc/VirtualMachine.rs
…oses the cycle

An Error that reaches itself through two of its own properties crashed the
process when it was printed:

    const e = new Error('cyc'); e.cause = e; e.errors = [e]; throw e;

The set of values that are being rendered lived with two of the callers
that start the render of an error. The console formatter recorded an
error and removed it again before it called the printer. The loop that
prints the cause recorded the next error. The uncaught entries recorded
nothing.

Every render of an error passes print_error_instance_js. It now writes
[Circular] for an error that a caller further up is rendering. The body
records the error before the first render it nests, and
print_error_instance_js removes the record when the body returns. An
error that nests no render is never recorded. The console formatter no
longer records errors. It keeps its stack check for them.

An Error-valued own property that closes a cycle is printed in place,
under its key. That includes a cause that is not enumerable. A member of
an AggregateError that is being rendered prints [Circular] on its own
line. The walk over the members is not changed in any other way.
@robobun
robobun force-pushed the farm/6002b032/formatter-visited-helpers branch from 18a3f20 to 7bfdf30 Compare September 27, 2026 19:21
@robobun
robobun force-pushed the farm/6002b032/error-printer-cyclic-cause-errors branch from ca0e47c to f2c583d Compare September 27, 2026 19:21
@robobun

robobun commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Revision f2c583d answers the review of 2026-09-27. It replaces the revision that the hold notice of 2026-09-26 is about.

Changed for the findings:

  • A cycle that closes through a cause that is not enumerable (new Error(msg, { cause })) now prints cause: [Circular], in the property block, like an assigned cause. Two values for it are in the test table.
  • The console formatter runs its stack check for an error again. Tag::Error stays in can_have_circular_references. print_as_prelude skips only the record.
  • A member of an AggregateError that is being rendered prints [Circular] on its own line.
  • The body does not use VisitedRemove now. print_error_instance_js removes the record after the body returns, so the guard and its SAFETY comment are the same as on main.
  • The test for two renders without a cycle uses an error with meta = {}, so each render records the error and removes the record.

Not changed: an assigned cause is rendered twice at each nested level. Main does the same. The fix changes text for chains without a cycle, so it is a separate change.

The PR is a draft until the release numbers are in the description.

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline nit, I also checked the record/release pairing of the new recorded flag: the JSValue::ZERO caller in print_externally_remapped_zig_exception can never set it (both property branches are skipped in that mode), print_error_instance_js removes the entry before result? so error exits are covered, and Tag::Error is only produced for JSType::ErrorInstance, so every value that now skips the prelude insert is caught by the visited_contains short-circuit — none of these leak a visited-map entry.

Extended reasoning...

The push since the last review moved the stack check ahead of the is_recorded_by_its_printer early return, added the trailing newline for [Circular] AggregateError members, and nested an object in the "printed twice" fixture, addressing the earlier inline nits. The remaining posted finding is a dead circular branch in the append loop; no security-sensitive surface is touched.

Comment thread src/jsc/VirtualMachine.rs
…ng rendered

The loop over the own properties prints such an error in place, so it
never reaches the queue.

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

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.

2 participants