NEW326046
Deadlock: GC started inside ReadableStreamDefaultReader.releaseLock() in a worker waits on the reader's own lock; JIT worklist stays suspended and the main thread hangs
https://bugs.webkit.org/show_bug.cgi?id=326046
Summary Deadlock: GC started inside ReadableStreamDefaultReader.releaseLock() in a wo...
calvin.prewitt
Reported 2026-10-01 21:31:58 PDT
Investigated with AI but appears to be a bug that was rigorously tested and validated. ---- **Title:** Deadlock: GC started inside ReadableStreamDefaultReader.releaseLock() in a worker waits on the reader's own lock; JIT worklist stays suspended and the main thread hangs **Environment** - Safari 27.0 (WebKit 22625.1.29.11.27) - macOS 27.0 (26A428), Apple M5 Max (Mac17,7) **Summary** A dedicated worker reads a closed `ReadableStream` to its end and then calls `reader.releaseLock()`. If the JS that `releaseLock()` runs allocates and starts a collection (`InternalReadableStreamDefaultReader::releaseLock` → `Heap::collectInMutatorThread` → `runFixpointPhase`), that collection must mark the same reader. The reader's weak-handle owner (`JSReadableStreamDefaultReaderOwner::isReachableFromOpaqueRoots`) then waits on a lock that the worker thread already holds. In our samples the waiter is either the worker thread itself or a heap helper thread the collection is waiting for. The stuck collection leaves the process-wide JIT worklist suspended. The next collection on any other thread, the page's main thread included, blocks in `JITWorklist::suspendAllThreads()` forever. The page stops answering at 0% CPU. The window needs a worker heap of some size. Tiny workers don't hit it, but a worker that has loaded a large module does. **Steps to reproduce** 1. Put the three files below in one directory and serve it over HTTP (for example `python3 -m http.server`). Generate the module once with `node gen-big-module.mjs big-module.js` (about 2.4 MB). 2. Open `webkit-release.html?workers=8&seconds=15&mib=60&reads=2000&op=reader&release=always&load=./big-module.js` in Safari 27.0. The `load` value must be a relative URL such as `./big-module.js`; a bare name makes the worker's `import()` reject. 3. For the control, open the same URL with `release=never`. **Expected:** after about 15 s the page prints a JSON result with `"ok": true` (`started` equals `finished`). **Actual (`release=always`):** the page stops updating within a few seconds and never prints a result. A `sample` of the WebContent process shows the stacks below. **Results** (stock Safari 27.0 driven by safaridriver; a run counts as stalled when the page's 50 ms ticker stops): | Worker setup | `release=always` | `release=never` | | --- | --- | --- | | No module loaded (plain or async-generator reader, with or without allocation churn, or 64 MiB retained) | passed 17 of 17 | passed 11 of 11 | | Each worker loads a 2.4 MB generated module (`load=./big-module.js`) and never calls it | failed 3 of 3, then 3 of 3 again on 2026-10-02 | passed 3 of 3, and 3 of 3 again | | Each worker imports a real application's module graph (an 80 KB entry module and its imports) and never calls it | failed 8 of 8 (6 sampled stalls, same stacks) | passed 5 of 5 | `WritableStreamDefaultWriter.releaseLock()` with the same setup passed 5 of 5. **Stacks** (from `sample`, trimmed; every sampled stall shows the same shape) Worker thread, in `releaseLock()`, inside a collection that waits on its helpers: ``` WebCore::jsReadableStreamDefaultReaderPrototypeFunction_releaseLock WebCore::ReadableStreamDefaultReader::releaseLock(WebCore::JSDOMGlobalObject&) WebCore::InternalReadableStreamDefaultReader::releaseLock() WebCore::invokeReadableStreamDefaultReaderFunction JSC::Interpreter::executeCall (JIT frames) operationNewArrayWithProfile JSC::LocalAllocator::allocateSlowCase JSC::Heap::collectInMutatorThread() JSC::Heap::runCurrentPhase JSC::Heap::runFixpointPhase(JSC::GCConductor) JSC::MarkingConstraintSet::executeConvergenceImpl JSC::MarkingConstraintSolver::execute JSC::Heap::runTaskInParallel WTF::ParkingLot::parkConditionallyImpl __psynch_cvwait ``` Heap helper thread, marking that reader and waiting on the lock: ``` JSC::SlotVisitor::drainFromShared JSC::MarkingConstraintSolver::runExecutionThread JSC::MarkedSpace::forEachWeakInParallel<JSC::SlotVisitor&>::Task::run WebCore::JSReadableStreamDefaultReaderOwner::isReachableFromOpaqueRoots WTF::LockAlgorithm<...>::lockSlow WTF::ParkingLot::parkConditionallyImpl __psynch_cvwait ``` In other samples the waiter is the worker thread itself, in `JSReadableStreamDefaultReader::visitChildren` / `visitOutputConstraints`. Main thread, an Eden collection blocked on the suspended JIT worklist: ``` WebCore::OpportunisticTaskScheduler::EdenGCActivityCallback::doCollection JSC::Heap::collect JSC::Heap::collectInMutatorThread() JSC::Heap::finishChangingPhase JSC::Heap::stopThePeriphery JSC::JITWorklist::suspendAllThreads() WTF::LockAlgorithm<...>::lockSlow __psynch_cvwait ``` The JSC Heap Collector Thread and the JIT Worklist Helper Threads are also parked in `JITWorklist::suspendAllThreads()` / `lockSlow`. **Files** `webkit-release.html` ```html <!DOCTYPE html> <!-- Standalone WebKit repro: no runtime code. `workers` slots each start a Web Worker that grows a `mib` MiB wasm memory, then runs `reads` iterations of a stream lock cycle, then posts 'done'; the page ends it and starts the next, for `seconds` seconds. op=reader: read a closed one-chunk ReadableStream to its end op=generator: the same read through an async generator that calls releaseLock() in its finally block op=writer: write one chunk to a WritableStream and close it release=always: then call releaseLock(); release=never: do not garbage=N allocates N short-lived objects before each cycle; retain=M keeps about M MiB of plain objects alive in each worker; load=URL imports that module first and never calls it. ?workers=&seconds=&mib=&reads=&op=&release=&garbage= window.__testResults when done; window.__progress() while running. --> <html> <head><meta charset="utf-8"><title>releaseLock repro</title></head> <body> <pre id="out">running...</pre> <script type="module"> const params = new URLSearchParams(location.search); const workers = Number(params.get('workers') ?? 8); const seconds = Number(params.get('seconds') ?? 15); const deadline = performance.now() + seconds * 1000; let started = 0, finished = 0, pageTicks = 0; setInterval(() => { pageTicks += 1; }, 50); window.__progress = () => ({ pageTicks, started, finished }); function lifetime() { return new Promise((resolve, reject) => { const worker = new Worker(`webkit-release-worker.js?${params}`); started += 1; worker.onmessage = (event) => { worker.terminate(); if (event.data === 'done') { finished += 1; resolve(); } else reject(new Error(String(event.data))); }; worker.onerror = (event) => { worker.terminate(); reject(new Error(event.message || 'worker failed')); }; }); } async function slot() { while (performance.now() < deadline) await lifetime(); } try { await Promise.all(Array.from({ length: workers }, slot)); window.__testResults = { ok: finished > 0, pageTicks, started, finished, userAgent: navigator.userAgent }; } catch (error) { window.__testResults = { ok: false, error: String(error?.message ?? error) }; } document.getElementById('out').textContent = JSON.stringify(window.__testResults, null, 2); </script> </body> </html> ``` `webkit-release-worker.js` ```js const params = new URLSearchParams(location.search); const mib = Number(params.get('mib') ?? 60); const reads = Number(params.get('reads') ?? 2000); const op = params.get('op') ?? 'reader'; const release = params.get('release') ?? 'always'; // Short-lived objects allocated per cycle, so young collections come often. const garbage = Number(params.get('garbage') ?? 0); let sink; // A retained heap of plain objects, `retain` MiB or so, so each // collection has more to mark. const retained = []; for (let i = 0; i < Number(params.get('retain') ?? 0) * 16384; i++) retained.push({ i, s: `r${i}` }); function churn() { for (let i = 0; i < garbage; i++) sink = { i, a: [i, i + 1], s: `g${i}` }; } async function readerCycle() { const stream = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(16)); controller.close(); }, }); const reader = stream.getReader(); for (;;) { const { done } = await reader.read(); if (done) break; } if (release === 'always') reader.releaseLock(); } // The same read through an async generator that releases in its finally, // as a library wrapping a stream in an async iterable would. async function* chunks(stream) { const reader = stream.getReader(); try { for (;;) { const { done, value } = await reader.read(); if (done) break; yield value; } } finally { if (release === 'always') reader.releaseLock(); } } async function generatorCycle() { const stream = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(16)); controller.close(); }, }); for await (const chunk of chunks(stream)) void chunk; } async function writerCycle() { const stream = new WritableStream({ write() {} }); const writer = stream.getWriter(); await writer.write(new Uint8Array(16)); await writer.close(); if (release === 'always') writer.releaseLock(); } (async () => { try { // Optionally load a large unrelated module first (its code is never called). if (params.get('load')) await import(params.get('load')); const memory = new WebAssembly.Memory({ initial: 1, maximum: 65536 }); memory.grow(mib * 16); const bytes = new Uint8Array(memory.buffer); for (let at = 0; at < bytes.length; at += 4096) bytes[at] = 1; const cycle = op === 'writer' ? writerCycle : op === 'generator' ? generatorCycle : readerCycle; for (let i = 0; i < reads; i++) { churn(); await cycle(); } postMessage('done'); } catch (error) { postMessage(String(error?.message ?? error)); } })(); ``` `gen-big-module.mjs` (writes `big-module.js`, a module with 20,000 small functions and 20,000 object shapes, never called after load) ```js // Writes big-module.js: 20,000 small exported functions plus 20,000 object // shapes, about 2.4 MB. Its code is never called; loading it is the point. import { writeFileSync } from 'node:fs'; const lines = ['// Synthetic large module: many functions and object shapes, never called after load.']; for (let i = 0; i < 20000; i++) lines.push(`export function f${i}(x) { const o = { k${i}a: x, k${i}b: x + ${i}, ['m' + ${i % 97}]: ${i} }; return o.k${i}a + o.k${i}b; }`); lines.push('export const shapes = [];'); lines.push("for (let i = 0; i < 20000; i++) { const o = {}; o['p' + i] = i; o['q' + (i % 50)] = i; shapes.push(o); }"); writeFileSync(process.argv[2] ?? 'big-module.js', lines.join('\n') + '\n'); ```
Attachments
Test case: releaseLock() deadlocks on the main thread (single file, open in a new tab) (3.64 KB, text/html)
2026-10-25 09:58 PDT, alex.dima
no flags
sample of the deadlocked web content process, Safari 26.6.2 (21624.5.1.11.3) (261.21 KB, text/plain)
2026-10-25 09:59 PDT, alex.dima
no flags
Radar WebKit Bug Importer
Comment 1 2026-10-08 21:32:13 PDT
alex.dima
Comment 2 2026-10-25 09:58:03 PDT
Created attachment 482004 [details] Test case: releaseLock() deadlocks on the main thread (single file, open in a new tab)
alex.dima
Comment 3 2026-10-25 09:59:54 PDT
Created attachment 482005 [details] sample of the deadlocked web content process, Safari 26.6.2 (21624.5.1.11.3)
alex.dima
Comment 4 2026-10-25 10:00:55 PDT
I can reproduce this deadlock on the main thread, without a worker or a server, and it is a regression from 314030@main (ad57b514bb0d, "Potential use after free of m_stream in ReadableStreamDefaultReader::visitAdditionalChildren()", bug 309882). Cause: ReadableStreamDefaultReader::releaseLock() holds m_streamLock while InternalReadableStreamDefaultReader::releaseLock() runs the readableStreamDefaultReaderReleaseLockForBindings builtin. The builtin allocates (it creates TypeErrors to reject the closed promise and the pending reads), so a garbage collection can start on the calling thread while the lock is held. Marking the reader takes the same lock, in ReadableStreamDefaultReader::visitAdditionalChildrenInGCThread() (reached from JSReadableStreamDefaultReader::visitOutputConstraints()) and in ReadableStreamDefaultReader::isReachableFromOpaqueRoots(), as in the worker stacks above. Whether that happens on a heap helper thread that the collection waits for or on the calling thread itself (WTF::Lock is not recursive), the thread that called releaseLock() never returns. setup(), read(), cancel() and genericRelease() release m_streamLock before they call out; only releaseLock() holds it across JavaScript. Possible fix: in releaseLock(), check m_stream under the lock, call internalReader->releaseLock() without holding it, then take the lock again only to clear m_stream (std::exchange) before calling setDefaultReader(nullptr) on the stream. m_stream still only changes under the lock, so the use-after-free that 314030@main fixed stays fixed. Test case (attached index.html, a single file; file:// works): it creates 5,000 ReadableStreams from JavaScript, reads one chunk from each through a default reader, and then calls releaseLock() on each reader, allocating a 16 MiB ArrayBuffer every 250 calls so that collections keep starting. Steps to reproduce: 1. Open index.html in a new tab. It starts on load. Expected: the page reports "Finished without a deadlock" within a second or two. Actual: the page hangs in its first iteration: its clock stops, the tab stops responding, and the web content process stays at 0% CPU. Results on macOS 26.7.1 (25G241), Apple M5 Pro: - Safari 26.6.2 (21624.5.1.11.3): deadlocked on the first load (sample attached). - Playwright's WebKit build 2311 (625.1.21+, WebKit main from June 2026): 18 of 18 new web content processes deadlocked. - Playwright's WebKit build 2370 (627.1.2+, WebKit main from late September 2026): 6 of 6 deadlocked. ReadableStreamDefaultReader::releaseLock() is unchanged on main today. Main thread (Safari 26.6.2, trimmed): WebCore::ReadableStreamDefaultReader::releaseLock(WebCore::JSDOMGlobalObject&) WebCore::InternalReadableStreamDefaultReader::releaseLock() WebCore::invokeReadableStreamDefaultReaderFunction(...) JSC::call(...) JSC::globalFuncMakeTypeError(JSC::JSGlobalObject*, JSC::CallFrame*) JSC::ErrorInstance::create(...) JSC::LocalAllocator::allocateSlowCase(...) JSC::Heap::collectInMutatorThread() JSC::Heap::runCurrentPhase(JSC::GCConductor, JSC::CurrentThreadState*) JSC::Heap::runFixpointPhase(JSC::GCConductor) JSC::MarkingConstraintSet::executeConvergenceImpl(JSC::SlotVisitor&) JSC::MarkingConstraintSolver::execute(...) JSC::Heap::runTaskInParallel(...) WTF::Condition::waitUntilUnchecked<WTF::Lock>(WTF::Lock&, WTF::TimeWithDynamicClockType const&) Heap Helper Thread (Safari 26.6.2, trimmed): JSC::SlotVisitor::drainFromShared(JSC::SlotVisitor::SharedDrainMode, WTF::MonotonicTime) JSC::MarkingConstraintSolver::runExecutionThread(...) JSC::Subspace::forEachMarkedCellInParallel<JSC::SlotVisitor, ... WebCore::DOMGCOutputConstraint::executeImplImpl<JSC::SlotVisitor> ...>::Task::run(JSC::SlotVisitor&) WebCore::JSReadableStreamDefaultReader::visitOutputConstraints<JSC::SlotVisitor>(JSC::JSCell*, JSC::SlotVisitor&) WTF::LockAlgorithm<unsigned char, (unsigned char)1, (unsigned char)2, WTF::EmptyLockHooks<unsigned char>>::lockSlow(WTF::Atomic<unsigned char>&) In some hangs (3 of 15 in our last runs), the main thread waits on the lock itself instead: JSC::Heap::runFixpointPhase -> JSC::SlotVisitor::drainInParallel -> JSC::SlotVisitor::drain -> WTF::LockAlgorithm<...>::lockSlow. We hit this in VS Code's CI, in a test that reads a fetch() response body through response.body.getReader() and then calls releaseLock(). Since any page can hit it, not only workers, a more general title might fit, for example: "REGRESSION(314030@main): ReadableStreamDefaultReader.releaseLock() deadlocks when it triggers a GC (m_streamLock held across JavaScript)". Other Streams API bugs are in the WebCore Misc. component. CCing Chris Dumez, the author of 314030@main.
jmgasper
Comment 5 2026-11-01 13:35:15 PST
This also happens on a real site to me, not just in test cases. A reddit.com tab (https://www.reddit.com/r/framework/) hung the same way in a WebKit port built from main at fb054d0914 (October 2026; Haiku port). The web process sat at 0% CPU, and reloading the page hung it again. In this case the call comes from an animation-frame microtask, and the helper thread waits in visitAdditionalChildrenInGCThread() rather than isReachableFromOpaqueRoots(): Main thread (trimmed): WebKit::WebPage::updateRendering() WebCore::Document::updateAnimationsAndSendEvents() WebCore::EventLoopTaskGroup::performMicrotaskCheckpoint(JSC::VM&) JSC::runInternalMicrotask(...) (JIT frames) WebCore::ReadableStreamDefaultReader::releaseLock(WebCore::JSDOMGlobalObject&) WebCore::InternalReadableStreamDefaultReader::releaseLock() JSC::Interpreter::executeCall(...) (JIT frames) JSC::globalFuncMakeTypeError(JSC::JSGlobalObject*, JSC::CallFrame*) JSC::ErrorInstance::create(...) JSC::getStackTrace(...) JSC::JSGlobalObject::stackTraceLimit() const JSC::Structure::materializePropertyTable(JSC::VM&, bool) JSC::Heap::collectIfNecessaryOrDefer(JSC::GCDeferralContext*) JSC::Heap::collectInMutatorThread() JSC::Collector::runFixpointPhase(JSC::GCConductor) JSC::MarkingConstraintSolver::execute(...) JSC::Collector::runTaskInParallel(...) <- waits for the helpers Heap Helper Thread (trimmed): JSC::SlotVisitor::drainFromShared(...) JSC::MarkingConstraintSolver::runExecutionThread(...) JSC::Subspace::forEachMarkedCellInParallel<... WebCore::DOMGCOutputConstraint::executeImplImpl ...> WebCore::JSReadableStreamDefaultReader::visitAdditionalChildrenInGCThread<JSC::SlotVisitor>(JSC::SlotVisitor&) WTF::LockAlgorithm<...>::lockSlow(...) <- m_streamLock, held by the main thread We (myself and Claude) tried the fix suggested in comment 4: check m_stream under the lock, call internalReader->releaseLock() without holding it, then take the lock again only to std::exchange m_stream before calling setDefaultReader(nullptr). With the test case from attachment 482004 [details], the unpatched build deadlocked in its first iteration with the stacks above. The patched build passed 5 of 5 runs, each in a new web content process, and the Reddit page loads and scrolls normally. The change we ship, against main: --- a/Source/WebCore/Modules/streams/ReadableStreamDefaultReader.cpp +++ b/Source/WebCore/Modules/streams/ReadableStreamDefaultReader.cpp @@ ExceptionOr<void> ReadableStreamDefaultReader::releaseLock(JSDOMGlobalObject& globalObject) { Locker locker { m_streamLock }; if (!m_stream) return { }; + } - if (RefPtr internalReader = this->internalDefaultReader()) { - auto result = internalReader->releaseLock(); - if (!result.hasException()) { - RefPtr stream = std::exchange(m_stream, nullptr); - stream->setDefaultReader(nullptr); + if (RefPtr internalReader = this->internalDefaultReader()) { + auto result = internalReader->releaseLock(); + if (!result.hasException()) { + RefPtr<ReadableStream> stream; + { + Locker locker { m_streamLock }; + stream = std::exchange(m_stream, nullptr); } - return result; + if (stream) + stream->setDefaultReader(nullptr); } + return result; } ---
Note You need to log in before you can comment on or make changes to this bug.