Unverified Commit 5dc3ae1f authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Fix Nav Inspector request loop on repeat captures (#97050)

## Summary

Repro (from #96692): enable the Nav Inspector, click a `<Link
prefetch={true}>`, close the inspector, navigate home, re-enable it, and
click the same link. The app hung in a pending "Compiling..." state
while firing prefetch requests in an infinite loop (~30/sec).

The Instant Navigation Testing lock restricted navigation reads to
entries created within the current lock scope (`ownedEntries`), enforced
as a post-hoc filter after the cache lookup. But the segment cache
resolves lookups by most-specific-match, so a previous scope's
runtime-prefetch entries at concrete param keypaths kept winning the
lookup, the filter kept rejecting them, and the locked prefetch created
its replacement at a more generic keypath that could never win — every
scheduler pass discarded and refetched forever.

Rather than patch the filter, this replaces the `ownedEntries`
mechanism:

- Each lock scope owns a private segment `CacheMap` that starts empty
and is discarded at release, so a captured navigation structurally
observes only data fetched under the lock — cross-scope shadowing
becomes impossible by construction.
- The map is an explicit capability bound when work is created: a
prefetch task captures its map when scheduled
(`PrefetchTask.segmentCacheMap` — the single place that consults lock
state), a locked navigation inherits its driving task's map, and
everything else — unlocked navigations, hydration, refreshes,
traversals, server actions and patches — binds to the shared map. Reads
and response writes receive the map explicitly, so a request that
straddles a scope boundary still writes into the map its entries live
in.

In production builds without the testing API this compiles down to the
previous single-map behavior.

Includes the failing test from #96692 (thanks @samselikoff), hardened to
use the retry-based panel-reopen helper the sibling tests use.

## Verification

- `pnpm test-dev-turbo
test/development/app-dir/instant-navs-devtools/instant-navs-devtools.test.ts`
(32/32, includes the new regression test)
- `pnpm test-dev-webpack
test/development/app-dir/instant-navs-devtools/instant-navs-devtools.test.ts
-t "repeat clicks"`
- `pnpm test-dev-turbo
test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts`
- `pnpm test-start-turbo
test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts`
- `pnpm test-start-turbo
test/e2e/app-dir/segment-cache/basic/segment-cache-basic.test.ts`
(production paths unregressed)

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarSam Selikoff <sam.selikoff@gmail.com>
parent 6bee42b2
...@@ -9,6 +9,7 @@ import { createInitialCacheNodeForHydration } from './ppr-navigations' ...@@ -9,6 +9,7 @@ import { createInitialCacheNodeForHydration } from './ppr-navigations'
import { import {
resolveStaleAt, resolveStaleAt,
processRuntimePrefetchStream, processRuntimePrefetchStream,
segmentCacheMap,
writeDynamicRenderResponseIntoCache, writeDynamicRenderResponseIntoCache,
writePrerenderResponseIntoCache, writePrerenderResponseIntoCache,
} from '../segment-cache/cache' } from '../segment-cache/cache'
...@@ -155,7 +156,8 @@ export function createInitialRouterState({ ...@@ -155,7 +156,8 @@ export function createInitialRouterState({
staleAt, staleAt,
initialTree, initialTree,
initialRenderedSearch, initialRenderedSearch,
true // isResponsePartial true, // isResponsePartial
segmentCacheMap // hydration writes are bound to the shared map
) )
}) })
.catch(() => { .catch(() => {
...@@ -181,7 +183,8 @@ export function createInitialRouterState({ ...@@ -181,7 +183,8 @@ export function createInitialRouterState({
staleAt, staleAt,
initialTree, initialTree,
initialRenderedSearch, initialRenderedSearch,
false // isResponsePartial false, // isResponsePartial
segmentCacheMap // hydration writes are bound to the shared map
) )
}) })
.catch(() => { .catch(() => {
...@@ -219,7 +222,8 @@ export function createInitialRouterState({ ...@@ -219,7 +222,8 @@ export function createInitialRouterState({
processed.rootVaryParamsIterable, processed.rootVaryParamsIterable,
processed.staleAt, processed.staleAt,
processed.navigationSeed, processed.navigationSeed,
null null,
segmentCacheMap // hydration writes are bound to the shared map
) )
} }
}) })
......
...@@ -25,6 +25,8 @@ import { ...@@ -25,6 +25,8 @@ import {
type NavigationSeed, type NavigationSeed,
} from '../segment-cache/decode-server-response' } from '../segment-cache/decode-server-response'
import { import {
segmentCacheMap,
type SegmentCacheEntry,
type RouteTree, type RouteTree,
type RSCSegmentData, type RSCSegmentData,
type RefreshState, type RefreshState,
...@@ -45,6 +47,7 @@ import { discoverKnownRoute } from '../segment-cache/optimistic-routes' ...@@ -45,6 +47,7 @@ import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants' import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { urlSearchParamsToParsedUrlQuery } from '../../route-params' import { urlSearchParamsToParsedUrlQuery } from '../../route-params'
import type { NormalizedSearch } from '../segment-cache/cache-key' import type { NormalizedSearch } from '../segment-cache/cache-key'
import type { CacheMap } from '../segment-cache/cache-map'
import { import {
getRenderedSearchFromVaryPath, getRenderedSearchFromVaryPath,
type PageVaryPath, type PageVaryPath,
...@@ -178,6 +181,8 @@ export function createInitialCacheNodeForHydration( ...@@ -178,6 +181,8 @@ export function createInitialCacheNodeForHydration(
seedDynamicStaleAt, seedDynamicStaleAt,
false, false,
accumulation, accumulation,
// Hydration is bound to the shared map.
segmentCacheMap,
restrictToShell restrictToShell
) )
return task return task
...@@ -225,6 +230,9 @@ export function startPPRNavigation( ...@@ -225,6 +230,9 @@ export function startPPRNavigation(
seedDynamicStaleAt: number, seedDynamicStaleAt: number,
isSamePageNavigation: boolean, isSamePageNavigation: boolean,
accumulation: NavigationRequestAccumulation, accumulation: NavigationRequestAccumulation,
// The segment cache map this navigation is bound to: a locked navigation's
// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell // Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock. // entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean restrictToShell: boolean
...@@ -250,6 +258,7 @@ export function startPPRNavigation( ...@@ -250,6 +258,7 @@ export function startPPRNavigation(
oldRootRefreshState, oldRootRefreshState,
parentRefreshState, parentRefreshState,
accumulation, accumulation,
map,
restrictToShell restrictToShell
) )
} }
...@@ -269,6 +278,7 @@ function updateCacheNodeOnNavigation( ...@@ -269,6 +278,7 @@ function updateCacheNodeOnNavigation(
oldRootRefreshState: RefreshState, oldRootRefreshState: RefreshState,
parentRefreshState: RefreshState | null, parentRefreshState: RefreshState | null,
accumulation: NavigationRequestAccumulation, accumulation: NavigationRequestAccumulation,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell // Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock. // entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean restrictToShell: boolean
...@@ -331,6 +341,7 @@ function updateCacheNodeOnNavigation( ...@@ -331,6 +341,7 @@ function updateCacheNodeOnNavigation(
seedDynamicStaleAt, seedDynamicStaleAt,
parentNeedsDynamicRequest, parentNeedsDynamicRequest,
accumulation, accumulation,
map,
restrictToShell restrictToShell
) )
} }
...@@ -401,6 +412,7 @@ function updateCacheNodeOnNavigation( ...@@ -401,6 +412,7 @@ function updateCacheNodeOnNavigation(
oldCacheNode !== undefined oldCacheNode !== undefined
? oldCacheNode.bfcacheId ? oldCacheNode.bfcacheId
: generateBFCacheId(freshness), : generateBFCacheId(freshness),
map,
restrictToShell restrictToShell
) )
newCacheNode = result.cacheNode newCacheNode = result.cacheNode
...@@ -542,6 +554,7 @@ function updateCacheNodeOnNavigation( ...@@ -542,6 +554,7 @@ function updateCacheNodeOnNavigation(
oldRootRefreshState, oldRootRefreshState,
refreshState, refreshState,
accumulation, accumulation,
map,
restrictToShell restrictToShell
) )
...@@ -654,6 +667,7 @@ function createCacheNodeOnNavigation( ...@@ -654,6 +667,7 @@ function createCacheNodeOnNavigation(
seedDynamicStaleAt: number, seedDynamicStaleAt: number,
parentNeedsDynamicRequest: boolean, parentNeedsDynamicRequest: boolean,
accumulation: NavigationRequestAccumulation, accumulation: NavigationRequestAccumulation,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell // Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock. // entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean restrictToShell: boolean
...@@ -685,6 +699,7 @@ function createCacheNodeOnNavigation( ...@@ -685,6 +699,7 @@ function createCacheNodeOnNavigation(
// This segment was not part of the previous route, so mint a fresh // This segment was not part of the previous route, so mint a fresh
// bfcacheId. // bfcacheId.
generateBFCacheId(freshness), generateBFCacheId(freshness),
map,
restrictToShell restrictToShell
) )
const newCacheNode = result.cacheNode const newCacheNode = result.cacheNode
...@@ -719,6 +734,7 @@ function createCacheNodeOnNavigation( ...@@ -719,6 +734,7 @@ function createCacheNodeOnNavigation(
seedDynamicStaleAt, seedDynamicStaleAt,
parentNeedsDynamicRequest || needsDynamicRequest, parentNeedsDynamicRequest || needsDynamicRequest,
accumulation, accumulation,
map,
restrictToShell restrictToShell
) )
...@@ -947,6 +963,7 @@ function createCacheNodeForSegment( ...@@ -947,6 +963,7 @@ function createCacheNodeForSegment(
freshness: FreshnessPolicy, freshness: FreshnessPolicy,
dynamicStaleAt: number, dynamicStaleAt: number,
bfcacheId: number, bfcacheId: number,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell // Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock. // entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean restrictToShell: boolean
...@@ -1097,6 +1114,7 @@ function createCacheNodeForSegment( ...@@ -1097,6 +1114,7 @@ function createCacheNodeForSegment(
const segmentEntry = readSegmentCacheEntryForNavigation( const segmentEntry = readSegmentCacheEntryForNavigation(
now, now,
map,
tree.varyPath, tree.varyPath,
restrictToShell restrictToShell
) )
...@@ -1204,6 +1222,7 @@ function createCacheNodeForSegment( ...@@ -1204,6 +1222,7 @@ function createCacheNodeForSegment(
if (metadataVaryPath !== null) { if (metadataVaryPath !== null) {
const metadataEntry = readSegmentCacheEntryForNavigation( const metadataEntry = readSegmentCacheEntryForNavigation(
now, now,
map,
metadataVaryPath, metadataVaryPath,
restrictToShell restrictToShell
) )
...@@ -1413,6 +1432,9 @@ export function spawnDynamicRequests( ...@@ -1413,6 +1432,9 @@ export function spawnDynamicRequests(
// transition hasn't committed yet. // transition hasn't committed yet.
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null, navigationLock: NavigationLock | null,
// The segment cache map this navigation is bound to. See `segmentCacheMap`
// in cache.ts.
map: CacheMap<SegmentCacheEntry>,
signal: AbortSignal | undefined signal: AbortSignal | undefined
): void { ): void {
const dynamicRequestTree = task.dynamicRequestTree const dynamicRequestTree = task.dynamicRequestTree
...@@ -1439,6 +1461,7 @@ export function spawnDynamicRequests( ...@@ -1439,6 +1461,7 @@ export function spawnDynamicRequests(
freshnessPolicy, freshnessPolicy,
routeCacheEntry, routeCacheEntry,
navigationLock, navigationLock,
map,
signal signal
) )
...@@ -1493,6 +1516,7 @@ export function spawnDynamicRequests( ...@@ -1493,6 +1516,7 @@ export function spawnDynamicRequests(
freshnessPolicy, freshnessPolicy,
routeCacheEntry, routeCacheEntry,
navigationLock, navigationLock,
map,
signal signal
) )
) )
...@@ -1771,6 +1795,7 @@ async function fetchMissingDynamicData( ...@@ -1771,6 +1795,7 @@ async function fetchMissingDynamicData(
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
routeCacheEntry: FulfilledRouteCacheEntry | null, routeCacheEntry: FulfilledRouteCacheEntry | null,
navigationLock: NavigationLock | null, navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>,
signal: AbortSignal | undefined signal: AbortSignal | undefined
): Promise<{ ): Promise<{
exitStatus: NavigationTaskExitStatus exitStatus: NavigationTaskExitStatus
...@@ -1834,7 +1859,8 @@ async function fetchMissingDynamicData( ...@@ -1834,7 +1859,8 @@ async function fetchMissingDynamicData(
staleAt, staleAt,
dynamicRequestTree, dynamicRequestTree,
result.renderedSearch, result.renderedSearch,
isResponsePartial isResponsePartial,
map
) )
}) })
.catch(() => { .catch(() => {
...@@ -1861,7 +1887,8 @@ async function fetchMissingDynamicData( ...@@ -1861,7 +1887,8 @@ async function fetchMissingDynamicData(
processed.rootVaryParamsIterable, processed.rootVaryParamsIterable,
processed.staleAt, processed.staleAt,
processed.navigationSeed, processed.navigationSeed,
null null,
map
) )
} }
}) })
......
...@@ -6,7 +6,10 @@ import type { ...@@ -6,7 +6,10 @@ import type {
import { ScrollBehavior } from '../router-reducer-types' import { ScrollBehavior } from '../router-reducer-types'
import { navigateToKnownRoute } from '../../segment-cache/navigation' import { navigateToKnownRoute } from '../../segment-cache/navigation'
import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response' import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'
import { invalidateSegmentCacheEntries } from '../../segment-cache/cache' import {
invalidateSegmentCacheEntries,
segmentCacheMap,
} from '../../segment-cache/cache'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree' import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations' import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
import { import {
...@@ -98,6 +101,8 @@ export function refreshDynamicData( ...@@ -98,6 +101,8 @@ export function refreshDynamicData(
scrollBehavior, scrollBehavior,
navigateType, navigateType,
navigationLock, navigationLock,
// A refresh is bound to the shared map.
segmentCacheMap,
null, null,
// Refresh navigations don't use route prediction, so there's no route // 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 // cache entry to mark as having a dynamic rewrite on mismatch. If a
......
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
completeTraverseNavigation, completeTraverseNavigation,
} from '../../segment-cache/navigation' } from '../../segment-cache/navigation'
import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response' import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'
import { segmentCacheMap } from '../../segment-cache/cache'
import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache' import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'
export function restoreReducer( export function restoreReducer(
...@@ -72,6 +73,8 @@ export function restoreReducer( ...@@ -72,6 +73,8 @@ export function restoreReducer(
restoreSeed.dynamicStaleAt, restoreSeed.dynamicStaleAt,
false, false,
accumulation, accumulation,
// A history-traversal restore is bound to the shared map.
segmentCacheMap,
// A history-traversal restore never restricts to the shell. // A history-traversal restore never restricts to the shell.
false false
) )
...@@ -96,6 +99,8 @@ export function restoreReducer( ...@@ -96,6 +99,8 @@ export function restoreReducer(
// dynamic requests ungated (null lock) so they render from cache or fetch // dynamic requests ungated (null lock) so they render from cache or fetch
// normally rather than being withheld behind the lock. // normally rather than being withheld behind the lock.
null, null,
// A history-traversal restore is bound to the shared map.
segmentCacheMap,
// Not an HMR refresh, so there's no request generation to cancel. // Not an HMR refresh, so there's no request generation to cancel.
undefined undefined
) )
......
...@@ -44,7 +44,10 @@ import { ...@@ -44,7 +44,10 @@ import {
extractInfoFromServerReferenceId, extractInfoFromServerReferenceId,
omitUnusedArgs, omitUnusedArgs,
} from '../../../../shared/lib/server-reference-info' } from '../../../../shared/lib/server-reference-info'
import { invalidateEntirePrefetchCache } from '../../segment-cache/cache' import {
invalidateEntirePrefetchCache,
segmentCacheMap,
} from '../../segment-cache/cache'
import { startRevalidationCooldown } from '../../segment-cache/scheduler' import { startRevalidationCooldown } from '../../segment-cache/scheduler'
import { getDeploymentId } from '../../../../shared/lib/deployment-id' import { getDeploymentId } from '../../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../../navigation-build-id' import { getNavigationBuildId } from '../../../navigation-build-id'
...@@ -516,6 +519,8 @@ export function serverActionReducer( ...@@ -516,6 +519,8 @@ export function serverActionReducer(
scrollBehavior, scrollBehavior,
navigateType, navigateType,
navigationLock, navigationLock,
// A server-action redirect navigation is bound to the shared map.
segmentCacheMap,
null, null,
// Server action redirects don't use route prediction - we already // Server action redirects don't use route prediction - we already
// have the route tree from the server response. If a mismatch occurs // have the route tree from the server response. If a mismatch occurs
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
completeHardNavigation, completeHardNavigation,
navigateToKnownRoute, navigateToKnownRoute,
} from '../../segment-cache/navigation' } from '../../segment-cache/navigation'
import { segmentCacheMap } from '../../segment-cache/cache'
import { refreshReducer } from './refresh-reducer' import { refreshReducer } from './refresh-reducer'
import { getCurrentNavigationLock } from '../ppr-navigations' import { getCurrentNavigationLock } from '../ppr-navigations'
...@@ -65,6 +66,8 @@ export function serverPatchReducer( ...@@ -65,6 +66,8 @@ export function serverPatchReducer(
scrollBehavior, scrollBehavior,
navigateType, navigateType,
navigationLock, navigationLock,
// A server-patch retry navigation is bound to the shared map.
segmentCacheMap,
null, null,
// Server patch (retry) navigations don't use route prediction. This is // Server patch (retry) navigations don't use route prediction. This is
// typically a retry after a previous mismatch, so the route was already // typically a retry after a previous mismatch, so the route was already
......
...@@ -13,12 +13,10 @@ ...@@ -13,12 +13,10 @@
*/ */
import type { FlightRouterState } from '../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { PendingSegmentCacheEntry, SegmentCacheEntry } from './cache' import type { SegmentCacheEntry } from './cache'
import type { CacheMap } from './cache-map'
import type { FetchStrategy } from './types' import type { FetchStrategy } from './types'
import type { import type { NavigationLockPrefetch } from './navigation-testing-lock'
NavigationLockPrefetch,
NavigationLockState,
} from './navigation-testing-lock'
export type { export type {
NavigationLockPrefetch, NavigationLockPrefetch,
...@@ -33,16 +31,11 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null { ...@@ -33,16 +31,11 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
return null return null
} }
export function recordNavigationLockOwnedEntry( export function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {
_entry: SegmentCacheEntry return null
): void {} }
export function trackNavigationLockPrefetchEntry(
_prefetch: NavigationLockPrefetch,
_entry: PendingSegmentCacheEntry
): void {}
export function finishNavigationLockPrefetchSpawning( export function resolveNavigationLockPrefetch(
_prefetch: NavigationLockPrefetch _prefetch: NavigationLockPrefetch
): void {} ): void {}
...@@ -57,10 +50,6 @@ export function isNavigationLocked(): boolean { ...@@ -57,10 +50,6 @@ export function isNavigationLocked(): boolean {
return false return false
} }
export function getCurrentNavigationLock(): NavigationLockState | null {
return null
}
export function beginLockedNavigation(): Promise<void> | null { export function beginLockedNavigation(): Promise<void> | null {
return null return null
} }
......
...@@ -26,11 +26,8 @@ import { ...@@ -26,11 +26,8 @@ import {
import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers' import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'
import { refreshOnInstantNavigationUnlock } from '../use-action-queue' import { refreshOnInstantNavigationUnlock } from '../use-action-queue'
import { subtreeHasSpeculativePrefetch } from './scheduler' import { subtreeHasSpeculativePrefetch } from './scheduler'
import { import type { SegmentCacheEntry } from './cache'
waitForSegmentCacheEntry, import { createCacheMap, type CacheMap } from './cache-map'
type PendingSegmentCacheEntry,
type SegmentCacheEntry,
} from './cache'
import type { FetchStrategy } from './types' import type { FetchStrategy } from './types'
type InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa' type InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'
...@@ -100,22 +97,18 @@ function writeCookieValue(value: InstantCookie): void { ...@@ -100,22 +97,18 @@ function writeCookieValue(value: InstantCookie): void {
/** /**
* The "wait for the locked navigation's prefetch to fulfill" state for a single * The "wait for the locked navigation's prefetch to fulfill" state for a single
* locked navigation. `promise` resolves once that prefetch has spawned every * locked navigation. `promise` resolves when the driving prefetch task
* request and all of them have fulfilled, so the navigation reads present data * completes — which the scheduler only allows after a full pass has observed
* rather than a still-in-flight entry. Owned by the prefetch task (one per * every segment response it cares about (see `blockTaskOnPendingResponse` in
* navigation, so successive navigations in a scope resolve independently) and * scheduler.ts) — so the navigation reads present data rather than a
* also tracked in `NavigationLockState.activePrefetches` so the lock can * still-in-flight entry. Owned by the prefetch task (one per navigation, so
* force-resolve any that are still pending when it's released. * successive navigations in a scope resolve independently) and also tracked
* * in `NavigationLockState.activePrefetches` so the lock can force-resolve any
* `pendingCount` holds one reference for the scheduler while it is still * that are still pending when it's released.
* spawning, plus one per in-flight entry; `promise` resolves when it drains to
* 0. `trackedEntries` dedupes entry registration.
*/ */
export type NavigationLockPrefetch = { export type NavigationLockPrefetch = {
promise: Promise<void> promise: Promise<void>
resolve: () => void resolve: () => void
pendingCount: number
trackedEntries: Set<PendingSegmentCacheEntry>
} }
export type NavigationLockState = { export type NavigationLockState = {
...@@ -131,16 +124,19 @@ export type NavigationLockState = { ...@@ -131,16 +124,19 @@ export type NavigationLockState = {
// during a lock scope. // during a lock scope.
fetch: typeof fetch fetch: typeof fetch
// Every prefetch-completion state for this scope that hasn't resolved yet. // Every prefetch-completion state for this scope that hasn't resolved yet.
// A prefetch removes itself when it drains; on release, any still here are // A prefetch removes itself when its driving task completes; on release, any
// force-resolved so no navigation hangs waiting on a prefetch that the scope // still here are force-resolved so no navigation hangs waiting on a prefetch
// ended before it could finish. // that the scope ended before it could finish.
activePrefetches: Set<NavigationLockPrefetch> activePrefetches: Set<NavigationLockPrefetch>
// Every segment entry that was (re)fetched within this lock scope. Navigation // The scope's private segment cache. Prefetch tasks scheduled while the
// reads are restricted to these, so each instant() navigation observes only // lock is held are bound to this map instead of the shared one, and a
// data fetched under the lock — a "clean read" — and never matches a stale // locked navigation inherits the map of the task that drives it (see
// entry left in the cache by an earlier navigation or prefetch. See // `segmentCacheMap` in cache.ts). It starts empty, so each instant()
// `readSegmentCacheEntryForNavigation`. // navigation observes only data fetched under the lock — a "clean read" —
ownedEntries: Set<SegmentCacheEntry> // and never matches a stale entry left in the shared cache by an earlier
// navigation, prefetch, or scope. Discarded when the lock is released; its
// entries are reclaimed by the LRU under memory pressure.
segmentCacheMap: CacheMap<SegmentCacheEntry>
// The withheld-data gate for the current locked navigation. A locked // The withheld-data gate for the current locked navigation. A locked
// navigation's dynamic write waits on this rather than on the scope-wide // navigation's dynamic write waits on this rather than on the scope-wide
// `released`. Each navigation captures the promise when it begins (via // `released`. Each navigation captures the promise when it begins (via
...@@ -167,12 +163,8 @@ export function getPreLockFetch(): typeof fetch | null { ...@@ -167,12 +163,8 @@ export function getPreLockFetch(): typeof fetch | null {
* Creates the "wait for prefetch to fulfill" state for one locked navigation, * Creates the "wait for prefetch to fulfill" state for one locked navigation,
* registers it on the current lock, and returns it (the caller stores it on the * registers it on the current lock, and returns it (the caller stores it on the
* prefetch task and awaits `.promise`). Returns null if no lock is held. * prefetch task and awaits `.promise`). Returns null if no lock is held.
* * Resolved by the scheduler via `resolveNavigationLockPrefetch` when the
* `pendingCount` starts at 1, representing the scheduler itself while it is * driving prefetch task completes.
* still spawning requests; that reference is released by
* `finishNavigationLockPrefetchSpawning`. Each spawned pending entry adds
* another (see `trackNavigationLockPrefetchEntry`). `promise` resolves when the
* count drains to 0 — i.e. spawning finished and every entry fulfilled.
*/ */
export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null { export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
if (lockState !== null) { if (lockState !== null) {
...@@ -183,8 +175,6 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null { ...@@ -183,8 +175,6 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
const prefetch: NavigationLockPrefetch = { const prefetch: NavigationLockPrefetch = {
promise, promise,
resolve: resolve!, resolve: resolve!,
pendingCount: 1,
trackedEntries: new Set(),
} }
lockState.activePrefetches.add(prefetch) lockState.activePrefetches.add(prefetch)
return prefetch return prefetch
...@@ -193,68 +183,28 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null { ...@@ -193,68 +183,28 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
} }
/** /**
* Records a freshly-created segment entry as owned by the current lock scope, so * Returns the current lock scope's private segment cache map, or null when no
* navigation reads will match it — and only entries created within the scope * lock is held. See `NavigationLockState.segmentCacheMap`.
* (see `NavigationLockState.ownedEntries`). Called from
* `createDetachedSegmentCacheEntry`, the single factory every creation path
* funnels through, so re-keyed entries created during response processing (e.g.
* a runtime prefetch resolving a concrete param) are owned too. No-op when no
* lock is held.
*/ */
export function recordNavigationLockOwnedEntry(entry: SegmentCacheEntry): void { export function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {
if (lockState !== null) { return lockState !== null ? lockState.segmentCacheMap : null
lockState.ownedEntries.add(entry)
}
}
/**
* Called by `upgradeToPendingSegment` whenever the locked-navigation prefetch
* spawns a pending segment entry. Adds the entry to the prefetch's ref count and
* decrements when it fulfills (or rejects — `waitForSegmentCacheEntry` resolves
* to null). Deduped so the same entry never double-counts.
*/
export function trackNavigationLockPrefetchEntry(
prefetch: NavigationLockPrefetch,
entry: PendingSegmentCacheEntry
): void {
if (prefetch.trackedEntries.has(entry)) {
return
}
prefetch.trackedEntries.add(entry)
prefetch.pendingCount++
const onSettled = () => {
prefetch.pendingCount--
settleNavigationLockPrefetchIfDrained(prefetch)
}
// Decrement whether the entry fulfills or its request rejects, so a failed
// segment can't leave the navigation waiting forever.
waitForSegmentCacheEntry(entry).then(onSettled, onSettled)
} }
/** /**
* Called once the scheduler has finished spawning every request for the * Called by the scheduler when the locked-navigation prefetch task completes.
* locked-navigation prefetch, releasing the scheduler's reference from the ref * A task only completes after a full pass observed every segment response it
* count. The prefetch resolves here if every spawned entry already fulfilled. * cares about, so the data the navigation will read has settled by this
* point. Unregisters from the lock (if still held) and resolves. Resolving is
* idempotent, so it's safe even if the lock already force-resolved this on
* release.
*/ */
export function finishNavigationLockPrefetchSpawning( export function resolveNavigationLockPrefetch(
prefetch: NavigationLockPrefetch
): void {
prefetch.pendingCount--
settleNavigationLockPrefetchIfDrained(prefetch)
}
function settleNavigationLockPrefetchIfDrained(
prefetch: NavigationLockPrefetch prefetch: NavigationLockPrefetch
): void { ): void {
if (prefetch.pendingCount === 0) { if (lockState !== null) {
// Unregister from the lock (if still held) and resolve. Resolving is lockState.activePrefetches.delete(prefetch)
// idempotent, so it's safe even if the lock already force-resolved this on
// release.
if (lockState !== null) {
lockState.activePrefetches.delete(prefetch)
}
prefetch.resolve()
} }
prefetch.resolve()
} }
function acquireLock(): void { function acquireLock(): void {
...@@ -274,7 +224,7 @@ function acquireLock(): void { ...@@ -274,7 +224,7 @@ function acquireLock(): void {
resolveReleased: resolveReleased!, resolveReleased: resolveReleased!,
fetch: window.fetch, fetch: window.fetch,
activePrefetches: new Set(), activePrefetches: new Set(),
ownedEntries: new Set(), segmentCacheMap: createCacheMap(),
currentNavigation, currentNavigation,
resolveCurrentNavigation: resolveCurrentNavigation!, resolveCurrentNavigation: resolveCurrentNavigation!,
} }
...@@ -563,10 +513,6 @@ export function isNavigationLocked(): boolean { ...@@ -563,10 +513,6 @@ export function isNavigationLocked(): boolean {
return false return false
} }
export function getCurrentNavigationLock(): NavigationLockState | null {
return lockState
}
/** /**
* Returns the current locked navigation's withheld-data gate — the same * Returns the current locked navigation's withheld-data gate — the same
* immutable promise `beginLockedNavigation` handed that navigation — or null * immutable promise `beginLockedNavigation` handed that navigation — or null
......
...@@ -17,6 +17,8 @@ import { createHrefFromUrl } from '../router-reducer/create-href-from-url' ...@@ -17,6 +17,8 @@ import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants' import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { import {
EntryStatus, EntryStatus,
segmentCacheMap,
type SegmentCacheEntry,
readRouteCacheEntry, readRouteCacheEntry,
deprecated_requestOptimisticRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry,
resolveStaleAt, resolveStaleAt,
...@@ -27,6 +29,7 @@ import { ...@@ -27,6 +29,7 @@ import {
} from './cache' } from './cache'
import { discoverKnownRoute } from './optimistic-routes' import { discoverKnownRoute } from './optimistic-routes'
import { createCacheKey, type NormalizedSearch } from './cache-key' import { createCacheKey, type NormalizedSearch } from './cache-key'
import type { CacheMap } from './cache-map'
import { schedulePrefetchTask } from './scheduler' import { schedulePrefetchTask } from './scheduler'
import { PrefetchPriority, FetchStrategy } from './types' import { PrefetchPriority, FetchStrategy } from './types'
import { getLinkForCurrentNavigation } from '../links' import { getLinkForCurrentNavigation } from '../links'
...@@ -105,7 +108,9 @@ export function navigate( ...@@ -105,7 +108,9 @@ export function navigate(
freshnessPolicy, freshnessPolicy,
scrollBehavior, scrollBehavior,
navigateType, navigateType,
navigationLock navigationLock,
// An unlocked navigation is bound to the shared map.
segmentCacheMap
) )
} }
...@@ -120,7 +125,10 @@ function navigateImpl( ...@@ -120,7 +125,10 @@ function navigateImpl(
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior, scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null navigationLock: NavigationLock | null,
// The segment cache map this navigation is bound to: a locked navigation's
// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.
map: CacheMap<SegmentCacheEntry>
): AppRouterState | Promise<AppRouterState> { ): AppRouterState | Promise<AppRouterState> {
const now = Date.now() const now = Date.now()
const href = url.href const href = url.href
...@@ -142,7 +150,8 @@ function navigateImpl( ...@@ -142,7 +150,8 @@ function navigateImpl(
scrollBehavior, scrollBehavior,
navigateType, navigateType,
route, route,
navigationLock navigationLock,
map
) )
} }
...@@ -179,7 +188,8 @@ function navigateImpl( ...@@ -179,7 +188,8 @@ function navigateImpl(
scrollBehavior, scrollBehavior,
navigateType, navigateType,
optimisticRoute, optimisticRoute,
navigationLock navigationLock,
map
) )
} }
} }
...@@ -202,7 +212,8 @@ function navigateImpl( ...@@ -202,7 +212,8 @@ function navigateImpl(
freshnessPolicy, freshnessPolicy,
scrollBehavior, scrollBehavior,
navigateType, navigateType,
navigationLock navigationLock,
map
).catch(() => { ).catch(() => {
// If the navigation fails, return the current state // If the navigation fails, return the current state
return state return state
...@@ -224,6 +235,9 @@ export function navigateToKnownRoute( ...@@ -224,6 +235,9 @@ export function navigateToKnownRoute(
scrollBehavior: ScrollBehavior, scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null, navigationLock: NavigationLock | null,
// The segment cache map this navigation is bound to: a locked navigation's
// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.
map: CacheMap<SegmentCacheEntry>,
debugInfo: Array<unknown> | null, debugInfo: Array<unknown> | null,
// The route cache entry used for this navigation, if it came from route // 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 // prediction. Passed through so it can be marked as having a dynamic rewrite
...@@ -337,6 +351,7 @@ export function navigateToKnownRoute( ...@@ -337,6 +351,7 @@ export function navigateToKnownRoute(
navigationSeed.dynamicStaleAt, navigationSeed.dynamicStaleAt,
isSamePageNavigation, isSamePageNavigation,
accumulation, accumulation,
map,
restrictToShell restrictToShell
) )
if (task !== null) { if (task !== null) {
...@@ -350,6 +365,7 @@ export function navigateToKnownRoute( ...@@ -350,6 +365,7 @@ export function navigateToKnownRoute(
routeCacheEntry, routeCacheEntry,
navigateType, navigateType,
navigationLock, navigationLock,
map,
signal signal
) )
} }
...@@ -384,7 +400,8 @@ function navigateUsingPrefetchedRouteTree( ...@@ -384,7 +400,8 @@ function navigateUsingPrefetchedRouteTree(
scrollBehavior: ScrollBehavior, scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
navigationLock: NavigationLock | null navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>
): AppRouterState { ): AppRouterState {
const routeTree = route.tree const routeTree = route.tree
const canonicalUrl = route.canonicalUrl + url.hash const canonicalUrl = route.canonicalUrl + url.hash
...@@ -413,6 +430,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -413,6 +430,7 @@ function navigateUsingPrefetchedRouteTree(
scrollBehavior, scrollBehavior,
navigateType, navigateType,
navigationLock, navigationLock,
map,
null, null,
route, route,
// Not an HMR refresh, so there's no request generation to cancel. // Not an HMR refresh, so there's no request generation to cancel.
...@@ -444,7 +462,8 @@ async function navigateToUnknownRoute( ...@@ -444,7 +462,8 @@ async function navigateToUnknownRoute(
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior, scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>
): Promise<AppRouterState> { ): Promise<AppRouterState> {
// Runs when a navigation happens but there's no cached prefetch we can use. // 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 // Don't bother to wait for a prefetch response; go straight to a full
...@@ -559,7 +578,8 @@ async function navigateToUnknownRoute( ...@@ -559,7 +578,8 @@ async function navigateToUnknownRoute(
staleAt, staleAt,
currentFlightRouterState, currentFlightRouterState,
renderedSearch, renderedSearch,
isResponsePartial isResponsePartial,
map
) )
}) })
.catch(() => { .catch(() => {
...@@ -586,7 +606,8 @@ async function navigateToUnknownRoute( ...@@ -586,7 +606,8 @@ async function navigateToUnknownRoute(
processed.rootVaryParamsIterable, processed.rootVaryParamsIterable,
processed.staleAt, processed.staleAt,
processed.navigationSeed, processed.navigationSeed,
null null,
map
) )
} }
}) })
...@@ -627,6 +648,7 @@ async function navigateToUnknownRoute( ...@@ -627,6 +648,7 @@ async function navigateToUnknownRoute(
scrollBehavior, scrollBehavior,
navigateType, navigateType,
navigationLock, navigationLock,
map,
debugInfo, debugInfo,
// Unknown route navigations don't use route prediction - the route tree // Unknown route navigations don't use route prediction - the route tree
// came directly from the server. If a mismatch occurs during dynamic data // came directly from the server. If a mismatch occurs during dynamic data
...@@ -870,13 +892,13 @@ async function ensurePrefetchThenNavigate( ...@@ -870,13 +892,13 @@ async function ensurePrefetchThenNavigate(
// Create this navigation's "wait for prefetch to fulfill" state and schedule // Create this navigation's "wait for prefetch to fulfill" state and schedule
// the prefetch as a locked-navigation prefetch. The prefetch's promise // the prefetch as a locked-navigation prefetch. The prefetch's promise
// resolves once it has spawned every request and all of them have fulfilled, // resolves when the task completes — after every segment response the task
// so the navigation below reads present data rather than a still-in-flight // cares about has settled — so the navigation below reads present data
// entry. // rather than a still-in-flight entry.
const { beginNavigationLockPrefetch } = const { beginNavigationLockPrefetch } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock') require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const navigationLockPrefetch = beginNavigationLockPrefetch() const navigationLockPrefetch = beginNavigationLockPrefetch()
schedulePrefetchTask( const prefetchTask = schedulePrefetchTask(
cacheKey, cacheKey,
currentFlightRouterState, currentFlightRouterState,
fetchStrategy, fetchStrategy,
...@@ -889,7 +911,10 @@ async function ensurePrefetchThenNavigate( ...@@ -889,7 +911,10 @@ async function ensurePrefetchThenNavigate(
} }
// Prefetch is complete. Proceed with the normal navigation flow, which // Prefetch is complete. Proceed with the normal navigation flow, which
// will now find the route in the cache. // will now find the route in the cache. The navigation inherits the map of
// the prefetch task that drives it: the task was scheduled inside the lock
// scope, so this is the scope's private map, and the navigation reads only
// data fetched under the lock.
const result = await navigateImpl( const result = await navigateImpl(
state, state,
url, url,
...@@ -901,7 +926,8 @@ async function ensurePrefetchThenNavigate( ...@@ -901,7 +926,8 @@ async function ensurePrefetchThenNavigate(
freshnessPolicy, freshnessPolicy,
scrollBehavior, scrollBehavior,
navigateType, navigateType,
navigationLock navigationLock,
prefetchTask.segmentCacheMap
) )
// Only transition to captured-SPA once the navigation is known to be an SPA. // Only transition to captured-SPA once the navigation is known to be an SPA.
......
...@@ -69,10 +69,11 @@ describe('instant-nav-panel', () => { ...@@ -69,10 +69,11 @@ describe('instant-nav-panel', () => {
}) })
} }
async function clickLink(browser: Playwright, href: string) { async function clickLink(browser: Playwright, href: string, id?: string) {
await browser.eval((page) => { const selector = id ? `#${id}` : `[href="${href}"]`
document.querySelector<HTMLAnchorElement>(`[href="${page}"]`)!.click() await browser.eval((selector) => {
}, href) document.querySelector<HTMLAnchorElement>(selector)!.click()
}, selector)
} }
function getInstantNavPanel(browser: Playwright) { function getInstantNavPanel(browser: Playwright) {
...@@ -698,18 +699,54 @@ describe('instant-nav-panel', () => { ...@@ -698,18 +699,54 @@ describe('instant-nav-panel', () => {
await openInstantNavPanel(browser) await openInstantNavPanel(browser)
await clickStartCapturing(browser) await clickStartCapturing(browser)
// The prefetch link shares its href with #link-to-target, so select it await clickLink(
// by id rather than by href. browser,
await browser.eval(() => { '/target-page/my-post?search=foo',
document 'link-to-target-prefetch'
.querySelector<HTMLAnchorElement>('#link-to-target-prefetch')! )
.click()
})
await expectSpaPanel(browser) await expectSpaPanel(browser)
await expectTargetPageSpaShellWithRuntimeData(browser) await expectTargetPageSpaShellWithRuntimeData(browser)
}) })
it('works for repeat clicks to links with prefetch={true} (regression)', async () => {
const browser = await openHomeWithTargetPageWarmup()
// 1. Enable the Nav Inspector and click the link
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
await clickLink(
browser,
'/target-page/my-post?search=foo',
'link-to-target-prefetch'
)
await expectSpaPanel(browser)
// 2. Close the Nav Inspector and navigate home
await closePanelViaHeader(browser)
await waitForPanelRouterTransition()
await waitForInstantModeCookieAbsent(browser)
await clickLink(browser, '/')
await browser.waitForElementByCss('[data-testid="home-title"]')
await waitForAppHydration(browser)
// 3. Enable the inspector and click the link again. This used to hang
// in a pending state while firing an infinite loop of prefetch
// requests: the previous capture's runtime-prefetch entries survive in
// the segment cache at concrete vary paths, shadowing the entries the
// new capture's prefetch creates at the more generic shell vary paths,
// so every scheduler pass discarded and refetched forever.
await reopenInstantNavPanelFromMenu(browser)
await expectIdlePanel(browser)
await clickStartCapturing(browser)
await clickLink(
browser,
'/target-page/my-post?search=foo',
'link-to-target-prefetch'
)
await expectSpaPanel(browser)
})
it('should restart capture and return to awaiting navigation after resuming from SPA state', async () => { it('should restart capture and return to awaiting navigation after resuming from SPA state', async () => {
const browser = await openHomeWithTargetPageWarmup() const browser = await openHomeWithTargetPageWarmup()
......
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