Repository navigation
refactor: wake the uv embed thread from NodeBindings instead of patching libuv - #54228
codebytere wants to merge 29 commits into
Conversation
60a9f84 to
ca37a39
Compare
MarshallOfSound
left a comment
There was a problem hiding this comment.
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.
ca37a39 to
5bd6fbc
Compare
MarshallOfSound
left a comment
There was a problem hiding this comment.
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.
5bd6fbc to
aa78c40
Compare
MarshallOfSound
left a comment
There was a problem hiding this comment.
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
CallCompletedhook alongsideNativeCallIntoJSScopeand registerMicrotasksCompletedon every context we attach an env to (workers included). Same cheap compare, covers anyv8::Function::Callat depth 0 and any checkpoint regardless of who ran it. Still misses the starts-work-then-nests case, so pair it with aRunLoop::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_configureis 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.
|
@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 |
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.
aa78c40 to
90b2d50
Compare
…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.
90b2d50 to
ff88f7b
Compare
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.
# Conflicts: # shell/common/api/electron_api_testing.cc
MarshallOfSound
left a comment
There was a problem hiding this comment.
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.
…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
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
left a comment
There was a problem hiding this comment.
LGTM, thanks for working on this!
MarshallOfSound
left a comment
There was a problem hiding this comment.
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.
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
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 readsuv_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 inlib/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 auv_async_send();docs/breaking-changes.mdcovers 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
npm testpassesRelease Notes
Notes: none