Skip to content

refactor: wake the uv embed thread from NodeBindings instead of patching libuv - #54228

Open
codebytere wants to merge 29 commits into
mainfrom
uv-embedder-wake
Open

codebytere wants to merge 29 commits into
mainfrom
uv-embedder-wake

Conversation

@codebytere

@codebytere codebytere commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Description of Change

Electron runs Node's event loop on the main thread and has a helper thread that sleeps until the loop has work. A libuv handle started from outside the loop doesn't wake that thread. Today patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch (libuv/libuv#3308) makes libuv wake it on every handle change, and the helper thread reads uv_backend_timeout() off the loop thread, which is a data race.

This removes that patch. Timers and immediates started from JS keep waking the helper thread through the existing process.activateUvLoop() wrappers in lib/common/init.ts. For everything else, the main thread now computes the poll timeout itself and re-checks the loop's next deadline after every Chromium task (including tasks run by a nested loop), after microtask checkpoints, and after a native callback's call into JS, waking the helper thread only when the deadline moved earlier. A native module that starts a libuv handle from its own OS callback, with no JS on the stack, now needs a uv_async_send(); docs/breaking-changes.md covers it.

A new spec starts timers, fs, network and threadpool work from every kind of JS entry in the main process and renderer, including nested run loops and native event sources, and fails if any of it runs more than 100 ms late. It passes on Linux, macOS and Windows CI; main without the libuv patch fails 16 of those cases. CI builds of this branch and main were also compared by hand on macOS and Windows, with no difference.

Checklist

Release Notes

Notes: none

@codebytere codebytere added semver/none no-backport run-full-macos Rull the full macos test suite including all tests on mas and x64 labels Sep 23, 2026
@codebytere
codebytere force-pushed the uv-embedder-wake branch 6 times, most recently from 60a9f84 to ca37a39 Compare September 23, 2026 12:17
@codebytere
codebytere marked this pull request as ready for review September 23, 2026 13:02
@codebytere
codebytere requested review from a team as code owners September 23, 2026 13:02

@MarshallOfSound MarshallOfSound left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Went through the new wake logic. Two cases I think still lose the wake (JS run inside a nested run loop, and a stale UvRunOnce surviving StopPolling() on the renderer's primary bindings), one stale-clock issue with a suggestion, and the fixture's native-event context isn't exercising the path it says it does. Details inline.

Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread spec/fixtures/apps/uv-wake/main.js Resolved
Comment thread spec/node-uv-loop.spec.ts Resolved

@MarshallOfSound MarshallOfSound left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the quick turnaround, the round-one fixes all look right. Second pass found one more wake hole in the browser (promise continuations after a native-event entry), a re-entrant variant of the StopPolling() desync, and a narrower leftover of the nested-loop case; the other two are small.

Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread spec/node-uv-loop.spec.ts Resolved

@MarshallOfSound MarshallOfSound left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The round-two fixes all hold, and there's one straightforward bug in the deadline check itself (sleep/wake clock mismatch on macOS, suggestion inline). But I want to step back before we do another round of these.

This is the third pass where "check the deadline when JS leaves through a door we know about" has grown another door. Round one it was nested run loops. Round two it was native-event entries and their microtask continuations. This round it's a JS frame that starts a timer and then nests (setInterval followed by showSaveDialogSync), Menu::ActivatedAt doing its own Function::Call outside the new scope, the worker path depending on task-observer registration order, and an addon calling napi_call_function from its own WndProc / CFRunLoop callback. Every one of those is individually fixable, and I'm sure you'd have them done by tomorrow, but the set isn't closed: correctness now depends on every native-to-JS call site in shell/ (and in third-party addons) going through CallMethodWithArgs / V8FunctionInvoker or remembering the scope, and on observer ordering we don't control. The next person to add a MakeCallback somewhere reintroduces "timers don't fire until you move the mouse" with nothing to catch it.

The thing the libuv patch and the activateUvLoop wrappers had going for them is that they sat at the point where work is given to the loop, so they didn't care how JS was entered. I think whatever replaces them needs that same property: one entry-independent signal, with the leave-JS checks as the optimisation on top rather than the only mechanism. Options I can see, roughly in order of how much I like them:

  • Keep the isolate-level CallCompleted hook alongside NativeCallIntoJSScope and register MicrotasksCompleted on every context we attach an env to (workers included). Same cheap compare, covers any v8::Function::Call at depth 0 and any checkpoint regardless of who ran it. Still misses the starts-work-then-nests case, so pair it with a RunLoop::NestingObserver.
  • Keep the timer/immediate wrappers (they're a property set and a uv_async_send, not the expensive part of what this PR removes) as the backstop for the JS-started cases, and let the new checks handle native-started handles.
  • Ask libuv for a supported hook. An "embedder, the backend timeout just got earlier" callback is exactly what uv_loop_configure is for, and we're clearly not the only embedder who polls from another thread. Carrying our small patch until that lands is less risky than carrying an open-ended list of call sites.

Happy to be argued out of any of these, but I don't think we should land the enumerate-the-doors version as-is. Inline comments below are the concrete holes from this pass; three of the five disappear under any of the options above.

Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread shell/common/node_bindings.cc Resolved
Comment thread docs/breaking-changes.md Resolved
@codebytere

Copy link
Copy Markdown
Member Author

@MarshallOfSound agreed on the framing - three rounds of adding doors is the signal, and the property that matters is a wake at the point work is given to the loop rather than wherever JS happened to be entered from.

i'm going with your second option: the setTimeout/setInterval/setImmediate/nextTick wrappers come back as the entry-independent backstop for JS-started work, the task-observer and microtask checks stay for handles native code starts, and NativeCallIntoJSScope goes away. That closes the timer-then-nest, Menu::ActivatedAt, worklet-ordering and addon napi_call_function cases by construction instead of by call site, and the PR gets smaller rather than bigger. i picked it over the first option because that one re-adds the isolate-global hook and per-context worklet registration, which are the two pieces that already broke once each here, plus a nesting observer; and over the third because deleting the patch is the point. The clock-mismatch fix and the docs wording go in with it. Will push shortly.

Adds a fixture app that starts timers, immediates, fs, threadpool, net,
fs.watch, MessagePort and child process work from inside a uv callback, a
Chromium task, a promise continuation of one, a native window focus event
(browser) and rAF/input events (renderer), and records how long each takes
to complete beyond its own delay while nothing else drives the loop. The
spec fails if any case exceeds its budget.
…v loop earlier work

The main thread now computes uv_backend_timeout() at the end of UvRunOnce()
and hands it to the embed thread instead of the embed thread reading loop
state itself, and after every microtask checkpoint compares the loop's next
deadline against the one the embed thread is asleep on, waking it through
the existing async handle when JS entered from outside uv_run() gave the
loop earlier work. This is the embedder-side design suggested in
libuv/libuv#3308 and removes the need for UV_LOOP_INTERRUPT_ON_IO_CHANGE.
NodeBindings now wakes its own embed thread when the loop's deadline moves,
so libuv no longer has to interrupt the poller on handle and watcher
changes.
…e calls into JS

process.activateUvLoop() covers timers and immediates that JavaScript
starts, wherever it was entered from. For handles native code starts,
and for Node-internal timers, NodeBindings also checks the loop's
deadline after every task on its thread, which fires for tasks inside a
nested run loop too, and, in the browser and utility processes, when a
top-level v8::Function::Call from native code returns, since under
kExplicit a global shortcut, a menu action or a native module's own OS
callback is neither a task nor followed by a checkpoint. Workers skip the
microtask hook: their checkpoint runs in an earlier task observer, and a
pooled worklet's queue can go away under its environment.

The loop time is refreshed before computing the embed thread's timeout
and before comparing against it, and a deadline that has already passed
on the loop clock wakes the embed thread rather than assuming it is
back, since that clock counts system sleep on macOS while the poll's
timeout does not. A UvRunOnce() that belongs to polling stopped since,
including underneath it, no longer posts the embed thread, and
UvRunOnce() skips a pooled worklet environment whose first context
Blink has disposed.
net.listen() with the connection made by the other process, a native
uv_timer_start() completing through MakeCallback, timers/promises from
a promise continuation, and fs.watch touched by the other process, so
the task, nesting, microtask and native-call checks each have a case
that fails without them. net.connect() to an IP defers through
process.nextTick and so cannot complete under a nested callback scope;
it is replaced rather than skipped.
A handler that starts a socket or watcher and then blocks in a
synchronous dialog or a drag gets it polled while the nested loop runs,
through base::RunLoop::NestingObserver next to the task observer.
Workers and node-integrated subframes create and destroy a NodeBindings
each; the epoll fd polling the loop's backend fd was never closed.
…d of after a timer

kqueue reports only writes made after the loop registered the watcher,
and the other process's timer accuracy was being measured along with
it. On macOS a watcher started from a native event while JavaScript
blocks in a nested loop is the documented remaining case and is
skipped there.
@deepak1556
deepak1556 requested a review from ckerr September 25, 2026 03:12

@MarshallOfSound MarshallOfSound left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nearly there. One real thing from the epoll_ change (destruction order), the net.listen op turns out not to be the unwrapped op we wanted, and the breaking-changes paragraph over-promises in three small ways. Rest looks good.

Comment thread shell/common/node_bindings_linux.cc Resolved
Comment thread spec/fixtures/apps/uv-wake/ops.js Resolved
Comment thread docs/breaking-changes.md Resolved
…g JavaScript frame

net.listen() wakes the loop by itself through Node's wrapped
process.nextTick, so it could not fail without the checks. The testing
binding now listens with libuv directly and the other process connects;
with the checks compiled out every cell of this op outside the uv
context times out.
Any handle a native module starts from its own OS callback needs the
uv_async_send(), whether or not it called into JavaScript first; only
the four wrapped JavaScript calls are exempt in the nested cases; and a
synchronous dialog on macOS or Windows is a native modal loop, so work a
handler starts right before one waits there too.
# Conflicts:
#	shell/common/api/electron_api_testing.cc
Comment thread docs/breaking-changes.md Resolved
A uv_prepare_t or uv_check_t started from a task adds no deadline and no
watcher, so uv_backend_timeout() alone does not see it. Comparing the
loop's active handle count against the one recorded at hand-off covers
those, at the same check points.

@deepak1556 deepak1556 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, thanks for working on this!

@MarshallOfSound MarshallOfSound left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

One more pass over the handle-count addition. The comparison itself has a gap for exactly the handles it was added for (unref'd prepare/check, and any stop/unref since hand-off), and adding it has quietly made the deadline branch untested again. Also the spec wants the serial tag. Docs nits left out.

Comment thread shell/common/node_bindings.cc Resolved
Comment thread spec/fixtures/apps/uv-wake/ops.js Resolved
Comment thread spec/node-uv-loop.spec.ts Resolved
libuv's active_handles only counts referenced handles and the usual
prepare/check observer is unreferenced, so the comparison missed the
case it was added for and drifted after any unref or stop. There is no
public signal for a started handle; a lone uv_prepare_t or uv_check_t
runs when the loop next iterates, as it does in Node.js, and the docs
say so. The fixture keeps a referenced 60 s interval alive instead, so
every timer op re-arms Node's already-active timer earlier and only the
deadline comparison can see it.
It registers a global shortcut, injects a real key and asserts 100 ms
budgets, none of which tolerate other spec windows on the same display.
# Conflicts:
#	shell/common/api/electron_api_testing.cc
# Conflicts:
#	shell/common/api/electron_api_testing.cc
# Conflicts:
#	shell/common/api/electron_api_testing.cc

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

no-backport run-full-macos Rull the full macos test suite including all tests on mas and x64 semver/none

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants