Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/jsc/JSGlobalObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1353,6 +1353,17 @@ impl JSGlobalObject {
Zig__GlobalObject__createForTestIsolation(old_global, console)
}

/// The realm's `ScriptExecutionContext` went through `prepareForDestruction()`:
/// a `bun test --isolate` global whose file finished (from the start of
/// [`VirtualMachine::swap_global_for_test_isolation`] on), or any global once
/// VM teardown began. JS the realm leaked (a threadpool job's `.then`, an
/// event handler) still runs and still reaches host functions; the ones that
/// drive state outside the realm check this to stay inert. `false` for a
/// global that is not a `Zig::GlobalObject`.
Comment on lines +1356 to +1362

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 you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

pub fn is_context_stopped(&self) -> bool {
Zig__GlobalObject__isContextStopped(self)
}

pub fn to_type_error(&self, code: JscError, args: Arguments<'_>) -> JSValue {
code.fmt(self, args)
}
Expand Down Expand Up @@ -1590,6 +1601,7 @@ unsafe extern "C" {
old_global: &JSGlobalObject,
console: *mut c_void,
) -> *mut JSGlobalObject;
safe fn Zig__GlobalObject__isContextStopped(this: &JSGlobalObject) -> bool;
}

impl ScriptExecutionContextIdentifier {
Expand Down
4 changes: 3 additions & 1 deletion src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5185,7 +5185,9 @@ impl VirtualMachine {
// graph) for an hour. Every TimeoutObject / ImmediateObject /
// AbortSignal timeout in the heap belongs to the outgoing file (the
// new global doesn't exist yet), so drop them eagerly, same as
// `global_exit()`. Runs no user JS.
// `global_exit()`. Runs no user JS. So does a `jest.useFakeTimers()`
// the file left on: the hook puts the thread back on the real clock
// here, after the last drain above ran the outgoing realm's JS.
Comment on lines +5188 to +5190

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 you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

//
// The hook also runs `StatWatcherScheduler::shutdown_for_exit` first:
// it drains the (already-closed — the caller ran
Expand Down
11 changes: 11 additions & 0 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4380,6 +4380,17 @@ extern "C" void Zig__GlobalObject__stopActiveDOMObjectsForTestIsolation(Zig::Glo
globalObject->scriptExecutionContext()->prepareForDestruction();
}

// The realm's context went through prepareForDestruction(): a `bun test --isolate` global retired by
// the function above, or any global once VM teardown began. Script the realm leaked can still run.
Comment on lines +4383 to +4384

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 you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

extern "C" bool Zig__GlobalObject__isContextStopped(JSC::JSGlobalObject* lexicalGlobalObject)
{
auto* globalObject = dynamicDowncast<Zig::GlobalObject>(lexicalGlobalObject);
if (!globalObject)
return false;
auto* context = globalObject->scriptExecutionContext();
return !context || context->activeDOMObjectsAreStopped();
}

extern "C" void Zig__GlobalObject__destructOnExit(Zig::GlobalObject* globalObject)
{
auto& vm = JSC::getVM(globalObject);
Expand Down
53 changes: 29 additions & 24 deletions src/runtime/jsc_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1621,9 +1621,10 @@ fn cron_clear_all_reload(vm: &mut VirtualMachine) {

/// `RuntimeHooks::cancel_all_timers` — cancel every `TimeoutObject` /
/// `ImmediateObject` still linked in the current thread's timer heap so the
/// in-heap `+1` ref and the JS pin drop before the GC sweep / `~VM`.
/// `timer::All` lives in `bun_runtime`; callers (`global_exit`,
/// `WebWorker::shutdown`) are in `bun_jsc`, hence the hook.
/// in-heap `+1` ref and the JS pin drop before the GC sweep / `~VM`, and put
/// the thread back on the real clock.
/// `timer::All` lives in `bun_runtime`; callers (VM teardown, the `--isolate`
/// swap) are in `bun_jsc`, hence the hook.
Comment on lines +1624 to +1627

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 you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

///
/// # Safety
/// `vm` is the live per-thread VM; `runtime_state()` must still be installed.
Expand All @@ -1633,6 +1634,23 @@ unsafe fn cancel_all_timers(vm: *mut VirtualMachine) {
if state.is_null() {
return;
}
// Fake-timer activation lives in the per-thread `timer::All`, not the JS
// global, so under `--isolate` it belongs to the outgoing file exactly like
// the timers below: left on, it would route every later file's `setTimeout`
// into the never-driven fake heap. The swap calls this hook after the last
// point where the outgoing realm's JS runs as the live realm; anything that
// realm runs later is inert (`FakeTimers.rs` `called_from_retired_realm`).
// The fake heap itself stays populated for `cancel_all_timeout_objects`,
// which walks both heaps.
// SAFETY: `state` is the live boxed per-thread `RuntimeState`; `vm` per fn
// contract; `reset_for_isolation` touches only `fake_timers.active`, the
// `CURRENT_TIME` static and VM fields.
unsafe {
let fake_timers = &mut *ptr::addr_of_mut!((*state).timer.fake_timers);
if fake_timers.is_active() {
fake_timers.reset_for_isolation((*vm).global());
}
}
// Drain the `fs.watchFile` scheduler queue while the timer heap and JSC
// are both still live. Each queued `StatWatcher` holds a `RefPtr` back to
// the scheduler and the scheduler holds a queue ref on the watcher, so any
Expand Down Expand Up @@ -1717,11 +1735,12 @@ fn stop_dns_for_vm_teardown() -> SweepResult {
/// prepareForDestruction discards the pre-exit queues.)
pub(crate) fn stop_active_handles_for_test_isolation(vm: &mut VirtualMachine) {
let _ = vm.event_loop_mut().drain_microtasks();
let _ = stop_active_handles(vm, StopReason::TestIsolation);
let _ = stop_active_handles(StopReason::TestIsolation);
}

pub(crate) fn stop_active_handles_for_vm_teardown(vm: &mut VirtualMachine) -> SweepResult {
stop_active_handles(vm, StopReason::VmTeardown)
/// `_vm`: the caller holds this thread's VM exclusively, on the JS thread.
pub(crate) fn stop_active_handles_for_vm_teardown(_vm: &mut VirtualMachine) -> SweepResult {
stop_active_handles(StopReason::VmTeardown)
}

#[derive(Clone, Copy, PartialEq, Eq)]
Expand All @@ -1731,32 +1750,18 @@ enum StopReason {
TestIsolation,
}

fn stop_active_handles(vm: &mut VirtualMachine, reason: StopReason) -> SweepResult {
fn stop_active_handles(reason: StopReason) -> SweepResult {
let state = runtime_state();
if state.is_null() {
return SweepResult::Idle;
}
let mut result = SweepResult::Idle;
// Fake-timer state lives in the per-thread `timer::All`, not the JS
// global, so a file that leaves it active routes every later file's
// `setTimeout` into the never-driven fake heap. Leave the heap itself
// intact: `swap_global_for_test_isolation` runs `cancel_all_timeout_objects`
// next, which walks both heaps and releases `TimeoutObject` pins and
// discards `AbortSignalTimeout` timers at a point where no user JS can
// touch the outgoing signals.
{
let all = timer_all();
// SAFETY: `state` is non-null so `timer_all()` is non-null; single
// JS thread, no re-entry while we hold the field borrow.
if !all.is_null() && unsafe { (*all).fake_timers.is_active() } {
let global = vm.global();
// SAFETY: as above; only touches `fake_timers.active` and the
// `CURRENT_TIME` static.
unsafe { (*all).fake_timers.reset_for_isolation(global) };
}
if !all.is_null() {
// SAFETY: as above; `disable` borrows only `event_loop_delay` and
// reaches the heap through `timer_all()` (disjoint-field access).
// SAFETY: `state` is non-null so `timer_all()` is live; single JS
// thread; `disable` borrows only `event_loop_delay` and reaches the
// heap through `timer_all()` (disjoint-field access).
unsafe { (*all).event_loop_delay.disable() };
}
}
Expand Down
49 changes: 44 additions & 5 deletions src/runtime/test_runner/timers/FakeTimers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ impl CurrentTime {
/// and `performance.timeOrigin` go back to real as well.
#[unsafe(no_mangle)]
extern "C" fn Bun__FakeTimers__setSystemTime(global: &JSGlobalObject, ms: f64) {
if called_from_retired_realm(global) {
return;
}
let Some(current) = CURRENT_TIME.get_timespec_now() else {
return;
};
Expand Down Expand Up @@ -187,10 +190,10 @@ impl FakeTimers {
}

/// Restore real timers without draining the fake heap. Used by the
/// `--isolate` file boundary so `swap_global_for_test_isolation`'s
/// `cancel_all_timeout_objects` (which runs after the outgoing global's
/// JS has stopped) can walk the still-populated fake heap and release
/// `TimeoutObject` pins and discard `AbortSignalTimeout` timers.
/// `cancel_all_timers` hook (the `--isolate` swap, VM teardown) right
/// before `cancel_all_timeout_objects`, which walks the still-populated
/// fake heap itself to release `TimeoutObject` pins and discard
/// `AbortSignalTimeout` timers once the outgoing global's JS has stopped.
Comment on lines +193 to +196

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 you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

pub(crate) fn reset_for_isolation(&mut self, global: &JSGlobalObject) {
CURRENT_TIME.clear(global);
self.active = false;
Expand Down Expand Up @@ -316,6 +319,15 @@ impl FakeTimers {
// JS Functions
// ===

/// Under `--isolate` a file's `jest`/`vi` object outlives the file: JS it
/// leaked (a threadpool job's `.then`) still runs in the retired realm while a
/// later file owns the thread. The fake clock is per thread, not per realm, so
/// from a retired realm every control below is inert: it neither installs,
/// drives, reads, nor removes the clock of the file that is running now.
Comment on lines +322 to +326

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 you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

fn called_from_retired_realm(global: &JSGlobalObject) -> bool {
global.is_context_stopped()
}

fn error_unless_fake_timers(global: &JSGlobalObject) -> JsResult<()> {
// SAFETY: per-thread `timer::All`, live for the VM lifetime.
if unsafe { (*timer_all()).fake_timers.is_active() } {
Expand Down Expand Up @@ -352,6 +364,9 @@ fn set_fake_timer_marker(global: &JSGlobalObject, enabled: bool) -> JsResult<()>

#[bun_jsc::host_fn]
fn use_fake_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(frame.this());
}
// SAFETY: FFI call into C++ JSMock
let mut js_now = JSMock__getCurrentUnixTimeMs();

Expand Down Expand Up @@ -396,6 +411,9 @@ fn use_fake_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSVal

#[bun_jsc::host_fn]
fn use_real_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(frame.this());
}
// SAFETY: per-thread `timer::All`; the borrow ends before `release`.
let cleared = unsafe { (*timer_all()).fake_timers.deactivate(global) };
cleared.release(global.bun_vm_ptr());
Expand All @@ -408,6 +426,9 @@ fn use_real_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSVal

#[bun_jsc::host_fn]
fn advance_timers_to_next_timer(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(frame.this());
}
error_unless_fake_timers(global)?;

FakeTimers::execute_next(global)?;
Expand All @@ -417,6 +438,9 @@ fn advance_timers_to_next_timer(global: &JSGlobalObject, frame: &CallFrame) -> J

#[bun_jsc::host_fn]
fn advance_timers_by_time(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(frame.this());
}
error_unless_fake_timers(global)?;

let arg = frame.arguments_as_array::<1>()[0];
Expand Down Expand Up @@ -453,6 +477,9 @@ fn advance_timers_by_time(global: &JSGlobalObject, frame: &CallFrame) -> JsResul

#[bun_jsc::host_fn]
fn run_only_pending_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(frame.this());
}
error_unless_fake_timers(global)?;

FakeTimers::execute_only_pending_timers(global)?;
Expand All @@ -462,6 +489,9 @@ fn run_only_pending_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResu

#[bun_jsc::host_fn]
fn run_all_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(frame.this());
}
error_unless_fake_timers(global)?;

FakeTimers::execute_all_timers(global)?;
Expand All @@ -471,6 +501,9 @@ fn run_all_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValu

#[bun_jsc::host_fn]
fn get_timer_count(global: &JSGlobalObject, _frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(JSValue::js_number(0.0));
}
error_unless_fake_timers(global)?;

// SAFETY: per-thread `timer::All`, live for the VM lifetime.
Expand All @@ -481,6 +514,9 @@ fn get_timer_count(global: &JSGlobalObject, _frame: &CallFrame) -> JsResult<JSVa

#[bun_jsc::host_fn]
fn clear_all_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(frame.this());
}
error_unless_fake_timers(global)?;

// SAFETY: per-thread `timer::All`; the borrow ends before `release`.
Expand All @@ -491,7 +527,10 @@ fn clear_all_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSVa
}

#[bun_jsc::host_fn]
fn is_fake_timers(_global: &JSGlobalObject, _frame: &CallFrame) -> JsResult<JSValue> {
fn is_fake_timers(global: &JSGlobalObject, _frame: &CallFrame) -> JsResult<JSValue> {
if called_from_retired_realm(global) {
return Ok(JSValue::FALSE);
}
// SAFETY: per-thread `timer::All`, live for the VM lifetime.
let is_active = unsafe { (*timer_all()).fake_timers.is_active() };

Expand Down
95 changes: 95 additions & 0 deletions test/cli/test/isolation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,101 @@ describe.concurrent("bun test --isolate", () => {
expect(exitCode).toBe(0);
});

test("with --isolate, jest timer controls called by a finished file's leaked continuation are inert", async () => {
// The boundary reset above covers fake timers a file left on. This covers
// the file reaching back afterwards: a threadpool job it leaked completes
// while the next file runs, and its `.then` (running in the retired
// global) calls jest.useFakeTimers() / useRealTimers() / runAllTimers().
// The fake clock is per thread, so those calls used to install, drain or
// remove the clock of the file that is running now. The two files
// handshake through marker files so the calls land at known points, not
// after a sleep.
const fixtures = {
"a-finished.test.ts": `
import { expect, jest, test } from "bun:test";
import { existsSync, writeFileSync } from "node:fs";
import { join } from "node:path";

const marker = (name: string) => join(import.meta.dir, name);
const hop = (until: string, then: () => unknown): unknown =>
Bun.password.hash("pw", { algorithm: "bcrypt", cost: 4 }).then(() =>
existsSync(marker(until)) ? then() : hop(until, then),
);

test("leaks a threadpool chain that calls jest timer controls once the next file runs", () => {
hop("b-on-real-timers", () => {
jest.useFakeTimers();
jest.setSystemTime(0);
writeFileSync(marker("a-installed-fake-timers"), "");
return hop("b-on-fake-timers", () => {
jest.advanceTimersByTime(1000);
jest.runAllTimers();
jest.clearAllTimers();
jest.useRealTimers();
writeFileSync(marker("a-removed-fake-timers"), String(jest.isFakeTimers()) + " " + jest.getTimerCount());
});
});
expect(1).toBe(1);
});
`,
"b-live.test.ts": `
import { expect, jest, test } from "bun:test";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";

const marker = (name: string) => join(import.meta.dir, name);
// setImmediate never goes through the fake clock, so this turns the
// event loop (landing the finished file's continuations) either way.
const until = async (name: string) => {
while (!existsSync(marker(name))) await new Promise(resolve => setImmediate(resolve));
};

test("the finished file's calls do not reach this file's clock", async () => {
writeFileSync(marker("b-on-real-timers"), "");
await until("a-installed-fake-timers");
expect(jest.isFakeTimers()).toBe(false);
expect(performance.now()).toBeGreaterThan(0);
expect(await new Promise(resolve => setTimeout(() => resolve("fired"), 1))).toBe("fired");

jest.useFakeTimers();
let calls = 0;
setTimeout(() => calls++, 1000);
writeFileSync(marker("b-on-fake-timers"), "");
await until("a-removed-fake-timers");
expect(readFileSync(marker("a-removed-fake-timers"), "utf8")).toBe("false 0");
expect(jest.isFakeTimers()).toBe(true);
expect(jest.getTimerCount()).toBe(1);
expect(calls).toBe(0);
jest.runAllTimers();
expect(calls).toBe(1);
jest.useRealTimers();
});
`,
};
const files = ["./a-finished.test.ts", "./b-live.test.ts"];

using isolated = tempDir("isolate-retired-fake-timers", fixtures);
const serial = await runTests(String(isolated), ["--isolate"], files);
expect(normalizeBunSnapshot(serial.stderr, isolated)).toContain("2 pass");
expect(normalizeBunSnapshot(serial.stderr, isolated)).toContain("0 fail");
expect(serial.exitCode).toBe(0);

// One worker takes both files (scale-up gated), so the finished file's
// chain keeps running inside the --parallel worker that runs the next one.
using parallel = tempDir("isolate-retired-fake-timers-parallel", fixtures);
await using proc = Bun.spawn({
cmd: [bunExe(), "test", "--parallel=2", ...files],
env: { ...bunEnv, BUN_TEST_PARALLEL_SCALE_MS: "60000" },
cwd: String(parallel),
stderr: "pipe",
stdout: "pipe",
});
const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(normalizeBunSnapshot(stderr, parallel)).toContain("2 pass");
expect(normalizeBunSnapshot(stderr, parallel)).toContain("0 fail");
expect(exitCode).toBe(0);
});

test("with --isolate, a leaked monitorEventLoopDelay() is disabled before next file", async () => {
// The monitor is per thread while its histogram belongs to the file's
// global. A file that enables it and never disables it used to leave the
Expand Down
Loading