Repository navigation
webview: retire the transport with its global under bun test --isolate - #40165
Conversation
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.
|
Warning Review limit reachedYour included review limit has been reached. You’re in a promotional period — use the checkbox below to run this 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 You can also wait for the limit to reset (next review available in 9 minutes), then comment 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (7)
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (11)
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. WalkthroughChangesThe 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
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Status: reproduced and fixed, waiting on CI. Reproduction: |
|
Updated 8:48 PM PT - Aug 22nd, 2026
❌ @robobun, your commit 37e8c84 has 1 failures in 🧪 To try this PR locally: bunx bun-pr 40165That installs a local version of the PR into your bun-40165 --bun |
There was a problem hiding this comment.
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:
retireGlobalrunsrejectAllAndMarkDeadbeforeprepareForDestruction, so promise rejection uses a still-valid global;m_globalis nulled only after, andonData's newm_deadguard prevents the null deref on late bytes.Bun__Chrome__retire/Bun__WebViewHost__retire:INSTANCE.swap+compare_exchangeinon_exitmeans a retired process's exit can't clobber a freshly-published successor; the box is freed exactly once (inon_exit), and the freed pointer is only used as a comparand.- Windows: GENERATION is bumped before
pipes.close(), so any queuedPipeEventfrom the retired Chrome is dropped inQueuedEvent::deliver. ~JSWebViewnow removes the session entry only whenit->value == m_viewId— safe becausem_nextViewIdis 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:
rejectAllAndMarkDeadruns whilem_globalis still the outgoing (valid) global;updateKeepAliveinside it derefs the VM keepalive against that global beforem_globalis nulled, som_sockRefdis correctly reset.ensureSpawnedon the next file seesm_dead && m_mode == None, resets state, andBun__Chrome__ensurefindsINSTANCEalready null so it spawns immediately (the stated goal).- On Windows,
retirebumpsGENERATIONbefore closing pipes, so anyPipeEventposted by the close's read-error path carries the old generation and is dropped indeliver. HostProcess::on_process_exitfrees the box and then usesthisonly as acompare_exchangecomparand — pointer identity, not a dereference.- The
~JSWebViewsession-map guard relies onm_nextViewIdnever 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.
Problem
bun test --parallel(it implies--isolate) on Windows crashes inJSC::TypeInfoBlob::blobunderJSCell::JSCell, fromBun::CDP::Ops::close(createError(g, "WebView closed")) andTransport::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 cachesm_global, the global that spawned Chrome (ChromeBackend.cpp:311).--isolatereplaces the global between files andensureSpawnedreturns early while the transport is up, so the next file's view allocates with a collected global's freed structures.Fix
Zig__GlobalObject__stopActiveDOMObjectsForTestIsolationcallsretireWebViewsForTestIsolation(global): the CDP transport (and the WebKit host client on macOS) rejects the pending promises on the outgoing global, marks its views closed and clearsm_global.Bun__Chrome__retire/Bun__WebViewHost__retireunpublish 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).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/--parallelruns with real Chrome.Background
--isolatekeeps one JSC VM and creates a freshZig::GlobalObjectper file. The old global is unprotected and collected.CDP::Transportowns the--remote-debugging-pipeconnection, the pending-reply map and oneWeak<JSWebView>per view, and allocates replies withm_global's structures.Structureis JSC's shape record for an object. A cell allocated with a structure from a collected global reads freed memory: theTypeInfoBlob::blobfault.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 inStringImpl::isSymbolunderIdentifierRepHash::hash,PropertyTable::reinsertand thePropertyTablecopy constructor (PropertyTable.cpp:116). That is aStructureof 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 --isolateover five files that each open a view against the fake Chrome fromtest/js/bun/webview/fake-chrome-fixture.ts, take a screenshot and thenclose(). Every other file gets objects built on the dead global: the screenshotBufferhas nolength, the "WebView closed"Errorhas nomessage, andinstanceof Erroris 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" becauseBun__Chrome__ensurerefuses 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 stalem_globalon every platform:WebSocket::stop()duringprepareForDestructiondrops the connection without a callback, so the transport stayed in WebSocket mode with a dead socket. The retire hook runs beforeprepareForDestruction, so the pending promises are rejected while the context is intact.onDatanow returns on a dead transport, and~JSWebViewremoves 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/withBUN_CHROME_PATHpointing at a--no-sandboxwrapper (this container runs as root), 58 pass inwebview-chrome.test.ts.--isolateand--parallelwith real Chrome across 3 files: each file spawns its own Chrome, no process is left behind.