Repository navigation
Conversation
|
Updated 5:29 PM PT - Nov 13th, 2026
✅ @robobun, your commit 547a8fec2a5cf65354f8ba79cff0abc112b87af5 passed in 🧪 To try this PR locally: bunx bun-pr 38458That installs a local version of the PR into your bun-38458 --bun |
|
Status: ready for review (head 88d5861).
|
|
No actionable comments were generated in the recent review. WalkthroughWorker teardown now uses configurable ChangesWorker teardown gates
Suggested reviewers: Merge Risk:
|
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. It extends debug-only test infrastructure with a second gate mode and reworks the condvar/atomic interplay in close_and_wait / test_gate::weak_post; the concurrency reasoning looks sound and release builds compile it all away, but given it was requested in a specific review thread and touches the VM teardown wait, the reviewer who asked for it should confirm the shape matches what they had in mind.
What was reviewed:
- Traced the
closed-mode path: manualactive.fetch_add+Accessguard is balanced against the innerenter()in the post closure, andclose_and_wait's post-Closedactivewait cannot return before the parked poster has reported. - Traced the
draining-mode path:parkedis incremented beforepark_untiland decremented afterreport+notify, sonothing_parkedcannot let the wait storeClosedunder a poster that has been let through. - Checked the ticket-outstanding bypass:
tickets == 0at check time means the poster itself holds no ticket, so parking it untilClosedcannot deadlock the wait-for-tickets. - Verified the release stub module still compiles (all changed hooks stubbed;
first_report_secsis only called undercfg(debug_assertions)), and no other reader of the old boolean feature flag remains.
Extended reasoning...
Overview
Follow-up to #38299: turns the debug-only BUN_DEBUG_TEST_WORKER_TEARDOWN_GATE from a boolean into a two-mode string (draining / closed), so the worker-teardown test can deterministically exercise both the "weak post released by the wait" and "weak post refused after Closed" paths, and assert the exact outcome word instead of just that a line appeared. Touches env_var.rs (flag kind change), VmHandle.rs (the test_gate module and two hook calls in close_and_wait), web_worker.rs / VirtualMachine.rs (pass the mode through), and the test file.
Security risks
None. Everything new is behind #[cfg(debug_assertions)] and a BUN_DEBUG_* env var read only for first-level workers; the release-build stub module makes every hook a no-op (including the new nothing_parked → true), so close_and_wait's production behaviour is byte-identical.
Level of scrutiny
Higher than the diff size suggests. The test_gate module is concurrent code that parks foreign threads on the same condvar the JS thread's teardown wait sleeps on, and the new closed mode reuses the production active count to keep close_and_wait from returning until the parked poster has reported. I walked both modes' wakeup orderings (see the summary above) and found them correct — in particular the double-Access in the closed path (one manual, one from the inner enter() inside the refused post) is balanced, and the parked counter is bumped before park_until so the JS thread cannot race past it to Closed. The waiter-thread test row is still timing-biased (stdout EOF vs. reap → post), which the PR body acknowledges and validates with 360/360 runs.
Other factors
This was requested in a specific review thread by a reviewer who presumably has the surrounding context (the deleted worker-refused-completion.test.ts, the exact bypass semantics they wanted). The PR body is thorough — cross-checked against main's src, clippy/release-check clean, source-lint test still passes — and the change is internally consistent. Deferring so the requesting reviewer can confirm this is the shape they asked for; nothing here needs changing from what I can see.
|
Closing this PR because it has been inactive for more than 90 days. |
…in each weak post's outcome BUN_DEBUG_TEST_WORKER_TEARDOWN_GATE now takes a mode. "draining" holds a cross-thread post until the worker's teardown is waiting, as before. The wait no longer stores Closed while a post that it released is not made yet, so such a post is always queued and released by the wait. "weak-draining:<TaskTag>" and "weak-closed:<TaskTag>" are for work that comes back as a weak post. Nothing ties a weak poster's timing to the worker, so the worker's teardown does not begin until the weak post with that task tag is at the gate. weak-draining then releases it during the wait. weak-closed holds it until the wait has ended, so it is refused and the poster frees its own payload, and close_and_wait does not return until that post is made. If a ticket is outstanding when the post arrives, weak-closed holds it only until Draining: the wait may be for the thread that makes the post (WebCrypto posts its result from the pool task that carries the ticket). worker-late-completion.test.ts runs each weak row under both weak modes and asserts the exact line: released by the wait under weak-draining, refused under weak-closed, released under both for the WebCrypto row. The host captures the worker's stdout and stderr, because the parent's flow-control message on a stdio port is one more weak post to the worker. With main's gate the outcome of the three weak rows is a race: this test fails in 20 of 20 runs against main's src, with either word in place of the other.
20df49a to
fae015f
Compare
Each mode is documented on its TestGate variant. The module block keeps only what the modes share and the lock hazard.
There was a problem hiding this comment.
Beyond the inline findings: the pushed commit only has the draining / closed modes — the weak-draining:<TaskTag> / weak-closed:<TaskTag> modes, the await_test_gate_weak_post call at the start of VirtualMachine::teardown, and the stdout: true, stderr: true Worker options the description relies on are not in this diff, so the description appears to be ahead of the code.
I also checked the closed-mode active accounting in test_gate::weak_post (the extra Access guard drops after the refused post is reported, so the active == 0 wait is released and the count is balanced) and the Relaxed loads of the gate mode (armed on the JS thread before any off-thread work exists) — neither affects correctness.
No build or test was run in this review; the description's pass/fail counts were not reproduced.
Extended reasoning...
The change extends a debug-only worker-teardown test gate (src/jsc/VmHandle.rs, src/jsc/web_worker.rs, src/bun_core/env_var.rs) from a boolean to a draining/closed mode and rewrites test/js/web/workers/worker-late-completion.test.ts to assert the exact outcome per mode; it touches no security-sensitive surface and the release build compiles the gate to empty stubs. The description names modes, a teardown hook and Worker stdio options that are absent from the pushed commit, which is the concrete fact behind deferring alongside the inline findings.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟡
test/js/web/workers/worker-late-completion.test.ts— Maintainers get three weak rows that can pass without the post under test ever reaching the gate, so a regression in the gated path goes unnoticed. The Worker at test/js/web/workers/worker-late-completion.test.ts:267 is created withoutstdout: true, stderr: true, so the parent's auto-piped worker.stdout/stderr readables post a flow-control ack to the worker's stdio ports from the parent thread. That ack is a weakCppTaskpost with the same tag and outcome the MessagePort, BroadcastChannel and crypto.subtle.digest rows match with.someat line 306. Fix: keep the row's own post the onlyCppTaskcandidate, e.g. passstdout: true, stderr: trueto the Worker so no ack is sent, and assert exactly one[vm] late postline per host.Why this was flagged
The host attaches a 'data' listener to worker.stdout and worker.stderr (src/js/node/worker_threads.ts:1095-1100), which runs
port.postMessage(true)(src/js/node/worker_threads.ts:366). Once the worker's side of that stdio pipe is attached, MessagePortPipe::send calls scheduleDrain -> ScriptExecutionContext::postTaskTo from the parent thread (src/jsc/bindings/webcore/MessagePortPipe.cpp:57-65,74), which is a weak post reported by the gate aslate post: CppTask (...). The rows at test/js/web/workers/worker-late-completion.test.ts:231-243 useweak: "CppTask", and expectLateLine passes if any[vm]line equals the expected string (line 306). Underclosedthe ack parks the parent thread until the worker is Closed, soport1.postMessage("late")runs only after teardown; postTaskTo then returns false on isTerminating and the row's own post is never gated, yet the ack'sCppTask (refused)line satisfies the assertion. The base had the same masking, but this PR's description says the host sets both stdio options to stop this second post; the code does not.Verification: nit — lost test coverage only (a weak row can pass on a line produced by a post other than the one under test); triggers when the parent's post-constructor nextTick runs after the worker's preload has attached its stdio ports. test/js/web/workers/worker-late-completion.test.ts:267 is
new Worker(..., { eval: true, workerData: data, transferList: [port2] })with no stdout/stderr option. -
🔴
src/jsc/VmHandle.rs:459— CI runs of the weak rows in worker-late-completion.test.ts become flaky after merging: the test now demands one exact outcome, but nothing in the runtime holds the teardown for a weak post that has not reached the gate yet. At src/jsc/VmHandle.rs:457close_and_waitstoresClosedas soon astickets == 0 && nothing_parked(s), which is immediately when the parent'sport1.postMessagehas not arrived; a later arrival isRefused, so underdrainingthe host printsrefusedwhile the test expectsreleased by the wait. Fix: make the worker's teardown wait until the expected weak post is at the gate beforeClosedis stored, or keep the test's either-outcome match. [also at: test/js/web/workers/worker-late-completion.test.ts:306 - Maintainers get a flakier weak-post suite than today: each weak row now asserts one exact outcome, but nothing in this…; test/js/web/workers/worker-late-completion.test.ts:307 - CI will see the six weak-row variants fail intermittently under load, because nothing makes the worker's teardown wait…]Why this was flagged
Trigger: any weak row under load. The host at test/js/web/workers/worker-late-completion.test.ts:269 posts
port1.postMessage("late")only when the parent receives "armed"; the worker exits two immediates after sending it. The worker'sclose_and_waitat src/jsc/VmHandle.rs:457-459 storesClosedon its first pass becausetickets == 0andparked == 0(theparkedcounter at src/jsc/VmHandle.rs:645 is only incremented once the poster is already insideweak_post). When the parent's post arrives after that,post(task)at src/jsc/VmHandle.rs:647 isRefused, and the host prints[vm] late post: CppTask (refused). The test at test line 306 compares with===againstreleased by the waitunderdraining, so the row fails. On the base branch the same row matchedstartsWith("[vm] late post: <tag> (")so either outcome passed. The PR description says the fix isawait_test_gate_weak_postas the first call ofVirtualMachine::teardownplus tag-specific modes, butgrepforawait_test_gate_weak_post,weak-draining,weak-closedfinds nothing in the repo, and src/jsc/VirtualMachine.rs:1751-1840 calls nothing of the kind beforeclose_and_wait.Verification: Nothing holds the worker's teardown for a weak post that has not yet entered the gate. At src/jsc/VmHandle.rs:457-459
close_and_waitstoresClosedwhentickets == 0andnothing_parked(s);parkedis only incremented at line 645 insideweak_post, after the poster has already reached the gate. A post still on its way counts as nothing.await_test_gate_weak_post,weak-closedandweak-drainingare not in src/. -
🟡
src/jsc/VmHandle.rs:581— nit: themode()match on 1/2 at src/jsc/VmHandle.rs:577-581 hand-mirrors theTestGatediscriminants declared at src/jsc/VmHandle.rs:550-554, so a future renumbering of one side silently breaks the other. Fix: derive one from the other, e.g. match onTestGate::Draining as u8/TestGate::Closed as u8, or add a singleTestGate::from_u8beside the enum thatmode()andfrom_env()both use.Why this was flagged
The enum
TestGateat src/jsc/VmHandle.rs:548-554 is the source of the values stored byarm_test_gateat src/jsc/VmHandle.rs:573 (mode as u8). The readermode()at src/jsc/VmHandle.rs:577-581 matches literal1and2instead of the enum's values. Nothing fails today; the two tables agree. If a variant is added or renumbered on one side only,mode()returnsOffor the wrong mode and the gate silently stops parking posts, with no compile error. REVIEW.md's one-source-of-truth check for mirrored discriminants is what this flags.Verification: nit. Trigger: a future edit that renumbers a
TestGatevariant on one side; nothing fails in the merged code today. src/jsc/VmHandle.rs:548-554 declaresTestGate; the writerarm_test_gateat line 573 storesmode as u8; the readermode()at lines 576-582 decodes with hand-written literals, so a renumbering on either side would silently decode toOffwith no compiler diagnostic.
|
The review above reads commit 20df49a, which the push to fae015f replaced. The current head has what it reports as missing: The |
|
CI on fe87164: |
…own gate modes The gate has two modes again, draining and closed, and no task tag. The worker's teardown no longer waits inside the runtime for a weak post. The gate prints "[vm] weak post at the gate: <tag>" when it has counted a weak post, and a weak row's worker stays in a read of the host's stdin until the test has seen that line and closes the stdin. The worker is not stopping while it waits, so work that a stopping VM skips still runs. An unknown value of BUN_DEBUG_TEST_WORKER_TEARDOWN_GATE is refused by name and the process exits. Before, it read as "off" (main's old "1" included), and a row then ran ungated with nothing that named the variable. TestGate exists only with debug assertions and is pub(crate). Release builds keep four empty hooks. Each weak row asserts the exact ordered list of its lines: the marker of the parent's post where there is one, the arrival at the gate, the outcome. The second host that arms the gate captures the worker's stdio too. A WebAssembly.compile row covers the deferred work that a JSC helper thread posts. The BroadcastChannel entry leaves flaky-tests.txt: the row cannot lose its post to the teardown any more.
There was a problem hiding this comment.
Beyond the inline finding, I also checked the new closed-mode hold in weak_post for a deadlock against close_and_wait: the poster holds active while parked on Closed, but close_and_wait stores Closed and calls state_published before it waits on active, and the poster's Access drop notifies under Closed, so neither side waits on the other. The tickets == 0 read followed by active.fetch_add cannot race the teardown in the test, since the "weak post at the gate" line is printed only after the increment and the worker stays in readSync(0) until the test sees it. Also grepped for ungated uses of TestGate, test_gate() and arm_test_gate after the #[cfg(debug_assertions)] gating: none remain, though I did not run the release cargo check.
Extended reasoning...
The latest commit reworks the debug-only worker teardown test gate in src/jsc/VmHandle.rs (new Closed mode, parked counter, exit(1) on an unknown env value), cfg-gates the gate surface in src/jsc/web_worker.rs and src/jsc/VirtualMachine.rs, and restructures test/js/web/workers/worker-late-completion.test.ts around a stdin hold; it touches no security-sensitive surface. One confirmed finding is posted inline, and this note records the concurrency and release-build concerns that were examined by reading and ruled out.
…are exit TestGate::from_env returns the message as an Err and WebWorker::create sets error_message with it, so new Worker() throws a TypeError and the process exits through its normal path. The bare Global::exit(1) skipped the VM teardown, and on the ASAN lane (BUN_DESTRUCT_VM_ON_EXIT=1 with detect_leaks=1:abort_on_error=1) LeakSanitizer then reported the live VM and aborted the host with 134.
There was a problem hiding this comment.
I reviewed the latest push and found no bugs; the unknown-mode path now surfaces as a TypeError from the Worker constructor rather than a bare exit, which resolves the ASAN concern from the previous round. Since the gate's ordering argument and the new stdin hold in the weak rows can only be settled by running the suite, which this review did not do, a human look at the CI results (especially the Windows debug lane, where a worker's readSync(0) on a piped stdin is new) is still worthwhile.
What was reviewed:
weak_postcounters: the closed path's manualactivebump is released by theAccessguard on every return; the draining path'sparkedinc/dec brackets the post and notifies the condvar, andclose_and_waitpublishesClosedonly whenparked == 0, so no held post is closed past.- Release build by reading:
TestGate,test_gate()andarm_test_gateare referenced only under#[cfg(debug_assertions)]; the releasetest_gatestubs leaveclose_and_waitbehavior-identical, and no other test in the tree still sets the old=1value. - The
from_envearly return inWebWorker::createmirrors the sibling exec-argv exit (only RAII-managed state is held above it) and the C++ caller maps the null return to a TypeError with the message the test asserts. - Not run: the test file itself; the 1030/1030 determinism figure and the
tickets == 0snapshot always yielding REFUSED for the non-ticketed rows rest on the author's runs.
Extended reasoning...
The change reworks the debug-only worker teardown test gate in src/jsc/VmHandle.rs (new TestGate enum with draining/closed modes, a parked counter, a restructured weak_post), threads the mode through src/jsc/web_worker.rs and src/jsc/VirtualMachine.rs under cfg(debug_assertions), converts the env var from a feature flag to a string, and rewrites test/js/web/workers/worker-late-completion.test.ts so each weak row asserts its exact ordered stderr lines under both gates while removing the flaky-tests entry. It touches no security-sensitive surface; release builds are behavior-identical because the test_gate stubs are empty and all new items are cfg-gated. The prior round's only finding (a bare exit under LeakSanitizer) is addressed by commit 547a8fe, and no third-party objection is outstanding. Deferral rather than approval is because the correctness of the new test depends on cross-thread timing and platform behavior (stdin hold inside a worker, stderr line ordering) that reading cannot settle and no run was performed in this review.
Follow-up to #38299 (review thread).
Problem
worker-late-completion.test.tspass forreleased by the waitand forrefused. No test reaches theClosed -> Refusedpaths on purpose.test/flaky-tests.txt.Fix
BUN_DEBUG_TEST_WORKER_TEARDOWN_GATEtakes a mode.drainingis the old mode, and the wait now storesClosedonly after each held post is made.closedholds a weak post untilClosed(refused), or untilDrainingif a ticket is outstanding.new Worker()throw aTypeErrorthat names the variable.src/every weak variant fails. Self-reviewed: 11 concerns raised, 9 addressed (Notes).Background
Ticket(Draining), then refuses posts (Closed). A weak poster holds no ticket.mod test_gate,src/jsc/VmHandle.rs, debug builds only) parks a cross-thread post and prints its outcome.VirtualMachine::teardown(the previous version): it is runtime code for a test.Downsides
=1now makesnew Worker()throw. Open macros: parse a file that imports a macro on a dedicated pool #46862 and FileSink: close a file before end() or Bun.write() reports it closed #46088 set it and needdraining.Notes
Measurements (debug ASAN build, Linux x64, 16 cores)
With this change:
-t gate): 10 runs one at a time, 15 runs in each of 3 parallel loops, 8 runs in each of 6 parallel loops (load average 24). 103 runs of 10 variants, 1030 of 1030 pass. Each run asserts the exact ordered lines, so each saw one weak post, the row's own.The base's
src/with this test: all 10 weak variants fail. The old gate does not print the arrival line, so the test does not release the worker and each variant ends at the test timeout. The unknown-mode test fails too, because the old flag accepts1.What main's gate does with a weak post (measured with the previous version of this test, which only read the outcome word, 20 runs for each variant):
Main as it is (main's test and main's
src/), the 4 weak rows, 10 runs in each of 6 parallel loops: 5 of 60 runs fail. Each time it is the waiter row, and the host printed no[vm]line.test/flaky-tests.txthad the same symptom for the BroadcastChannel row on debian 13 x64-asan (seen was false). This PR removes that entry.Why the rows need a hold, and where it lives
markTerminating()(ScriptExecutionContext::postTaskTo), and a worker does not wait for a weak post. A post that comes after the worker began to exit is dropped, or it finds the VM already closed.process.exit()from an immediate took about 900 ms to take effect in a debug build, so the post always came first. worker: wake the loop when a worker stops itself from an immediate (process.exit() / uncaught error) #38483 fixed that latency.VirtualMachine::teardownuntil the post was at the gate. The self-review rejected that: it is runtime code for a test, it waits with no deadline, and it needs a task tag in the variable that no test pins.fs.readSync(0), so it is still running and not stopping. The test reads the host's stderr and closes the host's stdin when it sees the arrival line. If the host exits first, the test fails at once with the host's output.Self-review: 11 concerns raised, 9 addressed
new Worker()throws, with a test. A first version ended the process with a bareexit(1). That skips the VM teardown, and on the ASAN lane (BUN_DESTRUCT_VM_ON_EXIT=1,detect_leaks=1:abort_on_error=1) LeakSanitizer reported the live VM and aborted the host with 134 after 7 s.TestGatewaspubonly to pass the dead-code lint in release: now#[cfg(debug_assertions)]andpub(crate).terminate() waits for work that cannot be cancelled) could park its parent on the stdio message before it calledterminate(): it captures the worker's stdio now.The stdio message
worker.stdoutandworker.stderrstreams ask for data withport.postMessage(true)(src/js/internal/worker/stdio.ts:54). When the worker's end of the port is attached, that is a weak post to the worker. It reached the gate in 7 of 120 runs of the waiter row, and a stack trace at the gate showedMessagePort.postMessageon the parent's thread.stdout: true, stderr: trueon the Worker it reached the gate in 0 of 120 runs. Both hosts set the options.The build
bun bdfails on current main inBunPlugin.cpp(no member named 'SuspendExceptionScope' in namespace 'JSC'). Fix the debug build: include FrameTracers.h and wtf/Scope.h in BunPlugin.cpp #48722 has the fix. I built with that two-line fix applied locally. It is not part of this diff.cargo check -p bun_jsc --release(against release codegen),cargo clippy -p bun_jsc -p bun_core,cargo fmt --check: clean.test/js/node/worker_threads/worker_threads.test.tsandtest/js/web/workers/worker.test.ts(208 pass),test/internal/source-lints/vm-thread-door.test.ts.Related open PRs
1. After a rebase they get the error that names the variable, and needdraining.host()in this test file (a textual conflict) and builds a worker's stdio on first use, which removes the stdio message. Whichever lands second rewords the capture comment.no test proof · iteration 5 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/web/workers/worker-late-completion.test.ts