Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 4 additions & 1 deletion src/runtime/timer/TimeoutObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,14 @@ impl TimeoutObject {
}

pub(crate) fn set_idle_start(
_this: &Self,
this: &Self,
this_value: JSValue,
global: &JSGlobalObject,
value: JSValue,
) {
if let Some(ms) = value.get_number() {
this.internals.set_idle_start(ms);
}
js::idle_start_set_cached(this_value, global, value);
}
}
26 changes: 26 additions & 0 deletions src/runtime/timer/timer_object_internals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,32 @@ impl TimerObjectInternals {
Ok(this_value)
}

/// Node's deadline is `_idleStart + _idleTimeout`; writing `_idleStart`
/// must move the heap entry so `t2._idleStart = t1._idleStart` works.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn set_idle_start(&self, idle_start_ms: f64) {
if self.flags.get().kind() == Kind::SetImmediate
|| self.flags.get().has_cleared_timer()
|| self.event_loop_timer_state() != EventLoopTimerState::ACTIVE
|| !idle_start_ms.is_finite()
{
return;
}

let state = crate::jsc_hooks::runtime_state();
debug_assert!(!state.is_null(), "RuntimeState not installed");

let scheduled_time = Timespec::EPOCH
.add_ms((idle_start_ms as i64).saturating_add(i64::from(self.interval.get())));
// SAFETY: `state` is the boxed per-thread `RuntimeState`; fresh
// `&mut` to `.timer` for this call only. The timer is ACTIVE so
// `update()` removes then re-inserts with no refcount change.
unsafe {
(*state)
.timer
.update(self.event_loop_timer(), &scheduled_time)
};
}

pub(crate) fn do_refresh(
&self,
global_object: &JSGlobalObject,
Expand Down
73 changes: 73 additions & 0 deletions test/js/node/timers/node-timers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,79 @@ describe("clear", () => {
});
});

describe("_idleStart", () => {
// https://github.com/oven-sh/bun/issues/26508
// Next.js 16 Cache Components writes `t2._idleStart = t1._idleStart` so two
// `setTimeout(fn)` calls share a deadline and both fire before any
// `setImmediate` scheduled from `t1`'s callback.
it("reschedules the timer when written (Next.js pattern)", async () => {
const script = `
async function once() {
let immediateRan = false;
let order = [];
const t1 = setTimeout(() => {
order.push("t1");
setImmediate(() => { immediateRan = true; });
});
// Force the monotonic clock past a millisecond boundary so t2 would
// land in a later event-loop turn without the _idleStart assignment.
{ const s = performance.now(); while (performance.now() - s < 2) {} }
const { promise, resolve } = Promise.withResolvers();
const t2 = setTimeout(() => {
order.push("t2");
resolve({ immediateRan, order: order.join(",") });
});
t2._idleStart = t1._idleStart;
return promise;
}
for (let i = 0; i < 50; i++) {
const { immediateRan, order } = await once();
if (immediateRan) {
console.log("FAIL: immediate ran before t2 on iteration " + i);
process.exit(1);
}
if (order !== "t1,t2") {
console.log("FAIL: wrong order " + order + " on iteration " + i);
process.exit(1);
}
}
console.log("ok");
`;
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(stdout.trim()).toBe("ok");
expect(exitCode).toBe(0);
});

it("ignores non-finite values and cleared timers", async () => {
const t1 = setTimeout(() => {}, 10) as any;
t1._idleStart = "not a number";
expect(t1._idleStart).toBe("not a number");
t1._idleStart = NaN;
expect(Number.isNaN(t1._idleStart)).toBeTrue();
t1._idleStart = Infinity;
expect(t1._idleStart).toBe(Infinity);
clearTimeout(t1);
t1._idleStart = 0;
expect(t1._idleStart).toBe(0);
});

it("does not overflow for extreme finite values", () => {
const t1 = setTimeout(() => {}, 10) as any;
t1._idleStart = Number.MAX_VALUE;
expect(t1._idleStart).toBe(Number.MAX_VALUE);
t1._idleStart = -Number.MAX_VALUE;
expect(t1._idleStart).toBe(-Number.MAX_VALUE);
clearTimeout(t1);
Comment on lines +273 to +292

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.

🟡 The two auxiliary _idleStart tests only assert expect(t1._idleStart).toBe(<value>) — a cached-property round-trip that idle_start_set_cached already satisfied unconditionally before this PR — so both pass with USE_SYSTEM_BUN=1, and deleting the !is_finite() or has_cleared_timer() guards breaks neither. To make them load-bearing, assert on scheduling behavior (e.g. that after t1._idleStart = NaN the 10ms timer still fires at ~10ms, not immediately). Separately, in the extreme-values test clearTimeout(t1) runs after the assertions, so a failed first expect leaks a ref'd timer rescheduled to i64::MAX ms — wrap in try/finally or t1.unref() right after creation.

Extended reasoning...

What the bug is

Two auxiliary tests in the new _idleStart describe block — "ignores non-finite values and cleared timers" and "does not overflow for extreme finite values" — assert only that t1._idleStart reads back the value just written. But TimeoutObject::set_idle_start ends with js::idle_start_set_cached(this_value, global, value) unconditionally (TimeoutObject.rs:133), both before and after this PR. The getter (get_idle_start) simply returns js::idle_start_get_cached(this_value). So every expect(t1._idleStart).toBe(X) in these two tests is a pure WriteBarrier cache round-trip that succeeds regardless of whether internals.set_idle_start(ms) was called, what it did, or whether the guards inside it ran.

Additionally, the "does not overflow for extreme finite values" test places clearTimeout(t1) after the two expect() calls, so if the first assertion throws, a ref'd timer whose heap deadline was just moved to i64::MAX milliseconds (~292 million years) leaks and keeps the event loop alive until the file-level timeout.

Code path

For the "not load-bearing" issue, trace each guard the tests are named after:

  • !idle_start_ms.is_finite() (timer_object_internals.rs:949) — deleting this guard: NaN as i64 == 0 and Infinity as i64 == i64::MAX (Rust's saturating float→int cast). Both flow through .saturating_add(i64::from(interval)).max(0) and Timespec::EPOCH.add_ms(...) (which uses wrapping_add) without panicking. The test then reads back the cached JS value — written unconditionally at TimeoutObject.rs:133 — so expect(Number.isNaN(t1._idleStart)).toBeTrue() and expect(t1._idleStart).toBe(Infinity) still pass. The test never observes when the timer fires.
  • has_cleared_timer() (line 947) — deleting this guard: after clearTimeout(t1), cancel() sets event_loop_timer_state = CANCELLED, so the very next clause event_loop_timer_state() != EventLoopTimerState::ACTIVE (line 948) already short-circuits. And again, expect(t1._idleStart).toBe(0) only checks the cache.

Both tests therefore pass with USE_SYSTEM_BUN=1 — the pre-PR setter was js::idle_start_set_cached(...) and nothing else, which is exactly what these assertions exercise.

For the leak-on-failure issue: t1._idleStart = Number.MAX_VALUE on an active setTimeout(() => {}, 10) computes (Number.MAX_VALUE as i64).saturating_add(10).max(0) = i64::MAX, then All::update() reinserts the timer at Timespec::EPOCH.add_ms(i64::MAX). A fresh setTimeout has has_js_ref = true (Flags default), so is_keeping_event_loop_alive remains set. If expect(t1._idleStart).toBe(Number.MAX_VALUE) at line 289 throws, execution never reaches line 290 (which would clamp the deadline back to 0 via .max(0)) or line 292's clearTimeout, and the ref'd far-future timer hangs the process.

Why existing code doesn't prevent it

REVIEW.md is explicit on both counts:

"Confirm deleting each load-bearing clause of your fix breaks at least one test — a test that passes both ways is worse than no test."

"Release every resource via using/await using or try/finally registered BEFORE the assertions (cleanup after expectations leaks on the first failure and poisons later tests on persistent CI runners)."

CLAUDE.md also states: "Your test is NOT VALID if it passes with USE_SYSTEM_BUN=1."

The primary "reschedules the timer when written (Next.js pattern)" test is load-bearing (it fails on USE_SYSTEM_BUN=1 per the PR description) and covers the actual fix, so the core change is properly tested. The concern is only the two auxiliary tests: their names promise coverage of the is_finite() / has_cleared_timer() guards and overflow handling, but their assertions cannot distinguish presence from absence of those guards. The one thing the extreme-values test does provide is implicit "does not abort" coverage — removing .saturating_add would panic on i64::MAX + 10 under the dev profile's overflow-checks + panic = "abort" — but the explicit expect calls contribute nothing beyond that.

Step-by-step proof

Auxiliary tests pass on system Bun:

  1. Run with USE_SYSTEM_BUN=1 (pre-PR set_idle_start = only js::idle_start_set_cached(this_value, global, value)).
  2. t1._idleStart = NaN → setter caches NaN in the WriteBarrier slot; native heap deadline unchanged.
  3. expect(Number.isNaN(t1._idleStart)).toBeTrue() → getter returns cached NaN → passes.
  4. Same for "not a number", Infinity, post-clear 0, and ±Number.MAX_VALUE — every assertion is cache_get(cache_set(X)) === X.

Deleting !is_finite() breaks nothing:

  1. Remove || !idle_start_ms.is_finite() from timer_object_internals.rs:949.
  2. t1._idleStart = NaN → NaN as i64 == 0 → 0.saturating_add(10).max(0) = 10 → update() reschedules to EPOCH+10ms. No panic.
  3. js::idle_start_set_cached(..., NaN) still runs (TimeoutObject.rs:133) → expect(Number.isNaN(t1._idleStart)).toBeTrue() → still passes.
  4. clearTimeout(t1) at the end removes the timer regardless of where it was rescheduled to. Test green.

Leak on assertion failure:

  1. const t1 = setTimeout(() => {}, 10) → has_js_ref = true, is_keeping_event_loop_alive = true, state = ACTIVE.
  2. t1._idleStart = Number.MAX_VALUE → heap deadline moved to i64::MAX ms; timer still ACTIVE and ref'd.
  3. Suppose expect(t1._idleStart).toBe(Number.MAX_VALUE) throws (e.g. the cache mechanism regresses) → test body exits.
  4. Line 290 (t1._idleStart = -Number.MAX_VALUE, which would clamp to 0) and line 292 (clearTimeout(t1)) never execute.
  5. Ref'd timer at i64::MAX ms keeps the event loop alive → file hangs until the runner timeout.

Note: only the first assertion failing leaks the far-future timer. If the second fails, line 290 has already rescheduled to ms=0 ((-Number.MAX_VALUE as i64).saturating_add(10).max(0) = 0), which fires-now and self-clears.

Impact

Low. The primary Next.js-pattern test is solid, so the fix itself has real coverage. These two tests are misleadingly named (they suggest guard coverage they don't provide) but not actively harmful — they still document that the cached JS value is preserved for edge inputs, and the extreme-values test implicitly guards against a debug-build overflow abort. The leak scenario requires a nearly-tautological cache round-trip assertion to fail, which is implausible in practice. Neither issue causes a concrete failure if merged as-is, hence nit.

Fix

For the load-bearing gap, assert on scheduling behavior instead of the cached value. For example:

it("ignores non-finite values", async () => {
  const start = performance.now();
  const { promise, resolve } = Promise.withResolvers();
  const t1 = setTimeout(resolve, 10) as any;
  try {
    t1._idleStart = NaN;      // must NOT reschedule to fire-now
    t1._idleStart = Infinity; // must NOT reschedule to never
    await promise;
    expect(performance.now() - start).toBeGreaterThanOrEqual(9);
  } finally {
    clearTimeout(t1);
  }
});

Now deleting !is_finite() reschedules the timer to fire-now (NaN→0) or never (Infinity→i64::MAX), and the test observes the difference.

For the leak, wrap the extreme-values body in try/finally or add t1.unref() immediately after creation:

it("does not overflow for extreme finite values", () => {
  const t1 = setTimeout(() => {}, 10) as any;
  try {
    t1._idleStart = Number.MAX_VALUE;
    expect(t1._idleStart).toBe(Number.MAX_VALUE);
    t1._idleStart = -Number.MAX_VALUE;
    expect(t1._idleStart).toBe(-Number.MAX_VALUE);
  } finally {
    clearTimeout(t1);
  }
});

});
});

describe.each(["with", "without"])("setImmediate %s timers running", mode => {
// TODO(@190n) #17901 did not fix this for Windows
it.todoIf(isWindows && mode == "with")(
Expand Down