Skip to content

[JSC] Add VM::addTerminationDeadline() / cancelTermination() / hasPendingTermination() for embedder-scoped wall-clock time limits - #440

Merged
dylan-conway merged 2 commits into
mainfrom
claude/vm-cancel-termination-and-deadline
Aug 15, 2026
Merged

dylan-conway merged 2 commits into
mainfrom
claude/vm-cancel-termination-and-deadline

Conversation

@dylan-conway

@dylan-conway dylan-conway commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

An embedder that gives one bounded call a time limit — node:vm's timeout in Bun — needs two things JSC doesn't serve directly: request termination at a wall-clock deadline, and once that call is over, take the request back so nothing of it reaches whatever the same VM entry runs next. Bun has been (mis)using the per-VM Watchdog for this: it is a CPU-time budget for a whole VM entry, gets armed mid-entry, its timer / deadline / CPU deadline outlive the call with no way to retire them (a late fire terminated unrelated code — a worker's entry body cut short, main-thread code stopped — or re-armed under a cleared limit and hit ASSERT(hasTimeLimit())), and instantiating it makes every later VM entry/exit pay the Watchdog entry-scope service forever. JSRunLoopTimer fires on the VM's own run loop under the API lock, so it cannot interrupt a busy VM. And "taking a termination back" means clearing the NeedTermination trap, the request flag and a pending TerminationException in concert — VM/VMTraps' business, which embedders currently do by hand.

VM::addTerminationDeadline(MonotonicTime) -> Ref<TerminationDeadline> (runtime/TerminationDeadline.{h,cpp}) — a VM's deadlines are kept earliest-first and served by a single VMTraps::queue() timer for the earliest one (the Watchdog's shape, so cancelled deadlines don't accumulate as timers; ≤ one timer per timeout window while runs happen, none while idle); when a deadline passes, notifyNeedTermination() is called from that thread. TerminationDeadline::didFire() reports whether that happened (it is final once cancel(VM&) returns, and true implies the notify has already been issued), cancel(VM&) withdraws it, and VM destruction detaches whatever is still pending so a late timer never touches a dead VM. Zero cost for VMs that never use it (a null RefPtr, no entry-scope service).

VM::hasPendingTermination() — a termination has been requested and not withdrawn, in whichever form: unhandled trap, request flag, or the TerminationException as the pending exception (V8's IsExecutionTerminating).

VM::cancelTermination() — withdraws whatever termination is pending (V8's CancelTerminateExecution), for a time-limited scope that has ended. It cannot tell requests apart, so an embedder whose VM may also be stopped from outside (a worker being terminated) checks that first or requests again; it does not undo executionForbidden(); asserts the API lock, no DeferTermination in progress, and not a forbidExecutionOnTermination() VM.

$vm.callWithTimeLimit(fn, ms) is the intended embedder pattern end to end (including re-requesting termination for an enclosing limited call whose own limit passed meanwhile — one trap bit serves nested requests), plus $vm.cancelTermination / $vm.hasPendingTermination; all allowIfNotFuzz.

Test: JSTests/stress/vm-termination-deadline.js — a passed limit cuts its call short and nothing is left pending; a limit that passes while the call is blocked in native code takes effect once script runs again; a limit that passes with the request never acted on is withdrawn cleanly; a met limit's late expiry terminates nothing (×20 short limits interleaved with ordinary code); ordinary throws pass through; nested limits with the inner firing, the outer firing, and both having passed each behave; hasPendingTermination() is false after every case. Passes repeatedly on a debug+ASAN jsc and under --useJIT=0, --useConcurrentJIT=0, --useFTLJIT=0; neighbouring termination tests unchanged. (A TerminationDeadline outliving its VM is not reachable from one jsc process; it is covered by construction — willDestroyVM() under the set's lock — and reviewed as such.)

Bun's node:vm implementation becomes: deadline = vm.addTerminationDeadline(now + timeout) → run → deadline->cancel(vm); if (deadline->didFire() && scriptAllowed) { vm.cancelTermination(); throw ERR_SCRIPT_EXECUTION_TIMEOUT }, with no timer thread or termination-state surgery of its own.

…() for embedder-scoped wall-clock time limits

An embedder that gives one bounded call a time limit (node:vm's `timeout`
in Bun) has two needs JSC does not serve directly today: request
termination at a wall-clock deadline, and — once that call is over —
take the request back so that nothing of it reaches whatever the same VM
entry runs next. The per-VM Watchdog is a CPU-time budget for the whole
entry: armed mid-entry, its timer, deadline and CPU deadline outlive the
call that armed it and there is no way to retire them, so a late fire
either terminates unrelated code or re-arms under a cleared limit
(asserting hasTimeLimit()). And "taking a termination back" means
clearing three pieces of state (the NeedTermination trap, the request
flag, a pending TerminationException) that only VM/VMTraps should be
touching in concert.

* VM::requestTerminationAt(MonotonicTime) -> Ref<VM::TerminationDeadline>:
  the deadline is served by one WorkQueue timer per VM for the earliest
  pending deadline (the Watchdog's shape, so cancelled deadlines do not
  linger as timers); when it passes, notifyNeedTermination() is called
  from the timer thread. TerminationDeadline::didFire() says whether that
  happened, cancel() withdraws it, and VM destruction detaches whatever is
  still pending, so a late timer never touches a dead VM.
* VM::cancelTerminationRequest(): withdraws a requested termination in
  whichever form it has reached — unhandled trap, request flag, pending
  TerminationException — for use by the scope that requested it once that
  scope has ended. Asserts the API lock and no DeferTermination in
  progress.
* $vm.requestTerminationAfter / terminationDeadlineDidFire /
  cancelTerminationDeadline / cancelTerminationRequest, and
  $vm.callWithTimeLimit(fn, ms) showing the intended embedder pattern
  (including re-requesting for an enclosing limited call whose own limit
  passed meanwhile).
* JSTests/stress/vm-termination-deadline.js: a passed limit cuts its call
  short and leaves nothing behind; a met limit's late expiry terminates
  nothing; ordinary throws pass through; nested limits (inner fires /
  outer fires / both fire) each behave.
@coderabbitai

coderabbitai Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 54 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7f0927a3-9d33-437a-818e-3c18e782725b

📥 Commits

Reviewing files that changed from the base of the PR and between 1f44d5c and c7a62c0.

📒 Files selected for processing (8)
  • JSTests/stress/vm-termination-deadline.js
  • Source/JavaScriptCore/CMakeLists.txt
  • Source/JavaScriptCore/Sources.txt
  • Source/JavaScriptCore/runtime/TerminationDeadline.cpp
  • Source/JavaScriptCore/runtime/TerminationDeadline.h
  • Source/JavaScriptCore/runtime/VM.cpp
  • Source/JavaScriptCore/runtime/VM.h
  • Source/JavaScriptCore/tools/JSDollarVM.cpp

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

…/ cancelTermination / hasPendingTermination; smaller $vm surface; sharper test

* Move the deadline classes out of VM.h into runtime/TerminationDeadline.{h,cpp}
  (TZone-allocated; VM.h keeps forward declarations, a RefPtr and three
  short methods). TerminationDeadline is now just {deadline, fired}: no
  back-pointer to its set — cancel() takes the VM, which the contract
  already requires to be alive — and cancel() is void, didFire() being
  final once it returns. The set tracks its armed timer with a
  MonotonicTime (infinity = none) and never arms for infinity;
  willDestroyVM() naming as for Watchdog/VMTraps.
* VM::requestTerminationAt -> addTerminationDeadline ([[nodiscard]]:
  dropping the Ref does not cancel), VM::cancelTerminationRequest ->
  cancelTermination, so the two no longer read as a pair (one adds a
  timer, the other withdraws termination state), and add
  VM::hasPendingTermination() covering all three forms a request can be
  in. Document that cancelTermination() withdraws whatever is pending —
  an embedder whose VM may also be stopped from outside checks that
  first — and does not undo executionForbidden(); assert against NaN
  deadlines and against VMs that forbidExecutionOnTermination().
* $vm: keep callWithTimeLimit (per-VM stack of active limits as VM side
  data rather than a thread_local; validates ms; "cut short" judged by
  hasTerminationRequest() so a termination swallowed in C++ still
  counts), cancelTermination and hasPendingTermination; drop the unused
  index-table hooks; register them allowIfNotFuzz.
* Test: the blocked case really blocks (sleepSeconds is a shell global)
  and no longer depends on trap-delivery latency; the "both limits
  passed" case now reaches the enclosing re-request path; a
  deterministic "limit passes with the request never acted on" case; and
  hasPendingTermination() must be false after every case.
@dylan-conway dylan-conway changed the title [JSC] Add VM::requestTerminationAt() and VM::cancelTerminationRequest() for embedder-scoped wall-clock time limits [JSC] Add VM::addTerminationDeadline() / cancelTermination() / hasPendingTermination() for embedder-scoped wall-clock time limits Aug 15, 2026
@dylan-conway
dylan-conway merged commit 8a31c0d into main Aug 15, 2026
44 checks passed
Comment on lines +32 to +33
// It is wall-clock: time spent blocked counts.
shouldBe(timesOut(() => { $vm.sleepSeconds && $vm.sleepSeconds(1); for (;;) { } }, 20), true, "blocked then looping");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 sleepSeconds is a global shell builtin (registered in jsc.cpp), not a property of $vm, so $vm.sleepSeconds is undefined and the && short-circuits — this callback degenerates to for (;;) {}, identical to line 28. The assertion still passes, but the "wall-clock: time spent blocked counts" property is never actually exercised. Use the global sleepSeconds(1) (guarded with typeof sleepSeconds === 'function' if defensiveness is desired).

Extended reasoning...

What the bug is

Line 33 of the new test is intended to verify that VM::requestTerminationAt() uses wall-clock time (so time spent blocked in a syscall counts toward the deadline), as opposed to the CPU-time semantics of Watchdog:

// It is wall-clock: time spent blocked counts.
shouldBe(timesOut(() => { $vm.sleepSeconds && $vm.sleepSeconds(1); for (;;) { } }, 20), true, "blocked then looping");

However, sleepSeconds is registered only as a global function by the jsc shell — Source/JavaScriptCore/jsc.cpp:706 has addFunction(vm, "sleepSeconds"_s, functionSleepSeconds, 1) — and there is no sleepSeconds on $vm (grep of Source/JavaScriptCore/tools/JSDollarVM.cpp returns zero matches, and this PR only adds requestTerminationAfter / terminationDeadlineDidFire / cancelTerminationDeadline / cancelTerminationRequest / callWithTimeLimit).

Step-by-step proof

  1. When line 33 executes, $vm.sleepSeconds evaluates to undefined (property lookup on the JSDollarVM object finds nothing).
  2. undefined && $vm.sleepSeconds(1) short-circuits to undefined; the sleep call is never made.
  3. The callback body reduces to for (;;) { } — byte-for-byte the same behaviour as the callback on line 28 (timesOut(() => { for (;;) { } }, 20)).
  4. Under a 20 ms limit, an infinite CPU-bound loop is terminated regardless, so timesOut(...) returns true and the shouldBe assertion passes.
  5. No time is ever spent blocked, so the property the comment claims to test — "time spent blocked counts" — is never exercised.

Why existing code doesn't prevent it

The author's own defensive guard ($vm.sleepSeconds && ...) shows awareness that the function might not exist, but the guard picked the wrong receiver. Because the guard silently degrades to a no-op rather than throwing, the test file passes cleanly and gives no signal that the intended coverage is missing.

Impact

This is a test-coverage gap in a newly added stress test, not a runtime correctness bug. The underlying implementation is wall-clock by construction (MonotonicTime deadline served by a separate WorkQueue timer thread in VM::TerminationDeadline::Set::armTimerIfNeeded), so the feature itself is fine — it just isn't being validated by the line that claims to validate it. Nothing breaks if merged as-is.

How to fix

Replace $vm.sleepSeconds && $vm.sleepSeconds(1) with the global:

shouldBe(timesOut(() => { typeof sleepSeconds === 'function' && sleepSeconds(1); for (;;) { } }, 20), true, "blocked then looping");

or simply sleepSeconds(1) if the guard isn't needed (all jsc-shell test hosts register it).

On the refutation

One verifier flagged bug_002 as a duplicate of bug_001. That is correct — they describe the same file/lines/issue — and this report is the merged result of both, so the objection is already addressed by the merge.

Comment on lines +60 to +62
// - both pass before the inner call ends: the inner error is caught by the outer function, which must still be
// stopped by its own, already-passed limit rather than loop forever.
shouldBe(timesOut(() => { try { $vm.callWithTimeLimit(() => { for (;;) { } }, 60); } catch { } for (;;) { } }, 30), true, "both limits passed");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 This test doesn't exercise the code path its comment describes. With outer=30ms and inner=60ms, the outer deadline fires first and terminates the inner for(;;) at t≈30ms; the inner scope's deadline->cancel() (on the 60ms deadline) returns false and propagates the raw TerminationException, which JS catch {} cannot catch — so the second for(;;) never runs and the enclosing-deadline re-notification loop in functionCallWithTimeLimit is never reached. The assertion still passes, but via the same path as line 59, and the "both pass before the inner call ends" / "the inner error is caught" comment is inaccurate for these timings.

Extended reasoning...

What the test claims vs. what it does

The comment at lines 60-61 says this case tests: "both pass before the inner call ends: the inner error is caught by the outer function, which must still be stopped by its own, already-passed limit rather than loop forever." That describes the scenario where the inner callWithTimeLimit converts its termination to a catchable RangeError, the JS catch {} swallows it, the second for(;;) runs, and the re-notification loop in functionCallWithTimeLimit (for (auto* enclosing : *s_activeTimeLimits) { if (enclosing->didFire()) { vm.notifyNeedTermination(); break; } }) is what stops it. With the timings actually written — outer=30ms, inner=60ms — none of that happens.

Step-by-step trace

  1. Outer callWithTimeLimit registers a deadline at t+30 and pushes it onto s_activeTimeLimits. It calls the outer arrow function.
  2. The outer arrow function calls inner callWithTimeLimit, which registers a deadline at t+60, pushes it, and calls () => { for(;;){} }.
  3. TerminationDeadline::Set arms one WorkQueue timer for the earliest deadline (30ms). At t≈30 timerFired() runs: it marks the 30ms deadline as fired (its m_deadline <= now), leaves the 60ms one in place (60 > 30), and calls vm.notifyNeedTermination().
  4. The inner for(;;) back-edge trap check throws TerminationException at t≈30ms — well before the 60ms deadline.
  5. Back in the inner functionCallWithTimeLimit: s_activeTimeLimits->removeLast() pops the inner pointer, then deadline->cancel() runs on the inner (60ms) deadline. Set::remove returns deadline.didFire(), which is false (the 60ms timer hasn't fired). So !deadline->cancel() is true and the function takes the early RELEASE_AND_RETURN, propagating the pending TerminationException unchanged. It never reaches cancelTerminationRequest() or the enclosing-deadline loop.
  6. Control unwinds into the outer arrow function's try { ... } catch { }. TerminationException is uncatchable by JS: UnwindFunctor::operator() in Interpreter.cpp guards findExceptionHandler with if (!m_isTermination), so the catch {} is skipped and the second for(;;) never runs.
  7. Back in the outer functionCallWithTimeLimit: deadline->cancel() on the 30ms deadline returns true, cancelTerminationRequest() clears the termination, the enclosing loop iterates over an empty s_activeTimeLimits, and a RangeError("timed out") is thrown. timesOut sees it and returns true — the assertion passes.

Why this matters

The assertion passes via exactly the same path as line 59 ("outer limit around a generous inner one"): outer fires, inner propagates the raw termination, outer converts it. The two things the comment says happen — both limits passing before the inner call ends, and the inner error being caught — do not occur under normal timing. For both to fire before the inner loop terminates, the WorkQueue timer or trap delivery would have to be delayed by ≥30ms, which the test cannot rely on.

Consequently the enclosing-deadline re-notification logic added in this PR (the block after vm.cancelTerminationRequest() that re-fires notifyNeedTermination() when an enclosing scope's deadline has also passed) has no test that deterministically exercises it.

Impact

No functional defect — the runtime code is fine and the test does not fail. This is a test-coverage / comment-accuracy gap: a reader will believe the nested "both fired" path is covered when it isn't, and a future regression in the re-notification loop would not be caught here.

Suggested fix

At minimum, swap the limits so the inner one is smaller (e.g. inner=20, outer=200): then the inner scope's cancel() returns true, it converts to a catchable RangeError, the JS catch {} actually catches it, and the second for(;;) runs and is stopped by the outer limit — matching the comment's "the inner error is caught by the outer function, which must still be stopped by its own limit." To specifically hit the re-notification loop (both fired before the inner scope exits), the inner call would need to block natively past both deadlines; if that can't be made deterministic, the comment should be adjusted to describe what the test actually verifies.

@github-actions

Copy link
Copy Markdown

Preview Builds

Commit Release Date
c7a62c07 autobuild-preview-pr-440-c7a62c07 2026-08-15 01:34:47 UTC

dylan-conway added a commit to oven-sh/bun that referenced this pull request Aug 15, 2026
…ermination is withdrawn when it ends (WebKit 8a31c0d8f1a1)

node:vm's `timeout` used JSC's per-VM Watchdog: a CPU-time budget for a
whole VM entry whose timer and deadlines outlived the run that armed
them, so a fire that landed after a short run terminated whatever the
thread ran next — main-thread code stopped silently, a worker's entry
body was cut short and its start never completed, an untimed nested run
hit RELEASE_ASSERT_NOT_REACHED in checkForTermination, and JSC's own
Watchdog::startTimer asserted when re-armed under a cleared limit — and
instantiating it made every later VM entry pay the Watchdog entry-scope
service. Bump WebKit to 8a31c0d8f1a1 (oven-sh/WebKit#440:
VM::addTerminationDeadline / cancelTermination / hasPendingTermination)
and rebuild the run/timeout/SIGINT scope on it:

* NodeVMRunTermination (src/jsc/bindings/vm/): one per vm run. Arms a
  wall-clock TerminationDeadline for `timeout` and, for breakOnSigint,
  holds SigintWatcher itself as the run's own receiver (receiver
  registered before the realm). finish() unregisters first, then
  classifies: not cut short -> nothing touched; the VM being stopped as a
  whole (worker terminate()/process.exit(): script gate closed) -> left
  pending for the caller to propagate; ours -> VM::cancelTermination(),
  the context's queued microtasks discarded, ERR_SCRIPT_EXECUTION_TIMEOUT
  (checked before SIGINT, as in Node) or _INTERRUPTED thrown, and an
  enclosing run whose own limit passed meanwhile re-requested. Nested
  runs each keep their own deadline.
* NodeVMScript / NodeVMModule call sites reduce to construct -> run ->
  finish -> RETURN_IF_EXCEPTION; setupWatchdog/checkForTermination and
  the SigintReceiver bases on the GC objects are gone; a context-less
  SourceTextModule's breakOnSigint now registers the caller's realm (it
  registered no realm before); a termination that unwound a module's
  evaluation but is not that run's (an enclosing timeout, a VM stop) is no
  longer recorded as the module's evaluation error; runInThisContext no
  longer discards the caller realm's whole microtask queue on timeout.
* Options parsing: the exception check after each validate*() call sits
  where it can fire.

Tests (test/js/node/vm/vm.test.ts): timeout is wall-clock and leaves
nothing armed against the caller; a timeout that never fires does not
accrue; nested runs each keep their own deadline (inner fires / outer
fires / both fired); a module whose evaluation times out is errored and
re-evaluate rethrows; a real SIGINT interrupts a stuck breakOnSigint run
and SIGINT handling is intact afterwards; a throwing option getter
surfaces as-is. vm.test.ts 255/255, Node's test-vm-timeout* and
test-vm-sigint*, and the sourcetextmodule leak/gc tests pass.
dylan-conway added a commit to oven-sh/bun that referenced this pull request Aug 17, 2026
…e-at-landing termination; exit/streams/serve/valkey/Bun.build fixes (#38660)

### What does this PR do?

Third batch of fixes from fuzzing `Worker` / `node:worker_threads`
termination and exit lifetimes (after #38436 and #38457), using
oven-sh/WebKit#440's embedder-scoped termination deadlines (already in
main's WebKit pin) for the node:vm change below.

**`process.exit()` unwinds a termination that became pending while
dispatching `'exit'`.** `Process_functionExit` dispatched the `'exit'`
listeners (which handles VM traps) and then looked up
`process.reallyExit` with no exception check in between; a worker whose
termination had been requested meanwhile carried a pending
TerminationException into `JSObject::get()`, where the first-ever lookup
of the static `reallyExit` reified it (a structure transition) and
reported "not found" because an exception was pending, and the prototype
walk asserted on the stale structure. Checking after the dispatch is
also Node's behaviour for a throwing `'exit'` listener.

**Re-tagging a held `ReadableStream` is pure.**
`readable_stream::Strong::get()` rebuilt the handle by sending the held
value through `ReadableStream::from_js` (the arbitrary-value converter)
via the throwing FFI path, whose exception check polls VM traps like
`RETURN_IF_EXCEPTION` — so "give me the stream I hold" could materialise
a worker's TerminationException right there and drop it
(`.ok().flatten()`), returning `None`/carrying on with the termination
pending. ~20 callers do that; two observed faces: `fetch()`'s
`has()`-then-`get().unwrap()` panicking (`Option::unwrap()` on `None`),
and `new Response(stream)` returning its object with an exception
pending ("allocated memory without checking for exceptions") when a
`terminate()` landed mid-construction. A `JSReadableStream`'s tag lookup
needs no scope at all, so it gets its own pure entry
(`ReadableStreamTag__taggedStream` / `ReadableStream::from_js_direct`,
the same split the generated classes' `from_js`/`from_js_direct` make)
and `Strong::get()` uses it; `fetch.rs`/`Body.rs` are unchanged from
main.


**valkey: a close event's result reaches `close()`'s caller.** On an
established socket uSockets dispatches the close event synchronously
from inside `close()`, and that event's trampoline folded whatever was
pending — including the exception a frame above `close()` was still
holding an `Err` for (`fail_with_js_value()`: reject queued commands,
then close). The timer drain's fold then hit "A JavaScript exception was
thrown, but it was cleared before it could be read" — deterministic with
a connection timeout firing in the tick where the worker's own
`process.exit()` was pending. `close()` now returns `Err` when the close
event left a termination pending (an ordinary `onclose` throw is folded
by the trampoline as any top-level callback's), `onclose` is not entered
on top of a pending exception, and the `in_close`/`close_event_threw`
handshake that laundered the result through the parent is gone.

**node:vm: wall-clock `timeout` on JSC's `TerminationDeadline`; a run's
termination is withdrawn when it ends** (supersedes #38495). `timeout`
used JSC's per-VM `Watchdog` — a CPU-time budget for a whole VM entry
whose timer and deadlines outlived the run that armed them — so a fire
landing after a short run terminated whatever the thread ran next:
main-thread code stopped silently, a worker's entry body was cut short
and its start never completed (a hang), an untimed nested run hit
`RELEASE_ASSERT_NOT_REACHED` in `checkForTermination`, JSC's
`Watchdog::startTimer` asserted when re-armed under a cleared limit, and
once instantiated every later VM entry paid the Watchdog entry-scope
service. Now one `NodeVMRunTermination` per run arms a wall-clock
`VM::addTerminationDeadline()` and, for `breakOnSigint`, holds
`SigintWatcher` as the run's own receiver; `finish()` unregisters, then
classifies: not cut short → nothing touched; the VM being stopped as a
whole (worker `terminate()`/`process.exit()`) → left pending to
propagate; ours → `VM::cancelTermination()`, the context's queued
microtasks discarded, `ERR_SCRIPT_EXECUTION_TIMEOUT` (before SIGINT, as
in Node) or `_INTERRUPTED` thrown, and an enclosing run whose own limit
passed meanwhile re-requested. Along the way: nested runs each keep
their own deadline; a context-less `SourceTextModule`'s `breakOnSigint`
registers a realm at all; a termination that unwound a module's
evaluation but isn't that run's is no longer recorded as the module's
error; `runInThisContext` no longer drops the caller realm's whole
microtask queue on timeout; the timeout is wall-clock like Node's (time
spent blocked counts). The hang half of #31885 is covered by a test here
(its crash half no longer reproduces on main). `SigintWatcher` now keeps
a single receiver list under one lock and records a SIGINT on each
receiver and requests its VM's termination in one step (two lists
signalled in two steps could terminate a run that had no SIGINT
recorded, letting a raw TerminationException escape `vm.runInContext`);
`GlobalObjectHolder` and realm registration are gone. On an
`afterEvaluate` context, microtasks a script left when its synchronous
part timed out run at the next evaluation's checkpoint under that run's
timeout, and a checkpoint that is itself cut short discards the rest —
both as in Node. `Bun.spawnSync`'s blocking fast path is no longer
conditional on a vm timeout: the old guard keyed off JSC's Watchdog,
which nothing arms any more (its bindings are deleted), and neither
spawnSync path is interruptible by the deadline — both throw the timeout
once the child exits, as Node does.

**A TerminationException that has left script is taken at the native/JS
boundary, as WebCore takes it; above that, "the VM has stopped" is a
flag and a `JsError::Terminated`, never a pending exception.** JSC
treats the TerminationException as an unwinding device for the script
frames above it: `VM::m_hasTerminationRequest` is reset when the
outermost `VMEntryScope` exits, `m_exception` is not, and JSC asserts
(`VMTraps::deferTerminationSlow`, `VM::setException`,
`Interpreter::executeCall`'s `assertNoException`) if the embedder is
still holding the exception under the next `DeferTermination` or entry.
WebCore therefore either takes it in the frame that called JS
(`JSExecState::profiledCall`'s `NakedPtr<Exception>` +
`forbidExecution()`) or leaves it pending and stops driving the VM. Bun
did neither: it kept a stopped worker's TerminationException pending
across the rest of the loop turn and all of teardown while continuing to
allocate, convert and call into JSC, re-asserted JSC's request bit
wherever it noticed (`keepTerminationRequest…`), and carved "is what's
pending the termination?" exceptions into every fold and gate that could
meet it — the source of the recurring `deferTerminationSlow` asserts,
"cleared before it could be read" panics and re-entry crashes in the two
previous batches. Now:
- Every Rust read of a pending exception at the FFI layer
(`TopExceptionScope::thrown()` / `return_if_exception()`, i.e. the
throwing FFI wrappers) and the C++ leaves that return to native code
without one (`GlobalObject::drainMicrotasks`, the timer trampoline,
`assignToStream`) apply one policy, `Bun::takeTerminationOutsideScript`:
a TerminationException with no script beneath it (`!vm.isEntered()`) is
the VM's stop arriving at native code — clear it, reset JSC's request
flag as an entry-scope exit would, `setExecutionForbidden()` (WebCore's
`forbidExecution()` at the same point) — and the caller learns
`JsError::Terminated`; beneath script (a host function, a nested tick)
it stays pending as `Thrown` for JSC to unwind, and the frame it lands
in takes it. `keepTerminationRequest…` and the carve-outs are gone.
- `JsError` gains `Terminated` ("already taken; nothing pending; stand
down"). The fold (`report_error_or_terminate` / `dispatch::fold`)
returns `Stopped` for it; `take_exception()` is total (a `Terminated`, a
termination still pending beneath script, or a `Thrown` that lost its
name through an error enum on an execution-forbidden VM all yield the
inert termination cell, which every reporter drops); host-function
trampolines handed `Terminated` rethrow only when there is script above
to unwind; loop level uses `Stopped` / `Stopped::throw`. `tick_turn`
propagates a stop out of every phase instead of probing
`has_exception()`.
- No script is entered on a VM whose stop was requested (any thread: the
script gate) or carried out (this thread: `executionForbidden`):
`clientData(vm)->isJSExecutionForbidden(vm)` gates `Bun__JSValue__call`,
`AsyncContextFrame::call`, EventEmitter's listener loop, the timer
trampoline, `NAPI_PREAMBLE` (Node's `can_call_into_js`,
`napi_cannot_run_js` for module API ≥ 10) and the microtask drain;
`uncaught_exception` / `unhandled_rejection` / socket, ServerWebSocket
and `Bun.serve` error handlers stand down on a stopped VM. A termination
is never turned into a value: `JSC__AnyPromise__wrap` /
`JSC__JSPromise__wrap` no longer reject a promise with a still-pending
TerminationException's string, `JSValue::toError` does not unwrap the
termination cell, `HTMLRewriter`'s handler thunk does not record it as
the handler's error, `NodeVMRunTermination::finish()` re-checks the gate
after `cancelTermination()` so a `terminate()` landing in that window
still wins, and the REPL no longer uses `executionForbidden` (one-way in
JSC) as a Ctrl-C flag.
- `ReadableStream::cancel`/`error` (which enter script) are
exception-checked FFI now and their callers propagate;
`test/internal/source-lints/jsresult-swallow.test.ts` ratchets the
shapes that got us here (discarding the result of a call that enters
script, collapsing a `JsResult` off the call, dropping a taken
exception): 21 grandfathered sites, new ones fail.

**Bun.build plugin requests: one owner, one answer.** An
`onResolve`/`onLoad` request handed to the plugins' VM was co-owned —
linked in the bundle thread's outstanding list and held by the JS side
at once — and when that VM shut down the *bundle* thread fabricated
answers for everything still linked while the JS thread could be
answering the same request; an answer already in flight was failed and
then delivered again (`unreachable!()` in `on_resolve` under a
terminate-during-`Bun.build` stress). Ownership is now linear: once
dispatched, a request belongs to the plugins' thread until that thread
hands it back with its one answer through the bundle thread's queue.
`BundlerPlugin` records what it holds;
`onResolveAsync`/`onLoadAsync`/`addError` forward only for a request
still held (a plugin answering twice is dropped there too);
`tombstone()` — the VM's stop phase — answers everything still held as
cancelled; a hop arriving after that, or released unrun by the dying VM,
is answered as cancelled on that same thread. The bundle thread never
answers a handed-over request: on cancellation it marks the pass, stops
handing requests over (answering later dispatches itself, through its
own queue) and consumes answers until none is pending.
`fail_outstanding_plugin_requests` and the per-request arbitration are
gone. `args.defer()` is refused (`ERR_INVALID_STATE`) once the request
is no longer held — after the callback settled it re-counted the load as
deferred (a build that never finished), and after the build it touched
freed memory.

**`Bun.build` `.defer()`: its notification gets its own queue node, and
the pass waits for the defer hop to come back.** With an `onLoad` that
calls `defer()` without awaiting it and answers straight away: the
deferral notification and the load's answer both used the Load's single
intrusive Mini-queue node, so a second enqueue rewrote/re-linked it (the
notification ran as a second answer — `unreachable` in `on_load` — or
was lost); and the `DeferredBatchTask` hop that resolves the `.defer()`
promises on the plugins' thread is embedded in `BundleV2` with nothing
ordering the pass's completion after it, so the pass finished and freed
`BundleV2` while the hop was still queued (**heap-use-after-free** in
`run_on_js_thread`, on main; in release builds the same accounting error
also surfaced as `panic: int cast: TryFromIntError(NegOverflow)` in
`on_parse_task_complete` on the bundle thread, and — the pass declaring
itself done one ParseTask early — as use-after-frees on the shared parse
pool: reading the freed `BundleV2` in `ParseTask::run_from_thread_pool`,
cloning freed options in `Transpiler::for_worker`, and parsing
plugin-provided contents freed by `deinit_without_freeing_arena`). The
notification now has its own node, and the pass marks the hop
outstanding and is not done until it posts itself back (also from
`release_unrun`).

**Requesting a VM's termination from its own thread no longer releases
the API lock.** `JSC__VM__notifyNeedTermination` dropped and retook the
JS API lock around `VM::notifyNeedTermination()` when the caller held
it; from the VM's own thread inside a host call (a worker terminating
itself on an unhandled rejection reported from within
`process.nextTick`'s drain) the release ran `JSLock::willReleaseLock`'s
microtask checkpoint mid-host-call under a pending exception
(`ExceptionScope::assertNoException`, arbitrary script re-entered).
`VMTraps::fireTrap` is `CONCURRENT_SAFE`; the lock juggling is gone.

**Bun.serve: a request context's microtask checkpoint lands the VM's
termination.** `RequestContext` drains microtasks after calling into
script and then keeps rendering — for a promise/stream body, attaching
its continuation with `then`. When that checkpoint met a worker's
TerminationException the render went on with it pending and JSC asserted
in the reaction setup (`assertNoException` via `JSC__JSValue___then`; on
main too). The drain — a uWS callback's frame — now takes it and reports
the VM stopped, and
`on_response`/`do_render_stream`/`do_render_with_body` leave the request
to the stop's connection close.

**Nothing queued runs after a worker's VM stops.** A worker that called
`process.exit()` (or was terminated) inside a callback still ran that
turn's remaining `process.nextTick` queue and microtasks — script after
`exit()`, which Node never runs — because the stop only closed the gate
for *new* entries while `GlobalObject::drainMicrotasks` kept draining.
The drain now runs nothing once the VM's stop was requested (JSC
discards its own queue the same way under `executionForbidden`), and
HTMLRewriter's shutdown release, which had keyed on "is the VM shutting
down", keys on the closed task queue so parked pipes are still freed.

**HTMLRewriter: a handler promise's reactions report a pending
exception.** `on_handler_resolve`/`on_handler_reject` resume the rewrite
(more handlers, sink writes, stream delivery) or fail the output stream
and then returned `Ok(undefined)` unconditionally; a termination met in
there stayed pending under a returned value ("host fn return/exception
state mismatch" in a worker terminated mid-transform; on main). They
return `Err` when the scope has an exception. And a transform parked on
a handler promise no longer leaks in a worker torn down mid-transform:
its pipe's ref was only ever released from the promise context's GC
destructor, which bails once the VM is shutting down ("the queue won't
drain"), so every parked pipe and its lol-html state leaked (2.2 MB /
9.6k allocations after six terminated workers under LSAN); on a
shutting-down VM the destructor now abandons the pipe inline,
script-free.

**Bun.serve counts a connection from accept, not from the end of the TLS
handshake.** A server keeps its JS wrapper — the handler shadows' only
GC root — Strong until it is drained, then downgrades it to a bare
`Weak` value on the premise that nothing reaches a dispatch trampoline
afterwards. But a TLS connection counted only once its handshake
completed (uWS fires its filter `+1` post-handshake for SSL) so a
handshake in flight when the listener closed could still reach
`onConnection`/request dispatch through whatever the wrapper and shadow
cells had become (UBSAN "member call on null `ClassInfo`" in
`on_connection_callback`; reproducibly on main under
`BUN_GARBAGE_COLLECTOR_LEVEL=1`, `JSObject::realm()` assert / SEGV in
`NodeHTTPServer__onRequest` for a TLS request reaching a drained
node:https server in a worker; observable without GC as a graceful
`stop()` answering a mid-handshake TLS client 503). uWS now also fires
an "accepted" filter event pair (`+2` at TCP accept for both transports,
`-2` on close/upgrade) and `NewServer` counts those, so `is_drained()` —
and with it the Strong hold — covers every HTTP/1 socket that can still
reach a handler; `js_value_for_dispatch()` is the script gate alone plus
a debug assertion of that invariant. (HTTP/3 connections are still not
counted; that is left as it is on main.)

**Async-iterable stream sources stand down on a termination.** When the
pump's abrupt completion is the TerminationException,
`takeAbruptCompletion` leaves it pending and returns nothing — "return,
run nothing" everywhere else in the streams port — but the
async-iterable source substituted `undefined` and ran its error tail
(`errorCodeIs` lookups, `iterator.throw(undefined)`) over the pending
termination, walking objects mid-teardown (JSC `object->structure() ==
this` assert with `new Response(gen())` from a worker's `Bun.serve`
handler / async-iterable `fetch()` bodies when `terminate()` lands; on
main). It now drops the iterator and pull promise and lets the
termination propagate.

**Streams tee tolerates a tee whose construction was cut short.** A
branch's start reaction is queued by the branch's construction, before
the tee records it; if construction stops after that (the second branch
throwing, a worker terminated in between), the reaction ran its
pull/close steps against unset branch slots (UBSAN null
`JSReadableStream` in `teeBranchDefaultController`; main's streams
code). The branch-controller helpers now treat a missing branch like a
torn-down one.

### How did you verify your code works?

`worker-terminate-lifetime.test.ts`: terminate() workers whose
Bun.serve() renders promise/stream bodies stuck in a microtask (asserted
before); terminate() during HTMLRewriter transforms with async element
handlers (panicked intermittently on release+ASAN before; also the LSAN
check for the parked-pipe leak); terminate() while async-iterable
Response/request bodies are pumped (asserted 4/4 on release+ASAN before,
and printed the termination as an unhandled rejection ~50% of the time
until the wrap/toError changes). `worker-terminate-funnels.test.ts`
(terminate() at every native→JS entry point) passes throughout.
`worker_threads.test.ts`: "nothing queued runs after the worker's VM
stops" (nextTick / microtask / nested shapes; releases run them) and "no
JS entry after a worker's termination has been thrown" — a worker stuck
in a MessagePort or socket-data callback with due timers, immediates,
nextTicks, microtasks, socket data, port deliveries, an interval and an
`'exit'` listener queued sees none of them run after `terminate()`
(releases run the nextTicks/microtasks). `serve.test.ts`: a TLS
connection whose ServerHello is held back until after a graceful
`stop()` is served (503 before the accept accounting).
`test/bundler/bundler_defer.test.ts`: 24 concurrent builds in a busy
worker (and on the main thread) with an un-awaited `defer()` + immediate
answer all succeed (ASAN reported the use-after-free before); `defer()`
after the build settled is refused. `test/js/node/vm/vm.test.ts`:
timeout is wall-clock and leaves nothing armed against the caller; a
timeout that never fires does not accrue over 100 runs; nested runs each
keep their own deadline (inner fires / outer fires / both fired); a
module whose evaluation times out is `errored` and re-`evaluate()`
rethrows; a real SIGINT interrupts only the innermost stuck
`breakOnSigint` run and a listener still sees the next SIGINT; a
throwing option getter surfaces as-is. vm.test.ts (257), Node's
`test-vm-timeout*`/`test-vm-sigint*` (7) and the SourceTextModule
leak/gc tests pass; the fuzz cases behind the watchdog findings (worker
never online after a timed vm run; later code cut short) run clean, as
do the fuzz seeds behind each termination-model signature
(`deferTerminationSlow` assert, "cleared before it could be read",
"Couldn't convert a JavaScript exception", "Expected an exception to be
thrown") on debug and release-ASAN.

The `process.exit()` and fetch changes come from fuzz signatures that
only reproduce under release-ASAN timing; fetch stream/body suites and
the worker fetch tests are unchanged locally.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
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.

1 participant