Repository navigation
ai slop #28795
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ai slop #28795
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -364,23 +364,30 @@ | |
|
|
||
| this.vm = vm; | ||
|
|
||
| vm.global.vm().holdAPILock(this, callback); | ||
| } | ||
|
|
||
| /// Deinit will clean up vm and everything. | ||
| /// Releases owned resources. | ||
| /// Early deinit may be called from caller thread, but full vm deinit will only be called within worker's thread. | ||
| fn deinit(this: *WebWorker) void { | ||
| log("[{d}] deinit", .{this.execution_context_id}); | ||
| this.parent_poll_ref.unrefConcurrently(this.parent); | ||
| bun.default_allocator.free(this.unresolved_specifier); | ||
| this.unresolved_specifier = &.{}; | ||
| for (this.preloads) |preload| { | ||
| bun.default_allocator.free(preload); | ||
| } | ||
| bun.default_allocator.free(this.preloads); | ||
| bun.default_allocator.destroy(this); | ||
| this.preloads = &.{}; | ||
| // Intentionally do NOT `bun.default_allocator.destroy(this)` here: the C++ | ||
| // `Worker` on the parent thread may still hold a raw `impl_` pointer to | ||
| // this struct and call `.ref()/.unref()/.terminate()` after the worker | ||
| // thread has exited. Reading `status == .terminated` from the parent | ||
| // thread's setRef/notifyNeedTermination guards returns safely as long as | ||
| // the struct itself remains alive. | ||
| } | ||
|
|
||
| fn flushLogs(this: *WebWorker) void { | ||
|
Check failure on line 390 in src/bun.js/web_worker.zig
|
||
| jsc.markBinding(@src()); | ||
| var vm = this.vm orelse return; | ||
| if (vm.log.msgs.items.len == 0) return; | ||
|
|
@@ -542,13 +549,17 @@ | |
| this.exitAndDeinit(); | ||
| log("[{d}] spin done", .{this.execution_context_id}); | ||
| } | ||
|
|
||
| /// This is worker.ref()/.unref() from JS (Caller thread) | ||
| pub fn setRef(this: *WebWorker, value: bool) callconv(.c) void { | ||
| if (this.hasRequestedTerminate()) { | ||
| // Also check `.terminated` status: a worker that exited naturally (not via | ||
| // terminate()) never sets `requested_terminate`, but its parent_poll_ref | ||
| // has been unref'd in deinit(). A late ref() here would re-pin the parent | ||
| // loop with no matching unref. | ||
| if (this.hasRequestedTerminate() or this.status.load(.acquire) == .terminated) { | ||
| return; | ||
| } | ||
|
|
||
|
Check failure on line 562 in src/bun.js/web_worker.zig
|
||
|
Comment on lines
552
to
562
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 The notifyNeedTermination() function (line 596) has the same TOCTOU double-unref race that this PR fixes in setRef(): the .terminated status check and the setRefInternal(false) call are non-atomic, and KeepAlive.status is a plain non-atomic enum, so both the worker's deinit() and the parent's notifyNeedTermination() path can simultaneously pass the idempotency guard and both decrement the parent event loop ref count. The TODO comment on that line already marks it as needing removal, and deleting it (as intended) would fix the race. Extended reasoning...What the bug is and how it manifests notifyNeedTermination() already has a .terminated status guard at line 582, but this guard and the subsequent setRefInternal(false) call at line 596 are two separate, non-atomic operations. For a naturally-exiting worker (where requested_terminate is never set), setRequestedTerminate() at line 585 swaps false to true and returns false, allowing execution to continue to the setRefInternal(false) call. The TOCTOU window exists between the status check passing and that call executing. The specific code path that triggers it Step-by-step race for a naturally-exiting worker while the parent calls Worker::terminate():
Why the KeepAlive guard does not prevent the race The refutation argues that KeepAlive.unref() provides practical idempotency via its check. This is only true for sequential calls. KeepAlive.status is declared as Status = enum { active, inactive, done } (posix_event_loop.zig line 10) - a plain enum, NOT std.atomic.Value. Both unref() (lines 45-56) and unrefConcurrently() (lines 59-64) perform a non-atomic read of this.status, then a non-atomic write, then call the event loop decrement. There is no atomic compare-and-swap. If two threads both read this.status == .active before either writes .inactive, both will proceed to write .inactive and both will call the loop's unref function - the data race causes a double-decrement of the parent event loop reference count. This is undefined behavior on the non-atomic field. Why the acquire/release ordering on status does not prevent the race The acquire load at line 582 creates a happens-before edge only when it observes the worker's release store of .terminated. When the acquire load returns .running (the TOCTOU window), no such edge exists. The C11 memory model does not guarantee that a thread which observed an old value via an acquire load will continue to see only old values in subsequent plain loads. The non-atomic reads within KeepAlive.unref() and unrefConcurrently() are the crux of the issue, independent of the acquire/release on status. Addressing the refutation The refutation states that notifyNeedTermination already has the terminated status check so both functions now have equivalent guard patterns. This is narrowly correct, but misses the problem: the check and the action (setRefInternal) are not atomic with respect to deinit(). The fact that setRef() previously lacked this check and was fixed by this PR does not mean notifyNeedTermination() is fully fixed - it already had the check but still has the same TOCTOU between the check passing and setRefInternal(false) executing while deinit() concurrently unrefs parent_poll_ref. Impact and fix The double-unref causes the parent event loop reference count to underflow, potentially allowing the parent process to exit prematurely. The // TODO(@190n) delete comment at line 595 already acknowledges this setRefInternal(false) call is intended to be removed. Deleting it fixes the race: deinit() already handles the unref unconditionally for the worker-exit path, making the parent-side call redundant and racy. This mirrors exactly the reasoning applied to setRef() in this PR. |
||
| this.setRefInternal(value); | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -410,4 +410,19 @@ describe("worker_threads", () => { | |
| await p; | ||
| expect(message).toEqual("hello"); | ||
| }); | ||
|
|
||
| // ref/unref/terminate after the worker thread has exited used to be a | ||
| // use-after-free because the Zig WebWorker struct was freed on the worker | ||
| // thread while the C++ Worker on the parent thread still held a dangling | ||
| // pointer. | ||
| test("ref/unref/terminate after worker exit does not crash", async () => { | ||
| const worker = new wt.Worker(new URL("worker-fixture-process-exit.js", import.meta.url).href, { | ||
| smol: true, | ||
| }); | ||
| await once(worker, "exit"); | ||
| worker.unref(); | ||
| worker.ref(); | ||
| worker.unref(); | ||
| await worker.terminate(); | ||
| }); | ||
| }); | ||
|
Comment on lines
+413
to
428
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 The new regression test has three organizational nit-level issues: it belongs in Extended reasoning...CLAUDE.md convention violation (bug_002) CLAUDE.md explicitly states: "If a test is for a specific numbered GitHub Issue, it should be placed in test/regression/issue/${issueNumber}.test.ts." The PR description says "Fixes #28415" and the test comment reads "ref/unref after the worker thread has exited used to be a use-after-free" — this is textbook regression test for a specific numbered issue. The test was added to Wrong The test at lines 417–427 uses Test only covers the post-clearImpl null-check path, not the mutex race window (bug_003) The call order inside The actual concurrent race the PR is fixing is: parent calls Addressing the refutation of bug_003 One verifier argued this is a test quality observation rather than a code bug, and that the concurrent race window is not practically testable deterministically from JavaScript. This is a fair point — the fix (mutex + null-check) is correct regardless of test placement, and a crash regression test that exercises any path through the fixed code has real value. The issue is narrowly scoped: the test is titled as exercising the UAF scenario, but by construction it can only reach the post-clearImpl null-check. This is nit-level; it does not affect correctness of the fix. Proof by example
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 The PR removes
bun.default_allocator.destroy(this)fromdeinit()with an intentional comment but adds no replacement mechanism to ever free theWebWorkerstruct. Every worker creation permanently leaks the ~200-byte struct allocation for the lifetime of the process, causing unbounded memory growth in long-running servers that spawn many workers.Extended reasoning...
What the bug is: In the old code,
deinit()calledbun.default_allocator.destroy(this)to release theWebWorkerstruct back to the allocator. This PR removes that call with the explicit comment// Intentionally do NOT bun.default_allocator.destroy(this), but adds no replacement path that ever frees the struct. The comment says the struct lives on until the parent thread frees it on its own event loop — but that freeing code was never added.The specific code path:
WebWorker.create()allocates the struct viabun.default_allocator.create(WebWorker). The worker thread eventually callsexitAndDeinit()→this.deinit(). The modifieddeinit()freesunresolved_specifierandpreloadsbut no longer callsdestroy(this).WebWorker__dispatchExit()posts the close event task to the parent thread, but that task does not call anyWebWorker__deinit/deinitFromParentexport — because no such export exists. Examining thecomptimeblock confirms only four exports:WebWorker__create,WebWorker__notifyNeedTermination,WebWorker__setRef, andWebWorker__updatePtr.Why existing code doesn't prevent it:
Worker::~Worker()in Worker.cpp is not modified by this PR and does not freeimpl_. Neither does thedispatchExittask lambda. There is noWorker__clearImplorWebWorker__deinitfunction anywhere in the diff. The CodeRabbit walkthrough describes such additions, but they do not appear in the actual two-file diff.Impact: Every call to
new Worker()ornew wt.Worker()leakssizeof(WebWorker)(approximately 160–200 bytes depending on alignment). In long-running server processes that repeatedly spawn and terminate workers (e.g., per-request worker pools, test harnesses, serverless function runtimes), this accumulates unboundedly, eventually causing OOM or requiring process restarts.The
updatePtrfailure path also leaks: WhenThread.spawnfails insideWebWorker__updatePtr,worker.deinit()is called withoutdestroy, leaving the half-initialized struct permanently allocated.Step-by-step proof:
new Worker(url); C++ callsWebWorker__create, which callsbun.default_allocator.create(WebWorker)and returns a pointer — this allocation is the only owner of the struct.exitAndDeinit().exitAndDeinit()callsWebWorker__dispatchExit()thenthis.deinit().deinit()freesunresolved_specifierandpreloads, then returns — nodestroy(this).WebWorker__dispatchExitposts a task to the parent loop. Inspecting the dispatch task: it fires thecloseevent and callsworker->deref()(C++ Worker refcount), but never calls any Zig-side free.Workeris GC'd, its destructor removes itself fromallWorkers— noimpl_free.WebWorkerstruct allocation is permanently unreachable: no pointer to it exists exceptimpl_in the now-destroyed C++Worker, and that was never freed.How to fix: Add a
WebWorker__deinitexport in thecomptimeblock that callsbun.default_allocator.destroy(this), and call it from the parent thread's close task in C++Worker::dispatchExitafter nulling outimpl_.