Skip to content

bun test: give a module mock a turn in each load that imports it, and let a factory's import() wait for a fetch in flight - #49027

Closed
robobun wants to merge 7 commits into
mainfrom
robobun/10e3cf25/mock-turns-per-load
Closed

robobun wants to merge 7 commits into
mainfrom
robobun/10e3cf25/mock-turns-per-load

Conversation

@robobun

@robobun robobun commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Question for @Jarred-Sumner: c7e4231 (#44833) gives a mock factory a private copy of a module that another load is fetching. This PR makes its import() wait for that fetch, as Bun 1.4.4 does. Copy or wait?

Problem

  • With bun-plugin-svelte, a vi.mock() factory imports a $state module while two components load. The module runs twice. Bun 1.4.4 passes 12 of 12 runs, main 1 of 12.
  • Cause: isWaitingForModule() (src/jsc/bindings/BunPlugin.cpp:8057) copies a module in flight for the factory.
  • Also, a mock that two loads import waits for the other load's pending factory (rankWaitingModuleMocks(), :2623).

Fix

  • A running factory's import(), vi.importActual() and vi.importMock() wait until the loader has the module, then share it.
  • A waiting mock takes its turn in the first free load that imports it.
  • Verified: test/js/bun/test/mock/mock-module.test.ts (33 new tests, 19 fail on main). Other suites: Notes.
  • Self-reviewed: 63 concerns raised, 9 addressed. The open ones are in Notes and keep this a draft.

Background

  • A load is one import() call or one test file's static imports. Its factories run one at a time.
  • Considered the copy plus a join of the two loads. Then a callback that never answers holds back unrelated loads.

Downsides

  • A test that needs the mock before it lets the other load's plugin callback answer never finishes loading. Main gave a second instance.
  • A CommonJS module that requires the mocked module while another load fetches it throws TypeError: require() async module. Main passes.
  • An import() call costs 9 more instructions. Release .text grows 9,728 bytes.
Notes

The repro with the first-party plugin (bun test --preload ./preload.ts ./state.test.js, node_modules with svelte 5.20.4 and bun-plugin-svelte). It is the new test a $state module of bun-plugin-svelte runs once for a factory and a component.

// preload.ts
import { SveltePlugin } from "bun-plugin-svelte";
Bun.plugin(SveltePlugin());
// session.svelte.ts
globalThis.sessions = (globalThis.sessions ?? 0) + 1;
export const session: { user: string | null } = $state({ user: null });
// state.test.js   (Header.svelte imports ./session.svelte, LoginButton.svelte imports { login } from ./api.js)
import { expect, test, vi } from "bun:test";
import { render } from "svelte/server";
vi.mock("./api.js", async () => {
  const { session } = await import("./session.svelte.ts");
  return { login: () => void (session.user = "ada") };
});
test("two components are loaded together", async () => {
  const [header, button] = await Promise.all([import("./Header.svelte"), import("./LoginButton.svelte")]);
  button.login();
  expect([globalThis.sessions, render(header.default).body]).toEqual([1, expect.stringContaining("hi ada")]);
});

Runs that pass: Bun 1.4.4 12 of 12, main (ed43633) 1 of 12, this PR 12 of 12. The same shape with a hand-written async onLoad() and no gate is in the tests ..., by loads that share no module.

What the author of the rule wrote. c7e4231, 2026-10-18: "A mock that is reached through a load's imports now waits until no load is reading a file, so the question always has an answer. It doesn't wait for a plugin's onLoad() callback in another load, which may depend on the test's progress." The start of a factory still does not wait for such a callback. The factory's own import() of that module now does. After the wait the call is resolved again: the factory shares the module, or gets the private copy if the module imports the mocked one.

Both answers, measured (release builds: Bun 1.4.4, main ed43633, this PR 03355f286):

Input Bun 1.4.4 main this PR
The Svelte repro above, 12 runs 12 pass 1 pass 12 pass
A factory import()s a module behind an async onLoad() of another load (7 test rows) one instance two instances, callback called twice one instance
A mock that two loads import, beside a pending async factory of one of them (6 test rows) pass 5 s timeout or never finished loading pass
The test needs the mock before it lets the other load's callback answer (test ... never settles) hangs passes with two instances never finished loading
Two pages loaded with Promise.all(), an async mock and a mock built on it fails pass pass

Addressed from the self-review:

  • A later mock no longer starts beside a pending factory that comes before it in each of its loads. The running factory has the turn in every load of its mock.
  • The target of a waiting import is not a load root before the import is resolved again.
  • What an onResolve() callback resolves does not wait in the place of the import.
  • A waiting import is one import for vi.dynamicImportSettled().
  • The comment in rankWaitingModuleMocks() says what waits now.
  • New tests: the shape without a gate, the shape with bun-plugin-svelte, two tests without a plugin, and the cost of the wait.

Open items. This PR stays a draft until each is fixed or decided.

  • The waiting import is resolved again from its specifier when it goes on. An onResolve() callback is asked once more for each wait. An alias that a plugin resolved is lost if Bun.plugin.clearAll() ran meanwhile.
  • It waits for one module at a time, and each wait ranks again. A factory imports the head of a chain of modules behind an async onLoad(), in flight for another load: 399 rankings against 1 on main at 200 modules, and 1.3 s against 0.11 s at 3,000 modules.
  • A CommonJS module that requires the mocked module (second bullet of Downsides).
  • A module that gets its record between the release of the wait and the resolve can give the other load the original of the mocked module. One fixture with three modules in a row fails so. It passes on main.
  • A module passed to import() has no registry entry until its fetch settles, so the wait does not see it. The callback is still called twice there, with one instance.
  • A mock below a module that two loads share still waits for the first load's pending factory. Only a mock that both loads import by themselves is covered.
  • vi.dynamicImportSettled() waits for a waiting import. Three fixtures that call it before they let the callback answer go from pass to a 5 s timeout. It is the first downside again.
  • Not every clause of the change has a test that fails without it. The self-review removed seven of nine, one at a time, with the test file still green. Some of the tests added since pin them. The rest are not written.
  • jsFunctionResumeImportsAfterFetches() has no throw scope around its loop.

The second part is not opened. The hang that started this work needs a change to the scheduler: a fetch that a plugin callback holds must hold back only the loads that import its module (error: "b.test.js" never finished loading after an earlier file left import("./slow.js") behind a callback that never answers). A build of that part (branch robobun/10e3cf25/mock-turn-after-unfinished-fetch) passes 73 of 74 fixture rows where main passes 23. It also gives a module behind a fresh helper's static import a second instance where main gives one, so it is not ready.

Measured on release builds, lto off, main ed43633 against this PR (03355f286).

  • Own instructions per call, no plugin and no mock (gdb stepi): moduleLoaderResolve() 256 and 256, moduleLoaderFetch() 198 and 198, moduleLoaderImportModule() 270 and 279 (53 and 55 conditional branches).
  • size .text: 150,971,049 and 150,980,777 (+9,728 B). BunPlugin::OnLoad grows 40 bytes, a waiting mock 16 bytes. One host function is added.
  • Rankings per test file (lldb breakpoint counts, debug builds): a 3,001-module graph with 50 preload mocks 52 and 52, the same with an async onLoad() 52 and 52, 200 import() roots 30 and 30. One waiting import adds 2 rankings and saves the second callback call, transpile and evaluation.
  • 131 fixture rows: exit 0 on main 107, on this PR 117. Pass on main and fail here: the two rows of the first downside. A 74-row matrix of the second part: main 23, this PR 24.
  • perf, valgrind and hyperfine are not installed on the machine.

Suites run on the debug build of this PR: mock-module.test.ts 350 pass, mock-hoist.test.ts 134, vitest-flavor.test.ts 191, vitest-apis.test.ts 151, vi-utils.test.ts 193, isolation.test.ts 154, rerun-each.test.ts 10, plugins.test.ts 278 pass and 1 fail (the same GC test fails on main's debug build). On the release build: test/aot/runner-suites/mock-module-{1..6} and mock-module-runs-{1..6}, 12 of 12.

Under --aot. A compiled import() does not pass moduleLoaderImportModule() and does not wait. Four tests behave differently compiled and are named in test/aot/runner-suites.known.txt or runner-suites.runs.txt, each with its reason. Main's compiled run gives the same result for the two that pass on main.

Open PRs whose merge with this branch conflicts in a file that this PR changes: #48795 (runner-suites.runs.txt), #48910 (docs/test/mocks.mdx), #48967 (BunPlugin.cpp, BunPlugin.h), #48503 (ZigGlobalObject.cpp, runner-suites.known.txt).


no test proof · iteration 2 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/test/mock/mock-module.test.ts

These cases pass today. They cover inputs that a change to the turns of
module mocks can break: a factory that calls require() for another mocked
module, an async onLoad() callback that declines beside a mock, a mock that
is removed or replaced while its load waits for its own onLoad() callback,
and a module behind an async onLoad() callback that a factory imports while
another load fetches it.
…oad that can give it

A mock that waited for its turn had a place in one load only, the first
load that reached its module. While a factory of that load was pending,
the mock waited for it, also when another load asked for the mock. So a
load that an onLoad() callback started never finished when it imported a
mocked module of the load that the callback belonged to.

A waiting mock now has a place in every load that reaches it. It takes its
turn in the first of those loads in which no other factory has the turn.
Two loads that share only a mocked module are no longer fetched together.
When another load comes to import a mock that waits behind a turn, the
mocks are ranked again.
…oad is fetching

When a running factory imported a module that another load was still
fetching, the runtime could not tell whether that module imports the mocked
module, and gave the factory a private copy at once. So a module behind an
async onLoad() callback ran twice, and the callback was called twice for one
file, unless the two loads happened to share a module.

The import(), vi.importActual() and vi.importMock() calls of a running
factory are now held until the loader has that module and has asked for its
imports. Then the call is resolved again: it shares the module, or gets a
copy if the module turns out to wait for the mock. require() and static
imports cannot wait, and keep the copy.
…iffer under --aot

The test of Bun.plugin.clearAll() while an import() of a factory waits is
a test of its own. Compiled runs the files themselves there, so the two
lists of the --aot suites name it. The tests of the wait itself pass
compiled.
… for its mock

A mock that two loads import took its turn in one of them, and the
factory held the turn in that load only. A later mock that both loads
import after it then started in the other load, beside the pending
factory that comes before it in both. Two pages loaded with
Promise.all(), which import an async mock and then a mock that is built
on it, passed before the mocks had a place per load and failed after.

The factory now has the turn in every load in which its mock has a
place. A mock still does not wait for the pending factory of a load
that alone imports that factory's module.

The import() of a factory that waits for a fetch in flight no longer
leaves its target in the load roots before it is resolved again, no
longer lets what an onResolve() callback resolves wait in its place,
and is one import() for vi.dynamicImportSettled(). The tests add the
shape without a gate, bun-plugin-svelte with a $state module, and the
price of the wait: a test file that needs the mock before it lets the
other load's callback answer never finishes loading.
@robobun

robobun commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 10:01 AM PT - Nov 15th, 2026

❌ @robobun, your commit 4af1051 has 2 failures in Build #141899 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 49027

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

bun-49027 --bun

@robobun

robobun commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: draft. It waits for an answer to the question in the description.

How I reproduced it

  • bun test --preload ./preload.ts ./state.test.js with bun-plugin-svelte. The files are in the Notes of the description. Bun 1.4.4 passes 12 of 12 runs. Main at ed43633 passes 1 of 12. This branch passes 12 of 12.
  • The second symptom: six tests under a mock doesn't wait for the pending factory of another load that imports it too in test/js/bun/test/mock/mock-module.test.ts time out on main and pass here.

CI at 4af1051 (build 141899, finished)

  • No test that this PR adds or changes failed, on any lane.
  • Two tests failed. Neither is in the diff.
    • test/bundler/compile-trim-template.test.ts on two Linux x64 lanes. It fails the same way on main (build 141851).
    • test/js/sql/postgres-listen-notify.test.ts on macOS x64. Two of its subprocess tests timed out. The same file was flaky on main in build 141851.
  • Five other tests failed once and passed on the retry. None of them is in the diff.

PR: #49027

…same in every run under --aot

The next file looked at the events after one read of a file. A compiled
import() of the factory is not dropped with its test file, and on the
lane with a sanitizer it went on before that look in some runs and after
it in others. The next file now loads the module itself and then reads
one more file, so a compiled import() has always gone on by then. The
test is named in runner-suites.known.txt.

Its list of runs is now the same plain and compiled, so its line leaves
runner-suites.runs.txt. The two tests of two import() calls in one tick
get lines there: which importer runs first is not fixed in a plain run.
Comment thread src/jsc/bindings/BunPlugin.cpp Resolved
Comment thread src/jsc/bindings/BunPlugin.cpp Resolved
Comment thread src/jsc/bindings/BunPlugin.cpp Resolved
Comment thread src/jsc/bindings/BunPlugin.cpp Resolved
Comment thread src/jsc/bindings/BunPlugin.h Resolved
Comment thread src/jsc/bindings/BunPlugin.h Resolved
Comment thread src/jsc/bindings/BunPlugin.h Resolved
@robobun

robobun commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR has had no review and no new commit since 2026-11-15.

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 29, 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