Unverified Commit 45d26dfd authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Fix dev overlay hydration error ordering (#94555)

### What?

Preserve FIFO ordering for events received while the dev overlay
connects its React dispatcher.

- Replace the separate global dispatch pointer and backlog with an
`EventQueue`.
- Keep new events queued until the existing backlog has finished
replaying.
- Add focused unit coverage for normal ordering, events enqueued during
replay, and replay failures.

### Why?

The React 18 Pages Router hydration test for an extra node inside
Suspense reports three events in this order:

1. The runtime hydration mismatch captured from the error/console path.
2. The recoverable hydration mismatch.
3. The recoverable Suspense boundary client-render fallback.

The overlay previously set `maybeDispatch` from `useInsertionEffect`,
but deferred replaying its existing queue with `setTimeout`. If the
first event arrived before the overlay connected, then the remaining
recoverable events arrived after `maybeDispatch` was exposed but before
the timeout, those newer events dispatched immediately and overtook the
queued event. The resulting order was 2, 3, 1, which caused the inline
snapshot failure.

Investigation also found that enabling Node.js streams was correlated
with the failure but was not its direct cause:

- The failing test uses the Pages Router renderer, which still calls
`ReactDOMServerPages.renderToReadableStream` and does not select the App
Router Node Fizz stream implementation.
- The Node streams default change did not modify the Pages client error
bridge or dev overlay queue.
- The queue race predates the Node streams rollout. Timing changes
around the rollout, including adjacent lazy loading of the overlay UX,
made the existing race reproducible.

The correct fix is therefore to enforce the overlay queue ordering
invariant rather than update the snapshot or special-case Node streams.

### How?

`EventQueue.connect()` leaves direct dispatch disabled while draining
the backlog. Events received during replay are appended to the same
queue and drained before the dispatcher becomes directly available. A
`finally` block preserves the previous cleanup and connection behavior
when a queued event throws, while `disconnect()` only clears the
currently connected dispatcher.

### Verification

- `pnpm prettier --with-node-modules --ignore-path .prettierignore
--write packages/next/src/next-devtools/dev-overlay.browser.tsx
packages/next/src/next-devtools/dev-overlay/event-queue.ts
packages/next/src/next-devtools/dev-overlay/event-queue.test.ts`
- `npx eslint --config eslint.config.mjs --fix
packages/next/src/next-devtools/dev-overlay.browser.tsx
packages/next/src/next-devtools/dev-overlay/event-queue.ts
packages/next/src/next-devtools/dev-overlay/event-queue.test.ts`
- `pnpm --filter=next build`
- `pnpm exec jest
packages/next/src/next-devtools/dev-overlay/event-queue.test.ts
--runInBand`
- `HEADLESS=true NEXT_TEST_REACT_VERSION=18.3.1
NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-webpack
test/development/acceptance/hydration-error.test.ts -t "should show
correct hydration error when client renders an extra node inside
Suspense content"`
- `HEADLESS=true NEXT_TEST_REACT_VERSION=18.3.1
NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-turbo
test/development/acceptance/hydration-error.test.ts -t "should show
correct hydration error when client renders an extra node inside
Suspense content"`

<!-- NEXT_JS_LLM_PR -->
parent 95c65e43
......@@ -49,6 +49,7 @@ import {
import type { SegmentNodeState } from './userspace/app/segment-explorer-node'
import type { DevToolsConfig } from './dev-overlay/shared'
import type { SegmentTrieData } from '../shared/lib/mcp-page-metadata-types'
import { EventQueue } from './dev-overlay/event-queue'
export interface Dispatcher {
onBuildOk(): void
......@@ -80,8 +81,7 @@ export interface Dispatcher {
}
type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
let maybeDispatch: Dispatch | null = null
const queue: Array<(dispatch: Dispatch) => void> = []
const eventQueue = new EventQueue<Dispatch>()
function loadDevOverlayUX() {
const { DevOverlay, FontStyles } =
......@@ -131,13 +131,9 @@ function createQueuable<Args extends any[]>(
queueableFunction: (dispatch: Dispatch, ...args: Args) => void
) {
return (...args: Args) => {
if (maybeDispatch) {
queueableFunction(maybeDispatch, ...args)
} else {
queue.push((dispatch: Dispatch) => {
queueableFunction(dispatch, ...args)
})
}
eventQueue.enqueue((dispatch) => {
queueableFunction(dispatch, ...args)
})
}
}
......@@ -239,17 +235,6 @@ export const dispatcher: Dispatcher = {
}),
}
function replayQueuedEvents(dispatch: NonNullable<typeof maybeDispatch>) {
try {
for (const queuedFunction of queue) {
queuedFunction(dispatch)
}
} finally {
// TODO: What to do with failed events?
queue.length = 0
}
}
function DevOverlayRoot({
enableCacheIndicator,
getOwnerStack,
......@@ -291,17 +276,15 @@ function DevOverlayRoot({
}, [shadowRoot, state.theme])
useInsertionEffect(() => {
maybeDispatch = dispatch
// Can't schedule updates from useInsertionEffect, so we need to defer.
// Could move this into a passive Effect but we don't want replaying when
// we reconnect.
const replayTimeout = setTimeout(() => {
replayQueuedEvents(dispatch)
eventQueue.connect(dispatch)
})
return () => {
maybeDispatch = null
eventQueue.disconnect(dispatch)
clearTimeout(replayTimeout)
}
}, [])
......
import { EventQueue } from './event-queue'
describe('EventQueue', () => {
it('preserves event order while connecting', () => {
const eventQueue = new EventQueue<(value: string) => void>()
const events: string[] = []
const recordEvent = (value: string) => events.push(value)
eventQueue.enqueue((emit) => emit('queued first'))
eventQueue.enqueue((emit) => emit('queued second'))
eventQueue.connect(recordEvent)
eventQueue.enqueue((emit) => emit('dispatched directly'))
expect(events).toEqual([
'queued first',
'queued second',
'dispatched directly',
])
})
it('drains events that are queued during replay', () => {
const eventQueue = new EventQueue<(value: string) => void>()
const events: string[] = []
eventQueue.enqueue((emit) => {
emit('queued first')
eventQueue.enqueue((queuedEmit) => queuedEmit('queued during replay'))
})
eventQueue.connect((value) => events.push(value))
expect(events).toEqual(['queued first', 'queued during replay'])
})
it('connects and clears the backlog when replay throws', () => {
const eventQueue = new EventQueue<(value: string) => void>()
const events: string[] = []
eventQueue.enqueue(() => {
throw new Error('replay failed')
})
eventQueue.enqueue((emit) => emit('remaining queued event'))
expect(() => eventQueue.connect((value) => events.push(value))).toThrow(
'replay failed'
)
eventQueue.enqueue((emit) => emit('new event'))
expect(events).toEqual(['new event'])
})
})
export class EventQueue<Dispatch> {
private dispatch: Dispatch | null = null
private readonly queue: Array<(dispatch: Dispatch) => void> = []
enqueue(event: (dispatch: Dispatch) => void): void {
if (this.dispatch) {
event(this.dispatch)
} else {
this.queue.push(event)
}
}
connect(dispatch: Dispatch): void {
try {
// Keep new events queued until the backlog is drained so they cannot overtake it.
for (let i = 0; i < this.queue.length; i++) {
this.queue[i](dispatch)
}
} finally {
this.queue.length = 0
this.dispatch = dispatch
}
}
disconnect(dispatch: Dispatch): void {
if (this.dispatch === dispatch) {
this.dispatch = null
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment