Skip to content

worker_threads: make postMessage on an exited worker a silent no-op - #33233

Closed
robobun wants to merge 2 commits into
mainfrom
claude/farm/72cd13af/worker-postmessage-noop-after-exit
Closed

robobun wants to merge 2 commits into
mainfrom
claude/farm/72cd13af/worker-postmessage-noop-after-exit

Conversation

@robobun

@robobun robobun commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #20425

What does this PR do?

worker.postMessage() throws once a worker has exited or been terminated:

InvalidStateError: Worker has been terminated
import { Worker } from "node:worker_threads";
const w = new Worker("", { eval: true });
await new Promise(r => w.on("exit", r));
w.postMessage("x"); // bun: throws InvalidStateError. node: no-op

The same happens after await worker.terminate(), and for the Web Worker global. Node implements a silent no-op; that is what lets a worker pool post to a worker without guarding against it having just died, while under Bun the same code throws in whatever context did the post. This is what breaks pgmock in #20425: its embedded x86 emulator posts to a worker that has exited, and postMessage@[native code] surfaces the InvalidStateError as an unhandled error.

The throw comes from WebKit's terminated check in Worker::postMessage (src/jsc/bindings/webcore/Worker.cpp):

if (m_state.load() == State::Closed)
    return Exception { InvalidStateError, "Worker has been terminated"_s };

The Closing state was added precisely so the in-handler window silently drops ("matching browser/Node semantics", per the comment in Worker.h), but Closed kept the throw. The throw is a Safari-only behavior: the HTML spec's "terminate a worker" never disentangles the implicit port, so Chrome, Firefox, and Node all no-op. Node's Worker.prototype.postMessage returns before serializing once the port is gone (lib/internal/worker.js: if (this[kPublicPort] === null) return;), and it nulls that port before emitting exit.

The fix: return early from Worker::postMessage, before serializing, once the worker has exited (m_state >= State::Closing). That matches Node in all three windows: inside the exit handler, after the exit event, and after terminate(). Returning before serialization also means a message to a dead worker can no longer throw DataCloneError or detach its transferList entries, which the previous Closing path did while serializing into a queue that could only be dropped.

How did you verify your code works?

  • test/js/node/worker_threads/worker_threads.test.ts: postMessage after the exit event, after terminate() resolves, and with a non-cloneable message plus a transferList from inside the exit handler onward.
  • test/js/web/workers/worker.test.ts: the Web Worker after terminate() (Closed), from inside the close handler with a non-cloneable value (Closing), and after a natural exit with a non-cloneable value and a transferList.

Every one fails on an unmodified build and passes with this change (bun bd test <file> both ways). Behavior checked against node v26.3.0. The error string "Worker has been terminated" exists at exactly one line in the source, the one changed here, and running the pgmock reproduction from #20425 on an unmodified build reproduces it at the expected postMessage@[native code] frame.

bun bd test <file> was already red on unmodified main for both files, independent of this change, so the following is included to get them reliably green:

  • The two "worker with event listeners doesn't close event loop" tests raced a spawned debug build against a hardcoded 1s setTimeout. Replaced the timer with awaiting the process and asserting the same output exactly, with an explicit 30s per-test timeout so a real hang is still bounded tightly (the fixture itself takes about a second under debug+ASAN). Also deduplicated the two copy-pasted bodies into a helper.
  • Several tests in these files only pass because the CI runner injects --timeout=90000. Set the same file-level setDefaultTimeout the shell test suites use. The precedence is explicit per-test timeout, then setDefaultTimeout(), then --timeout (verified empirically in a comment below), so this only raises the default for these two files and never tightens a CI budget.

[review] gate passed · iteration 6 · 4 files touched

fails on main (without fix)
ASAN without fix: 4 failed, 1 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/worker_threads/worker_threads.test.ts test/js/web/workers/worker.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (683555b1d)

test/js/web/workers/worker.test.ts:
(pass) web worker > preload > invalid file URL [11.23ms]
(pass) web worker > preload > string [137.90ms]
(pass) web worker > preload > array of 2 strings [147.45ms]
(pass) web worker > preload > array of string [130.95ms]
(pass) web worker > preload > error in preload doesn't crash parent [156.39ms]
(pass) web worker > worker [128.59ms]
(pass) web worker > worker-env [134.57ms]
(pass) web worker > worker-env: SHARE_ENV via the global Worker constructor [1067.25ms]
(pass) web worker > worker-env with a lot of properties [331.94ms]
(pass) web worker > argv / execArgv defaults [147.86ms]
(pass) web worker > argv / execArgv options [148.6
... (truncated)

release without fix: 4 failed, 1 skipped
bun test v1.4.0-canary.1 (1498d7b77)

test/js/web/workers/worker.test.ts:
(pass) web worker > preload > invalid file URL [0.21ms]
(pass) web worker > preload > string [5.09ms]
(pass) web worker > preload > array of 2 strings [3.52ms]
(pass) web worker > preload > array of string [4.23ms]
(pass) web worker > preload > error in preload doesn't crash parent [2.58ms]
(pass) web worker > worker [3.63ms]
(pass) web worker > worker-env [2.73ms]
166 |       ],
167 |       env: bunEnv,
168 |       stderr: "pipe",
169 |     });
170 |     const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
171 |     expect(JSON.parse(stdout)).toEqual({ seen: "from-parent", parentSees: "from-worker" });
                      ^
SyntaxError: JSON Parse error: Unexpected EOF
      at <anonymous> (/workspace/bun/test/js/web/workers/worker.test.ts:171:17)
(fail) web worker > worker-env: SHARE_ENV via the global Worker constructor [22.24ms]
(pass) web worker > worker-env with a lot of properties [5.95ms]
(pass) web worker > argv / execArgv defaults [3.46ms]
(pass) web worker > argv / execArgv options [3.25ms]
(pass) web worker > sending 50 mess
... (truncated)
passes on PR (with fix)
ASAN with fix: 1 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/worker_threads/worker_threads.test.ts test/js/web/workers/worker.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (683555b1d)

test/js/web/workers/worker.test.ts:
(pass) web worker > preload > invalid file URL [12.42ms]
(pass) web worker > preload > string [147.89ms]
(pass) web worker > preload > array of 2 strings [158.26ms]
(pass) web worker > preload > array of string [138.09ms]
(pass) web worker > preload > error in preload doesn't crash parent [167.95ms]
(pass) web worker > worker [133.82ms]
(pass) web worker > worker-env [139.41ms]
(pass) web worker > worker-env: SHARE_ENV via the global Worker constructor [1099.77ms]
(pass) web worker > worker-env with a lot of properties [335.87ms]
(pass) web worker > argv / execArgv defaults [147.42ms]
(pass) web worker > argv / execArgv options [144.9
... (truncated)

release with fix: 1 skipped
$ bun scripts/build.ts --profile=release
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     683555b1d7
  features     (none)

22 deps, 106 codegen, 1168 objects in 844ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1231] install /workspace/bun
bun install v1.4.0-canary.1 (1498d7b77)

Checked 124 installs across 170 packages (no changes) [9.00ms]
[2/1231] install /workspace/bun/packages/bun-error
bun install v1.4.0-canary.1 (1498d7b77)

Checked 1 install across 2 packages (no changes) [1.00ms]
[3/1231] gen bindgenv2
[4/1231] install /workspace/bun/src/node-fallbacks
bun install v1.4.0-canary.1 (1498d7b77)

Checked 129 installs across 147 packages (no changes) [6.00ms]
[5/1231] gen ErrorCode+*.h
[6/1231] fetch tinycc
[tinycc] up to date
[7/1230] fetch zlib
[zlib] up to date
[8/1230] fetch picohttpparser
[picoh
... (truncated)
diff hotspot
src/jsc/bindings/webcore/Worker.cpp                |  27 ++---
 src/jsc/bindings/webcore/Worker.h                  |   6 +-
 test/js/node/worker_threads/worker_threads.test.ts |  41 ++++++++
 test/js/web/workers/worker.test.ts                 | 115 ++++++++++++---------
 4 files changed, 122 insertions(+), 67 deletions(-)

gate history · 1 passed · 0 rejected · iteration 6

evidence per changed file
file                                                reads  edits  tests
src/jsc/bindings/webcore/Worker.cpp                     2      4      0
src/jsc/bindings/webcore/Worker.h                       1      1      0
test/js/node/worker_threads/worker_threads.test.ts      3      7      0
test/js/web/workers/worker.test.ts                      5      8      0

@github-actions github-actions Bot added the claude label Jul 2, 2026
@robobun

robobun commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 2:06 PM PT - Jul 13th, 2026

❌ @robobun, your commit 683555b has 1 failures in Build #72487 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 33233

That installs a local version of the PR into your bun-33233 executable, so you can run:

bun-33233 --bun

@github-actions

github-actions Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. Can't run pgmock package: Worker has been terminated #20425 - Reports InvalidStateError: Worker has been terminated when using pgmock, which calls postMessage() on a terminated worker — exactly the error this PR converts to a silent no-op.

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #20425

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Worker postMessage now silently drops messages from Closing onward, skips serialization in that case, updates related comments, and adds tests covering post-exit and post-terminate behavior in node and web worker suites.

Changes

Worker shutdown postMessage behavior

Layer / File(s) Summary
postMessage shutdown check
src/jsc/bindings/webcore/Worker.cpp, src/jsc/bindings/webcore/Worker.h
postMessage() returns {} when the worker is Closing or later, and nearby comments plus state-machine documentation were updated to match the new shutdown flow.
Node worker_threads shutdown tests
test/js/node/worker_threads/worker_threads.test.ts
Adds a longer default timeout and tests that postMessage after natural exit, after terminate, and from an exit handler does not throw and does not detach transferred buffers.
Web worker shutdown tests
test/js/web/workers/worker.test.ts
Adds a longer default timeout, refactors the event-loop survival checks into a shared helper, and adds postMessage no-throw coverage after terminate() and self-exit.

Possibly related PRs

  • oven-sh/bun#29957: Worker lifecycle changes around Closing/Closed state handling overlap with this PR’s shutdown postMessage() behavior.
  • oven-sh/bun#32809: This PR changes shutdown-time postMessage() handling before serialization and transfer-list processing, which is adjacent to transfer handling changes in that PR.
  • oven-sh/bun#29937: Both PRs touch the Worker::postMessage(...) pathway in src/jsc/bindings/webcore/Worker.cpp.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: making worker postMessage a silent no-op after exit.
Linked Issues check ✅ Passed The change directly addresses #20425 by preventing postMessage from throwing after a worker exits or is terminated.
Out of Scope Changes check ✅ Passed The test timeout tweaks and helper refactor are tied to the worker-message fix and test stability, not unrelated scope.
Description check ✅ Passed The PR description includes both required sections and provides clear implementation and verification details.

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/web/workers/worker.test.ts`:
- Around line 242-256: The Web Worker coverage is incomplete: the current test
only checks plain-string postMessage after termination/exit. Extend the existing
Worker postMessage no-op test to also cover a non-cloneable payload and a
transferList case, matching the behavior already asserted in
worker_threads.test.ts. Verify via Worker::postMessage that posting these to a
dead worker does not throw DataCloneError and does not detach the transferred
ArrayBuffer, so the Web Worker entry point exercises the same shared fix path in
Worker.cpp.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: df1b3176-f11c-48da-9bb1-296a01ec7aac

📥 Commits

Reviewing files that changed from the base of the PR and between 5b55beb and beeb403.

📒 Files selected for processing (4)
  • src/jsc/bindings/webcore/Worker.cpp
  • src/jsc/bindings/webcore/Worker.h
  • test/js/node/worker_threads/worker_threads.test.ts
  • test/js/web/workers/worker.test.ts

@github-actions

github-actions Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. node:worker_threads: +48 Node.js tests passing — MessagePort, stdio, SHARE_ENV, exit codes, transfer semantics, postMessageToThread + inspector #31216 - Also changes Worker::postMessage guard from == State::Closed to >= State::Closing in Worker.cpp, making postMessage on a terminated worker a silent no-op instead of throwing InvalidStateError

🤖 Generated with Claude Code

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any issues with the core fix, but this bundles a user-facing API behavior change with test-infrastructure adjustments (a 5-minute file-wide setDefaultTimeout and a rewrite of the event-loop hang tests to rely on that timeout instead of the previous 1s guard), so it's worth a maintainer confirming those trade-offs.

Extended reasoning...

Overview

The core change is a 2-line edit in Worker::postMessage (src/jsc/bindings/webcore/Worker.cpp): instead of throwing InvalidStateError when the worker is Closed, it now returns early (before serialization) whenever m_state >= Closing. Comments in Worker.cpp and Worker.h are updated to match. Four new tests cover the node and web Worker variants across natural exit, terminate(), and the in-exit-handler window (including the no-serialize / no-detach guarantee).

The PR also bundles two orthogonal test-infrastructure changes to get the touched files green locally: a setDefaultTimeout(5 min) at the top of both test files, and a refactor of the two "worker with event listeners doesn't close event loop" tests from a hardcoded 1s setTimeout kill to await using + Promise.all on stdout/exit, relying on the per-test timeout for hang detection.

Security risks

None identified. This loosens an error path (throw → silent no-op) on a dead worker, which cannot be used to smuggle data anywhere — the message is dropped before serialization. No auth, crypto, or permission code is touched.

Level of scrutiny

Medium. The native change is tiny and well-argued (Node's if (this[kPublicPort] === null) return;, HTML spec's non-disentangled implicit port, Chrome/Firefox parity), and the State enum ordering makes >= Closing correct. But it is a deliberate user-visible behavior change to a public API — code that previously caught InvalidStateError will now see a silent success — and it touches cross-thread worker lifecycle code, which historically warrants a human look.

Other factors

The bundled test changes are what tip this away from auto-approval:

  • Setting setDefaultTimeout to 5 minutes for entire files is a policy call a maintainer should ack (the description asserts CI's injected --timeout still governs, but that interaction is worth confirming).
  • The refactored hang-detection tests now rely on that 5-minute timeout to catch a true hang, versus the previous 1s bound. The new form is cleaner and follows the repo's "await the condition, don't setTimeout" guidance, but the failure-mode latency change is a trade-off someone should sign off on.

No bugs were found by the automated review; the diff is internally consistent and the enum comparison is sound.

@robobun

robobun commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Responding to the four bot comments above.

Not a duplicate of #31216. I checked that PR's head (refs/pull/31216/head): its Worker::postMessage in src/jsc/bindings/webcore/Worker.cpp still reads

if (m_state.load() == State::Closed)
    return Exception { InvalidStateError, "Worker has been terminated"_s };

at lines 208-209. #31216 is a large worker_threads compatibility batch that edits neighboring code in Worker.cpp (the dispatchExit close task) but does not change the postMessage guard, so there is no overlap with this fix.

#20425. Confirmed and linked with Fixes #20425. Its reported error, InvalidStateError: Worker has been terminated, comes from exactly one line in the source (the one changed here), and running the issue's pgmock reproduction on an unmodified build reproduces it with the expected frame:

postMessage@[native code]
@node_modules/pgmock/dist/main.js:2604:30

pgmock embeds an x86 emulator (v86) that posts to a worker after it has exited. To be explicit about scope: this PR removes that error, and the fixed build cannot produce it since the throw no longer exists. I did not run pgmock to completion, because its emulator needs several minutes of CPU even on a release build; if pgmock has unrelated problems under Bun past this point they would need a new issue.

CodeRabbit's review comment (cover non-cloneable messages and transferList on the Web Worker, matching the node test): done in bf444bb. Posting () => {} and postMessage(buffer, [buffer]) to a dead Web Worker now asserts no DataCloneError and no detach, same as the node variant.

claude[bot]'s note on the test-infrastructure changes:

  • The two event-loop-survival tests now carry an explicit 30s per-test timeout, so a real hang is bounded in 30s rather than by the file default. The fixture takes about a second under debug+ASAN, so that is 25x headroom versus the previous hardcoded 1s the debug build could not meet.
  • On the setDefaultTimeout / --timeout interaction: per src/runtime/test_runner/ScopeFunctions.rs, the precedence is explicit per-test timeout, then setDefaultTimeout, then the --timeout flag. The CI runner injects --timeout=90000 (270000 on ASAN lanes), and the value set here (5 minutes) exceeds both, so this only raises the default for these two files and never tightens a CI budget.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The core change looks correct and well-tested, but this is a user-visible behavior change in worker lifecycle code and there's a flagged possible duplicate (#31216) to reconcile, so worth a human look.

Extended reasoning...

Overview

The functional change is a two-line edit in Worker::postMessage (src/jsc/bindings/webcore/Worker.cpp): instead of throwing InvalidStateError when m_state == State::Closed, it now returns early (silent no-op) when m_state >= State::Closing, before serialization. Comments in Worker.cpp and Worker.h are updated to match. Four new tests cover the no-op behavior across both node:worker_threads and the Web Worker global, including non-cloneable payloads and transferList non-detachment.

Bundled alongside are test-infrastructure changes: setDefaultTimeout(5 min) added to both test files (which per the described precedence overrides CI's --timeout=90000, loosening the per-file cap from 90s to 300s), and a refactor of two pre-existing flaky tests that raced a spawned process against a hardcoded 1s setTimeout.

Security risks

None identified. This relaxes an error path to a no-op; no new data flows, no auth/crypto/permissions surface.

Level of scrutiny

Moderate. The C++ change itself is tiny and the reasoning (Node parity, HTML-spec alignment, fixes #20425/pgmock) is sound and well-documented. However, it is a user-visible behavior change — code that previously caught InvalidStateError will now see a silent drop — and it touches multi-threaded worker lifecycle code where state-ordering matters. The >= comparison on the State enum relies on declaration order (Pending < Running < Closing < Closed), which holds and is already used identically by wasTerminated() and setKeepAlive().

Other factors

  • Duplicate PR: github-actions flagged #31216 as making the same Worker.cpp change. A human should reconcile which PR to land.
  • Bundled test-infra changes: The setDefaultTimeout addition and event-loop test refactor are reasonable de-flake work per the description, but they're tangential to the fix and change CI timeout behavior for these files — a maintainer may want to weigh in on that separately.
  • No bugs were found by the automated review, and the CodeRabbit nit (parity coverage for Web Worker) was addressed in bf444bb.

@robobun

robobun commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

On the two open items in the review above:

The behavior change itself of course still warrants a maintainer's look.

@robobun

robobun commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status

Build 72487 at 683555b1 (rebased onto current main): 285 test jobs passed, 1 failed. Every Linux, Windows, and macOS lane that ran this PR's new tests is green.

The single failure is test/js/node/test/parallel/test-worker-message-port-transfer-terminate.js on debian-13 x64-asan, a JSC exception-scope assertion (!scope.exception() || !result in JSObject::getOwnPropertyDescriptor, JSObject.cpp:3936). This is a flake on main, not caused by this PR:

A separate fix session already owns test-worker-message-port-transfer-terminate.js. Ready for a maintainer's sign-off on the behavior change.

Rebase details

Rebased onto a59a9c37 (184 new commits). The only merge conflict came from #31216, which wrapped the State::Closing store in dispatchExit in a lock and added rejectAllCrossVMRequests; this change only touched the comment above that store. Resolution: keep #31216's code, integrate the updated comment. The Worker::postMessage guard itself was untouched by #31216 and auto-merged cleanly.

Post-rebase locally: bun bd test on both files is 117 pass / 0 fail; with Worker.cpp/Worker.h reverted to main it is 113 pass / 4 fail, exactly the four tests this PR adds.

@robobun
robobun force-pushed the claude/farm/72cd13af/worker-postmessage-noop-after-exit branch from bf444bb to f5dbe26 Compare July 2, 2026 09:32

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any issues, but this is a deliberate user-visible behavior change to Worker.postMessage (throw → silent no-op, and skipping serialization/transfer on a dead worker), so a maintainer should sign off on the semantics.

Extended reasoning...

Overview

The functional change is two lines in src/jsc/bindings/webcore/Worker.cpp: Worker::postMessage now returns {} when m_state >= Closing instead of throwing InvalidStateError when m_state == Closed. The remaining C++/header edits are comment-only, keeping the state-machine docs consistent. Tests add coverage for the no-op in both node:worker_threads and the Web Worker, plus two ride-along test-infra changes: a file-level setDefaultTimeout(5min) in both suites, and a refactor of two flaky "event loop doesn't close" tests from a 1s setTimeout race to awaiting the subprocess with a 30s per-test cap.

Security risks

None identified. No auth, crypto, or untrusted-input parsing is touched; the change short-circuits before serialization, so it strictly reduces the code that runs on this path.

Level of scrutiny

Medium. The diff is small and the reasoning (Node parity, HTML-spec alignment, Chrome/Firefox behavior) is well-documented and looks correct. But this is an intentional API semantics change on a shared entry point for both the Web Worker global and node:worker_threads: callers that previously got InvalidStateError (or a DataCloneError / detached buffer during the Closing window) now get a silent no-op. That's the kind of Node/Web-compat call a maintainer typically signs off on rather than a bot.

Other factors

  • The setDefaultTimeout addition changes the effective per-test budget for two whole test files based on a stated precedence (setDefaultTimeout > --timeout). It's plausible and the author cited the source, but it's a test-runner-semantics claim worth a second pair of eyes since it affects CI behavior beyond the fix itself.
  • The author's own thread comment notes the behavior change "still warrants a maintainer's look," which I agree with.
  • No CODEOWNERS entry covers this path; the bug-hunting pass found nothing.

@robobun

robobun commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

To close the one open question in the review above (the setDefaultTimeout / --timeout precedence), here it is verified empirically rather than by reading the runner source:

// a.test.ts
import { setDefaultTimeout, test } from "bun:test";
setDefaultTimeout(10_000);
test("needs 3s", async () => { await Bun.sleep(3000); });
$ bun test --timeout 1000 a.test.ts
 1 pass
 0 fail

The same test without the setDefaultTimeout call fails ("timed out after 1000ms") under --timeout 1000, so the flag is genuinely applied; setDefaultTimeout is what overrides it. A test with an explicit per-test timeout argument overrides setDefaultTimeout in turn.

So the precedence is: explicit per-test timeout, then setDefaultTimeout(), then --timeout. The file-level value set here (5 minutes) exceeds every CI-injected --timeout (90000, or 270000 on ASAN lanes), so it can only raise a budget, never lower one, and the two refactored event-loop tests carry an explicit 30s argument that still caps them tightly.

Agreed that the postMessage semantics change itself is the thing for a maintainer to sign off on.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/web/workers/worker.test.ts`:
- Around line 249-270: The current test only verifies the already-Closed case
and does not exercise the new Closing-state no-op path in Worker::postMessage.
Update the Web Worker test so postMessage is called synchronously from inside
the close event handler for the exited worker, before the handler returns, to
mirror the Node worker_threads coverage and hit the Closing branch. Keep the
existing terminate/exit setup, but move at least one postMessage assertion into
the close listener to confirm the message is dropped while the worker is still
transitioning.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 07b5a199-a579-4bd0-872e-beae17f8c613

📥 Commits

Reviewing files that changed from the base of the PR and between beeb403 and 1917772.

📒 Files selected for processing (4)
  • src/jsc/bindings/webcore/Worker.cpp
  • src/jsc/bindings/webcore/Worker.h
  • test/js/node/worker_threads/worker_threads.test.ts
  • test/js/web/workers/worker.test.ts

Comment thread test/js/web/workers/worker.test.ts Resolved
@robobun
robobun force-pushed the claude/farm/72cd13af/worker-postmessage-noop-after-exit branch from 1917772 to ef775ba Compare July 2, 2026 13:25
robobun added 2 commits July 13, 2026 20:02
Worker::postMessage threw InvalidStateError ("Worker has been terminated")
once the worker reached the Closed state, one tick after the exit event and
after terminate() resolved. Node implements a silent no-op, and so do Chrome
and Firefox: the HTML spec's "terminate a worker" never disentangles the
implicit port.

Return early, before serializing, once the worker has exited (>= Closing).
That matches Node's contract in all three windows (inside the exit handler,
after the exit event, after terminate()): no InvalidStateError, no
DataCloneError for a non-cloneable message, and no transferList detach.
Match the node:worker_threads coverage: posting a non-cloneable value or a
transferList entry to a dead Web Worker neither throws DataCloneError nor
detaches the buffer, since the message is dropped before serialization.
Exercise the Closing window too by posting a non-cloneable value from
inside the 'close' handler, before the state has advanced to Closed.

Give the two event-loop-survival tests an explicit 30s timeout so a real
hang is bounded tightly rather than by the file's default.
@robobun
robobun force-pushed the claude/farm/72cd13af/worker-postmessage-noop-after-exit branch from ef775ba to 683555b Compare July 13, 2026 20:11

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found, but this changes user-visible postMessage semantics (throw → silent no-op) for both the Web Worker and node:worker_threads, so a maintainer should sign off on the behavior change.

What was reviewed:

  • The >= State::Closing early return in Worker::postMessage — enum ordering is Pending < Running < Closing < Closed, so live workers still serialize; no memory/lifetime implications since it returns before touching SerializedScriptValue or the transfer list.
  • The enqueueToWorker comment update is consistent: with the guard moved to >= Closing, nothing can reach the inbox after exit, so the old "only the close-handler window lands here" case is gone.
  • New tests cover Closing (in-handler, non-cloneable value) and Closed (after exit / after terminate) for both APIs, plus transferList non-detach; the setDefaultTimeout precedence vs. CI's --timeout was verified in the thread.
Extended reasoning...

Overview

The functional change is two lines in src/jsc/bindings/webcore/Worker.cpp: Worker::postMessage now returns {} when m_state >= State::Closing instead of returning Exception { InvalidStateError } when m_state == State::Closed. The rest of the C++ diff is comment updates in enqueueToWorker, dispatchExit, and the state-machine header doc to reflect that postMessage no longer throws on Closed and no longer serializes-then-drops on Closing. Tests are added to both worker_threads.test.ts and worker.test.ts, plus a setDefaultTimeout(5min) in each file and a de-flake refactor of two existing event-loop-survival tests that previously raced a hardcoded 1s setTimeout.

Security risks

None. This removes an error path and returns early before any serialization, allocation, or transfer-list processing. No new untrusted-input handling, no auth/crypto/permissions surface.

Level of scrutiny

Moderate. The code change is trivially safe from a memory/threading standpoint (it's an atomic load followed by an early return, replacing an atomic load followed by an exception return), and State is a monotonic uint8_t enum so the >= comparison is well-defined. But it is a deliberate user-facing semantics change to Worker.prototype.postMessage for both the Web global and node:worker_threads, and the author themselves noted in the thread that "the postMessage semantics change itself is the thing for a maintainer to sign off on." A maintainer should confirm they want Bun to follow Node/Chrome/Firefox here rather than Safari's throw.

Other factors

  • The test-infrastructure changes (setDefaultTimeout(1000 * 60 * 5) at file scope in two large existing test files, and rewriting two existing tests) are bundled with the fix. The precedence argument (per-test > setDefaultTimeout > --timeout) was verified empirically in the thread and only raises budgets, but it's still a file-wide change to shared test files that's worth a maintainer glance.
  • The refactored event-loop tests are a strict improvement (they replace a CLAUDE.md-violating setTimeout race with awaiting the process and asserting exact stdout), and the new tests follow house style (try/catch → reject inside handlers, exitCode asserted last, non-cloneable value used to prove the Closing branch is actually reached).
  • CI was reported green pre-rebase (build 67982) and the post-rebase build is running; the only merge conflict was a comment-only overlap with #31216, resolved by keeping #31216's code.
  • CodeRabbit's one review comment (Web test didn't exercise the Closing branch) was addressed in ef775ba and the thread is resolved.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-13, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. The linked issue (#20425) stays open. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

@robobun robobun closed this Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can't run pgmock package: Worker has been terminated

1 participant