Skip to content

webview: retire the transport with its global under bun test --isolate - #40165

Merged
Jarred-Sumner merged 4 commits into
mainfrom
farm/b401f24a/webview-isolate-retire-transport
Aug 23, 2026
Merged

Jarred-Sumner merged 4 commits into
mainfrom
farm/b401f24a/webview-isolate-retire-transport

Conversation

@robobun

@robobun robobun commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • bun test --parallel (it implies --isolate) on Windows crashes in JSC::TypeInfoBlob::blob under JSCell::JSCell, from Bun::CDP::Ops::close (createError(g, "WebView closed")) and Transport::handleResponse (createBuffer(g, ...)). Sentry BUN-30VN and BUN-3DG7 (1.4.0), then BUN-2VZ1 in the GC marker.
  • CDP::transport() is a process singleton that caches m_global, the global that spawned Chrome (ChromeBackend.cpp:311). --isolate replaces the global between files and ensureSpawned returns early while the transport is up, so the next file's view allocates with a collected global's freed structures.
  • On POSIX the swap's socket sweep marks the transport dead. The Windows pipes are libuv handles, not usockets, so nothing retired it there.

Fix

  • Zig__GlobalObject__stopActiveDOMObjectsForTestIsolation calls retireWebViewsForTestIsolation(global): the CDP transport (and the WebKit host client on macOS) rejects the pending promises on the outgoing global, marks its views closed and clears m_global.
  • Bun__Chrome__retire / Bun__WebViewHost__retire unpublish and kill the browser. Its exit handler still reaps it but no longer reports the death. The next file spawns its own browser at once (before, it failed with "Failed to spawn Chrome" until the old one was reaped).
  • Verified: test/js/bun/webview/webview-chrome-pipe.test.ts (new case, fails on main on Linux and Windows), the 58 real-Chrome tests, and --isolate / --parallel runs with real Chrome.

Background

  • --isolate keeps one JSC VM and creates a fresh Zig::GlobalObject per file. The old global is unprotected and collected.
  • CDP::Transport owns the --remote-debugging-pipe connection, the pending-reply map and one Weak<JSWebView> per view, and allocates replies with m_global's structures.
  • A Structure is JSC's shape record for an object. A cell allocated with a structure from a collected global reads freed memory: the TypeInfoBlob::blob fault.
Notes

BUN-3DG7 is the same user and tag set (Windows x64, bun test --parallel, webview_chrome), one more 1.4.0 event: a fault in StringImpl::isSymbol under IdentifierRepHash::hash, PropertyTable::reinsert and the PropertyTable copy constructor (PropertyTable.cpp:116). That is a Structure of the dead global having its property table copied, the same freed-structure read one step later.

Repro with the released 1.4.1 canary on Windows, bun test --isolate over five files that each open a view against the fake Chrome from test/js/bun/webview/fake-chrome-fixture.ts, take a screenshot and then close(). Every other file gets objects built on the dead global: the screenshot Buffer has no length, the "WebView closed" Error has no message, and instanceof Error is false. That is the same path as the Sentry events, before the structure memory was unmapped.

Repro on Linux with the released bun: the swap's socket sweep rejects file 1's pending evaluate with "Chrome process closed the pipe", and file 2's new Bun.WebView() throws "Failed to spawn Chrome" because Bun__Chrome__ensure refuses to spawn while the old process is published. The fake now takes --exit-delay=<ms> so it outlives its pipes like a real browser does; the new test uses 20 s.

The WebSocket transport mode (backend.url, or an auto-detected DevToolsActivePort) had the same stale m_global on every platform: WebSocket::stop() during prepareForDestruction drops the connection without a callback, so the transport stayed in WebSocket mode with a dead socket. The retire hook runs before prepareForDestruction, so the pending promises are rejected while the context is intact.

onData now returns on a dead transport, and ~JSWebView removes its session entry only when the entry still points at that view. A browser spawned by a later file can hand out the same session id string (the fake does).

Other suites run: test/js/bun/webview/ with BUN_CHROME_PATH pointing at a --no-sandbox wrapper (this container runs as root), 58 pass in webview-chrome.test.ts. --isolate and --parallel with real Chrome across 3 files: each file spawns its own Chrome, no process is left behind.

The CDP Transport and the WebKit HostClient are process singletons that
cache the global object which spawned the browser. bun test --isolate
replaces the global between files but left the transport bound to the
old one. On Windows the Chrome pipes are libuv handles, not usockets
sockets, so the per-file socket sweep never closed them: the next file
reused the transport, and close() and incoming replies allocated with the
dead global's structures. On POSIX the sweep killed the connection, but
the next file could only spawn again once the old browser had been
reaped.

Retire the transport from the isolation hook: reject every pending
promise on the outgoing global, unpublish and kill the browser process,
and clear the cached global. The next file's first WebView spawns its
own browser.
@coderabbitai

coderabbitai Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

Your included review limit has been reached.

You’re in a promotional period — use the checkbox below to run this review for free:

  • Run review for free

On-demand reviews are free for the next 29 days. After that, they cost $0.25 per reviewed file.

How can I continue?

Run this review now using the option above, or comment @coderabbitai review --use-credits.

You can also wait for the limit to reset (next review available in 9 minutes), then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 17d72adb-cb86-4321-9518-011b86909387

📥 Commits

Reviewing files that changed from the base of the PR and between df220a6 and 37e8c84.

📒 Files selected for processing (7)
  • src/jsc/bindings/ZigGlobalObject.cpp
  • src/runtime/webview/ChromeBackend.cpp
  • src/runtime/webview/ChromeBackend.h
  • src/runtime/webview/ChromeProcess.rs
  • src/runtime/webview/HostProcess.rs
  • src/runtime/webview/JSWebView.cpp
  • src/runtime/webview/JSWebView.h

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ed5ad374-392b-4d89-bd01-15965680fb6e

📥 Commits

Reviewing files that changed from the base of the PR and between 8eb5b6e and df220a6.

📒 Files selected for processing (11)
  • src/jsc/bindings/ZigGlobalObject.cpp
  • src/runtime/webview/ChromeBackend.cpp
  • src/runtime/webview/ChromeBackend.h
  • src/runtime/webview/ChromeProcess.rs
  • src/runtime/webview/HostProcess.rs
  • src/runtime/webview/JSWebView.cpp
  • src/runtime/webview/JSWebView.h
  • src/runtime/webview/WebKitBackend.cpp
  • src/runtime/webview/WebKitBackend.h
  • test/js/bun/webview/fake-chrome-fixture.ts
  • test/js/bun/webview/webview-chrome-pipe.test.ts

Included review availability: 1 review is currently available. Your included PR review attempts over the past 7 days set your current allowance at 2 reviews per hour.


Walkthrough

Changes

The test-isolation cleanup path now retires WebView transports before global context destruction. Chrome and WebKit backends reject pending operations, terminate their child processes, ignore late data, and suppress retired-process notifications. Tests cover isolated files and pending evaluations.

WebView retirement

Layer / File(s) Summary
Test-isolation cleanup wiring
src/jsc/bindings/ZigGlobalObject.cpp, src/runtime/webview/JSWebView.*
Global cleanup invokes retireWebViewsForTestIsolation before context destruction. The function forwards the global to Chrome and Darwin WebKit backends.
Chrome transport and process retirement
src/runtime/webview/ChromeBackend.*, src/runtime/webview/ChromeProcess.rs
Chrome transport retirement rejects pending operations and clears the global. Chrome processes are unpublished and killed, while late data and retired-process notifications are ignored.
WebKit host retirement
src/runtime/webview/WebKitBackend.*, src/runtime/webview/HostProcess.rs
WebKit host retirement rejects pending operations, clears the matching global, kills the host, and suppresses retired-host notifications.
Session cleanup and isolation validation
src/runtime/webview/JSWebView.cpp, test/js/bun/webview/fake-chrome-fixture.ts, test/js/bun/webview/webview-chrome-pipe.test.ts
View destruction removes only matching session entries. The fixture supports delayed exit and no-reply evaluations. Integration tests verify transport retirement across isolated test files.

Suggested reviewers: jarred-sumner, dylan-conway

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: retiring the WebView transport with its global during isolated tests.
Description check ✅ Passed The description explains the problem, fix, verification steps, affected platforms, and regression test results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

@robobun

robobun commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

Status: reproduced and fixed, waiting on CI.

Reproduction: bun test --isolate with two files that each open a Bun.WebView against test/js/bun/webview/fake-chrome-fixture.ts (now spawned with --exit-delay=20000, so the fake outlives its pipes like a real browser). On main, Linux rejects file 1's pending evaluate with "Chrome process closed the pipe" and file 2 throws "Failed to spawn Chrome". On main, Windows lets file 2 reuse the transport of file 1's dead global: with five such files, every other file gets a screenshot Buffer without length and an Error without message. With the fix both platforms pass the new case in webview-chrome-pipe.test.ts, and --isolate / --parallel with real Chrome spawn one browser per file and leave no process behind.

@robobun

robobun commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 8:48 PM PT - Aug 22nd, 2026

❌ @robobun, your commit 37e8c84 has 1 failures in Build #103890 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 40165

That installs a local version of the PR into your bun-40165 executable, so you can run:

bun-40165 --bun

Comment thread src/jsc/bindings/ZigGlobalObject.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.h Resolved
Comment thread src/runtime/webview/ChromeProcess.rs Resolved
Comment thread src/runtime/webview/ChromeProcess.rs Resolved
Comment thread src/runtime/webview/ChromeProcess.rs Resolved
Comment thread src/runtime/webview/HostProcess.rs Resolved
Comment thread src/runtime/webview/HostProcess.rs Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/JSWebView.h 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.

I reviewed this PR and didn't find any bugs. Given it's a use-after-free fix that threads new lifetime rules through the C++/Rust FFI boundary (transport singleton ↔ per-file GlobalObject, INSTANCE unpublish vs. on_exit ordering, Windows generation stamping), a human look is still worthwhile.

What was reviewed:

  • retireGlobal runs rejectAllAndMarkDead before prepareForDestruction, so promise rejection uses a still-valid global; m_global is nulled only after, and onData's new m_dead guard prevents the null deref on late bytes.
  • Bun__Chrome__retire / Bun__WebViewHost__retire: INSTANCE.swap + compare_exchange in on_exit means a retired process's exit can't clobber a freshly-published successor; the box is freed exactly once (in on_exit), and the freed pointer is only used as a comparand.
  • Windows: GENERATION is bumped before pipes.close(), so any queued PipeEvent from the retired Chrome is dropped in QueuedEvent::deliver.
  • ~JSWebView now removes the session entry only when it->value == m_viewId — safe because m_nextViewId is monotonic across retires while a respawned fake reuses "S1".
Extended reasoning...

Overview

Fixes a use-after-free crash under bun test --isolate / --parallel: the process-wide CDP::Transport singleton caches m_global (the Zig::GlobalObject that first spawned Chrome), and --isolate swaps globals between files. On Windows the libuv pipes aren't swept with the socket groups, so the transport survived and the next file allocated JS objects with a collected global's freed Structures (the Sentry TypeInfoBlob::blob fault). The fix hooks Zig__GlobalObject__stopActiveDOMObjectsForTestIsolation to call retireWebViewsForTestIsolation, which rejects pending promises on the outgoing global, marks the transport dead, kills/unpublishes the browser subprocess, and clears m_global. Symmetric changes are made to the WebKit host backend on Darwin. Files touched: ZigGlobalObject.cpp (one-line hook), ChromeBackend.{cpp,h}, WebKitBackend.{cpp,h}, ChromeProcess.rs, HostProcess.rs, JSWebView.{cpp,h}, plus a new test in webview-chrome-pipe.test.ts and a fixture flag.

Security risks

None identified. This is internal lifecycle management for a test-runner code path; no user-controlled input reaches the new code. The retire functions unconditionally SIGKILL a subprocess we spawned ourselves.

Level of scrutiny

High. The bug is a memory-safety issue and the fix touches: raw-pointer FFI singletons (AtomicPtr<ChromeProcess> / HostProcess), the ordering between retire (swap INSTANCE, set retired, kill) and the async on_exit handler (which now uses compare_exchange instead of an unconditional store so it can't clobber a successor), cross-platform divergence (POSIX usocket close vs. Windows libuv pipes + generation-stamped queued events), and JSC global-object lifetime. I traced each of these:

  • rejectAllAndMarkDead runs while m_global is still the outgoing (valid) global; updateKeepAlive inside it derefs the VM keepalive against that global before m_global is nulled, so m_sockRefd is correctly reset.
  • ensureSpawned on the next file sees m_dead && m_mode == None, resets state, and Bun__Chrome__ensure finds INSTANCE already null so it spawns immediately (the stated goal).
  • On Windows, retire bumps GENERATION before closing pipes, so any PipeEvent posted by the close's read-error path carries the old generation and is dropped in deliver.
  • HostProcess::on_process_exit frees the box and then uses this only as a compare_exchange comparand — pointer identity, not a dereference.
  • The ~JSWebView session-map guard relies on m_nextViewId never resetting across retires (it's on the singleton, not per-global), which holds.

Other factors

The new test spawns bun test --isolate over two identical files against the fake-Chrome fixture with --exit-delay=20000 so the old process outlives its pipes; it asserts the first file's in-flight evaluate rejects with the new "WebView closed: its test file finished" message (isError: true verifies the Error was built on the correct global) and the second file spawns its own browser. The PR author reports it fails on main on both Linux and Windows and passes with the fix, plus verified against 58 real-Chrome tests and --isolate/--parallel runs. The comment-cop bot flagged verbose comments in the first commit; they were trimmed in 07fdfdb and all threads are resolved. No CODEOWNERS entry covers these paths. Given the subtlety of the lifetime/ordering across the C++/Rust boundary and the platform-specific paths, this deserves a human reviewer's eyes even though I found nothing wrong.

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.

3 participants