Skip to content

timers: share the timer state instead of borrowing it exclusively - #48854

Merged
dylan-conway merged 1 commit into
mainfrom
claude/timers-shared-state
Nov 13, 2026
Merged

dylan-conway merged 1 commit into
mainfrom
claude/timers-shared-state

Conversation

@dylan-conway

@dylan-conway dylan-conway commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

A timer runs JavaScript that sets and clears timers, so timer::All and the nodes in its heaps are reached again while a caller still uses them. They were handed out as &'static mut, or as raw pointers to dereference field by field. &mut All was live across callbacks in drain_timers, get_timeout and set_timeout (valueOf), and wtf_arm formed one on other threads.

What changes while shared is now a Cell, All takes &self, and timer_all() returns &All. Removes 114 unsafe blocks and 8 unsafe fn.

  • Owners hold a plain EventLoopTimer, not a JsCell of one.
  • All::remove and VirtualMachine::timer_remove take a reference. The test for an armed timer moved into timer_remove from its callers, so it is safe. All::remove still expects a linked timer.
  • All::insert and All::update take a raw pointer as before, because the heap keeps it.
  • Still unsafe: linking a node into the heap, reading a node out of it, and the collections, which are borrowed in blocks in which no JavaScript runs.
  • Deleted: timer_all_mut, the per-module accessors (timer_all, timer_heap, vm_timer), the SQL timer hooks (they repeated the ones on VirtualMachine), ClearedTimers, Deactivated, EventLoopDelayMonitor.rs, Timeout::cancel, three resets of links the heap had already cleared, and WTFTimer.repeat (never read).

Where the compiled code changes

  • Layout: a cell has no niche, so RuntimeState and EventLoopTimer are repr(C) to keep timer and next at offset 0. No type grew.
  • Android only: the existing RUNTIME_STATE is declared with #[thread_local], like the VM pointer, instead of thread_local!. A tick now names it three times instead of once, and on Android the macro's reads are not merged. A read compiles to the same code on Linux, macOS, Windows and FreeBSD.
  • Less work: FakeTimers::clear releases each timer as it pops it and no longer collects them.
  • Instructions (release, x64, before LTO): bun_runtime −274, bun_event_loop −7, bun_jsc +4, bun_sql_jsc +86 (reset_connection_timeout is inlined into its 7 callers, 32 fewer calls). 216 crates are byte-identical.
  • Hot paths: auto_tick −4, auto_tick_active −4, get_timeout −2, insert −1, set_timeout −13.
  • Longer functions: 14 in bun_runtime against 29 shorter, by 1 to 7 instructions (stop_advancing +7, Histogram::set_enabled +6, use_fake_timers_with_default +6), from fields read again after a call and register allocation. No new check, copy or allocation.

How did you verify your code works?

Debug build, 28 test files for timers, fake timers, AbortSignal.timeout, watchFile, cron, TLS and libuv timers: 24 in full (721 pass), the 4 slow ones by test name (cron's --hot test and the rest of node-tls-connect are left to CI). The 4 tests that fail also fail on main.


Generated by Claude Code

A timer runs JavaScript that sets and clears timers, so `timer::All` and the
nodes in its heaps are reached again while a caller still uses them. They were
handed out as `&'static mut` or as raw pointers to dereference per field.
`&mut All` was live across callbacks in `drain_timers`, `get_timeout` and
`set_timeout` (`valueOf`), and `wtf_arm` formed one on other threads.

- `EventLoopTimer`, the heap links and the scalars of `All` and `FakeTimers`
  are `Cell`s. `All` takes `&self` and `timer_all()` returns `&All`.
- Owners hold a plain `EventLoopTimer`, not a `JsCell` of one.
- Collections are borrowed in `unsafe` blocks in which no JavaScript runs.
- `All::remove` takes a reference. So does `VirtualMachine::timer_remove`,
  which is safe: the links cannot be written through a shared reference, and
  the test for an armed timer moved into it from its callers.
- `RuntimeState` and `EventLoopTimer` are `repr(C)`, which keeps `timer` and
  `next` at offset 0. A cell has no niche, so the fields would be reordered.
- `RUNTIME_STATE` is `#[thread_local]`, like the VM pointer.
- `FakeTimers::clear` releases each timer as it pops it.

Deleted: `timer_all_mut` and the per-module accessors (`timer_all`,
`timer_heap`, `vm_timer`), the SQL timer hooks, which repeated the ones on
`VirtualMachine`, `ClearedTimers`, `Deactivated`, `EventLoopDelayMonitor.rs`,
`Timeout::cancel`, three resets of links the heap had already cleared, and
`WTFTimer.repeat`, never read.
@robobun

robobun commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 12:05 PM PT - Nov 13th, 2026

@claude, your commit 78e15cf is building: #141170

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The timer system now uses cell-backed timer and heap fields with shared-reference operations. Runtime timer accessors and hooks use shared references. Timer owners across JavaScript, networking, DNS, test-runner, and SQL code use the updated APIs.

Changes

Timer state and heap

Layer / File(s) Summary
Timer node and intrusive heap
src/event_loop/EventLoopTimer.rs, src/io/heap.rs, src/install/lifecycle_script_runner.rs, src/install/PackageManager.rs
Timer fields and intrusive links use interior mutability. Heap operations and lifecycle subprocess removal use shared references. Lifecycle script list initialization now uses its default value.
Shared timer collection and hooks
src/runtime/jsc_hooks.rs, src/runtime/timer/mod.rs, src/runtime/timer/DateHeaderTimer.rs, src/runtime/timer/EventLoopDelayMonitor.rs
Timer collection operations and runtime accessors use shared references and cell-backed state. Event-loop ticking, cancellation, teardown, and event-loop delay monitoring use the updated APIs. The separate delay-monitor module was removed.
JavaScript timers and fake timers
src/runtime/timer/Timer.rs, src/runtime/timer/WTFTimer.rs, src/runtime/timer/timer_object_internals.rs, src/runtime/test_runner/timers/FakeTimers.rs, src/runtime/test_runner/*, src/runtime/cli/test_command.rs
JavaScript timer operations and fake-timer state use the shared timer collection and interior-mutability accessors. Fake-timer clearing drains the heap and releases timer owners. Test-runner timer handling uses the shared collection.
Timer-owning runtime components
src/jsc/AbortSignal.rs, src/jsc/GarbageCollectionController.rs, src/jsc/VirtualMachine.rs, src/jsc/web_worker.rs, src/runtime/api/bun/*, src/runtime/api/cron.rs, src/runtime/dns_jsc/*, src/runtime/node/quic/endpoint.rs, src/runtime/socket/*, src/runtime/valkey_jsc/js_valkey.rs, src/sql_jsc/shared/ConnectionTimers.rs
Timer owners store EventLoopTimer directly in place of JsCell wrappers where applicable. Their scheduling, firing, and removal paths use cell accessors and shared timer methods. VM timer hooks now accept shared VM and timer references.
Runtime timer integrations
src/runtime/bake/dev_server/*, src/runtime/napi/uv_posix.rs, src/runtime/node/histogram.rs, src/runtime/node/node_fs_stat_watcher.rs, src/runtime/dispatch.rs, src/runtime/hw_exports.rs, src/sql_jsc/jsc.rs
Development-server, N-API, Node.js, and dispatch call sites use the updated timer accessors. SQL timer heap hooks, the SQL VM timer accessor, and the TimerHeap wrapper were removed.

Suggested reviewers: jarred-sumner, alii

Merge Risk: Minimal · up to 78e15

This change moves timer state to shared references and cells and removes many unsafe blocks. No concrete behavior regression was found in review. The remaining uncertainty is the normal CI validation the author has already noted.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: timer state is now shared (through Cell and &self receivers) instead of being borrowed exclusively (through &mut). The changeset converts timer::All and EventLoopTimer…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the repository template. It has both required sections, 'What does this PR do?' and 'How did you verify your code works?'. The first section explains the motivation: timer stat…
Full details: Title check

Explanation

The title names the main change: timer state is now shared (through Cell and &self receivers) instead of being borrowed exclusively (through &mut). The changeset converts timer::All and EventLoopTimer access to shared references and Cell-based state, so the title matches the primary change.

Full details: Description check

Explanation

The description follows the repository template. It has both required sections, 'What does this PR do?' and 'How did you verify your code works?'. The first section explains the motivation: timer state was borrowed exclusively while JavaScript could re-enter it, and the change moves that state to shared references with Cell. It lists the API changes, the deleted items, and the compiled-code effects, including the Android-only thread-local change. The second section gives the build type, the 28 test files, the 24 run in full with 721 passing, the 4 slow tests run by name, the 4 failures that also fail on main, and the CI-deferred tests. The description is specific and complete enough for a reviewer to decide.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between e67258f and 78e15cf.

Files selected for processing: 40

  • src/event_loop/EventLoopTimer.rs
  • src/install/PackageManager.rs
  • src/install/lifecycle_script_runner.rs
  • src/io/heap.rs
  • src/jsc/AbortSignal.rs
  • src/jsc/GarbageCollectionController.rs
  • src/jsc/VirtualMachine.rs
  • src/jsc/web_worker.rs
  • src/runtime/api/bun/js_bun_spawn_bindings.rs
  • src/runtime/api/bun/subprocess.rs
  • src/runtime/api/cron.rs
  • src/runtime/bake/dev_server/hmr_socket.rs
  • src/runtime/bake/dev_server/lifecycle.rs
  • src/runtime/bake/dev_server/memory_cost.rs
  • src/runtime/bake/dev_server/source_map_store.rs
  • src/runtime/cli/test_command.rs
  • src/runtime/dispatch.rs
  • src/runtime/dns_jsc/dns.rs
  • src/runtime/dns_jsc/dns_sd.rs
  • src/runtime/hw_exports.rs
  • src/runtime/jsc_hooks.rs
  • src/runtime/napi/uv_posix.rs
  • src/runtime/node/histogram.rs
  • src/runtime/node/node_fs_stat_watcher.rs
  • src/runtime/node/quic/endpoint.rs
  • src/runtime/socket/UpgradedDuplex.rs
  • src/runtime/socket/WindowsNamedPipe.rs
  • src/runtime/test_runner/bun_test.rs
  • src/runtime/test_runner/jest.rs
  • src/runtime/test_runner/timers/FakeTimers.rs
  • src/runtime/test_runner/vi_wait.rs
  • src/runtime/timer/DateHeaderTimer.rs
  • src/runtime/timer/EventLoopDelayMonitor.rs
  • src/runtime/timer/Timer.rs
  • src/runtime/timer/WTFTimer.rs
  • src/runtime/timer/mod.rs
  • src/runtime/timer/timer_object_internals.rs
  • src/runtime/valkey_jsc/js_valkey.rs
  • src/sql_jsc/jsc.rs
  • src/sql_jsc/shared/ConnectionTimers.rs
Files with no reviewable changes: 2

  • src/runtime/hw_exports.rs
  • src/runtime/timer/EventLoopDelayMonitor.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@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 note, I also checked: the cross-thread wtf_arm/wtf_disarm path (node state/next/links are only touched under the wtf_timers guard, and ensure_uv_timer is skipped off the owning thread); the callers that lost their own state == ACTIVE check before timer_remove (GC controller arm/deinit, AbortSignal, cron, etc. — the check moved into VirtualMachine::timer_remove, so behavior is unchanged); and FakeTimers::clear releasing owners as it pops rather than collecting them. No build or test run was done in this review; the PR's test claims were not independently verified.

Extended reasoning...

The change is a ~3000-line refactor of the unsafe Rust timer subsystem across 40 files, converting exclusive borrows and raw pointer field access to shared &self with Cell/UnsafeCell interior mutability, changing RuntimeState to thread-local and repr(C), and deleting several accessors and files. It touches no injection, auth or data-exposure surface, but it is memory-safety-critical code reached from every timer, GC pacing tick and the fake-timer test runner. The size, the number of soundness arguments that now rest on SAFETY comments rather than the type system, and the Windows-only cfg-gated paths that cannot be checked by reading alone are why a human maintainer should still review it.

Comment thread src/runtime/timer/mod.rs Resolved

Copy link
Copy Markdown
Member Author

buildkite/bun (build 141170) was marked failed because the four darwin x64 - test-bun jobs expired in the queue before they started, so no test ran on them. The other 184 jobs passed. The four jobs are scheduled again in the same build, and there is nothing to change in this PR.


Generated by Claude Code

@dylan-conway
dylan-conway merged commit b6e7b9c into main Nov 13, 2026
10 of 11 checks passed
@dylan-conway
dylan-conway deleted the claude/timers-shared-state branch November 13, 2026 19:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants