Skip to content

fetch: hold tasklet mutex through derefFromThread so HTTP thread never drops last ref - #29453

Closed
robobun wants to merge 8 commits into
mainfrom
farm/186a659d/fetch-response-atom-cross-thread
Closed

robobun wants to merge 8 commits into
mainfrom
farm/186a659d/fetch-response-atom-cross-thread

Conversation

@robobun

@robobun robobun commented Apr 18, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes a flaky RELEASE_ASSERT in the x64 ASAN lane, observed in test/js/bun/http/proxy.test.js:

ASSERTION FAILED: wasRemoved
vendor/WebKit/Source/WTF/wtf/text/AtomStringImpl.cpp(409) : static void WTF::AtomStringImpl::remove(AtomStringImpl *)

The failing subprocess was NO_PROXY port handling > should handle NO_PROXY with multiple entries including port, exiting with code 132 (SIGILL from the RELEASE_ASSERT).

Root cause

FetchTasklet.toResponse() atomizes Response.status_text and Response.url for dedup (many responses share "OK"). Atom strings live in a per-thread table, so Response.destroy() must run on the thread that created them.

FetchTasklet.callback() runs on the HTTP thread with this defer order:

defer if (is_done) task.derefFromThread();  // runs LAST (after unlock)
task.mutex.lock();
defer task.mutex.unlock();                   // runs second-to-last

So on the HTTP thread: enqueue onProgressUpdate → unlock mutex → derefFromThread(). In the gap between unlock and derefFromThread(), the JS thread can:

  1. Run onProgressUpdate → onResolve → create the Response with atomized strings, resolve the fetch promise, unref poll_ref, deref the tasklet (2→1).
  2. Finish the user script, set is_shutting_down=true, and — with BUN_DESTRUCT_VM_ON_EXIT=1 (set by the ASAN CI lane via scripts/runner.node.mjs) — run destructOnExit → full GC → Response.finalize → Response.ref_count 2→1.

Then the HTTP thread resumes at derefFromThread() → tasklet 1→0 → sees isShuttingDown() → runs deinit() on the HTTP thread (branch added in #27385) → native_response.unref() → Response 1→0 → Response.destroy() derefs the atom strings from the HTTP thread → AtomStringImpl::remove() looks in the HTTP thread's table, doesn't find them, asserts.

The NO_PROXY parsing is unrelated — the bug is a generic fetch-vs-shutdown race that surfaced during that test run.

Fix

Swap the defer order in callback() so derefFromThread() runs while holding the mutex:

task.mutex.lock();
defer task.mutex.unlock();                   // runs LAST
defer if (is_done) task.derefFromThread();   // runs BEFORE unlock

onProgressUpdate (the only path that drops the other baseline ref) needs the mutex, so while the HTTP thread holds it the JS side cannot have deref'd yet. The HTTP thread's deref is therefore always N→N-1 with N≥2 — never the last ref. Since poll_ref is unref'd inside onProgressUpdate, the VM stays alive until the HTTP thread is done with the tasklet, and deinit() only ever runs on the JS thread that owns the atom strings.

This keeps the atom-string dedup (memory savings for repeated "OK" etc.) while closing the race structurally.

Secondary changes:

  • derefFromThread(): bun.debugAssert(count > 1) to document the invariant. The count == 1 branch is now unreachable from callback(); its isShuttingDown() arm is changed from deinit() to leak (defensive — deinit() touches jsc.Weak/jsc.Strong and atom strings that are JS-thread-only).
  • src/string/wtf.zig: add WTFStringImplStruct.isAtom(); fix pre-existing @as(1, u32) arg-order typos in the atom-flag constants (dead code until now) and the isStatic() mask (was checking s_refCountIncrement 0x2 instead of s_refCountFlagIsStaticString 0x1 — verified against WebKit StringImpl.h:381).
  • bun:internal-for-testing: add fetchTestingInternals.responseAtomFlags(response) returning {statusText, url} bools for whether each backing string is an atom.

How did you verify your code works?

New test/js/bun/http/fetch-response-shutdown-atom.test.ts:

  • Asserts the backing strings are atoms (documenting that dedup is intentional and the race is closed by defer ordering, not by dropping atoms).
  • A parallel batch of subprocesses with BUN_DESTRUCT_VM_ON_EXIT=1, http_proxy + NO_PROXY set as in the original report, exercises the shutdown path end-to-end.

Also:

  • bun bd test test/js/bun/http/proxy.test.js — 16/16 pass, 8 skip.
  • bun bd test test/js/web/fetch/response.test.ts — 14/14 pass.
  • bun bd test test/internal/ban-words.test.ts — 119/119 pass.
  • Smoke test: 50 concurrent fetches + streaming body — debugAssert(count > 1) holds.

Note on reproduction: the race window is a handful of instructions; I was unable to trigger it via timing in ~500 attempts. The fix is correct by construction — with the mutex held through derefFromThread(), the HTTP thread categorically cannot observe count == 1.

@robobun

robobun commented Apr 18, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:56 AM PT - May 4th, 2026

@robobun, your commit b466d42 is building: #51400

@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Replaced atom-creation with UTF-8 cloning for Response fields in fetch, added a JS-visible test helper to report whether Response strings are atom-backed, adjusted WTF string flag constants and added isAtom, and added a regression test exercising shutdown-time access to Response fields.

Changes

Cohort / File(s) Summary
Fetch & Response runtime
src/bun.js/webcore/fetch/FetchTasklet.zig, src/bun.js/webcore/Response.zig, src/js/internal-for-testing.ts
FetchTasklet.toResponse now uses bun.String.cloneUTF8(...) for status_text and url instead of createAtomIfPossible. Added jsResponseAtomFlagsForTesting and exposed it via fetchTestingInternals to report statusText/url atom flags.
String internals
src/string/wtf.zig
Changed several bitmask constants to use typed u32 literals and added pub inline fn isAtom(self: WTFStringImpl) bool to detect atom-string kind from m_hashAndFlags.
Regression test
test/js/bun/http/fetch-response-shutdown-atom.test.ts
Added tests that start ephemeral servers, validate Response.statusText and Response.url values, assert their atom flags via the new helper, and spawn multiple subprocesses (with BUN_DESTRUCT_VM_ON_EXIT=1 and proxy env variants) to exercise shutdown-time access to those fields.
🚥 Pre-merge checks | ✅ 1 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title does not match the actual changes made in the pull request. Update the title to reflect the actual fix: changing from atomized to cloneUTF8 strings for Response fields and reordering defers, e.g., 'fetch: use cloneUTF8 for Response statusText/url to avoid cross-thread atom deref race'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description check ✅ Passed The description comprehensively covers both required sections with detailed explanations of the root cause, fix, and verification steps.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@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 the current code and only fix it if needed.

Inline comments:
In `@test/js/bun/http/fetch-response-shutdown-atom.test.ts`:
- Around line 52-61: The test's env object spreads bunEnv which can contain
inherited no_proxy/NO_PROXY values that override the intended NO_PROXY and cause
flakes; update the env construction (the env variable in
fetch-response-shutdown-atom.test.ts) to explicitly clear or set both casings
before/when spreading (ensure both NO_PROXY and no_proxy are assigned the
intended value or emptied) and keep BUN_DESTRUCT_VM_ON_EXIT, http_proxy, and the
intended NO_PROXY value in place so proxy resolution is deterministic.
🪄 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: d5f73a9c-d11b-4a31-b467-9ff292ffc67e

📥 Commits

Reviewing files that changed from the base of the PR and between 8f2519f and 9d16b64.

📒 Files selected for processing (2)
  • src/bun.js/webcore/fetch/FetchTasklet.zig
  • test/js/bun/http/fetch-response-shutdown-atom.test.ts

@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.

LGTM — the two-line fix correctly replaces per-thread atom strings with thread-safe strings, categorically preventing the cross-thread deref assert.

Extended reasoning...

Overview\nThis PR modifies (2 lines changed) and adds a new regression test. The core change replaces with for and in .\n\n### Security risks\nNone. This is a memory-safety fix that removes a cross-thread invariant violation. If anything, the change makes the code more correct.\n\n### Level of scrutiny\nLow — the change is minimal (two function calls swapped) with a precise, well-documented root cause. The thread-safety contract of atom strings is explicitly documented in , and 's atomic refcount makes safe to deref from any thread. The performance regression (one small allocation for short strings like "OK") is negligible.\n\n### Other factors\nThe bug report identified a nit: the test uses an explicit ms timeout, violating the CRITICAL guideline in . This is already captured as an inline comment. The fix itself is unambiguously correct and complete.

@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.

LGTM — minimal, well-reasoned fix with good test coverage.

Extended reasoning...

Overview

Two-file change: replaces bun.String.createAtomIfPossible with bun.String.cloneUTF8 for Response.status_text and url in FetchTasklet.toResponse(), and adds a regression test that recreates the CI shutdown race conditions.

Security risks

None. The change narrows the string representation from atom (per-thread table) to plain WTFStringImpl (atomic refcount, no thread affinity). No auth, crypto, or permission paths are touched.

Level of scrutiny

Low. The fix is two lines in a well-understood code path, and the same cloneUTF8 pattern is already used elsewhere in the same function (onReject() also clones metadata.url with cloneUTF8). The root cause — atom strings having per-thread lifetime while derefFromThread() can run the destructor on the HTTP thread — is clearly documented and the fix is categorically correct.

Other factors

Both reviewer concerns (proxy env var casing determinism from coderabbitai, explicit test timeout from my prior review) were addressed in follow-up commits. The test now follows project conventions. No outstanding comments remain.

@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 the current code and only fix it if needed.

Inline comments:
In `@src/js/internal-for-testing.ts`:
- Around line 147-149: The return type for responseAtomFlags should be a named
interface rather than an inline object literal: create an interface named
ResponseAtomFlags that defines statusText: boolean and url: boolean, then
replace the inline type on the responseAtomFlags declaration (the arrow function
typed as (response: Response) => { statusText: boolean; url: boolean }) with the
new ResponseAtomFlags interface; ensure the function symbol
jsResponseAtomFlagsForTesting still uses the updated signature (response:
Response) => ResponseAtomFlags and update any imports/exports or usages
accordingly.
🪄 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: cff79304-2c4d-48be-a50b-f35d0858f063

📥 Commits

Reviewing files that changed from the base of the PR and between 39658f6 and 794e31f.

📒 Files selected for processing (4)
  • src/bun.js/webcore/Response.zig
  • src/js/internal-for-testing.ts
  • src/string/wtf.zig
  • test/js/bun/http/fetch-response-shutdown-atom.test.ts

Comment thread src/js/internal-for-testing.ts Resolved

@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.

LGTM — targeted fix replacing per-thread atom strings with thread-safe UTF-8 clones, prior review issues addressed.

Extended reasoning...

Overview

The PR touches five files: the core two-line fix in FetchTasklet.zig (replacing createAtomIfPossible with cloneUTF8 for status_text and url), a new isAtom() introspection method on WTFStringImplStruct, a Zig cast correctness fix (@as(1, u32) → @as(u32, 1)), a test-only helper exposed via bun:internal-for-testing, and a new regression test.

Security risks

None. The change makes string handling more correct by using thread-safe refcounting instead of a per-thread atom table. No auth, crypto, or permission code is touched.

Level of scrutiny

Low. The root cause (atom strings deref'd off their creating thread) is well-documented in src/string.zig and the WTF headers. The fix is mechanical: swap one string-creation function for another with the right thread-safety properties. The supporting test directly asserts the invariant (neither backing string is an atom) rather than relying on timing.

Other factors

Both prior review issues — proxy env var casing (CodeRabbit) and the explicit 90_000 test timeout (my prior review) — have been resolved in commits 4f529b0 and 39658f6 respectively. The CI failures reported by robobun are on unrelated Windows test files and predate this PR's changes. No bugs were found by the automated bug hunting system.

@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.

LGTM — the two-line fix ( in place of ) is correct by construction, the new helper and deterministic atom-flag test guard the invariant directly, and the prior feedback on env-var normalization and the explicit timeout was fully addressed.

Extended reasoning...

Overview

The PR touches (two call-sites), (three constant typo fixes + new accessor), a export, and a new regression test. No logic is refactored; the change is strictly additive/correctional.

Security risks

None. The changed code paths are internal string-lifecycle management with no user-controlled inputs. The fix tightens thread safety rather than relaxing it.

Level of scrutiny

Moderate. The root cause analysis (atom-string tables are per-thread; can run on the HTTP thread during shutdown) is accurate and verifiable against the WTF source. The fix is the minimal correct response: use a plain heap string whose refcount is atomic. The constant typo fixes ( → ) are mechanical and correct. The pre-existing bitmask issue noted by the bug hunter is out of scope and already inline-commented.

Other factors

All prior review feedback was addressed before this review cycle: env-var normalization (both casings of / and / set, / cleared) landed in 4f529b0, and the explicit 90-second timeout was dropped with iteration count reduced in 39658f6. The test validates the invariant deterministically via the atom-flag helper rather than relying on timing.

Comment thread src/string/wtf.zig Resolved

@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.

LGTM — all review feedback addressed (timeout removed, isStatic() mask corrected, proxy env casings normalized).

Extended reasoning...

Overview

Replaces bun.String.createAtomIfPossible with bun.String.cloneUTF8 for Response.status_text and Response.url in FetchTasklet.toResponse(). Also fixes a pre-existing Zig type-coercion typo (@as(1, u32) → @as(u32, 1)) and the wrong bitmask in isStatic() (was s_refCountIncrement / 0x2, should be s_refCountFlagIsStaticString / 0x1). Adds isAtom() to WTFStringImplStruct, a bun:internal-for-testing helper, and a regression test with a deterministic invariant check plus a shutdown-path stress loop.

Security risks

None. The change narrows thread-safety behavior — swapping from per-thread atom strings to heap strings with atomic refcounts. No auth, crypto, or permission paths are affected.

Level of scrutiny

Moderate-to-low. The core change is two call-site swaps (createAtomIfPossible → cloneUTF8), both of which are obviously correct given the documented per-thread constraint on atom strings. The isAtom() predicate and test helper are read-only introspection. The regression test provides a deterministic invariant check that would catch any future regression.

Other factors

All reviewer feedback has been incorporated: the explicit 90_000 timeout was removed per test/CLAUDE.md, the isStatic() wrong-mask bug (surfaced via the new atom-flag constants being referenced for the first time) was fixed and verified against WebKit source, and proxy env-var casing was normalized for test determinism. No outstanding comments remain.

@robobun robobun changed the title fetch: don't atomize Response status_text/url — cross-thread deref asserts fetch: hold tasklet mutex through derefFromThread so HTTP thread never drops last ref Apr 18, 2026
Comment thread src/string/wtf.zig Resolved

@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.

LGTM — all review feedback has been addressed.

Extended reasoning...

Overview

The PR fixes a cross-thread atom-string deref race in FetchTasklet.callback(). The root cause (defer order allowing the HTTP thread to drop the last tasklet ref while the JS thread was mid-teardown) is well-analyzed and the fix is correct by construction: moving derefFromThread() inside the mutex scope makes it structurally impossible for the HTTP thread to ever observe count == 1.

Secondary changes: fixed a pre-existing isStatic() mask bug (s_refCountIncrement 0x2 → s_refCountFlagIsStaticString 0x1), added isAtom() with an accurate doc comment, added a deterministic regression test, and exposed a test helper via bun:internal-for-testing.

Security risks

No security-sensitive paths affected. The change narrows a race window in memory ownership — it makes the code safer.

Level of scrutiny

The concurrency reasoning requires careful reading, but the invariant is simple: onProgressUpdate (the only other ref-dropper) needs the mutex, so holding it through derefFromThread() is a complete structural guarantee. Three prior rounds of review surfaced and resolved all issues (proxy env casing, test timeout, isStatic mask, doc comment contradiction). The bug hunting system found nothing.

Other factors

All inline comments are resolved. The new test exercises the shutdown path end-to-end with BUN_DESTRUCT_VM_ON_EXIT=1 and both proxy env casings set correctly. The debugAssert(count > 1) in derefFromThread() documents the new invariant for future readers.

robobun pushed a commit that referenced this pull request Apr 25, 2026
Previous build failed on a pre-existing unrelated ASAN ThreadLock flake
in test/regression/issue/26225.test.ts (node-fetch + form-data streaming
client subprocess). Same ThreadLock race identified in PR #29712 /
#29453 (FetchTasklet shutdown, unrelated to this PR's Bun.serve
fallback fix). Retrigger.
@robobun

robobun commented May 2, 2026

Copy link
Copy Markdown
Collaborator Author

Got a separate internal report of the same race framed as the JSC HandleSet angle rather than the atom-string one:

FetchTasklet.deinit() releases JSC Strong/Weak from HTTP thread during shutdown — in-flight streaming fetch at process shutdown; main thread runs queued onProgressUpdate.deref between HTTP thread's enqueue and derefFromThread. derefFromThread at count==1 + isShuttingDown() calls deinit() on the HTTP thread. clearData() mutates JSC HandleSet (Weak/Strong/JSPromise.Strong) without thread safety; races with main-thread heap teardown.

Same window (unlock → derefFromThread), same last-ref-on-HTTP-thread outcome. This PR's mutex-held derefFromThread closes it structurally, and the leak-instead-of-deinit() in the isShuttingDown() arm covers the jsc.Weak / jsc.Strong.Optional / ReadableStream.Strong / AbortSignal releases in clearData() as well as the atom strings. Noting here rather than opening a competing PR.

robobun and others added 8 commits May 4, 2026 10:30
…serts

FetchTasklet.toResponse() was using bun.String.createAtomIfPossible for
Response.status_text and Response.url. Atom strings live in a per-thread
table (see src/string.zig:279 "They cannot be used from other threads").

When the VM is shutting down with BUN_DESTRUCT_VM_ON_EXIT (set in the
ASAN CI lane), there is a window where:

  1. HTTP thread callback(is_done=true) releases the mutex
  2. JS thread runs onProgressUpdate -> onResolve -> creates the Response
     with atomized status_text/url, resolves the fetch promise, derefs
     the tasklet (2->1)
  3. JS thread finishes the user script, sets is_shutting_down=true,
     runs destructOnExit -> full GC -> Response.finalize -> Response
     ref_count 2->1
  4. HTTP thread resumes at derefFromThread() -> tasklet 1->0 ->
     sees isShuttingDown() -> runs deinit() on the HTTP thread ->
     native_response.unref() -> Response 1->0 -> Response.destroy()
     derefs the atom strings from the HTTP thread

AtomStringImpl::remove() then looks in the HTTP thread's atom table,
doesn't find the string (it's in the JS thread's table), and fires:

  ASSERTION FAILED: wasRemoved
  WTF/wtf/text/AtomStringImpl.cpp(409)

Observed as a flaky exit-code-132 failure of the
"NO_PROXY with multiple entries including port" subprocess in
test/js/bun/http/proxy.test.js on x64 ASAN.

Use cloneUTF8 instead: plain WTFStringImpl has an atomic refcount and
no per-thread table, so cross-thread deref is safe. The atomization
was a dedup micro-optimization; the strings are short either way.
env_loader.getHttpProxy/isNoProxy read lowercase first, so an inherited
lowercase no_proxy from bunEnv would override the test's uppercase
NO_PROXY and send the subprocess at the dead proxy. Set both.
Per test/CLAUDE.md. CI passes --timeout=90000 anyway; the 40-iteration
count was arbitrary since the race is not locally reproducible, so
16 is equally effective as regression documentation while fitting in
the default timeout for local runs.
The shutdown race is a handful of instructions wide and not reproducible
via timing alone, so the test now directly asserts the invariant that
makes the race harmless: the native backing strings are NOT atoms.

- Add WTFStringImplStruct.isAtom() (and fix pre-existing @as arg-order
  typo in the never-before-referenced s_hashFlagStringKind* constants).
- Add Response.jsResponseAtomFlagsForTesting() returning
  {statusText, url} bool flags for whether each backing bun.String is
  an atom StringImpl.
- Expose via bun:internal-for-testing as
  fetchTestingInternals.responseAtomFlags.
- Test asserts both flags are false. Before the fix (createAtomIfPossible)
  they're both true; after (cloneUTF8) both false. Also guards against
  future regressions that re-atomize these fields.
- Keep the stress subprocess test as end-to-end documentation of the
  shutdown path, reduced to a single batch of 8.
…refCountIncrement

WebKit's StringImpl::isStatic() checks m_refCount & s_refCountFlagIsStaticString
(0x1, the bottom bit per the comment at line 24). The Zig mirror was checking
s_refCountIncrement (0x2), so a static string (m_refCount=0x1) read as non-static
and a one-ref heap string (m_refCount=0x2) read as static. Only used in
allow_assert debug asserts in ref()/deref(); companion to the @as arg-order
typo fixes in the same constant block.
…ver drops last ref

Keep status_text/url atomized for memory dedup — instead close the race
structurally.

callback() previously did: enqueue -> unlock mutex -> derefFromThread().
In the gap between unlock and derefFromThread(), the JS thread could run
onProgressUpdate (deref 2->1, unref poll_ref), finish the script, and
start VM teardown. Then the HTTP thread's derefFromThread() would see
count==1 + isShuttingDown() and run deinit() on the HTTP thread, deref'ing
per-thread atom strings from the wrong thread -> wasRemoved assert.

Now derefFromThread() runs BEFORE unlock (inner defer). onProgressUpdate
needs the mutex, so while the HTTP thread holds it the JS side cannot have
dropped its baseline ref — the HTTP deref is always N->N-1 with N>=2,
never the last ref. poll_ref (unref'd inside onProgressUpdate) therefore
keeps the VM alive until the HTTP thread is done with the tasklet, and
deinit() only ever runs on the JS thread that owns the atoms.

Also:
- derefFromThread(): debugAssert(count > 1); change the now-unreachable
  isShuttingDown() branch to leak instead of deinit (defensive — deinit
  touches jsc.Weak/Strong and atom strings which are JS-thread-only).
- Response.zig: switch the testing helper to callframe.argument(0) to
  satisfy ban-words (arguments_old is banned).
- Test now asserts atoms ARE used (documenting the intent that the race
  is closed structurally, not by giving up dedup).
The comment described the abandoned cloneUTF8 approach ('assert NOT
atoms'). The final design keeps atoms and closes the race via defer
ordering in FetchTasklet.callback(); reword to match.
@Jarred-Sumner
Jarred-Sumner force-pushed the farm/186a659d/fetch-response-atom-cross-thread branch from f8b6523 to 22315fe Compare May 4, 2026 10:31
Jarred-Sumner pushed a commit that referenced this pull request May 4, 2026
Previous build failed on a pre-existing unrelated ASAN ThreadLock flake
in test/regression/issue/26225.test.ts (node-fetch + form-data streaming
client subprocess). Same ThreadLock race identified in PR #29712 /
#29453 (FetchTasklet shutdown, unrelated to this PR's Bun.serve
fallback fix). Retrigger.

@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 in the latest revision — all prior feedback has been addressed. Deferring to a human reviewer since the core fix relies on a cross-thread ref-counting invariant (mutex held through derefFromThread() ⇒ HTTP thread never sees count==1) that's correct-by-construction rather than reproduced, and intentionally swaps deinit() for a shutdown-time leak in the now-unreachable branch.

Extended reasoning...

Overview

This PR fixes a flaky RELEASE_ASSERT(wasRemoved) in AtomStringImpl::remove() by reordering two defer statements in FetchTasklet.callback() so that derefFromThread() runs while the tasklet mutex is still held. Since onProgressUpdate (the only JS-side path that drops the baseline ref) needs that same mutex, the HTTP thread's deref is guaranteed to observe count≥2 and can never be the last ref — so deinit() (and the per-thread atom-string deref inside Response.destroy()) only ever runs on the JS thread. Secondary changes: derefFromThread() now leaks instead of calling deinit() in the isShuttingDown() arm (defensive, since that arm is now unreachable from callback()), a new debugAssert(count > 1), fixes to pre-existing @as(1, u32) arg-order typos and the isStatic() mask in wtf.zig, a new isAtom() helper, a jsResponseAtomFlagsForTesting binding, and a regression test.

Security risks

None identified. No auth, crypto, permissions, or untrusted-input parsing is touched. The change is a defer reordering plus debug-assert/test scaffolding; the test-only binding is gated behind bun:internal-for-testing.

Level of scrutiny

High. This is concurrency-critical code in the production fetch path — the HTTP-thread/JS-thread ref-counting handoff for every fetch() response. The fix is small and the reasoning is well-documented, but its correctness rests on the invariant that onProgressUpdate is the only path that can drop the JS-side baseline ref and that it always acquires task.mutex before doing so. The author notes the race was not reproducible locally (~500 attempts), so the fix is "correct by construction" rather than empirically verified. There's also a deliberate behavior change (leak vs. deinit() at shutdown) that, while sensible given deinit() touches JS-thread-only state (jsc.Weak/jsc.Strong/atom strings), is a design call worth a human sign-off.

Other factors

All three of my prior inline comments (explicit test timeout, isStatic() mask, stale isAtom() doc comment) and CodeRabbit's proxy-env comment have been addressed and resolved. The wtf.zig constant fixes are verified against WebKit's StringImpl.h. The new test asserts the atom-flag invariant deterministically and exercises the shutdown path with BUN_DESTRUCT_VM_ON_EXIT=1. The PR is well-reasoned and I found no defects in the current revision; I'm deferring solely because cross-thread lifetime invariants in core fetch warrant a human reviewer who knows the tasklet lifecycle.

@robobun
robobun force-pushed the farm/186a659d/fetch-response-atom-cross-thread branch from b466d42 to 22315fe Compare May 4, 2026 19:05

@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.

All my earlier inline points are addressed and the mutex-ordering argument reads as correct, but since this reorders cross-thread ref-counting in the callback() hot path for every fetch and the fix is correct-by-construction rather than reproduced, I'd like a human to confirm the onProgressUpdate-is-the-only-JS-side-baseline-deref invariant before merge.

Extended reasoning...

Overview

This PR fixes a flaky RELEASE_ASSERT(wasRemoved) in AtomStringImpl::remove() observed in the x64 ASAN lane. The core change is in FetchTasklet.callback() (HTTP thread): the defer if (is_done) task.derefFromThread() is moved from before task.mutex.lock() to after it, so the deref now runs while the mutex is held rather than after it is released. derefFromThread() itself replaces its count==1 && isShuttingDown() branch's deinit() with a leak (process is exiting), and adds debugAssert(count > 1) to document that the branch is now unreachable from callback(). Secondary changes: an isAtom() helper plus @as(u32, 1) arg-order fixes and an isStatic() mask fix in wtf.zig (all previously dead/debug-only code), a jsResponseAtomFlagsForTesting binding exposed via bun:internal-for-testing, and a new regression test.

Security risks

None identified. No user-controlled input handling, auth, crypto, or permission surfaces are touched. The new responseAtomFlags binding is read-only introspection gated behind bun:internal-for-testing.

Level of scrutiny

High. FetchTasklet.callback() is the HTTP-thread progress handler for every fetch() — this is a production hot path, and the change is to cross-thread synchronization (defer ordering between a mutex unlock and an atomic refcount decrement). The correctness argument is a non-trivial invariant chain: holding the mutex blocks onProgressUpdate → which is the only JS-side baseline deref → so HTTP-side count ≥ 2 → so deinit() never runs off-thread → so atom strings / jsc.Weak / jsc.Strong are only released on the JS thread. The author explicitly notes the race was not reproducible in ~500 attempts, so the fix is validated by reasoning rather than by a failing-then-passing test. The wtf.zig constant fixes are mechanically verifiable against WebKit's StringImpl.h, and the test/binding additions are low-risk.

Other factors

All three of my earlier inline comments (explicit test timeout, isStatic() mask, stale isAtom() doc comment) and CodeRabbit's proxy-env-casing comment have been addressed; all threads are resolved. I checked for deadlock risk from running derefFromThread() under the mutex — in the now-asserted-normal case it's just an atomic fetchSub, and the defensive enqueueTaskConcurrent path uses its own internal lock with no dependency on the tasklet mutex. The reasoning looks sound to me, but the load-bearing assumption that onProgressUpdate is the only path that drops the JS-side baseline ref (and that it always acquires this mutex first) is exactly the kind of global invariant a maintainer familiar with FetchTasklet's lifecycle should confirm.

@robobun

robobun commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

Same wasRemoved assertion is now surfacing in test/js/web/fetch/fetch-http2-client.test.ts on debian-13-x64-asan — builds 52840, 52800, 52790.

Two different tests hit it ("Expect: 100-continue with final status before 100 skips body upload" and "concurrent requests multiplex on one h2 session"), both crashing at subprocess exit after a successful fetch — same window between callback()'s task.mutex.unlock() and derefFromThread(). The h2 path reaches FetchTasklet.callback() via sendProgressUpdateMultiplexed, so this PR's defer-order swap covers it. Noting here rather than opening a competing PR.

robobun added a commit that referenced this pull request May 11, 2026
Previous build hit a known WebKit AtomStringImpl race in
fetch-http2-client.test.ts (open PR #29453 addresses it) — unrelated to
this diff, which only touches src/dotenv/env_loader.zig and
test/cli/run/env.test.ts.
@robobun

robobun commented Jun 25, 2026

Copy link
Copy Markdown
Collaborator Author

Closing — superseded by the Rust port on main.

The bug this PR addressed (AtomStringImpl::remove wasRemoved assert when FetchTasklet is deinit'd on the HTTP thread during VM shutdown) is fixed in src/runtime/webcore/fetch/FetchTasklet.rs:

  • to_response() uses BunString::clone_utf8 for status_text/url (with a BunString::static_ fast-path for canonical status texts, which recovers most of the dedup benefit without per-thread atom tables). The comment there explicitly references the wasRemoved assert this PR was investigating.
  • deref_from_thread() when is_shutting_down() calls dealloc_for_shutdown(), which defers the actual deinit to the JS thread after the HTTP daemon parks (via http::defer_shutdown_reclaim), instead of running deinit() on the HTTP thread.
  • A broader shutdown-coordination mechanism (release_at_shutdown, dealloc_in_flight_for_exit, release_queued_tasks_for_shutdown) handles in-flight requests at process.exit().

The Zig files this PR modified (FetchTasklet.zig, Response.zig, string/wtf.zig) were removed in d451445 as part of the Zig→Rust migration, so there is nothing to rebase onto. src/CLAUDE.md now cites FetchTasklet.rs near Response::init as the canonical example of this bug class and its fix.

The root-cause analysis in this PR's description remains accurate for the record.

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.

1 participant