Skip to content

[BUG]: execProtocolRawSync spins forever at 100% CPU when the backend exits mid-message (swallow-all catch in the protocol loop) #1058

Open

Description

@drudolf

Describe the bug

When the WASM backend terminates while execProtocolRawSync is processing a message (e.g. exit(1) after hitting EOF during a COPY ... FROM STDIN issued via pglite.exec()), the protocol loop spins forever, synchronously, at 100% CPU. The call never returns, so no timer, Promise.race, or AbortSignal can interrupt it (the same structural observation made in #945), and the Node process has to be killed from outside.

Root cause, packages/pglite/src/pglite.ts, execProtocolRawSync:

while (
  this.#readOffset < message.length ||
  mod._pq_buffer_remaining_data() > 0
) {
  try {
    mod._PostgresMainLoopOnce()
  } catch (e: any) {
    if (e.status === this.POSTGRES_MAIN_LONGJMP) {
      mod._PostgresMainLongJmp()
    }
    // all other exceptions are swallowed and the loop continues
  }
}

After the backend exits, _PostgresMainLoopOnce() throws ExitStatus (status = 1). That is not the longjmp sentinel, so it is silently swallowed; the dead backend consumes no input, so #readOffset never advances and _pq_buffer_remaining_data() never drains — the while condition is permanently true. The result is a tight synchronous call → throw → swallow loop. The event loop never runs again.

Two aggravating factors:

  1. The finally (which restores process.exitCode, added for [BUG]: PGlite sets process.exitCode = 99 #975) never runs, because the loop never exits.
  2. There is no death detection: after exit(1), ready remains true and closed remains false, so callers cannot observe the crash even where the loop is escaped.

COPY FROM STDIN via exec() is just the easiest structural trigger — any exception from _PostgresMainLoopOnce that is not the longjmp sentinel arms the same loop (e.g. a WASM RuntimeError from an OOM abort, or the FATAL: terminating connection because protocol synchronization was lost class seen in #820).

To Reproduce

import { PGlite } from '@electric-sql/pglite';

const p = new PGlite();
await p.exec('CREATE TABLE t(a int)');
// Backend hits EOF mid-COPY and exits — exec() never settles, process pegs a core:
await p.exec('COPY t FROM STDIN');
console.log('never reached');

A transaction is not required; wrapping the COPY in BEGIN spins identically.

Logs

V8 sampling profile of the spinning process (node --prof, ~20k ticks): 99.9% of samples are inside execProtocolRawSync → two wasm frames, with C++ time dominated by exception allocation/stack capture — consistent with the throw-per-iteration loop above.

Details

  • PGlite version: 0.5.4 (also present unchanged in main's pglite.ts at time of filing)
  • Extensions: none
  • OS: macOS 15 (Darwin 25.3.0)
  • Runtime: Node 24.14.1

Suggested fix (verified against a patched 0.5.4 dist)

Rethrow anything that is not the longjmp sentinel, and guard the finally's own WASM calls so they cannot mask the original error against a dead runtime:

} catch (e: any) {
  if (e.status === this.POSTGRES_MAIN_LONGJMP) {
    mod._PostgresMainLongJmp()
  } else {
    throw e  // ExitStatus, RuntimeError, … — the backend is gone; looping cannot help
  }
}
// ...
} finally {
  try {
    mod._PostgresSendReadyForQueryIfNecessary()
    mod._pgl_pq_flush()
  } catch {
    // dead runtime — the rethrown error above is the one that matters
  }
  pglUtils.pgliteProc.exitCode = prevExitCode
}

With exactly this change applied to the 0.5.4 dist, the repro behaves well in both variants (with and without an open transaction):

  • the killing exec() rejects with ExitStatus { status: 1 } ("Program terminated with exit(1)")
  • follow-up queries reject immediately with the same error instead of spinning
  • close() resolves
  • the event loop stays alive throughout

Beyond the minimal fix, it would help to mark the instance dead on ExitStatus (flip ready/closed or expose a crashed flag) so callers get a coherent state instead of ready === true on a dead instance, and/or to add a progress guard to the loop (bail if an iteration neither advanced #readOffset nor drained the pq buffer) as defense in depth.

Additional context

Activity

  1. kang8 commented on Jul 21, 2026

    @kang8

    A query() issued immediately before close() hangs the event loop on ≥0.4.0 (was a clean reject on 0.3.16)

    Since the 0.4.0 rewrite, if a query is in-flight (issued but not yet awaited) when close() is called, the process hard-hangs — the event loop is blocked (a setTimeout never fires), matching this issue's "synchronous loop spins forever" symptom. On 0.3.16 the in-flight query simply rejects and close() resolves.

    Minimal repro (npm i @electric-sql/pglite@0.5.4 && node repro.mjs):

    import { PGlite } from '@electric-sql/pglite'
    
    const db = new PGlite()
    await db.exec('create table t (id int primary key, v text)') // ensures the instance is ready
    
    // Issue a query but DON'T await it, then close() while it is in-flight:
    const inflight = db.query('insert into t (id, v) values (1, $1)', ['a'])
    const closed = db.close()
    
    const outcome = await Promise.race([
      Promise.allSettled([inflight, closed]).then((s) => 'SETTLED: ' + s.map((x) => x.status).join(', ')),
      new Promise((r) => setTimeout(() => r('HUNG: 4s timer never fired = event loop blocked'), 4000)),
    ])
    console.log(outcome)
    process.exit(0)
    version result
    0.3.16 SETTLED: rejected, fulfilled (in-flight query rejects, close resolves)
    0.4.6 HUNG — setTimeout never fires (event loop blocked)
    0.5.4 HUNG — same

    Environment: Node v24.18.0, macOS. Tested 0.3.16 (OK), 0.4.6 and 0.5.4 (hang); appears to enter with the 0.4.0 core rewrite. Real-world impact: a test/dev harness that fires background writes and then closes an in-memory instance hangs instead of erroring; the trailing writes never settle.

  2. seandearnaley commented on Sep 12, 2026

    @seandearnaley

    What happens

    execProtocolRawSync (packages/pglite/src/pglite.ts) runs:

    while (this.#readOffset < message.length || mod._pq_buffer_remaining_data() > 0) {
      try { mod._PostgresMainLoopOnce() }
      catch (e) {
        const status = this.mod!._pgl_setPGliteExitStatus(-2)
        if (status === this.POSTGRES_MAIN_LONGJMP) mod._PostgresMainLongJmp()
      }
    }

    When _PostgresMainLoopOnce() throws a genuine WebAssembly trap (RuntimeError: function signature mismatch), _pgl_setPGliteExitStatus(-2) returns -3 (not POSTGRES_MAIN_LONGJMP), nothing advances #readOffset, and the loop re-enters _PostgresMainLoopOnce() immediately and forever. The calling process pins one CPU with a blocked event loop: no timer can fire, no promise settles, a vitest testTimeout never triggers, and a CI job sits silent until its own limit kills it.

    Reproduction of the wedge (deterministic for us, layout dependent)

    Node 26.8.2, @electric-sql/pglite 0.5.8 + @electric-sql/pglite-pgvector 0.0.9, PGlite.create({ extensions: { vector } }), memory://. The trap fires on the Bind of the second of two back-to-back identical extended-protocol round trips:

    P  DELETE FROM mastra_workflow_snapshot WHERE workflow_name = $1 AND run_id = $2
    D  B(agentic-loop, <uuid>)  D  E  S
    P  DELETE FROM mastra_workflow_snapshot WHERE workflow_name = $1 AND run_id = $2
    D  B(executionWorkflow, <uuid>)   <-- RuntimeError: function signature mismatch
    

    Stack at the trap: $palloc <- $initStringInfo <- $PostgresMainLoopOnce <- execProtocolRawSync. No Postgres ERROR/longjmp precedes it; _pgl_setPGliteExitStatus(-2) returns -3.

    • Same statement stream under Node 24.16.0: no trap.
    • Same process under Node 26.8.2 with one unrelated JS module added or removed from the import graph: the trap appears or disappears (heap layout dependent), so this is a latent memory-safety fault that layout exposes, not a compiler tier issue: --liftoff-only, --no-wasm-code-gc, --no-wasm-inlining, --no-wasm-inlining-call-indirect, --no-wasm-lazy-compilation, --no-wasm-dynamic-tiering, --gc-interval=200, --single-threaded-gc all still trap.
    • Replaying the byte-identical captured protocol stream (206 messages, recorded at execProtocolRawSync entry) on a fresh instance does NOT trap, with or without forced GC, inter-message delays, syncToFs, a prior instance created and closed, another WASM module (xxhash-wasm) instantiated alongside, or running inside the same vitest worker. Heap size (HEAPU8.length) is identical at every message in both. The corruption therefore depends on live in-process state we could not isolate from outside the module.

    Two asks

    1. Terminate the loop on a non-longjmp trap. A trap means the instance's memory is no longer trustworthy. Suggested shape: record the trap on the instance, throw a PGliteFatalError (with the original RuntimeError as cause) from execProtocolRawSync, and reject every later call on that instance instead of spinning. That alone turns a 30-minute silent hang into an immediate, named failure.
    2. The trap itself: a call_indirect type mismatch inside palloc (garbage CurrentMemoryContext->methods) at the start of message processing, with no preceding ERROR. Any pointers on how to obtain a debug build of postgres.wasm (or -sASSERTIONS/SAFE_HEAP) to narrow the use-after-free would let us continue.

    We can share the captured protocol stream and the inspector traces.

  3. tdrz commented on Oct 14, 2026

    @tdrz
    Contributor
    1. A query() issued immediately before close() hangs the event loop on ≥0.4.0 (was a clean reject on 0.3.16)

    This should be fixed in the next release.

    AFAIK not all errors are fatal, but need to confirm this.

  4. self-assigned this
    on Oct 14, 2026
  5. kang8 commented on Oct 20, 2026

    @kang8

    Thanks @tdrz — tested on 0.5.10: the hang is gone, but a query issued before close() is still not awaited. With the repro above, the insert now rejects with TypeError: Cannot read properties of undefined (reading '_PostgresSendReadyForQueryIfNecessary') while close() resolves, so the write is lost. Two queued query() calls followed by close() both reject the same way.

    It looks like #1140 only waits for a statement already holding #queryMutex. Public query()/exec()/transaction() call _checkReady() and then queue on #transactionMutex before they reach #queryMutex, so a close() issued in the same tick takes #queryMutex first, sets #closing and tears the module down. The queued statement then enters #runQuery without re-checking readiness (dumpDataDir does re-check inside the mutex). Having close() also take #transactionMutex would let it wait for queued statements; a _checkReady() inside _runExclusiveQuery would at least turn the TypeError into a clean PGlite is closing.

    The extra _checkReady() added to close() on main (5573bb0) doesn't seem to change this: awaiting _checkReady() before close() on 0.5.10 still reproduces it.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions