#1112·pglite

PGliteWorker can post to a closed BroadcastChannel during teardown

Author: esafakCreated Sep 22, 2026Updated Sep 22, 2026

Reproduction

Reproduced with @electric-sql/pglite 0.5.0, 0.5.6, 0.5.7, and 0.5.8 in Chromium.

pglite.worker.ts:

typescript
import { PGlite } from "@electric-sql/pglite";
import { worker } from "@electric-sql/pglite/worker";

worker({
    async init(options) {
        return new PGlite({ dataDir: options.dataDir });
    },
});

main.ts:

typescript
import { PGliteWorker } from "@electric-sql/pglite/worker";
import PGliteWorkerScript from "./pglite.worker?worker";

window.addEventListener("unhandledrejection", (event) => {
    console.error("Unhandled rejection:", event.reason);
});

const db = await PGliteWorker.create(
    new PGliteWorkerScript({ type: "module" }),
    { id: "broadcast-channel-close-repro" },
);

console.log("ready at close:", db.ready); // Usually false
await db.close();
await new Promise((resolve) => setTimeout(resolve, 100));

db.ready is commonly false when close() runs. The error is asynchronous, so wait briefly after closing.

Expected

close() should not produce an uncaught exception.

Actual

Shortly after closing:

InvalidStateError: Failed to execute 'postMessage' on 'BroadcastChannel': Channel is closed

In a multi-tab handoff this may also coincide with LeaderChangedError.

Cause

The notification loop schedules a timer while disconnected:

typescript
async #leaderNotifyLoop() {
    if (!this.#connected) {
        this.#broadcastChannel!.postMessage({
            type: "tab-here",
            id: this.#tabId,
        });
        setTimeout(() => this.#leaderNotifyLoop(), 16);
    }
}

close() closes the channel but does not cancel or guard the timer:

typescript
async close() {
    if (this.#closed) return;
    this.#closed = true;
    this.#broadcastChannel?.close();
    this.#tabChannel?.close();
    this.#releaseTabCloseLock?.();
    this.#workerProcess.terminate();
}

The timer callback discards the async loop's promise, so postMessage() throwing becomes an unhandled rejection. The leader-here handler can re-arm the same loop during handoff.

Request

Please ensure that after close() resolves no internal timer accesses a closed channel or produces an unhandled rejection, with a regression test covering startup and leader-change teardown.

This is distinct from PR #1109, which addresses RPCs hanging across leader changes.