Unverified Commit 554a1e3c authored by Sam Selikoff's avatar Sam Selikoff Committed by GitHub

Fix Navigation Inspector Continue Rendering with loading.tsx (#94355)

## Summary

- Add regression coverage for Navigation Inspector `Continue Rendering`
with a route-level `loading.tsx`
- Fix Instant Navigation lock timing by snapshotting the active lock
when a dynamic request starts
- Prevent inspector re-arm from trapping in-flight dynamic responses
behind the next capture lock

## Why

The Navigation Inspector recently changed `Continue Rendering` to re-arm
capture after releasing the current lock. That surfaced a race in the
lower-level Instant Navigation lock handling.

The flow was:

1. `Continue Rendering` deletes the `next-instant-navigation-testing`
cookie.
2. Deleting the cookie releases the current navigation lock and triggers
a soft refresh.
3. The inspector quickly writes a new pending cookie to re-arm capture.
4. A route-level `loading.tsx` navigation may still have dynamic data
applying from the unlock-triggered refresh.
5. Before this change, `fetchMissingDynamicData` waited on whichever
lock was active when the response was applied.

That meant the refresh response could accidentally see the newly
re-armed lock and suspend forever.

This surfaced with `loading.tsx` more reliably than inline Suspense
because the route-level loading boundary commits the segment loading
shell, then final content depends on the unlock refresh path. Inline
Suspense generally keeps the deferred dynamic work associated with the
original captured navigation, so it waits on the original lock and
resumes when that lock is released.

## Fix

Dynamic requests now capture the current navigation lock when the
request starts, then wait only on that specific lock when applying the
response.

This preserves the intended behavior:

- Requests started during a capture still wait for that capture to
release.
- Requests started after unlock are not blocked by a later re-arm.
- The inspector can continue re-arming capture without racing in-flight
refresh responses.

Conceptually, a dynamic request should wait on the lock that existed
when that request started, not whatever lock happens to exist later when
its response is applied.
parent 5b99d26d
......@@ -127,6 +127,8 @@ export type NavigationRequestAccumulation = {
scrollRef: ScrollRef | null
}
export type NavigationLock = Promise<void> | null
const noop = () => {}
export function createInitialCacheNodeForHydration(
......@@ -1383,7 +1385,8 @@ export function spawnDynamicRequests(
// The original navigation's push/replace intent. Threaded through to the
// server-patch retry logic so it can inherit the intent if the original
// transition hasn't committed yet.
navigateType: 'push' | 'replace'
navigateType: 'push' | 'replace',
navigationLock: NavigationLock
): void {
const dynamicRequestTree = task.dynamicRequestTree
if (dynamicRequestTree === null) {
......@@ -1407,7 +1410,8 @@ export function spawnDynamicRequests(
primaryUrl,
nextUrl,
freshnessPolicy,
routeCacheEntry
routeCacheEntry,
navigationLock
)
const separateRefreshUrls = accumulation.separateRefreshUrls
......@@ -1459,7 +1463,8 @@ export function spawnDynamicRequests(
// hard refresh.
nextUrl,
freshnessPolicy,
routeCacheEntry
routeCacheEntry,
navigationLock
)
)
}
......@@ -1697,7 +1702,8 @@ async function fetchMissingDynamicData(
url: URL,
nextUrl: string | null,
freshnessPolicy: FreshnessPolicy,
routeCacheEntry: FulfilledRouteCacheEntry | null
routeCacheEntry: FulfilledRouteCacheEntry | null,
navigationLock: NavigationLock
): Promise<{
exitStatus: NavigationTaskExitStatus
url: URL
......@@ -1734,7 +1740,7 @@ async function fetchMissingDynamicData(
// writing the dynamic data. This allows tests to assert on the prefetched
// UI state.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
await waitForNavigationLock()
await waitForNavigationLock(navigationLock)
}
// TODO: Implement Shell extraction as part of Cached Navigations.
......@@ -2152,16 +2158,25 @@ function createDeferredRsc<
}
/**
* Helper for the Instant Navigation Testing API. Waits for the navigation lock
* to be released before returning. The network request has already completed by
* the time this is called, so this only delays writing the dynamic data.
* Helper for the Instant Navigation Testing API. Snapshots the lock that is
* active when a navigation starts, so the navigation can wait for the same lock
* even if another lock is acquired before its dynamic response is applied.
*
* Not exposed in production builds by default.
*/
async function waitForNavigationLock(): Promise<void> {
export function getCurrentNavigationLock(): NavigationLock {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { getCurrentNavigationLock: getCurrentLock } =
require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock')
return getCurrentLock()
}
return null
}
async function waitForNavigationLock(lock: NavigationLock): Promise<void> {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { waitForNavigationLockIfActive } =
require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock')
await waitForNavigationLockIfActive()
await waitForNavigationLockIfActive(lock)
}
}
......@@ -10,7 +10,7 @@ import {
} from '../../segment-cache/navigation'
import { invalidateSegmentCacheEntries } from '../../segment-cache/cache'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { FreshnessPolicy } from '../ppr-navigations'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
import {
invalidateBfCache,
UnknownDynamicStaleTime,
......@@ -61,6 +61,7 @@ export function refreshDynamicData(
const currentRenderedSearch = state.renderedSearch
const currentFlightRouterState = state.tree
const scrollBehavior = ScrollBehavior.NoScroll
const navigationLock = getCurrentNavigationLock()
// Create a NavigationSeed from the current FlightRouterState.
// TODO: Eventually we will store this type directly on the state object
......@@ -92,6 +93,7 @@ export function refreshDynamicData(
nextUrlForRefresh,
scrollBehavior,
navigateType,
navigationLock,
null,
// Refresh navigations don't use route prediction, so there's no route
// cache entry to mark as having a dynamic rewrite on mismatch. If a
......
......@@ -6,6 +6,7 @@ import type {
import { extractPathFromFlightRouterState } from '../compute-changed-path'
import {
FreshnessPolicy,
getCurrentNavigationLock,
spawnDynamicRequests,
startPPRNavigation,
type NavigationRequestAccumulation,
......@@ -43,6 +44,7 @@ export function restoreReducer(
const restoredUrl = action.url
const restoredNextUrl =
extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname
const navigationLock = getCurrentNavigationLock()
const now = Date.now()
// TODO: Store the dynamic stale time on the top-level state so it's known
......@@ -89,7 +91,8 @@ export function restoreReducer(
// to find and mark the entry.
null,
// History traversal always uses 'replace'.
'replace'
'replace',
navigationLock
)
return completeTraverseNavigation(
state,
......
......@@ -67,7 +67,7 @@ import {
type ActionRevalidationKind,
} from '../../../../shared/lib/action-revalidation-kind'
import { isExternalURL } from '../../app-router-utils'
import { FreshnessPolicy } from '../ppr-navigations'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
import { processFetch } from '../fetch-server-response'
import {
invalidateBfCache,
......@@ -496,6 +496,7 @@ export function serverActionReducer(
false // hasDynamicRewrite
)
}
const navigationLock = getCurrentNavigationLock()
return navigateToKnownRoute(
now,
......@@ -511,6 +512,7 @@ export function serverActionReducer(
nextUrl,
scrollBehavior,
navigateType,
navigationLock,
null,
// Server action redirects don't use route prediction - we already
// have the route tree from the server response. If a mismatch occurs
......
......@@ -11,7 +11,7 @@ import {
navigateToKnownRoute,
} from '../../segment-cache/navigation'
import { refreshReducer } from './refresh-reducer'
import { FreshnessPolicy } from '../ppr-navigations'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
export function serverPatchReducer(
state: ReadonlyReducerState,
......@@ -43,6 +43,7 @@ export function serverPatchReducer(
const retryCanonicalUrl = createHrefFromUrl(retryUrl)
const retryNextUrl = action.nextUrl
const scrollBehavior = ScrollBehavior.Default
const navigationLock = getCurrentNavigationLock()
const now = Date.now()
return navigateToKnownRoute(
now,
......@@ -58,6 +59,7 @@ export function serverPatchReducer(
retryNextUrl,
scrollBehavior,
navigateType,
navigationLock,
null,
// Server patch (retry) navigations don't use route prediction. This is
// typically a retry after a previous mismatch, so the route was already
......
......@@ -26,9 +26,11 @@ function parseCookieValue(raw: string): InstantNavCookieState {
}
try {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed) && parsed.length >= 3) {
const rawState = parsed[2]
return rawState === null ? 'mpa' : 'spa'
if (Array.isArray(parsed)) {
if (parsed.length >= 3) {
const rawState = parsed[2]
return rawState === null ? 'mpa' : 'spa'
}
}
} catch {}
return 'pending'
......@@ -189,7 +191,11 @@ export function startListeningForInstantNavigationCookie(): void {
if (state === 'pending') {
// External actor starting a new lock scope.
if (lockState !== null) {
releaseLock()
// This can be the delayed CookieStore event for the pending
// cookie that was already observed synchronously from
// document.cookie. Keep the existing lock identity so work that
// captured it keeps waiting on the same promise.
return
}
acquireLock()
}
......@@ -262,14 +268,23 @@ export function isNavigationLocked(): boolean {
return false
}
export function getCurrentNavigationLock(): Promise<void> | null {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
return lockState !== null ? lockState.promise : null
}
return null
}
/**
* Waits for the navigation lock to be released, if it's currently held.
* No-op if the lock is not acquired.
*/
export async function waitForNavigationLockIfActive(): Promise<void> {
export async function waitForNavigationLockIfActive(
lock: Promise<void> | null = getCurrentNavigationLock()
): Promise<void> {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (lockState !== null) {
await lockState.promise
if (lock !== null) {
await lock
}
}
}
......@@ -16,6 +16,8 @@ import {
startPPRNavigation,
spawnDynamicRequests,
FreshnessPolicy,
getCurrentNavigationLock,
type NavigationLock,
type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
......@@ -64,6 +66,8 @@ export function navigate(
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace'
): AppRouterState | Promise<AppRouterState> {
let navigationLock: NavigationLock = null
// Instant Navigation Testing API: when the lock is active, ensure a
// prefetch task has been initiated before proceeding with the navigation.
// This guarantees that segment data requests are at least pending, even
......@@ -74,6 +78,7 @@ export function navigate(
const { isNavigationLocked } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
if (isNavigationLocked()) {
navigationLock = getCurrentNavigationLock()
return ensurePrefetchThenNavigate(
state,
url,
......@@ -84,7 +89,8 @@ export function navigate(
nextUrl,
freshnessPolicy,
scrollBehavior,
navigateType
navigateType,
navigationLock
)
}
}
......@@ -99,7 +105,8 @@ export function navigate(
nextUrl,
freshnessPolicy,
scrollBehavior,
navigateType
navigateType,
navigationLock
)
}
......@@ -113,7 +120,8 @@ function navigateImpl(
nextUrl: string | null,
freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace'
navigateType: 'push' | 'replace',
navigationLock: NavigationLock
): AppRouterState | Promise<AppRouterState> {
const now = Date.now()
const href = url.href
......@@ -134,7 +142,8 @@ function navigateImpl(
freshnessPolicy,
scrollBehavior,
navigateType,
route
route,
navigationLock
)
}
......@@ -170,7 +179,8 @@ function navigateImpl(
freshnessPolicy,
scrollBehavior,
navigateType,
optimisticRoute
optimisticRoute,
navigationLock
)
}
}
......@@ -192,7 +202,8 @@ function navigateImpl(
currentFlightRouterState,
freshnessPolicy,
scrollBehavior,
navigateType
navigateType,
navigationLock
).catch(() => {
// If the navigation fails, return the current state
return state
......@@ -213,6 +224,7 @@ export function navigateToKnownRoute(
nextUrl: string | null,
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
navigationLock: NavigationLock,
debugInfo: Array<unknown> | null,
// The route cache entry used for this navigation, if it came from route
// prediction. Passed through so it can be marked as having a dynamic rewrite
......@@ -276,7 +288,8 @@ export function navigateToKnownRoute(
freshnessPolicy,
accumulation,
routeCacheEntry,
navigateType
navigateType,
navigationLock
)
}
return completeSoftNavigation(
......@@ -309,7 +322,8 @@ function navigateUsingPrefetchedRouteTree(
freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
route: FulfilledRouteCacheEntry
route: FulfilledRouteCacheEntry,
navigationLock: NavigationLock
): AppRouterState {
const routeTree = route.tree
const canonicalUrl = route.canonicalUrl + url.hash
......@@ -336,6 +350,7 @@ function navigateUsingPrefetchedRouteTree(
nextUrl,
scrollBehavior,
navigateType,
navigationLock,
null,
route
)
......@@ -364,7 +379,8 @@ async function navigateToUnknownRoute(
currentFlightRouterState: FlightRouterState,
freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace'
navigateType: 'push' | 'replace',
navigationLock: NavigationLock
): Promise<AppRouterState> {
// Runs when a navigation happens but there's no cached prefetch we can use.
// Don't bother to wait for a prefetch response; go straight to a full
......@@ -529,6 +545,7 @@ async function navigateToUnknownRoute(
nextUrl,
scrollBehavior,
navigateType,
navigationLock,
debugInfo,
// Unknown route navigations don't use route prediction - the route tree
// came directly from the server. If a mismatch occurs during dynamic data
......@@ -966,7 +983,8 @@ async function ensurePrefetchThenNavigate(
nextUrl: string | null,
freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace'
navigateType: 'push' | 'replace',
navigationLock: NavigationLock
): Promise<AppRouterState> {
const link = getLinkForCurrentNavigation()
const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR
......@@ -996,7 +1014,8 @@ async function ensurePrefetchThenNavigate(
nextUrl,
freshnessPolicy,
scrollBehavior,
navigateType
navigateType,
navigationLock
)
// Only transition to captured-SPA once the navigation is known to be an SPA.
......
export default function Loading() {
return <div>Loading await connection page...</div>
}
import { connection } from 'next/server'
export default async function TargetPage() {
await connection()
return (
<div>
<h1>Target Page</h1>
<div data-testid="dynamic-content">Dynamic content loaded</div>
</div>
)
}
......@@ -33,49 +33,41 @@ export default function Page() {
</li>
</ol>
<nav style={{ marginTop: '1.5rem' }}>
<Link
href="/target-page/my-post?search=foo"
id="link-to-target"
style={{
display: 'inline-block',
padding: '0.5rem 1rem',
background: '#0070f3',
color: '#fff',
borderRadius: 6,
textDecoration: 'none',
}}
>
Go to target page &rarr;
</Link>
<Link
href="/mpa-target"
id="link-to-mpa-target"
style={{
display: 'inline-block',
marginLeft: '0.75rem',
padding: '0.5rem 1rem',
background: '#111',
color: '#fff',
borderRadius: 6,
textDecoration: 'none',
}}
>
Go to MPA target &rarr;
</Link>
{/* <Link
href="/blocking-page?foo=bar"
id="link-to-target"
style={{
display: 'inline-block',
padding: '0.5rem 1rem',
background: '#0070f3',
color: '#fff',
borderRadius: 6,
textDecoration: 'none',
}}
>
Go to blocking page
</Link> */}
<div>
<Link
href="/target-page/my-post?search=foo"
id="link-to-target"
style={{
display: 'inline-block',
padding: '0.5rem 1rem',
background: '#0070f3',
color: '#fff',
borderRadius: 6,
textDecoration: 'none',
}}
>
Go to target page &rarr;
</Link>
<Link
href="/mpa-target"
id="link-to-mpa-target"
style={{
display: 'inline-block',
marginLeft: '0.75rem',
padding: '0.5rem 1rem',
background: '#111',
color: '#fff',
borderRadius: 6,
textDecoration: 'none',
}}
>
Go to MPA target &rarr;
</Link>
</div>
<div>
<Link href="/await-connection">Page with await connection</Link>
</div>
</nav>
</div>
)
......
......@@ -13,8 +13,6 @@ describe.skip('instant-nav-panel', () => {
files: __dirname,
})
const targetPage = '/target-page/my-post?search=foo'
async function waitForPanelRouterTransition() {
// Run all the necessary CSS transitions
// and click-outside event handler adjustment due to cascading update.
......@@ -301,12 +299,26 @@ describe.skip('instant-nav-panel', () => {
.waitFor({ state: 'visible', timeout: 30000 })
}
async function expectAwaitConnectionPageLoading(browser: Playwright) {
await retry(
async () => {
const text = await browser.elementByCss('body').text()
expect(text).toContain('Loading await connection page...')
},
30_000,
500
)
expect(
await browser.locator('[data-testid="dynamic-content"]').count()
).toBe(0)
}
async function openHomeWithTargetPageWarmup() {
const [browser] = await Promise.all([
next.browser('/'),
isNextDev && !isTurbopack
? // warmup target page compilation before clicking Start, to avoid extra flakiness.
next.render(targetPage).catch(() => {})
next.render('/target-page/my-post?search=foo').catch(() => {})
: null,
])
await clearInstantModeCookie(browser)
......@@ -384,7 +396,7 @@ describe.skip('instant-nav-panel', () => {
describe('MPA captures', () => {
it('should show page load state after clicking Start and refreshing', async () => {
const browser = await next.browser(targetPage)
const browser = await next.browser('/target-page/my-post?search=foo')
await clearInstantModeCookie(browser)
await openInstantNavPanel(browser)
......@@ -421,7 +433,7 @@ describe.skip('instant-nav-panel', () => {
})
it('should reset the panel and app when pressing the close button from captured MPA state', async () => {
const browser = await next.browser(targetPage)
const browser = await next.browser('/target-page/my-post?search=foo')
await clearInstantModeCookie(browser)
await openInstantNavPanel(browser)
......@@ -441,7 +453,7 @@ describe.skip('instant-nav-panel', () => {
})
it('should keep params and searchParams RSC content suspended for a captured MPA page load', async () => {
const browser = await next.browser(targetPage)
const browser = await next.browser('/target-page/my-post?search=foo')
await clearInstantModeCookie(browser)
await openInstantNavPanel(browser)
......@@ -480,7 +492,7 @@ describe.skip('instant-nav-panel', () => {
})
it('should re-arm capture and return to awaiting navigation after Continue Rendering from MPA state', async () => {
const browser = await next.browser(targetPage)
const browser = await next.browser('/target-page/my-post?search=foo')
await clearInstantModeCookie(browser)
await openInstantNavPanel(browser)
......@@ -519,7 +531,7 @@ describe.skip('instant-nav-panel', () => {
})
// Navigate to target page via SPA (use eval to bypass overlay pointer interception)
await clickLink(browser, targetPage)
await clickLink(browser, '/target-page/my-post?search=foo')
// Panel should transition to client navigation capture state
await expectSpaPanel(browser)
......@@ -537,7 +549,7 @@ describe.skip('instant-nav-panel', () => {
await clickStartCapturing(browser)
// Navigate to target page via SPA (use eval to bypass overlay pointer interception)
await clickLink(browser, targetPage)
await clickLink(browser, '/target-page/my-post?search=foo')
// Dynamic data should be suspended under the lock.
// Use a longer timeout because dev mode needs to compile the target page.
......@@ -557,7 +569,7 @@ describe.skip('instant-nav-panel', () => {
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
await clickLink(browser, targetPage)
await clickLink(browser, '/target-page/my-post?search=foo')
await expectSpaPanel(browser)
await expectTargetPageSpaShell(browser)
......@@ -575,7 +587,7 @@ describe.skip('instant-nav-panel', () => {
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
await clickLink(browser, targetPage)
await clickLink(browser, '/target-page/my-post?search=foo')
await expectSpaPanel(browser)
await expectTargetPageSpaShell(browser)
......@@ -586,8 +598,23 @@ describe.skip('instant-nav-panel', () => {
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
await clickLink(browser, targetPage)
await clickLink(browser, '/target-page/my-post?search=foo')
await expectSpaPanel(browser)
await clickContinueRendering(browser)
await expectPendingPanel(browser)
await expectTargetPageRendered(browser)
await waitForInstantModeCookie(browser)
})
it('should continue rendering a captured await connection navigation with loading.tsx', async () => {
const browser = await openHomeWithTargetPageWarmup()
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
await clickLink(browser, '/await-connection')
await expectSpaPanel(browser)
await expectAwaitConnectionPageLoading(browser)
await clickContinueRendering(browser)
await expectPendingPanel(browser)
......@@ -608,7 +635,7 @@ describe.skip('instant-nav-panel', () => {
await waitForInstantNavPanelOpen(browser)
await expectMpaPanel(browser)
await clickLink(browser, targetPage)
await clickLink(browser, '/target-page/my-post?search=foo')
await expectSpaPanel(browser)
await expectTargetPageSpaShell(browser)
})
......@@ -618,7 +645,7 @@ describe.skip('instant-nav-panel', () => {
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
await clickLink(browser, targetPage)
await clickLink(browser, '/target-page/my-post?search=foo')
await expectSpaPanel(browser)
await browser.refresh()
......
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