Repository navigation
Conversation
|
Updated 2:06 PM PT - Jul 13th, 2026
❌ @robobun, your commit 683555b has 1 failures in
🧪 To try this PR locally: bunx bun-pr 33233That installs a local version of the PR into your bun-33233 --bun |
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
WalkthroughWorker 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. ChangesWorker shutdown postMessage behavior
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
src/jsc/bindings/webcore/Worker.cppsrc/jsc/bindings/webcore/Worker.htest/js/node/worker_threads/worker_threads.test.tstest/js/web/workers/worker.test.ts
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
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
setDefaultTimeoutto 5 minutes for entire files is a policy call a maintainer should ack (the description asserts CI's injected--timeoutstill 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.
|
Responding to the four bot comments above. Not a duplicate of #31216. I checked that PR's head ( 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 #20425. Confirmed and linked with 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 claude[bot]'s note on the test-infrastructure changes:
|
There was a problem hiding this comment.
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.cppchange. A human should reconcile which PR to land. - Bundled test-infra changes: The
setDefaultTimeoutaddition 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.
|
On the two open items in the review above:
The behavior change itself of course still warrants a maintainer's look. |
CI statusBuild 72487 at The single failure is
A separate fix session already owns Rebase detailsRebased onto Post-rebase locally: |
bf444bb to
f5dbe26
Compare
There was a problem hiding this comment.
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
setDefaultTimeoutaddition 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.
|
To close the one open question in the review above (the // a.test.ts
import { setDefaultTimeout, test } from "bun:test";
setDefaultTimeout(10_000);
test("needs 3s", async () => { await Bun.sleep(3000); });The same test without the So the precedence is: explicit per-test timeout, then Agreed that the |
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
src/jsc/bindings/webcore/Worker.cppsrc/jsc/bindings/webcore/Worker.htest/js/node/worker_threads/worker_threads.test.tstest/js/web/workers/worker.test.ts
1917772 to
ef775ba
Compare
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.
ef775ba to
683555b
Compare
There was a problem hiding this comment.
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::Closingearly return inWorker::postMessage— enum ordering isPending < Running < Closing < Closed, so live workers still serialize; no memory/lifetime implications since it returns before touchingSerializedScriptValueor the transfer list. - The
enqueueToWorkercomment 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
setDefaultTimeoutprecedence vs. CI's--timeoutwas 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
setTimeoutrace 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
Closingbranch) was addressed in ef775ba and the thread is resolved.
|
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. |
Fixes #20425
What does this PR do?
worker.postMessage()throws once a worker has exited or been terminated:The same happens after
await worker.terminate(), and for the WebWorkerglobal. 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 breakspgmockin #20425: its embedded x86 emulator posts to a worker that has exited, andpostMessage@[native code]surfaces theInvalidStateErroras an unhandled error.The throw comes from WebKit's terminated check in
Worker::postMessage(src/jsc/bindings/webcore/Worker.cpp):The
Closingstate was added precisely so the in-handler window silently drops ("matching browser/Node semantics", per the comment inWorker.h), butClosedkept 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'sWorker.prototype.postMessagereturns before serializing once the port is gone (lib/internal/worker.js:if (this[kPublicPort] === null) return;), and it nulls that port before emittingexit.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 afterterminate(). Returning before serialization also means a message to a dead worker can no longer throwDataCloneErroror detach its transferList entries, which the previousClosingpath 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:postMessageafter theexitevent, afterterminate()resolves, and with a non-cloneable message plus a transferList from inside the exit handler onward.test/js/web/workers/worker.test.ts: the WebWorkerafterterminate()(Closed), from inside theclosehandler 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 expectedpostMessage@[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: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.--timeout=90000. Set the same file-levelsetDefaultTimeoutthe shell test suites use. The precedence is explicit per-test timeout, thensetDefaultTimeout(), 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)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 0 rejected · iteration 6
evidence per changed file