Skip to content
Source
Sign inSign up
TanStack/router

router-ssr-query-core: reader.releaseLock() can deadlock WebKit's GC after hydration #8795

OpenEmilEinarsen(GitHub profile, opens in a new tab) opened this issue 4 comments

Which project does this relate to?

Start

Describe the bug

In Playwright's WebKit on Linux, a page using @tanstack/react-router-ssr-query can freeze for good right after load. The main thread never comes back.

Stall dumps put the WebKit web process main thread in a garbage collection, waiting on a lock nobody else holds:

Heap::collectInMutatorThread
  -> marking constraint
  -> JSReadableStreamDefaultReaderOwner::isReachableFromOpaqueRoots
  -> Lock::lockSlow

WebKit's native ReadableStreamDefaultReader.releaseLock() runs stream JavaScript while it holds the reader's lock. If a GC starts there, the marking constraint tries to take the same lock and the page deadlocks.

router-ssr-query-core calls reader.releaseLock() in a finally when the dehydrated query stream ends, which is just after load:

https://github.com/TanStack/router/blob/6b9fe6d29552270836c511bc9b343d73541f4424/packages/router-ssr-query-core/src/index.ts#L244-L260

Numbers:

  • Bare-page probe in Playwright's WebKit (script below): 7 of 120 rounds froze with releaseLock(), 0 of 120 without it.
  • Our app's Playwright suite: 3 fixture timeouts in 400 walks before patching, 0 in 1,200 walks after dropping the releaseLock() call.

I don't know whether Safari itself is affected. I have only seen it in Playwright's WebKit build on Linux.

Complete minimal reproducer

No app reproducer. The standalone script below reproduces the WebKit side without TanStack. It does what router-ssr-query-core does (read a stream to the end, then releaseLock()) under allocation pressure.

webkit-release-lock.ts (Linux, node webkit-release-lock.ts, Node 24, @playwright/test 1.62.0)
import { webkit } from '@playwright/test'

const RELEASED_ROUND_LIMIT = 360
const DROPPED_ROUND_COUNT = 120
const STREAMS_PER_ROUND = 200
const ROUND_DEADLINE_MS = 20_000

const browser = await webkit.launch()
let releasedWalk: RoundWalk
let droppedWalk: RoundWalk

try {
	releasedWalk = await walkRounds('released')
	droppedWalk = await walkRounds('dropped')
} finally {
	await browser.close()
}

console.table({ 'reader released': releasedWalk, 'reader dropped': droppedWalk })

console.log(JSON.stringify({ webkit: browser.version(), arch: process.arch }))

if (releasedWalk.frozenRoundCount === 0 || droppedWalk.frozenRoundCount > 0) process.exitCode = 1

type ReaderEnd = 'released' | 'dropped'

type RoundWalk = { roundCount: number; frozenRoundCount: number }

async function walkRounds(readerEnd: ReaderEnd): Promise<RoundWalk> {
	const roundLimit = readerEnd === 'released' ? RELEASED_ROUND_LIMIT : DROPPED_ROUND_COUNT
	let frozenRoundCount = 0

	for (let roundNumber = 1; roundNumber <= roundLimit; roundNumber++) {
		const roundContext = await browser.newContext()

		try {
			const probePage = await roundContext.newPage()
			await probePage.goto('data:text/html,<p>release-lock probe</p>')

			const isFrozen = await Promise.race([
				probePage
					.evaluate(readStreamsUnderCollection, { readerEnd, streamCount: STREAMS_PER_ROUND })
					.then(() => false),
				new Promise<boolean>((resolve) => setTimeout(() => resolve(true), ROUND_DEADLINE_MS)),
			])

			if (isFrozen) frozenRoundCount++
		} finally {
			await roundContext.close().catch(() => {})
		}

		if (readerEnd === 'released' && frozenRoundCount > 0)
			return { roundCount: roundNumber, frozenRoundCount }
	}

	return { roundCount: roundLimit, frozenRoundCount }
}

async function readStreamsUnderCollection({
	readerEnd,
	streamCount,
}: {
	readerEnd: ReaderEnd
	streamCount: number
}) {
	let garbageObjects: Array<{ index: number; pair: number[]; text: string }> = []

	function allocateGarbage(objectCount: number) {
		for (let objectIndex = 0; objectIndex < objectCount; objectIndex++)
			garbageObjects.push({
				index: objectIndex,
				pair: [objectIndex, objectIndex + 1],
				text: `g${objectIndex}${Math.random()}`,
			})

		if (garbageObjects.length > 300_000) garbageObjects = []
	}

	async function drainChunks(chunkReader: ReadableStreamDefaultReader<{ chunk: number }>) {
		try {
			for (;;) {
				const { done } = await chunkReader.read()

				if (done) return
				allocateGarbage(500)
			}
		} finally {
			if (readerEnd === 'released') chunkReader.releaseLock()
		}
	}

	const allocationTimer = setInterval(() => allocateGarbage(20_000), 1)

	try {
		for (let streamIndex = 0; streamIndex < streamCount; streamIndex++) {
			let streamController: ReadableStreamDefaultController<{ chunk: number }> | undefined

			const chunkStream = new ReadableStream<{ chunk: number }>({
				start(controller) {
					streamController = controller
				},
			})

			const chunkDrain = drainChunks(chunkStream.getReader())

			for (let chunkIndex = 0; chunkIndex < 10; chunkIndex++) {
				streamController?.enqueue({ chunk: chunkIndex })

				if (chunkIndex % 3 === 0) await new Promise((resolve) => setTimeout(resolve, 0))
			}

			streamController?.close()
			await chunkDrain
		}
	} finally {
		clearInterval(allocationTimer)
	}
}

Steps to Reproduce the Bug

  1. On Linux, install @playwright/test 1.62.0 and its WebKit (npx playwright install webkit).
  2. Run node webkit-release-lock.ts.
  3. The "reader released" walk freezes a round (20 s deadline) within a few hundred rounds. The "reader dropped" walk never freezes.

Expected behavior

Hydration finishes and the page stays responsive. Instead, the page sometimes freezes for good right after load.

Platform

  • @tanstack/router-ssr-query-core 1.169.3 (via @tanstack/react-router-ssr-query 1.167.3, @tanstack/react-start 1.169.2, @tanstack/react-router 1.170.44)
  • OS: Linux (GitHub Actions runners)
  • Browser: Playwright WebKit from @playwright/test 1.62.0
  • Bundler: Vite 8.2.4

Additional context

Proposed fix: drop the finally { reader.releaseLock() }. Once the loop exits the stream has ended (or the reader has been cancelled), and nothing else reads it, so the lock does not need releasing. We ship this as a pnpm patch and will open a PR.

The WebKit deadlock itself is a WebKit bug. Removing the call avoids it until WebKit fixes it.

Drafted with AI assistance.

  1. schiller-manuel(GitHub profile, opens in a new tab)commented

    we require an actual app as the reproducer

    did you create a webkit bug report or is there one existing already? please link to it

  2. schiller-manuel(GitHub profile, opens in a new tab) added labelsinformation needed

  3. There's an existing WebKit report for the same deadlock: https://bugs.webkit.org/show_bug.cgi?id=326046 (imported to Apple as rdar://189584524). It reproduces in Safari 27 on macOS, inside a worker, so this isn't limited to Playwright's Linux WebKit build. The mechanism is the same: a GC started inside ReadableStreamDefaultReader.releaseLock() waits on the reader's own lock.

    I'll put together a minimal Start app with react-router-ssr-query and a Playwright loop that shows the freeze, and link it here.

  4. App reproducer: https://github.com/EmilEinarsen/tanstack-ssr-query-webkit-freeze

    It's a minimal Start app wired with setupRouterSsrQueryIntegration. Its loader prefetches queries, so the dehydrated stream carries data. A Playwright script loads it in WebKit in a fresh context per round, and counts a round as frozen when the page stops answering. NO_RELEASE_LOCK=1 builds it with the change from #8796.

    Playwright 1.62.0, WebKit 26.5, in mcr.microsoft.com/playwright:v1.62.0-noble:

    VariantFrozen rounds
    releaseLock() as published5 of 5,636
    releaseLock() removed (#8796)0 of 6,000

    On its own the tiny page barely allocates, and it did not freeze in 2,000 rounds. So PRESSURE=1 runs a timer for the first 3 s after load that allocates small objects, to keep the collector busy the way a large app does. That script never touches streams. The only releaseLock() on the page is the one in router-ssr-query-core, and the only difference between the two variants is removing that call. Our production app freezes without any added pressure: 3 in 400 runs before the change, 0 in 1,200 after.

  5. TheBinaryGuy(GitHub profile, opens in a new tab)commented

    We hit this in a production app too (HushOS), so a few data points in case they help:

    It also happens on macOS, in a real app. We saw it in Playwright's WebKit on macOS (webkit-2359), in a sign-out, sign-in, reload loop under CPU load: one page froze for good on load. sample of the frozen WebContent process showed the same deadlock as above. The main thread was in releaseLock → InternalReadableStreamDefaultReader::releaseLock → makeTypeError → collectInMutatorThread, and a heap helper was parked in JSReadableStreamDefaultReaderOwner::isReachableFromOpaqueRoots → Lock::lockSlow. The only releaseLock() a page load of ours made was the one in setupCoreRouterSsrQueryIntegration's finally. A minimal page (construct a stream, read it to the end, releaseLock(), in a loop) froze 3 of 13 runs under CPU load, against 0 of 13 without the releaseLock().

    Start's server-function client has the same call. In @tanstack/start-client-core 1.170.37, client-rpc/serverFnFetcher.js (lines 196 and 212, processFramedResponse) and client-rpc/frame-decoder.js (line 154) call reader.releaseLock() after a stream ends. So an app using streamed server functions can freeze the same way. A fix in router-ssr-query-core alone wouldn't cover Start.

    What we ship meanwhile. We patch out the finally { reader.releaseLock() } in router-ssr-query-core. Nothing reads the stream after it ends: the reader and stream are garbage collected with it. Cancelling the stream when a batch fails to hydrate is kept. With it, a page load makes no releaseLock() call at all.

    Until WebKit ships a fix for https://bugs.webkit.org/show_bug.cgi?id=326046, would dropping the release once the stream has ended, in both packages, be a change you'd accept?

Sign in to join this conversation.