Skip to content

JSPI pthread entry can exit prematurely during a mailbox callback, causing double exit #28258

Open

Description

@Axelwickm

With -pthread -sJSPI, repeated creation/joining of short-lived threads can hang in Playwright WebKit on Linux. A reduced reproducer contains only four std::threads incrementing an atomic counter; it has no OR-Tools code or dependencies.

The evidence points to a pending JSPI pthread entry not retaining the runtime: checkMailbox() can call maybeExit() before the entry promise continuation runs, and finish() subsequently attempts a second thread exit. A deliberately forced ordering in Chromium produces Assertion failed: self in _emscripten_thread_exit.

Version of emscripten/emsdk

emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 6.0.8 (aeb67926e7de656da38bc807d83050af93578758)
clang version 24.0.0git (https:/github.com/llvm/llvm-project 4bfd08c2d769736841ae4f5705d76fa6daa39027)
Target: wasm32-unknown-emscripten
Thread model: posix
InstalledDir: /home/axel/own/or-tools-wasm/emsdk/upstream/bin
  • Host: Linux x86_64, Pop!_OS 24.04; Node 26.13.1 runs the browser harness.
  • Playwright 1.65.0: WebKit 27.2 (build 2388), Chromium 158.0.8127.18.
  • Runs below are restricted to two available CPUs (taskset -c 0,1). Select CPUs allowed on your machine.
  • The natural WebKit hang was also observed after compiling the original tiny reproduction with the official emscripten/emsdk:7.0.0 Docker image. The detailed trace and forced-ordering tests below use 6.0.8.
  • This is Linux Playwright WebKit, not a test on released Apple Safari.

Failing command line in full

Save the following as repro.cpp:

#include <thread>
#include <atomic>
extern "C" int work() {
 std::atomic<int> counter{0};
 std::thread workers[4];
 for(auto& worker:workers)worker=std::thread([&]{counter.fetch_add(1);});
 for(auto& worker:workers)worker.join();
 return counter.load();
}

The JSPI build command is:

em++ repro.cpp -O2 -pthread --no-entry \
  -sJSPI=1 -sJSPI_EXPORTS=work \
  -sEXPORTED_FUNCTIONS=_work -sEXPORTED_RUNTIME_METHODS=ccall,PThread \
  -sPTHREAD_POOL_SIZE=8 -sPTHREAD_POOL_SIZE_STRICT=2 \
  -sMODULARIZE=1 -sEXPORT_ES6=1 -sENVIRONMENT=web,worker \
  -o repro.js

Save the runner in the expandable section below as run.mjs next to repro.cpp. It compiles the source, serves the files with COOP/COEP headers, and checks 1,000 calls. It requires em++ on PATH (or EMXX=/absolute/path/to/em++). It uses a temporary writable compiler cache unless EM_CACHE is set.

npm init -y
npm install --save-dev playwright-core@1.65.0
npx playwright-core install --with-deps webkit chromium

# Natural failure: no runtime mutation and no forced mailbox callback.
REPRO_BROWSER=webkit timeout -k 5s 35s taskset -c 0,1 node run.mjs

# Diagnostic forced ordering, with Emscripten assertions enabled.
REPRO_BROWSER=chromium REPRO_FORCE_MAILBOX=1 REPRO_ASSERTIONS=1 \
  timeout -k 5s 45s taskset -c 0,1 node run.mjs

# Same forced ordering, with the experimental keepalive correction.
REPRO_BROWSER=chromium REPRO_FORCE_MAILBOX=1 REPRO_ASSERTIONS=1 REPRO_KEEPALIVE=1 \
  timeout -k 5s 45s taskset -c 0,1 node run.mjs

The timeout includes compilation. Allow longer on the first build if compiling uncached system libraries takes longer. The natural failure's iteration count varies; the external timeout bounds the hang.

REPRO_FORCE_MAILBOX=1 explicitly modifies generated JS to enqueue queueMicrotask(checkMailbox) immediately before calling the promising pthread entry. This is a controlled scheduling test of the observed lifecycle overlap, not an unmodified Chromium reproduction. The default WebKit case makes no such modification. REPRO_ASSERTIONS=1 adds -sASSERTIONS=1 to the build.

Complete standalone run.mjs
// Standalone JSPI/pthread stress reproduction.
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createReadStream } from 'node:fs';
import { mkdtemp, rm, readFile, writeFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const browserName = process.env.REPRO_BROWSER ?? 'webkit';
const flavor = process.env.REPRO_FLAVOR ?? 'jspi';
assert.ok(['jspi', 'asyncify'].includes(flavor));
const { [browserName]: browserType } = await import('playwright-core');
assert.ok(browserType, `Unknown browser: ${browserName}`);
const directory = await mkdtemp(path.join(tmpdir(), 'ortools-pthread-repro-'));
let server, browser;
try {
  execFileSync(process.env.EMXX ?? 'em++', [
    fileURLToPath(new URL('./repro.cpp', import.meta.url)),
    '-O2', '-pthread', '--no-entry',
    ...(process.env.REPRO_ASSERTIONS === '1' ? ['-sASSERTIONS=1'] : []),
    ...(flavor === 'jspi' ? ['-sJSPI=1', '-sJSPI_EXPORTS=work'] : ['-sASYNCIFY=1']),
    '-sEXPORTED_FUNCTIONS=_work', '-sEXPORTED_RUNTIME_METHODS=ccall,PThread',
    '-sPTHREAD_POOL_SIZE=8', '-sPTHREAD_POOL_SIZE_STRICT=2',
    '-sMODULARIZE=1', '-sEXPORT_ES6=1', '-sENVIRONMENT=web,worker',
    '-o', path.join(directory, 'repro.js'),
  ], { stdio: 'inherit', env: { ...process.env, EM_CACHE: process.env.EM_CACHE ?? path.join(directory, 'cache') } });
  if (process.env.REPRO_KEEPALIVE === '1' || process.env.REPRO_FORCE_MAILBOX === '1') {
    assert.equal(flavor, 'jspi');
    const filename = path.join(directory, 'repro.js');
    let source = await readFile(filename, 'utf8');
    const entry = 'var result=WebAssembly.promising(getWasmTableEntry(ptr))(arg);';
    assert.ok(source.includes(entry), 'Pthread entry implementation changed');
    const prefix = (process.env.REPRO_FORCE_MAILBOX === '1' ? 'queueMicrotask(checkMailbox);' : '')
      + (process.env.REPRO_KEEPALIVE === '1' ? 'runtimeKeepalivePush();' : '');
    source = source.replace(entry, prefix + entry);
    if (process.env.REPRO_KEEPALIVE === '1') {
      assert.ok(source.includes('result=await result;finish(result)'));
      source = source.replace('result=await result;finish(result)',
        'try{result=await result}finally{runtimeKeepalivePop()}finish(result)');
    }
    await writeFile(filename, source);
  }
  // Diagnostic control only: retain JSPI, use Emscripten's mailbox fallback.
  if (process.env.REPRO_NO_WAITASYNC === '1') {
    const filename = path.join(directory, 'repro.js');
    const source = await readFile(filename, 'utf8');
    assert.ok(source.includes('var waitAsyncPolyfilled='), 'Mailbox implementation changed');
    await writeFile(filename, source.replace('var waitAsyncPolyfilled=', 'var waitAsyncPolyfilled=true||'));
  }
  server = createServer((request, response) => {
    response.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
    response.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
    response.setHeader('Cache-Control', 'no-store');
    const filename = new URL(request.url, 'http://localhost').pathname;
    if (filename === '/') { response.setHeader('Content-Type', 'text/html'); response.end('<html></html>'); return; }
    if (!['/repro.js', '/repro.wasm'].includes(filename)) { response.writeHead(404); response.end(); return; }
    response.setHeader('Content-Type', filename.endsWith('.wasm') ? 'application/wasm' : 'text/javascript');
    createReadStream(path.join(directory, filename.slice(1))).pipe(response);
  });
  await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  browser = await browserType.launch({ headless: true });
  console.log({ browser: browserName, version: browser.version(), flavor });
  const page = await browser.newPage();
  const browserErrors = [];
  page.on('console', message => {
    console.log(message.text());
    // This diagnostic deliberately joins on the page thread; debug builds warn.
    const expectedJoinWarning = message.text().startsWith('Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html');
    if (message.type() === 'error' && !expectedJoinWarning) browserErrors.push(message.text());
  });
  page.on('pageerror', error => { browserErrors.push(String(error)); console.error(error); });
  await page.goto(`http://127.0.0.1:${server.address().port}/`);
  await page.evaluate(async () => {
    const { default: createModule } = await import('/repro.js');
    const module = await createModule();
    try {
      for (let iteration = 0; iteration < 1000; iteration++) {
        console.log('pthread', iteration);
        if (await module.ccall('work', 'number', [], [], { async: true }) !== 4) throw new Error('Incorrect thread count');
      }
    } finally { module.PThread.terminateAllThreads(); }
  });
  // Let asynchronous worker error events arrive before declaring success.
  await page.waitForTimeout(100);
  assert.equal(browserErrors.length, 0, `Browser errors: ${browserErrors.slice(0, 3).join('\n')}`);
  console.log('PASS: 1000 iterations');
} finally {
  await browser?.close();
  if (server) await new Promise(resolve => server.close(resolve));
  await rm(directory, { recursive: true, force: true });
}

Expected and actual behavior

Expected: every call returns 4 and the runner completes without pthread errors.

Unmodified WebKit failure (fresh run of the files above):

{ browser: 'webkit', version: '27.2', flavor: 'jspi' }
pthread 0
pthread 1
pthread 2
node:internal/modules/run_main:111
    triggerUncaughtException(
    ^

page.evaluate: Target page, context or browser has been closed
    at /tmp/ortools-upstream-issue/run.mjs:75:14 {
  log: []
}

Node.js v26.13.1

It stopped making progress at iteration 2; the external 35-second timeout returned status 124. The “page ... has been closed” error above appears when that timeout terminates the browser; it is not the original cause of the stall.

Forced Chromium ordering with assertions (fresh run):

Aborted(Assertion failed: self, at: /emsdk/emscripten/system/lib/pthread/pthread_create.c,312,_emscripten_thread_exit)
worker: onmessage() captured an uncaught exception: RuntimeError: Aborted(Assertion failed: self, at: /emsdk/emscripten/system/lib/pthread/pthread_create.c,312,_emscripten_thread_exit)
RuntimeError: Aborted(Assertion failed: self, at: /emsdk/emscripten/system/lib/pthread/pthread_create.c,312,_emscripten_thread_exit)
    at abort (http://127.0.0.1:44999/repro.js:1:10785)
    at ___assert_fail (http://127.0.0.1:44999/repro.js:1:24945)
    at http://127.0.0.1:44999/repro.wasm:wasm-function[86]:0x30fb
    at http://127.0.0.1:44999/repro.js:1:11586
    at finish (http://127.0.0.1:44999/repro.js:1:23237)
    at invokeEntryPoint (http://127.0.0.1:44999/repro.js:1:23290)
    at async handleMessage (http://127.0.0.1:44999/repro.js:1:8825)

The runner returned status 1, rejecting the collected browser errors. It deliberately checks worker/page errors as well as returned values, since a correct return value alone can miss a subsequent invalid thread exit.

Same forced ordering with the keepalive control:

pthread 997
pthread 998
pthread 999
PASS: 1000 iterations

Exit status 0. The harness ignores only Emscripten's expected debug warning about deliberately joining on the page thread; assertion and worker errors still fail the run.

Lifecycle evidence

In a separate diagnostic variant using bounded pthread_timedjoin_np calls (to let the page return and flush traces), one worker reported:

before await: pthread_self = 70176
mailbox callback: pthread_self = 70176
after mailbox callback: pthread_self = 0
after await: pthread_self = 0

The corresponding join timed out. The source paths explain how this can occur:

  1. invokeEntryPoint in libpthread.js resets runtimeKeepaliveCounter and noExitRuntime, then awaits the promise returned by the pthread entry without retaining the runtime across that interval.
  2. An asynchronous mailbox notification calls checkMailbox(), which uses callUserCallback(). That helper calls maybeExit() in its finally block. With no keepalive, the thread can exit while the entry continuation remains pending.
  3. _emscripten_thread_exit clears the current pthread identity and publishes the exited state, permitting join/cleanup and worker reuse.
  4. The original invokeEntryPoint resumes and calls finish(), attempting another _emscripten_thread_exit. The forced-ordering assertion catches the case where the current pthread identity is already null.

Experimental correction and controls

Keeping the runtime alive across the pending JSPI entry prevented the observed failure. The runner's REPRO_KEEPALIVE=1 prototype inserts runtimeKeepalivePush() before invoking the promising entry, then balances it with runtimeKeepalivePop() in a finally around the await, before finish().

This is a diagnostic prototype, not a proposed production-ready patch: the push/pop also needs to be balanced if invocation itself throws synchronously; explicit pthread exit, cancellation, and rejection paths need appropriate regression coverage.

Observed controls:

  • WebKit JSPI with the keepalive prototype: 1,000 iterations passed, retaining native Atomics.waitAsync.
  • Chromium with forced mailbox ordering, assertions, and the keepalive prototype: 1,000 iterations passed without assertion/page errors.
  • Unmodified WebKit Asyncify and unmodified Chromium JSPI: 1,000 iterations passed in earlier controls. These passes do not establish that Chromium can never hit the race naturally.
  • Disabling the Emscripten asynchronous mailbox path also avoided the natural hang, but the keepalive correction addresses the lifecycle issue without disabling JSPI or native asynchronous waits.
  • The downstream complete Vite WebKit solver fixture passed with the diagnostic keepalive correction across all solver groups/executor modes (1.6 minutes).

Downstream failing CI runs

These are the original integration failures that prompted reduction; they show timeouts, not the isolated assertion, and are supporting context rather than a requirement to reproduce:

Both jobs are from run 43463119879, commit 5d4913b129e74df0f2ae07deac3e15f1942e36da. They timed out in the CP-SAT fixture group after 600 seconds. The tiny reproducer above removes the solver and bundler dependencies.

Full link command and output with -v appended

The following is the actual verbose build of the unmodified minimal source:

EM_CACHE=/tmp/ortools-runtime-upgrade/em-cache emsdk/upstream/emscripten/em++ /tmp/ortools-upstream-issue/repro.cpp -O2 -pthread --no-entry -sJSPI=1 -sJSPI_EXPORTS=work -sEXPORTED_FUNCTIONS=_work -sEXPORTED_RUNTIME_METHODS=ccall,PThread -sPTHREAD_POOL_SIZE=8 -sPTHREAD_POOL_SIZE_STRICT=2 -sMODULARIZE=1 -sEXPORT_ES6=1 -sENVIRONMENT=web,worker -o /tmp/ortools-upstream-issue/repro.js -v
Complete verbose compiler/linker output
 "/home/axel/own/or-tools-wasm/emsdk/upstream/bin/clang++" -target wasm32-unknown-emscripten -fignore-exceptions -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr --sysroot=/tmp/ortools-runtime-upgrade/em-cache/sysroot -D__EMSCRIPTEN_SHARED_MEMORY__=1 -Xclang -iwithsysroot/include/fakesdl -Xclang -iwithsysroot/include/compat -O2 -pthread -v -c /tmp/ortools-upstream-issue/repro.cpp -o /tmp/emscripten_temp_md32zugb/repro.o
clang version 24.0.0git (https:/github.com/llvm/llvm-project 4bfd08c2d769736841ae4f5705d76fa6daa39027)
Target: wasm32-unknown-emscripten
Thread model: posix
InstalledDir: /home/axel/own/or-tools-wasm/emsdk/upstream/bin
 (in-process)
 "/home/axel/own/or-tools-wasm/emsdk/upstream/bin/clang-24" -cc1 -triple wasm32-unknown-emscripten -O2 -emit-obj -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name repro.cpp -mrelocation-model static -mframe-pointer=none -ffp-contract=on -fno-rounding-math -mconstructor-aliases -target-feature +atomics -target-feature +bulk-memory -target-feature +mutable-globals -target-feature +sign-ext -target-cpu generic -fvisibility=hidden -debugger-tuning=gdb -fdebug-compilation-dir=/home/axel/own/or-tools-wasm -v -fcoverage-compilation-dir=/home/axel/own/or-tools-wasm -resource-dir /home/axel/own/or-tools-wasm/emsdk/upstream/lib/clang/24 -D __EMSCRIPTEN_SHARED_MEMORY__=1 -isysroot /tmp/ortools-runtime-upgrade/em-cache/sysroot -internal-isystem /tmp/ortools-runtime-upgrade/em-cache/sysroot/include/wasm32-emscripten/noeh/c++/v1 -internal-isystem /tmp/ortools-runtime-upgrade/em-cache/sysroot/include/wasm32-emscripten/c++/v1 -internal-isystem /tmp/ortools-runtime-upgrade/em-cache/sysroot/include/c++/v1 -internal-isystem /home/axel/own/or-tools-wasm/emsdk/upstream/lib/clang/24/include -internal-isystem /tmp/ortools-runtime-upgrade/em-cache/sysroot/include/wasm32-emscripten -internal-isystem /tmp/ortools-runtime-upgrade/em-cache/sysroot/include -fdeprecated-macro -ferror-limit 19 -pthread -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcxx-exceptions -fignore-exceptions -fexceptions -fno-color-diagnostics -vectorize-loops -vectorize-slp -iwithsysroot/include/fakesdl -iwithsysroot/include/compat -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr -o /tmp/emscripten_temp_md32zugb/repro.o -x c++ /tmp/ortools-upstream-issue/repro.cpp
clang -cc1 version 24.0.0git based upon LLVM 24.0.0git default target x86_64-unknown-linux-gnu
ignoring nonexistent directory "/tmp/ortools-runtime-upgrade/em-cache/sysroot/include/wasm32-emscripten/noeh/c++/v1"
ignoring nonexistent directory "/tmp/ortools-runtime-upgrade/em-cache/sysroot/include/wasm32-emscripten/c++/v1"
ignoring nonexistent directory "/tmp/ortools-runtime-upgrade/em-cache/sysroot/include/wasm32-emscripten"
#include "..." search starts here:
#include <...> search starts here:
 /tmp/ortools-runtime-upgrade/em-cache/sysroot/include/fakesdl
 /tmp/ortools-runtime-upgrade/em-cache/sysroot/include/compat
 /tmp/ortools-runtime-upgrade/em-cache/sysroot/include/c++/v1
 /home/axel/own/or-tools-wasm/emsdk/upstream/lib/clang/24/include
 /tmp/ortools-runtime-upgrade/em-cache/sysroot/include
End of search list.
 /home/axel/own/or-tools-wasm/emsdk/upstream/bin/clang --version
clang: warning: future releases of the clang compiler will prefer GCC installations containing libstdc++ include directories; '/usr/lib/gcc/x86_64-linux-gnu/13' would be chosen over '/usr/lib/gcc/x86_64-linux-gnu/14' [-Wgcc-install-dir-libstdcxx]
 /home/axel/own/or-tools-wasm/emsdk/upstream/bin/wasm-ld -o /tmp/ortools-upstream-issue/repro.wasm /tmp/tmpo4f3cus3libemscripten_js_symbols.so -Bstatic --import-memory --shared-memory --export=work --export=_emscripten_stack_alloc --export=_emscripten_thread_free_data --export=_emscripten_thread_crashed --export=__wasm_call_ctors --export=_emscripten_tls_init --export=_emscripten_thread_init --export=pthread_self --export=__set_thread_state --export=emscripten_stack_get_current --export=_emscripten_stack_restore --export=emscripten_stack_set_limits --export=_emscripten_thread_exit --export-if-defined=__start_em_asm --export-if-defined=__stop_em_asm --export-if-defined=__start_em_lib_deps --export-if-defined=__stop_em_lib_deps --export-if-defined=__start_em_js --export-if-defined=__stop_em_js --export-table -z stack-size=65536 --no-growable-memory --initial-memory=16777216 --no-entry --no-stack-first --table-base=1 --global-base=1024 /tmp/emscripten_temp_md32zugb/repro.o -L/tmp/ortools-runtime-upgrade/em-cache/sysroot/lib/wasm32-emscripten -L/home/axel/own/or-tools-wasm/emsdk/upstream/emscripten/src/lib /tmp/ortools-runtime-upgrade/em-cache/sysroot/lib/wasm32-emscripten/crtbegin-mt.o -lGL-mt-getprocaddr -lal -lhtml5 -lstubs -lnoexit -lc-mt -ldlmalloc-mt -lclang_rt.builtins-mt -lc++-mt-noexcept -lc++abi-mt-noexcept -lsockets-mt -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr
 /home/axel/own/or-tools-wasm/emsdk/upstream/bin/llvm-objcopy /tmp/ortools-upstream-issue/repro.wasm /tmp/ortools-upstream-issue/repro.wasm '--remove-section=llvm.func_attr.annotate.*' --remove-section=producers --remove-section=name '--remove-section=.debug*'
 /home/axel/own/or-tools-wasm/emsdk/upstream/bin/wasm-opt --strip-target-features --post-emscripten -O2 --low-memory-unused --zero-filled-memory --pass-arg=directize-initial-contents-immutable /tmp/ortools-upstream-issue/repro.wasm -o /tmp/ortools-upstream-issue/repro.wasm --mvp-features --enable-threads --enable-bulk-memory --enable-bulk-memory-opt --enable-call-indirect-overlong --enable-multivalue --enable-mutable-globals --enable-nontrapping-float-to-int --enable-reference-types --enable-sign-ext --enable-reference-types
 /home/axel/own/or-tools-wasm/emsdk/node/24.19.0_64bit/bin/node /home/axel/own/or-tools-wasm/emsdk/upstream/emscripten/tools/acorn-optimizer.mjs /tmp/emscripten_temp_md32zugb/repro.js JSDCE --minify-whitespace --export-es6 -o /tmp/emscripten_temp_md32zugb/repro.jso1.js
 /home/axel/own/or-tools-wasm/emsdk/node/24.19.0_64bit/bin/node /home/axel/own/or-tools-wasm/emsdk/upstream/emscripten/tools/preprocessor.mjs - modularize.js --expand-macros
 /home/axel/own/or-tools-wasm/emsdk/node/24.19.0_64bit/bin/node /home/axel/own/or-tools-wasm/emsdk/upstream/emscripten/tools/acorn-optimizer.mjs /tmp/tmpt1zeq4wz.js --minify-whitespace --export-es6 -o /tmp/tmpt1zeq4wz.jso2.js

I searched existing issues/PRs. #27721 and #26692 concern related shutdown/keepalive behavior but appear to describe different failures; please redirect this report if there is an existing duplicate.

Investigation and report prepared with AI assistance; the reported reproductions and controls were executed locally.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions