Skip to content
Closed

ai slop #28795

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions src/bun.js/web_worker.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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

View check run for this annotation

Claude / Claude Code Review

WebWorker struct permanently leaked: destroy() removed with no replacement

The PR removes `bun.default_allocator.destroy(this)` from `deinit()` with an intentional comment but adds no replacement mechanism to ever free the `WebWorker` struct. 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.
Comment on lines 367 to 390

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 PR removes bun.default_allocator.destroy(this) from deinit() with an intentional comment but adds no replacement mechanism to ever free the WebWorker struct. 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() called bun.default_allocator.destroy(this) to release the WebWorker struct 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 via bun.default_allocator.create(WebWorker). The worker thread eventually calls exitAndDeinit() → this.deinit(). The modified deinit() frees unresolved_specifier and preloads but no longer calls destroy(this). WebWorker__dispatchExit() posts the close event task to the parent thread, but that task does not call any WebWorker__deinit / deinitFromParent export — because no such export exists. Examining the comptime block confirms only four exports: WebWorker__create, WebWorker__notifyNeedTermination, WebWorker__setRef, and WebWorker__updatePtr.

Why existing code doesn't prevent it: Worker::~Worker() in Worker.cpp is not modified by this PR and does not free impl_. Neither does the dispatchExit task lambda. There is no Worker__clearImpl or WebWorker__deinit function 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() or new wt.Worker() leaks sizeof(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 updatePtr failure path also leaks: When Thread.spawn fails inside WebWorker__updatePtr, worker.deinit() is called without destroy, leaving the half-initialized struct permanently allocated.

Step-by-step proof:

  1. JavaScript calls new Worker(url); C++ calls WebWorker__create, which calls bun.default_allocator.create(WebWorker) and returns a pointer — this allocation is the only owner of the struct.
  2. Worker thread runs, eventually calls exitAndDeinit().
  3. exitAndDeinit() calls WebWorker__dispatchExit() then this.deinit().
  4. deinit() frees unresolved_specifier and preloads, then returns — no destroy(this).
  5. WebWorker__dispatchExit posts a task to the parent loop. Inspecting the dispatch task: it fires the close event and calls worker->deref() (C++ Worker refcount), but never calls any Zig-side free.
  6. When the C++ Worker is GC'd, its destructor removes itself from allWorkers — no impl_ free.
  7. The WebWorker struct allocation is permanently unreachable: no pointer to it exists except impl_ in the now-destroyed C++ Worker, and that was never freed.

How to fix: Add a WebWorker__deinit export in the comptime block that calls bun.default_allocator.destroy(this), and call it from the parent thread's close task in C++ Worker::dispatchExit after nulling out impl_.

jsc.markBinding(@src());
var vm = this.vm orelse return;
if (vm.log.msgs.items.len == 0) return;
Expand Down Expand Up @@ -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

View check run for this annotation

Claude / Claude Code Review

notifyNeedTermination() has same TOCTOU race as setRef() — unaddressed double-unref

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
Comment on lines 552 to 562

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 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():

  1. Parent: status.load(.acquire) returns .running (guard at line 582 passes)
  2. Worker: setStatus(.terminated) [release store at line 604], then vm.onExit(), WebWorker__dispatchExit(), then this.deinit()
  3. Worker: deinit() calls parent_poll_ref.unrefConcurrently(parent): reads KeepAlive.status == .active, writes .inactive, calls vm.event_loop.unrefConcurrently() [unref Fix ?? operator  #1]
  4. Parent: setRequestedTerminate() atomically swaps false to true, returns false (continues past line 585)
  5. Parent: setRefInternal(false) calls parent_poll_ref.unref(parent): if step 3 store has not propagated, reads KeepAlive.status == .active, writes .inactive, calls event_loop.unref() [unref Fix calling #private() functions in classes #2 - double-decrement]

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);
}

Expand Down
15 changes: 15 additions & 0 deletions test/js/web/workers/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

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 new regression test has three organizational nit-level issues: it belongs in test/regression/issue/28415.test.ts per the CLAUDE.md convention; it uses the Web Worker API (new Worker()) but is placed inside describe("worker_threads") where every other test uses new wt.Worker(); and the unref()/ref() calls happen after await promise, so the test only exercises the C++ null-check guard rather than the mutex-protected concurrent race window that the PR actually fixes.

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 test/js/web/workers/worker.test.ts instead of test/regression/issue/28415.test.ts. The test/regression/issue/ directory is actively used (e.g., 00631.test.ts, 012039.test.ts) and the project has a clear, documented convention for exactly this case. This is a nit — the test still runs and provides coverage, but it violates the stated standard.

Wrong describe block (bug_004)

The test at lines 417–427 uses new Worker("http://localhost/does-not-exist") and worker.addEventListener("close", ...), which are Web Worker API patterns. Yet it is nested inside describe("worker_threads", ...) (line 302), which is explicitly labelled "TODO: move to node:worker_threads tests directory" and contains exclusively new wt.Worker() calls. The Web Worker tests live in describe("web worker", ...) just above. Placing a Web Worker test inside the worker_threads describe block is misleading and inconsistent with the surrounding test structure. This is a pure organizational nit — the test executes correctly regardless.

Test only covers the post-clearImpl null-check path, not the mutex race window (bug_003)

The call order inside exitAndDeinit() is: (1) Worker__clearImpl(cpp_worker) — sets impl_ = null under the C++ mutex; then (2) WebWorker__dispatchExit() — posts the close task to the parent thread. The test resolves promise inside the close event handler, which only fires after step (2) has already delivered the task to the parent's event loop. By that point impl_ is guaranteed to be null. Therefore the worker.unref()/ref()/unref() calls after await promise can only reach the early-return null-check in Worker::setKeepAlive() — they never race with the mutex-protected window where impl_ transitions from non-null to null.

The actual concurrent race the PR is fixing is: parent calls setKeepAlive() while the worker thread holds the mutex inside clearImpl(). Moving the ref/unref sequence into the close event listener (before resolve()) would fire while the parent is still processing the task posted by dispatchExit, which — while not a guaranteed overlap with clearImpl — is at least a closer approximation of the deferred-lifetime scenario. CodeRabbit raised this exact concern and it was marked "Addressed in commit d615ea4", but the merged code still has the calls outside the close handler.

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

  1. new Worker("http://localhost/does-not-exist") spawns a worker that immediately fails to load and exits.
  2. worker.terminate() sets the C++ TerminateRequestedFlag and calls WebWorker__notifyNeedTermination(impl_).
  3. The worker thread runs exitAndDeinit(): calls Worker__clearImpl (sets impl_ = null under mutex), then WebWorker__dispatchExit (posts the close task to the parent loop).
  4. The parent loop fires the close task: the close event listener calls resolve().
  5. await promise returns. At this point impl_ is already null — has been since step 3.
  6. worker.unref() → Worker::setKeepAlive(false) → acquires m_implMutex, checks !impl_ (true), returns immediately. The null-check guard fires, not the concurrent-access path.
  7. The test passes, but without ever having two threads simultaneously contending on m_implMutex during the impl_ transition.

Loading