Skip to content

fix(test): invoke JS-level then() for lazy promise subclasses in expect().rejects/resolves - #27260

Closed
robobun wants to merge 1 commit into
mainfrom
claude/fix-shell-rejects-timeout
Closed

robobun wants to merge 1 commit into
mainfrom
claude/fix-shell-rejects-timeout

Conversation

@robobun

@robobun robobun commented Feb 20, 2026 •

Copy link
Copy Markdown
Collaborator

Reproduction

import { expect, test } from "bun:test";
import { $ } from "bun";

test("", async () => {
  expect($`bad-command`).rejects.toThrow();
});

bun test hangs forever (never exits).

Root cause

ShellPromise is a lazy Promise subclass — it only starts the shell interpreter when .then() is called:

then(onfulfilled, onrejected) {
  this.#run();  // <-- shell starts here
  return super.then(onfulfilled, onrejected);
}

expect().resolves / .rejects extracts the internal JSPromise via asAnyPromise() and blocks on it with waitForPromise(), which watches the internal promise state directly without ever calling .then(). So #run() never fires, the shell never runs, the promise never settles, and waitForPromise() 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 what await value does 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 in expect.zig:

  • processPromise — .resolves / .rejects
  • getValueAsToThrow — expect(fn).toThrow() where fn returns a promise
  • executeCustomMatcher — async custom matchers

Verification

git stash push -- src/  && bun bd test test/regression/issue/14670.test.ts  → 4 fail (subprocess hangs, killed by timeout)
git stash pop           && bun bd test test/regression/issue/14670.test.ts  → 4 pass

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

@coderabbitai

coderabbitai Bot commented Feb 20, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

A 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 #14670 to verify ShellPromise behavior with rejects.toThrow() does not timeout.

Changes

Cohort / File(s) Summary
Promise Handling Fix
src/bun.js/test/expect.zig
Adds a guard to processPromise that detects when a resolved/rejected promise is still pending and attempts to trigger lazy initialization by calling value.then() with no-op handlers before waiting on the promise.
Regression Test for Issue #14670
test/regression/issue/14670.test.ts
Introduces new test cases verifying that ShellPromise with rejects.toThrow() does not timeout, covering both awaited and non-awaited variants with shell commands.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main fix: invoking JS-level then() for lazy promise subclasses in expect().rejects/resolves, which directly addresses the timeout issue in issue #14670.
Linked Issues check ✅ Passed The PR directly addresses issue #14670 by implementing a fix that ensures lazy ShellPromise initialization runs when using expect().rejects.toThrow(), resolving the timeout issue described in the linked issue.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the timeout issue in issue #14670: the processPromise() guard invokes JS-level then() for lazy initialization, and the regression test verifies the fix covers the reported behavior.
Description check ✅ Passed The PR description provides a comprehensive explanation of the issue, root cause, fix, and verification steps.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@robobun

robobun commented Feb 20, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 2:27 AM PT - May 12th, 2026

❌ @robobun, your commit 196ccbf has 1 failures in Build #53651 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 27260

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

bun-27260 --bun

@claude

claude Bot commented Feb 20, 2026

Copy link
Copy Markdown
Contributor

✅ a91ae — Looks good!

Reviewed 2 files across src/bun.js/test/ and test/regression/issue/: Fixes expect().rejects.toThrow() hanging forever on lazy promise subclasses by invoking the JS-level then() to trigger initialization.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 1a86bd8 and 130c2da.

📒 Files selected for processing (2)
  • src/bun.js/test/expect.zig
  • test/regression/issue/14670.test.ts

Comment thread test/regression/issue/14670.test.ts Resolved
Comment thread test/regression/issue/14670.test.ts Resolved
…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
@robobun
robobun force-pushed the claude/fix-shell-rejects-timeout branch from e09b0b8 to 196ccbf Compare May 12, 2026 08:17
}

if (return_value.asAnyPromise()) |promise| {
try triggerLazyPromise(globalThis, return_value, promise);

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.

🔴 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 then getter (get then() { throw ... }).
  • An overridden then() that throws before returning.
  • A subclass without Symbol.species whose constructor doesn't accept the standard executor — Promise.prototype.then calls NewPromiseCapability on the species constructor and throws a TypeError if resolve/reject aren'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

  1. 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")); });
  2. Test "a": getValueAsToThrow runs, line 593 sets vm.onUnhandledRejection = onQuietUnhandledRejectionHandlerCaptureValue.
  3. return_value is the Bad instance; return_value.asAnyPromise() succeeds (it extends Promise), entering the branch at line 603.
  4. Line 604: triggerLazyPromise calls then_fn.call(...), which throws → error.JSError propagates via try.
  5. Lines 605-606 and 625 are skipped; scope.apply(vm) never runs. vm.onUnhandledRejection is still the quiet handler.
  6. 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.

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.

Timeout in test when expecting promise from bun shell to throw

1 participant