Skip to content

Having multiple JavaScript contexts causes a race condition in uv event loop handling #894

Closed

Description

@rprichard

I'm experiencing a problem where, intermittently, setImmediate stops working -- its callback is not called. If setImmediate is called again, repeatedly, none of the callbacks are called. They are not called until some other node.js callback runs, such as fs.readFile, which flushes them all out.

The problem also happens with process.nextTick, but it seems to reproduce more readily with setImmediate.

The problem might be Windows only, as I haven't seen it on other OS's.

I debugged the problem on Windows, and I think I largely understand what's breaking.

The UV event loop integration in NodeBindings expects the "embed" thread to block on the UV event loop, and when something happens, it wakes up the main thread, and waits until the main thread has finished before blocking on the UV event loop again. The interaction between the two threads is governed by the NodeBindings::embed_sem_ semaphore. The semaphore is initially 0. NodeBindings::UvRunOnce increments it, and NodeBindings::EmbedThreadRunner decrements it. UvRunOnce is called from NodeBindings::RunMessageLoop, which gets the cycle started.

Unfortunately, when there is more than one JavaScript context, AtomRendererClient::DidCreateScriptContext calls NodeBindings::RunMessageLoop more than once, which allows the semaphore to increase arbitrarily, and allows the embed thread to run while the main thread is calling uv_run.

I think this isn't supposed to happen, so we don't need to know any more to implement a fix.

That said, I spent a lot of time instrumenting and debugging the program, so I'll also explain what I think is going on.

For setImmediate, the important thing is that AtomBindings::ActivateUVLoop works. ActivateUVLoop runs on the main thread and works by calling uv_async_send, which on Windows, posts a packet to the run loop's IO Completion Port. This packet is dequeued (and requeued) in NodeBindingsWin::PollEvents. Here's what's supposed to happen next:

  1. [embed] Embed thread wakes up the main thread, then blocks on the semaphore.
  2. [main] UvRunOnce calls uv_run with flags UV_RUN_ONCE | UV_RUN_NOWAIT.
  3. [main] uv_run calls uv_poll_ex.
  4. [main] uv_poll_ex dequeues the async req.
  5. [main] uv_poll_ex inserts the async req into loop->pending_reqs_tail.
  6. [main] uv_run returns.
  7. [main] Main thread signals embed thread to start again.
  8. [embed] PollEvents notices that uv_loop_->pending_reqs_tail is non-NULL, so it immediately returns (without checking the IOCP).
  9. [embed] Embed thread wakes up the main thread, then blocks on the semaphore.
  10. [main] UvRunOnce calls uv_run again with the same flags.
  11. [main] uv_run calls uv_process_reqs, which calls uv_process_async_wakeup_req, which calls AtomBindings::OnCallNextTick.
  12. [main] AtomBindings::OnCallNextTick resets self->pending_next_ticks_.

In the failure I'm seeing, I think step 8 happens between steps 4 and 5. PollEvents decides that it should block on the IOCP, but when it does block, there is no packet to dequeue. The async req sits unexamined in the loop->pending_reqs_tail queue, because the embed thread isn't waking up the main thread. Later calls to AtomBindings::ActivateUVLoop do nothing because self->pending_next_ticks_ is non-empty.

Here's the test case I have:

package.json:

{
    "name": "AtomImmediateBug",
    "version": "0.1.0",
    "main": "main.js"
}

main.js:

var app = require("app");
var BrowserWindow = require("browser-window");
var bw = null;
app.on("ready", function() {
    bw = new BrowserWindow({ width: 300, height: 300 });
    bw.loadUrl("file://" + __dirname + "/index.html");
    bw.openDevTools();
});

index.html:

<html>
    <head>
        <script>
            console.log("index.html")
            var clickCount = 0;
            var counter = 0;
            function stress() {
                console.log("click " + ++clickCount);
                setImmediate(stressContinue);
            }
            function stressContinue() {
                counter++;
                if (counter >= 5) {
                    console.log("DONE");
                    counter = 0;
                } else {
                    setImmediate(stressContinue);
                }
            }
        </script>
    </head>
    <body>
    <a href="javascript:stress();">Stress</a>
        <!-- Each iframe adds a RunMessageLoop call, which might make it easier
             to reproduce the problem. -->
        <iframe src="index2.html"></iframe>
        <iframe src="index2.html"></iframe>
        <iframe src="index2.html"></iframe>
        <iframe src="index2.html"></iframe>
    </body>
</html>

index2.html:

<html>
    <head>
        <script>console.log("index2.html")</script>
    </head>
    <body>
    </body>
</html>

Click the Stress link until DONE stops appearing. For me, it usually broke in under 10 clicks.

I tested this program with v0.19.4 atom-shell on 32-bit Windows 7 Ultimate SP1. I ran Windows in a 4-core VM in VirtualBox 4.3.10 on a 4-core/8-thread 64-bit Ubuntu machine.

Adding a sleep between steps 4 and 5 above might also help. At one point, it helped enormously when the test case used process.nextTick instead of setImmediate.

Here's the vendor/node patch that does that:

diff --git a/deps/uv/src/win/core.c b/deps/uv/src/win/core.c
index c9e4c88..0ff80a4 100644
--- a/deps/uv/src/win/core.c
+++ b/deps/uv/src/win/core.c
@@ -310,6 +310,7 @@ static void uv_poll(uv_loop_t* loop, DWORD timeout) {
                             timeout);

   if (overlapped) {
+    Sleep(300);
     /* Package was dequeued */
     req = uv_overlapped_to_req(overlapped);
     uv_insert_pending_req(loop, req);
@@ -346,6 +347,7 @@ static void uv_poll_ex(uv_loop_t* loop, DWORD timeout) {

   if (success) {
     for (i = 0; i < count; i++) {
+      Sleep(300);
       /* Package was dequeued */
       req = uv_overlapped_to_req(overlappeds[i].lpOverlapped);
       uv_insert_pending_req(loop, req);

Activity

  1. changed the title [-]Having multiple Javascript contexts causes a race condition in uv event loop handling[/-] [+]Having multiple JavaScript contexts causes a race condition in uv event loop handling[/+] on Dec 5, 2014
  2. rprichard commented on Dec 5, 2014

    @rprichard
    ContributorAuthor

    My attached test case reproduced easily for me (under 10 clicks) on two other Windows installs (a Windows 7 non-VM and a single-core Windows 8.1 VM), so maybe it'll reproduce for others, too.

  3. zcbenz commented on Dec 5, 2014

    @zcbenz
    Contributor

    Excellent research on this bug! I'll try to find a way to fix this.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions