Repository navigation
Conversation
WalkthroughA guard is added to processPromise in expect.zig to synchronously trigger lazy work on pending promises by calling their then() method with no-op handlers. A regression test file is added for issue Changes
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
|
Updated 2:27 AM PT - May 12th, 2026
❌ @robobun, your commit 196ccbf has 1 failures in
🧪 To try this PR locally: bunx bun-pr 27260That installs a local version of the PR into your bun-27260 --bun |
|
✅ a91ae — Looks good! Reviewed 2 files across |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/regression/issue/14670.test.ts`:
- Around line 17-19: The "expect($`bad-command`).rejects.toThrow() without
quiet" test incorrectly uses .quiet(), duplicating the quiet-path; update the
test so it invokes the command without .quiet() (i.e., call $`bad-command`
directly) and keep the assertion expect(...).rejects.toThrow() so the non-quiet
behavior of $`bad-command` is actually tested; locate the test named
"expect($`bad-command`).rejects.toThrow() without quiet" and remove the .quiet()
call on the $`bad-command` expression.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
src/bun.js/test/expect.zigtest/regression/issue/14670.test.ts
…n expect() expect($`bad-command`).rejects.toThrow() hung forever because ShellPromise is lazy — it only starts the shell when .then() is called. expect().resolves / .rejects / toThrow(fn-returning-promise) called waitForPromise() which polls the internal JSC promise state directly without going through .then(), so the shell never ran and the promise never settled. Before waitForPromise(), call the user-visible .then() (with no handlers) if the promise is still pending, triggering any lazy initialization. The returned promise is marked handled to avoid spurious unhandled-rejection warnings. Applied at all three waitForPromise() sites in expect.zig: processPromise (.resolves/.rejects), getValueAsToThrow (expect(fn).toThrow()), and executeCustomMatcher. Fixes #14670
e09b0b8 to
196ccbf
Compare
| } | ||
|
|
||
| if (return_value.asAnyPromise()) |promise| { | ||
| try triggerLazyPromise(globalThis, return_value, promise); |
There was a problem hiding this comment.
🔴 If triggerLazyPromise throws here (e.g. a Promise subclass with a throwing .then getter/method or a species constructor that fails NewPromiseCapability), the try propagates out before scope.apply(vm) runs at line 606/625, leaving vm.onUnhandledRejection stuck on the quiet capture handler for the rest of the file. Before this PR there were no fallible calls between the override at line 593 and the restore. Add errdefer scope.apply(vm); after line 590 (or convert to defer and drop the explicit calls), matching the pattern in html_rewriter.zig:447-456.
Extended reasoning...
What the bug is
getValueAsToThrow temporarily swaps out the VM's unhandled-rejection handler:
// expect.zig:590-595
var scope = vm.unhandledRejectionScope();
const prev_unhandled_pending_rejection_to_capture = vm.unhandled_pending_rejection_to_capture;
vm.unhandled_pending_rejection_to_capture = &return_value;
vm.onUnhandledRejection = &VirtualMachine.onQuietUnhandledRejectionHandlerCaptureValue;
return_value_from_function = value.call(...) catch |err| globalThis.takeException(err);
vm.unhandled_pending_rejection_to_capture = prev_unhandled_pending_rejection_to_capture;The handler is restored exclusively via scope.apply(vm) (VirtualMachine.zig:461-465) at line 606 (promise branch) or line 625 (fall-through). Prior to this PR every operation between line 593 and those restore points was infallible — value.call(...) uses catch, and handleRejectedPromises() / waitForPromise() return void — so scope.apply(vm) was always reached.
This PR inserts try triggerLazyPromise(globalThis, return_value, promise) at line 604, before scope.apply(vm). triggerLazyPromise does try value.get(globalThis, "then") and try then_fn.call(...), either of which can return error.JSError. When that happens, the try propagates the error out of getValueAsToThrow and scope.apply(vm) is never executed.
How it can be triggered
Any Promise subclass whose JS-level .then invocation throws synchronously:
- A throwing
thengetter (get then() { throw ... }). - An overridden
then()that throws before returning. - A subclass without
Symbol.specieswhose constructor doesn't accept the standard executor —Promise.prototype.thencalls NewPromiseCapability on the species constructor and throws aTypeErrorifresolve/rejectaren't set.
This PR's whole purpose is to support Promise subclasses with custom .then() overrides (ShellPromise, LazyReject in the test), so a misbehaving .then() on the same path is squarely within the new surface area.
Why nothing else restores the handler
UnhandledRejectionScope.apply (VirtualMachine.zig:461-465) is the only thing that writes back the saved onUnhandledRejection/onUnhandledRejectionCtx/unhandled_error_counter. The callers of getValueAsToThrow (toThrow.zig:35, expect.zig:630) just try and propagate. The test runner installs its own handler exactly once per file at test_command.zig:2120-2121, before the repeat_count loop — there is no per-test reset, and a grep across src/test_runner/ confirms no other assignment.
Impact
After the leak, vm.onUnhandledRejection remains onQuietUnhandledRejectionHandlerCaptureValue (VirtualMachine.zig:472-477), which only increments unhandled_error_counter and writes through unhandled_pending_rejection_to_capture if non-null. unhandled_pending_rejection_to_capture was restored at line 595 (so there is no dangling stack write), but the jest handler that normally fails the test on an unhandled rejection (jest.on_unhandled_rejection.onUnhandledRejection) is no longer installed. Every subsequent test in the same file will silently swallow unhandled promise rejections instead of failing.
Step-by-step proof
- User writes:
class Bad extends Promise { then() { throw new Error("nope"); } } test("a", () => expect(() => new Bad(r => {})).toThrow()); test("b", () => { Promise.reject(new Error("should fail")); });
- Test "a":
getValueAsToThrowruns, line 593 setsvm.onUnhandledRejection = onQuietUnhandledRejectionHandlerCaptureValue. return_valueis theBadinstance;return_value.asAnyPromise()succeeds (it extendsPromise), entering the branch at line 603.- Line 604:
triggerLazyPromisecallsthen_fn.call(...), which throws →error.JSErrorpropagates viatry. - Lines 605-606 and 625 are skipped;
scope.apply(vm)never runs.vm.onUnhandledRejectionis still the quiet handler. - Test "a" fails with the thrown error (fine), but test "b" now runs with the quiet handler installed: its unhandled rejection is silently counted instead of being reported, and the test incorrectly passes.
Fix
Make the restore exception-safe — the codebase already does this in html_rewriter.zig:447-456 with defer { ...; scope.apply(vm); }. Either:
var scope = vm.unhandledRejectionScope();
errdefer scope.apply(vm);or convert both explicit scope.apply(vm) calls to a single defer scope.apply(vm); after line 590.
Reproduction
bun testhangs forever (never exits).Root cause
ShellPromiseis a lazy Promise subclass — it only starts the shell interpreter when.then()is called:expect().resolves/.rejectsextracts the internalJSPromiseviaasAnyPromise()and blocks on it withwaitForPromise(), which watches the internal promise state directly without ever calling.then(). So#run()never fires, the shell never runs, the promise never settles, andwaitForPromise()spins forever.The same hang occurs with
expect(() => $...).toThrow()(the function-returning-a-promise path), and with any user-defined Promise subclass that defers work to.then().Fix
Before
waitForPromise(), if the promise is still pending, call the user-visible.then()on the original value — with no handlers — to trigger any lazy initialization. This matches whatawait valuedoes observably. The returned promise is marked handled so a rejection there doesn't surface as an unhandled-rejection warning (we observe the original promise, not the chained one).Applied at all three
waitForPromise()sites inexpect.zig:processPromise—.resolves/.rejectsgetValueAsToThrow—expect(fn).toThrow()wherefnreturns a promiseexecuteCustomMatcher— async custom matchersVerification
The regression test spawns a subprocess with a 20s timeout so unfixed builds fail cleanly instead of hanging the test runner. It covers
.rejects.toThrow(),.resolves,expect(() => $...).toThrow(), and a shell-free lazy Promise subclass.Closes #14670