Skip to content

node:test: do not call the public Promise methods in the runner - #46959

Closed
robobun wants to merge 2 commits into
robobun/410b6466/node-test-thenable-failurefrom
robobun/410b6466/node-test-promise-methods
Closed

robobun wants to merge 2 commits into
robobun/410b6466/node-test-thenable-failurefrom
robobun/410b6466/node-test-promise-methods

Conversation

@robobun

@robobun robobun commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • Under bun test, test() throws when the file replaced Promise.resolve: error: replaced Promise.resolve at new TestNode, then # Unhandled error between tests, 0 pass. Node passes.
  • The runner calls public Promise methods at 33 sites, first at src/js/node/test.ts:1556. A replaced then makes subtests fail or not run.

Fix

  • The runner uses private names (Promise.$resolve, $then, $newPromise) and await. A subtest chain link is an async function that awaits the previous link.
  • Correct: over the new fixture the runner makes 0 public Promise calls (base: 435).
  • From review: a hook that aborts its signal and then throws leaves no unhandled rejection.
  • Verified: test/js/node/test_runner/node-test.test.ts, 7 new tests, 6 fail on the base. Self-reviewed as the earlier single PR: 10 concerns raised, 10 addressed.

Background

  • Built-in modules can call private names that user code cannot replace.
  • A promise resolved with a second promise calls the public then of the second one. await of a native promise calls no method.
  • Considered .$then for .then: 4 chain links pass an async callback, so a replaced then still runs.
  • The base of this PR is node:test: fail a test whose error is a thenable #46919.

Downsides

  • Two timings change. A subtest whose skip is set after t.test() returned settles one microtask earlier. A thenable from an inline describe() callback gets 1 then() call (base: 2).
  • A subtest with a timeout enters JS from native code 10 times (base: 9), an inline suite 17 (15). Release binary text: +749 B.
  • Other built-in modules still call public Promise methods: 169 sites in 43 files.
Notes

Origin. A differential run against Node found this. The tracker has no issue for it. The smallest file:

import { test } from "node:test";
const original = Promise.resolve;
Promise.resolve = () => { throw new Error("replaced Promise.resolve"); };
try {
  test("declared while Promise.resolve is replaced", () => {});
} finally {
  Promise.resolve = original;
}

Node v26.3.0: 1 pass. The base (#46919 at 022175c) and main: 0 pass, 1 fail, 1 error. This branch: 1 pass. The same file with Promise.prototype.then and a subtest: the subtest fails on the base and passes here and in Node.

Why a swap of the method names is not enough. The engine calls the public then when a promise is resolved with a native promise. Checked on JSC and on V8 with a wrapper that counts calls of Promise.prototype.then:

operation public then calls
originalThen.call(p, async () => {}) 1
an async function that does return promise 1
resolve(promise) in a new Promise executor 1
await promise 0
a then callback that returns no promise 0

On the base four chain links resolve a promise with a promise: subtestChain.then(async () => ...) in scheduleImmediateBeforeHook, .then(run) in scheduleSubtest and scheduleSuiteSubtest, and .then(() => gate.promise) in addSuite. A throwing then rejects such a link, and the links after it do not run.

What changed in the runner (src/js/node/test.ts)

  • TestNode.subtestChain starts as undefined. No promise is made for a node that has no subtest.
  • appendSubtestStep(owner, step) appends an async link. The step awaits the link before it, does its work and records a failure on its node. The three async links use it: a subtest, an inline suite, a before hook added to a running test. The stored link is step(previous).$then(). That plain reaction keeps the links that wait out of the async stack of the step that runs.
  • A skipped subtest or suite is a plain $then link. Its callback returns nothing.
  • An inline suite has a gate that its children wait for. awaitSuiteGate() awaits the link before the suite, one more microtask, and then the gate. The gate opens when the value of the describe() callback settles.
  • untilStopped(stop, promise) replaces Promise.race([stop, promise]) for the timeout of a test. The race of a hook rejects one stop promise from its timer and its abort listener, and then uses untilStopped() too.
  • Two handlers that only kept a rejection from a report are gone: the .catch() on the stop promise and the one on the plan promise. untilStopped() attaches a reaction to each of them at once.
  • run(): await undefined in place of await Promise.resolve(), and $pokePromiseAsHandled() in place of .catch(() => {}) on the promise that reads the stderr of a child.
  • internal/test_runner/mock_timers.ts: $newPromise() in place of Promise.withResolvers().

Results that change for a file that replaces nothing (each has a test in fixtures/33-subtest-chain.js, and Node v26.3.0 gives the same verdict for each test of that file)

  • A describe() callback in a running test that returns a thenable: then() is called 1 time (base: 2).
  • A thenable from such a callback whose then() throws fails its suite (base: the throw leaves describe() and fails the test with that error).
  • A hook with a signal that aborts that signal and then throws: the abort is not reported (base and main: the test that runs fails with AbortError, Node passes it). The abort rejects the stop promise of the hook before untilStopped() gives it a reaction, so the runner marks that promise as handled. Only a hook with a signal pays for the mark.
  • A subtest whose options object gets skip = true after t.test() returned settles one microtask earlier. Node ignores that assignment.

Measurements (the base is #46919 at 022175c. Its numbers for a test that passes are the numbers of main)

  • Public Promise calls over fixtures/32-replaced-promise-methods.js with its last block removed (that block throws at declaration on the base). A preload wraps the ten methods for the whole process. Base: 436 (resolve 172, then 228, race 19, catch 11, withResolvers 6). This branch: 1. The fixture makes that one call itself. Node v26.3.0 passes the fixture, so each recorded window is empty.
  • Public Promise member tokens in the compiled node/test.js: 33 to 0 (resolve 10, then 14, race 4, catch 4, withResolvers 1). mock_timers.js: 1 to 0.
  • Heap cells for each unit (bun:jsc heapStats(), slope between N=100 and N=300, GC off, debug build), base to this branch: declaration of a test 15 to 14, run of a top-level test 39 to 39, awaited subtest 62 to 61, skipped subtest 16 to 14, subtest with a timeout 79 to 75, top-level test with a timeout 55 to 51, inline suite with one test 118 to 117, subtest under beforeEach and afterEach 78 to 77, subtest under a beforeEach with a timeout 87 to 88, two subtests with one await 125 to 123.
  • Microtask jobs for each unit (gdb breakpoint on JSC::MicrotaskQueue::enqueue, N=0 and N=200, debug build): top-level test 5 to 5, awaited subtest 11 to 10, skipped subtest 3 to 3, subtest with a timeout 12 to 11, inline suite with one test 21 to 19.
  • Calls from native code into JS for each unit (breakpoints on the vmEntryToJavaScript* entries): top-level test 6 to 6, awaited subtest 9 to 9, skipped subtest 3 to 3, subtest with a timeout 9 to 10, inline suite with one test 15 to 17. An await resumes in JS where a then reaction with a native callback did not.
  • Instructions in user space for each unit on release builds ((N=20000 minus N=0) / 20000, median of 7 interleaved runs). JIT off: top-level test 96,278 to 93,503 (ranges 94,920 to 98,660 and 90,831 to 96,218), awaited subtest 58,047 to 58,043 (ranges 57,766 to 58,395 and 57,956 to 58,224). JIT on: top-level test 38,068 to 37,062, awaited subtest 28,790 to 28,945. The ranges overlap in all four.
  • Release binary, same build directory, only the two files differ: text 107,557,799 to 107,558,548 B (+749), data +0, bss +0. Compiled node/test.js 65,067 to 65,676 B, mock_timers.js 18,717 to 18,857 B. Host functions added: 0.
  • perf is not in the build container. The instruction counts come from perf_event_open with PERF_COUNT_HW_INSTRUCTIONS for user space, the counter that perf stat -e instructions:u reads.

Order that user code sees. 54 traces record the order of subtest bodies and of the code after await t.test() against a counter of microtasks. 44 are the same as on the base. 9 differ for the subtest whose skip is set late. 1 differs for the describe() thenable. The AsyncLocalStorage store that a subtest body sees is the same.

Existing tests. Of the 31 runs of the existing fixtures, 30 print the same output as on main. 07-failing-hooks.js differs in two stack frames of the runner. The two fixtures of #46919 print the same output on the base and on this branch.

Vendored Node tests. 112 of the 113 vendored Node tests that use node:test give the same result as on main on the debug build. The other one, test-runner-mock-timers-scheduler.js, asserts that its first mocked wait takes less than 100 ms of wall-clock time. On the debug build that time is at the limit: median 98 ms on main and 100 ms on this branch, and the test fails in 7 and in 12 of 20 runs. On release builds the time is 2 ms on both (20 runs each), and the test passes. A mocked wait after the first one takes the same time on both (0.11 ms on the debug build).

Coverage. 51 variants of the compiled runner each put one public call back or remove one part: each changed call site, the await of the link before in each step, the extra microtask and the wait of the gate, the plain reaction at the end of a link, the order of an abort against a hook that ended, the mark on the stop promise of a hook, and the record of a describe() callback that rejects. At least one new test fails for each. Review found that the last of these had no test: two tests of 33-subtest-chain.js had suites with todo, so they passed with and without that record. The test now compares the errors and the verdicts of that fixture with an exact list. One of the 7 new tests passes on the base: it pins that an error of a test:stderr listener of run() still goes to the stream only.

Not changed

  • A describe() callback in a running test that awaits its own child test waits until the test times out. Node passes. The base does the same.
  • A subtest declared after its parent finished resolves with no report. Node reports a failed test.
  • The constructor and Symbol.species lookups of then stay, as in Node.
  • await of a native promise reads its constructor. A file that replaces Promise.prototype.constructor makes each await call the public then(), in this runner and in the runner of Node. Node v26.3.0 makes 11 such calls for a test with two subtests, and 0 with the intrinsic constructor. The fixture says that it does not cover this.
  • The other built-in modules. The count in Downsides comes from a lint rule for .then(), .catch(), .finally() and the static Promise methods over src/js. The rule is not part of this PR.

Other PRs


[human-review] gate passed · iteration 0 · 6 files touched

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

test/js/node/test_runner/node-test.test.ts:
(pass) node:test > should run hooks in the right order [1992.82ms]
(pass) node:test > should run basic tests [2025.68ms]
(pass) node:test > should run tests with different variations [1802.90ms]
(pass) node:test > should run async tests [1896.39ms]
(pass) node:test > should run all tests from multiple files [2240.46ms]
(pass) node:test > should run test() and describe() called inside another test() as subtests [1898.96ms]
(pass) node:test > should run before hooks created on a running test once and validate hook options [1923.98ms]
(pass) node:test > should fail tests whose hooks, bodies, or inline suite callbacks fail [2002.83ms]
(pass) node:test > should support done callbacks in tests and hooks [1833.45ms]
(pass) node:test > should count runtime t.todo()/t.skip() as todo/skip and keep runner timers real under mock timers [2068.74ms]
(pass) node:test > should count runtime t.todo()/t.skip() as todo/skip under --concurren
... (truncated)

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

test/js/node/test_runner/node-test.test.ts:
(pass) node:test > should run basic tests [56.31ms]
(pass) node:test > should run hooks in the right order [81.97ms]
(pass) node:test > should run tests with different variations [42.03ms]
(pass) node:test > should run async tests [45.54ms]
(pass) node:test > should run all tests from multiple files [79.91ms]
(pass) node:test > should run test() and describe() called inside another test() as subtests [46.27ms]
(pass) node:test > should run before hooks created on a running test once and validate hook options [52.51ms]
(pass) node:test > should fail tests whose hooks, bodies, or inline suite callbacks fail [67.69ms]
(pass) node:test > should support done callbacks in tests and hooks [57.98ms]
(pass) node:test > should count runtime t.todo()/t.skip() as todo/skip and keep runner timers real under mock timers [49.03ms]
(pass) node:test > should count runtime t.todo()/t.skip() as todo/skip under --concurrent too [51.12ms]
(pass) node:test > should run todo bodies under --todo instead of registering an empty function [48.05ms]
(pass) node:test > should forward Infinity and finite timeouts s
... (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/node/test_runner/node-test.test.ts
bun test v1.4.4 (367d939d9)

test/js/node/test_runner/node-test.test.ts:
(pass) node:test > should run hooks in the right order [2060.06ms]
(pass) node:test > should run basic tests [2162.58ms]
(pass) node:test > should run tests with different variations [1853.48ms]
(pass) node:test > should run async tests [1865.39ms]
(pass) node:test > should run all tests from multiple files [2220.86ms]
(pass) node:test > should run test() and describe() called inside another test() as subtests [2027.47ms]
(pass) node:test > should run before hooks created on a running test once and validate hook options [2210.63ms]
(pass) node:test > should fail tests whose hooks, bodies, or inline suite callbacks fail [2194.90ms]
(pass) node:test > should support done callbacks in tests and hooks [2067.52ms]
(pass) node:test > should count runtime t.todo()/t.skip() as todo/skip and keep runner timers real under mock timers [2088.69ms]
(pass) node:test > should count runtime t.todo()/t.skip() as todo/skip under --concurren
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 1411ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/355] gen JS modules (bundle-modules)
Preprocess modules (6832ms)
Bundle modules (255ms)
Postprocesss modules (145ms)
Bundle Functions (581ms)
Generate Code (80ms)

[7.91s] Bundled "src/js" for production
  2694 kb
  202 internal modules
  12 native modules
  49 internal functions across 15 files
[2/306] build.rs build_script_build
[3/306] rustc bun_platform 
[4/306] cxx obj/src/jsc/bindings/webcore/streams/CrossRealmTransform.cpp.o
[5/306] cxx obj/src/jsc/bindings/webcore/streams/JSCrossRealmTransformState.cpp.o
[6/306] cc obj/codegen/InternalModuleRegistryConstants.S.o
[7/306] cxx obj/src/jsc/bindings/webcore/streams/JSCountQueuingStrategy.cpp.o
[8/306] cxx obj/src/jsc/bindings/webcore/streams/JSByteLengthQueuingStrategy.cpp.o
[9/306] cxx obj/src/jsc/bindings/webcore/streams/JSCompressionStream.cpp.o
[10/306] cxx obj/src/jsc/bindings/webcore/streams/BunAsyncIterableSource.cpp.o
[11/306] cxx obj/src/jsc/bindings/webcore/streams/JSCompressionStreamShared.cpp.o
[12/306] cxx obj/src/jsc/bindings/webcore/J
... (truncated)
diff hotspot
src/js/internal/test_runner/mock_timers.ts         |   4 +-
 src/js/node/test.ts                                | 159 ++++---
 .../fixtures/32-replaced-promise-methods.js        | 473 +++++++++++++++++++++
 .../node/test_runner/fixtures/33-subtest-chain.js  | 198 +++++++++
 .../34-promise-methods-replaced-before-load.js     |  72 ++++
 test/js/node/test_runner/node-test.test.ts         | 202 ++++++++-
 6 files changed, 1035 insertions(+), 73 deletions(-)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                                                      reads  edits  tests
src/js/internal/test_runner/mock_timers.ts                    1      2     82
src/js/node/test.ts                                           9      5     98
…ode/test_runner/fixtures/32-replaced-promise-methods.js      0      0     84
test/js/node/test_runner/fixtures/33-subtest-chain.js         0      0     81
…ner/fixtures/34-promise-methods-replaced-before-load.js      0      0     78
test/js/node/test_runner/node-test.test.ts                    3      0     78

A test file can replace Promise.resolve, Promise.prototype.then and the other
public Promise methods. The runner called them at 33 sites. So test() threw
while Promise.resolve was replaced, and a replaced then() lost subtests.

- The runner calls private names: Promise.$resolve, $then, $newPromise.
- A link of the subtest chain is an async function that awaits the previous
  link. A then() callback that returns a promise calls the public then().
- untilStopped() replaces Promise.race() for the timeout of a test, and for
  the timeout and the signal of a hook.
- mock_timers.ts makes its promise with $newPromise().
@robobun

robobun commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:55 AM PT - Oct 26th, 2026

✅ @robobun, your commit 226eaffad8b4b7054c3d9af49f09b795ce59906c passed in Build #132984! 🎉


🧪   To try this PR locally:

bunx bun-pr 46959

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

bun-46959 --bun

@robobun

robobun commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready for review. The base of this PR is #46919.

How it was reproduced: a node:test file that calls test() while Promise.resolve is replaced with a function that throws. On the base and on a release build of main (179664e), bun test prints error: replaced Promise.resolve at new TestNode and reports 0 pass, 1 fail, 1 error. Node v26.3.0 passes the file. The same file with Promise.prototype.then and a subtest: the subtest fails on the base. The fixture test/js/node/test_runner/fixtures/32-replaced-promise-methods.js records each call of a public Promise method while the runner works. On the base the runner makes 435 such calls over it, counted without the last block of the fixture (that block stops the file on the base). On this branch it makes 0.

@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 dropped .catch(() => {}) defuses in createStopController and on the plan pending promise: every current caller in executeTestNode hands stop.promise and pending to untilStopped synchronously (or awaits pending directly), and the stop timer's $rejectPromise fires at most once since dispose() clears the single timer, so no new unhandled rejection is reachable from those sites.

Extended reasoning...

The change rewrites ~33 public Promise call sites in src/js/node/test.ts and one in mock_timers.ts to JSC private intrinsics, restructures the subtest chain around async step functions, and adds three fixtures plus seven tests. It touches no auth, injection, or data-exposure surface; the hostile-userland concern is the point of the change. Three confirmed findings are posted inline, so a human look is already signalled; this note only records the defuse-removal check that was examined and ruled out.

Comment thread src/js/node/test.ts Resolved
Comment thread src/js/node/test.ts Resolved
A hook with a signal can abort that signal and then throw. The abort rejects
the stop promise of the hook before the runner gives that promise a reaction,
so `bun test` reported the abort as an unhandled error. The runner now marks
the stop promise as handled when the hook has a signal.

Tests:
- Two tests of the chain fixture had names that end in "fails the suite" and
  did not observe that failure. Their suites are no longer todo, so the two
  tests fail, and the test compares the errors and the verdicts of the
  fixture with an exact list.
- The fixture for replaced methods says that a replaced
  Promise.prototype.constructor is not covered.
@robobun

robobun commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator Author

The three inline findings, with 226eaff:

  1. The two tests that could not fail: fixed. Their suites are no longer todo, and the test compares the errors and the verdicts of 33-subtest-chain.js with an exact list.
  2. A hook that aborts its own signal and then throws: fixed, with a fixture row. The abort was reported as an unhandled error on main and on the base too.
  3. A replaced Promise.prototype.constructor: not changed. Node's runner calls the public then() in that case too. The fixture header and the description now say so.

One result of the verification for this push is new in the description: the vendored test-runner-mock-timers-scheduler.js has a wall-clock limit of 100 ms that a debug build sits on. It fails in 7 of 20 runs on main and in 12 of 20 on this branch there (median 98 ms and 100 ms). On release builds the time is 2 ms on both.

@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 re-reviewed after the follow-up commit and found no bugs; it addresses the three inline points from the earlier pass (the $pokePromiseAsHandled(stop) in the signal branch, the two chain-fixture tests now running un-todo'd with an exact report() comparison, and the constructor-replacement caveat noted in the fixture). Because this rewrites the subtest-chain and timeout-race scheduling of node:test with acknowledged microtask-timing changes, a human look at the ordering contract would still be worthwhile.

What was reviewed:

  • untilStopped and raceWithTimeoutAndSignal: both racers attach a reaction before anything can reject; the timer-only path needs no poke since the timer cannot fire before untilStopped runs or the finally clears it.
  • appendSubtestStep / awaitSuiteGate / scheduleSkipDirective: each link awaits the previous one rather than resolving a promise with a promise, and subtestChain stays undefined until the first subtest.
  • Every $-intrinsic introduced ($pokePromiseAsHandled, $isPromise, the FirstResolvingFunctionCallCheck pair, $newPromise) is declared in src/js/builtins.d.ts and already used by sibling builtins; mock_timers.ts still clears the listener and timer on both settle paths.
Extended reasoning...

The PR replaces every public Promise call in src/js/node/test.ts (and one in src/js/internal/test_runner/mock_timers.ts) with JSC private intrinsics, restructures the per-test subtest chain into async links that await their predecessor, and swaps Promise.race for an untilStopped helper; the second commit adds $pokePromiseAsHandled(stop) for a hook that aborts its own signal before throwing and tightens the chain fixture to an exact report assertion. It touches no auth, crypto, or input-parsing surface. The three inline comments from the prior run are all addressed in the code, and no CODEOWNERS entry covers the changed paths. The reason for defer rather than approve is the size and subtlety of the scheduling rewrite, which changes observable microtask ordering in two documented cases and is the kind of Node-compat contract a maintainer should weigh.

@robobun

robobun commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR has had no review and no new commit since October 26, 2026.

The branch stays, so the work is not lost. To pick it up again, update the branch from main and reopen this PR.

@robobun robobun closed this Nov 26, 2026
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.

1 participant