Skip to content

timers: reschedule timer when _idleStart is written - #36859

Merged
Jarred-Sumner merged 4 commits into
mainfrom
claude/farm/64b1d83e/idle-start-reschedules-timer
Aug 4, 2026
Merged

Jarred-Sumner merged 4 commits into
mainfrom
claude/farm/64b1d83e/idle-start-reschedules-timer

Conversation

@robobun

@robobun robobun commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #26508.

Repro

Next.js 16's app-render-scheduling.ts creates two setTimeout(fn) calls and then writes t2._idleStart = t1._idleStart so both timers share a deadline and fire in the same event-loop turn, before any setImmediate scheduled from t1's callback.

let immediateRan = false;
const t1 = setTimeout(() => {
  setImmediate(() => { immediateRan = true; });
});
// force the monotonic clock past a millisecond boundary
{ const s = performance.now(); while (performance.now() - s < 2) {} }
const t2 = setTimeout(() => {
  if (immediateRan) process.exit(1);
});
t2._idleStart = t1._idleStart;

100 iterations: Node 0 failures, Bun (before) 94 failures, Bun (after) 0 failures.

Cause

TimeoutObject::set_idle_start (added in #26021) only cached the JS value. It never updated the EventLoopTimer.next deadline in the native timer heap, so the assignment had no scheduling effect and t2 could fire in a later turn after the setImmediate.

Fix

TimerObjectInternals::set_idle_start recomputes the deadline as Timespec::EPOCH.add_ms(idle_start_ms + interval) and calls All::update() to remove and re-insert the timer. The heap comparison in EventLoopTimer::less already collapses sub-millisecond precision for JS timers and uses the insertion epoch as tiebreak, so after t2._idleStart = t1._idleStart the two timers compare equal on deadline and t1 still fires first (lower epoch).

The setter is a no-op for cleared timers, non-ACTIVE timers, and non-finite values; the JS value is always cached regardless.

Verification

New _idleStart describe in test/js/node/timers/node-timers.test.ts:

  • "reschedules the timer when written (Next.js pattern)": spawns a subprocess running 50 iterations of the busy-loop repro, asserting the immediate never runs between t1 and t2 and order is always t1,t2. Fails on USE_SYSTEM_BUN=1 ("FAIL: immediate ran before t2 on iteration 0"), passes with bun bd test.
  • "ignores non-finite values and cleared timers": edge-case coverage for string/NaN/Infinity/post-clear writes.

no test proof · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/node/timers/node-timers.test.ts

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. Previously the setter only
cached the JS value without updating the native timer heap, so the
assignment had no scheduling effect.

TimerObjectInternals::set_idle_start now recomputes the deadline
(idle_start_ms + interval) and re-inserts the EventLoopTimer into the
heap. Because EventLoopTimer::less already collapses sub-millisecond
precision for JS timers and epoch tiebreaks on insertion order, t1 still
fires before t2 after the rewrite.

Fixes #26508
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 22 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 79835f32-2ce5-435a-a35a-2d5ee8fe9a3c

📥 Commits

Reviewing files that changed from the base of the PR and between cf653ce and 3316c34.

📒 Files selected for processing (2)
  • src/runtime/timer/timer_object_internals.rs
  • test/js/node/timers/node-timers.test.ts

Walkthrough

Changes

Idle-start rescheduling

Layer / File(s) Summary
Reschedule active timeout deadlines
src/runtime/timer/TimeoutObject.rs, src/runtime/timer/timer_object_internals.rs
Numeric _idleStart assignments update active timeout deadlines. Immediates, cleared timers, inactive timers, and non-finite values are ignored.
Validate timer ordering and value retention
test/js/node/timers/node-timers.test.ts
Tests verify reassigned _idleStart ordering and retention of string, NaN, Infinity, and cleared-timer values.

Possibly related PRs

  • oven-sh/bun#35849: Modifies TimerObjectInternals, but addresses GC root-table ownership instead of _idleStart rescheduling.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the primary change: rescheduling timers when _idleStart is written.
Description check ✅ Passed The description explains the problem, cause, fix, linked issue, and verification results in sufficient detail.
Linked Issues check ✅ Passed The changes address issue #26508 by applying _idleStart writes to native timer scheduling and preserving expected timer ordering.
Out of Scope Changes check ✅ Passed The changes are limited to _idleStart scheduling behavior, timer internals, and focused tests for the linked issue.

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

@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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime/timer/timer_object_internals.rs`:
- Around line 949-961: Update the deadline calculation in the timer scheduling
path around event_loop_timer_state and scheduled_time to validate that the
finite _idleStart conversion is within a safely addable range, then use
checked_add for the interval before constructing the Timespec. If validation or
addition fails, return without updating the cached deadline; preserve the
existing assignment for valid values. Add a regression test covering
Number.MAX_VALUE on an active timeout.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 37026d67-7446-4fc1-8711-7ac964c3350e

📥 Commits

Reviewing files that changed from the base of the PR and between 81dac41 and cf653ce.

📒 Files selected for processing (3)
  • src/runtime/timer/TimeoutObject.rs
  • src/runtime/timer/timer_object_internals.rs
  • test/js/node/timers/node-timers.test.ts

Number.MAX_VALUE as i64 saturates to i64::MAX; adding interval on top
could overflow. Saturating parks the timer far in the future, which
matches Node (diff = now - MAX_VALUE is negative so the timer is not
considered expired).
add_ms does not normalize negative nsec (unlike add_ms_float), so a
negative input produces a non-normalized Timespec. A deadline in the
past is equivalent to 'fire now', so clamp to 0.
@Jarred-Sumner
Jarred-Sumner merged commit d6a03fc into main Aug 4, 2026
34 of 48 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the claude/farm/64b1d83e/idle-start-reschedules-timer branch August 4, 2026 00:32
Comment on lines +273 to +292
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);

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);
  }
});

springmin pushed a commit to springmin/bun that referenced this pull request Aug 4, 2026
Fixes oven-sh#26508.

## Repro

Next.js 16's
[`app-render-scheduling.ts`](https://github.com/vercel/next.js/blob/31b62520366aefef9d6800cd519157a16f958052/packages/next/src/server/app-render/app-render-scheduling.ts#L29-L49)
creates two `setTimeout(fn)` calls and then writes `t2._idleStart =
t1._idleStart` so both timers share a deadline and fire in the same
event-loop turn, before any `setImmediate` scheduled from `t1`'s
callback.

```js
let immediateRan = false;
const t1 = setTimeout(() => {
  setImmediate(() => { immediateRan = true; });
});
// force the monotonic clock past a millisecond boundary
{ const s = performance.now(); while (performance.now() - s < 2) {} }
const t2 = setTimeout(() => {
  if (immediateRan) process.exit(1);
});
t2._idleStart = t1._idleStart;
```

100 iterations: **Node** 0 failures, **Bun (before)** 94 failures, **Bun
(after)** 0 failures.

## Cause

`TimeoutObject::set_idle_start` (added in oven-sh#26021) only cached the JS
value. It never updated the `EventLoopTimer.next` deadline in the native
timer heap, so the assignment had no scheduling effect and `t2` could
fire in a later turn after the `setImmediate`.

## Fix

`TimerObjectInternals::set_idle_start` recomputes the deadline as
`Timespec::EPOCH.add_ms(idle_start_ms + interval)` and calls
`All::update()` to remove and re-insert the timer. The heap comparison
in `EventLoopTimer::less` already collapses sub-millisecond precision
for JS timers and uses the insertion epoch as tiebreak, so after
`t2._idleStart = t1._idleStart` the two timers compare equal on deadline
and `t1` still fires first (lower epoch).

The setter is a no-op for cleared timers, non-ACTIVE timers, and
non-finite values; the JS value is always cached regardless.

## Verification

New `_idleStart` describe in `test/js/node/timers/node-timers.test.ts`:
- "reschedules the timer when written (Next.js pattern)": spawns a
subprocess running 50 iterations of the busy-loop repro, asserting the
immediate never runs between `t1` and `t2` and order is always `t1,t2`.
Fails on `USE_SYSTEM_BUN=1` ("FAIL: immediate ran before t2 on iteration
0"), passes with `bun bd test`.
- "ignores non-finite values and cleared timers": edge-case coverage for
string/NaN/Infinity/post-clear writes.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/node/timers/node-timers.test.ts

<!-- robobun:evidence:end -->
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.

Bun 1.3.7 does not correctly support Next.js 16 Cache Components

2 participants