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'
import {
resolveStaleAt,
processRuntimePrefetchStream,
segmentCacheMap,
writeDynamicRenderResponseIntoCache,
writePrerenderResponseIntoCache,
} from '../segment-cache/cache'
......@@ -155,7 +156,8 @@ export function createInitialRouterState({
staleAt,
initialTree,
initialRenderedSearch,
true // isResponsePartial
true, // isResponsePartial
segmentCacheMap // hydration writes are bound to the shared map
)
})
.catch(() => {
......@@ -181,7 +183,8 @@ export function createInitialRouterState({
staleAt,
initialTree,
initialRenderedSearch,
false // isResponsePartial
false, // isResponsePartial
segmentCacheMap // hydration writes are bound to the shared map
)
})
.catch(() => {
......@@ -219,7 +222,8 @@ export function createInitialRouterState({
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
segmentCacheMap // hydration writes are bound to the shared map
)
}
})
......
......@@ -25,6 +25,8 @@ import {
type NavigationSeed,
} from '../segment-cache/decode-server-response'
import {
segmentCacheMap,
type SegmentCacheEntry,
type RouteTree,
type RSCSegmentData,
type RefreshState,
......@@ -45,6 +47,7 @@ import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { urlSearchParamsToParsedUrlQuery } from '../../route-params'
import type { NormalizedSearch } from '../segment-cache/cache-key'
import type { CacheMap } from '../segment-cache/cache-map'
import {
getRenderedSearchFromVaryPath,
type PageVaryPath,
......@@ -178,6 +181,8 @@ export function createInitialCacheNodeForHydration(
seedDynamicStaleAt,
false,
accumulation,
// Hydration is bound to the shared map.
segmentCacheMap,
restrictToShell
)
return task
......@@ -225,6 +230,9 @@ export function startPPRNavigation(
seedDynamicStaleAt: number,
isSamePageNavigation: boolean,
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
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
......@@ -250,6 +258,7 @@ export function startPPRNavigation(
oldRootRefreshState,
parentRefreshState,
accumulation,
map,
restrictToShell
)
}
......@@ -269,6 +278,7 @@ function updateCacheNodeOnNavigation(
oldRootRefreshState: RefreshState,
parentRefreshState: RefreshState | null,
accumulation: NavigationRequestAccumulation,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
......@@ -331,6 +341,7 @@ function updateCacheNodeOnNavigation(
seedDynamicStaleAt,
parentNeedsDynamicRequest,
accumulation,
map,
restrictToShell
)
}
......@@ -401,6 +412,7 @@ function updateCacheNodeOnNavigation(
oldCacheNode !== undefined
? oldCacheNode.bfcacheId
: generateBFCacheId(freshness),
map,
restrictToShell
)
newCacheNode = result.cacheNode
......@@ -542,6 +554,7 @@ function updateCacheNodeOnNavigation(
oldRootRefreshState,
refreshState,
accumulation,
map,
restrictToShell
)
......@@ -654,6 +667,7 @@ function createCacheNodeOnNavigation(
seedDynamicStaleAt: number,
parentNeedsDynamicRequest: boolean,
accumulation: NavigationRequestAccumulation,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
......@@ -685,6 +699,7 @@ function createCacheNodeOnNavigation(
// This segment was not part of the previous route, so mint a fresh
// bfcacheId.
generateBFCacheId(freshness),
map,
restrictToShell
)
const newCacheNode = result.cacheNode
......@@ -719,6 +734,7 @@ function createCacheNodeOnNavigation(
seedDynamicStaleAt,
parentNeedsDynamicRequest || needsDynamicRequest,
accumulation,
map,
restrictToShell
)
......@@ -947,6 +963,7 @@ function createCacheNodeForSegment(
freshness: FreshnessPolicy,
dynamicStaleAt: number,
bfcacheId: number,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
......@@ -1097,6 +1114,7 @@ function createCacheNodeForSegment(
const segmentEntry = readSegmentCacheEntryForNavigation(
now,
map,
tree.varyPath,
restrictToShell
)
......@@ -1204,6 +1222,7 @@ function createCacheNodeForSegment(
if (metadataVaryPath !== null) {
const metadataEntry = readSegmentCacheEntryForNavigation(
now,
map,
metadataVaryPath,
restrictToShell
)
......@@ -1413,6 +1432,9 @@ export function spawnDynamicRequests(
// transition hasn't committed yet.
navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null,
// The segment cache map this navigation is bound to. See `segmentCacheMap`
// in cache.ts.
map: CacheMap<SegmentCacheEntry>,
signal: AbortSignal | undefined
): void {
const dynamicRequestTree = task.dynamicRequestTree
......@@ -1439,6 +1461,7 @@ export function spawnDynamicRequests(
freshnessPolicy,
routeCacheEntry,
navigationLock,
map,
signal
)
......@@ -1493,6 +1516,7 @@ export function spawnDynamicRequests(
freshnessPolicy,
routeCacheEntry,
navigationLock,
map,
signal
)
)
......@@ -1771,6 +1795,7 @@ async function fetchMissingDynamicData(
freshnessPolicy: FreshnessPolicy,
routeCacheEntry: FulfilledRouteCacheEntry | null,
navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>,
signal: AbortSignal | undefined
): Promise<{
exitStatus: NavigationTaskExitStatus
......@@ -1834,7 +1859,8 @@ async function fetchMissingDynamicData(
staleAt,
dynamicRequestTree,
result.renderedSearch,
isResponsePartial
isResponsePartial,
map
)
})
.catch(() => {
......@@ -1861,7 +1887,8 @@ async function fetchMissingDynamicData(
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
map
)
}
})
......
......@@ -6,7 +6,10 @@ import type {
import { ScrollBehavior } from '../router-reducer-types'
import { navigateToKnownRoute } from '../../segment-cache/navigation'
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 { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
import {
......@@ -98,6 +101,8 @@ export function refreshDynamicData(
scrollBehavior,
navigateType,
navigationLock,
// A refresh is bound to the shared map.
segmentCacheMap,
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
......
......@@ -17,6 +17,7 @@ import {
completeTraverseNavigation,
} from '../../segment-cache/navigation'
import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'
import { segmentCacheMap } from '../../segment-cache/cache'
import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'
export function restoreReducer(
......@@ -72,6 +73,8 @@ export function restoreReducer(
restoreSeed.dynamicStaleAt,
false,
accumulation,
// A history-traversal restore is bound to the shared map.
segmentCacheMap,
// A history-traversal restore never restricts to the shell.
false
)
......@@ -96,6 +99,8 @@ export function restoreReducer(
// dynamic requests ungated (null lock) so they render from cache or fetch
// normally rather than being withheld behind the lock.
null,
// A history-traversal restore is bound to the shared map.
segmentCacheMap,
// Not an HMR refresh, so there's no request generation to cancel.
undefined
)
......
......@@ -44,7 +44,10 @@ import {
extractInfoFromServerReferenceId,
omitUnusedArgs,
} 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 { getDeploymentId } from '../../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../../navigation-build-id'
......@@ -516,6 +519,8 @@ export function serverActionReducer(
scrollBehavior,
navigateType,
navigationLock,
// A server-action redirect navigation is bound to the shared map.
segmentCacheMap,
null,
// Server action redirects don't use route prediction - we already
// have the route tree from the server response. If a mismatch occurs
......
......@@ -10,6 +10,7 @@ import {
completeHardNavigation,
navigateToKnownRoute,
} from '../../segment-cache/navigation'
import { segmentCacheMap } from '../../segment-cache/cache'
import { refreshReducer } from './refresh-reducer'
import { getCurrentNavigationLock } from '../ppr-navigations'
......@@ -65,6 +66,8 @@ export function serverPatchReducer(
scrollBehavior,
navigateType,
navigationLock,
// A server-patch retry navigation is bound to the shared map.
segmentCacheMap,
null,
// Server patch (retry) navigations don't use route prediction. This is
// typically a retry after a previous mismatch, so the route was already
......
......@@ -37,7 +37,6 @@ import {
type PrefetchTask,
type PrefetchSubtaskResult,
} from './scheduler'
import type { NavigationLockPrefetch } from './navigation-testing-lock'
import {
type RouteVaryPath,
type SegmentVaryPath,
......@@ -383,8 +382,32 @@ export const MetadataOnlyRequestTree: FlightRouterState = [
'metadata-only',
]
let routeCacheMap: CacheMap<RouteCacheEntry> = createCacheMap()
let segmentCacheMap: CacheMap<SegmentCacheEntry> = createCacheMap()
const routeCacheMap: CacheMap<RouteCacheEntry> = createCacheMap()
/**
* The shared segment cache map. Segment cache functions do not access this
* ambiently — every unit of work is bound to a map when it is created, and
* reads and writes receive that map explicitly:
*
* - A prefetch task captures its map when it is scheduled
* (`PrefetchTask.segmentCacheMap` in scheduler.ts). Almost always this one;
* a task scheduled while the Instant Navigation Testing lock is held gets
* the lock scope's private map instead (which starts empty and is discarded
* at release), so a locked navigation observes only data fetched under the
* lock — never a stale entry left in the shared cache by an earlier
* navigation, prefetch, or scope.
* - A locked navigation inherits the map of the prefetch task that drives it
* (see `ensurePrefetchThenNavigate` in navigation.ts).
* - Everything else — unlocked navigations, hydration, and router work that
* is not a captured navigation (refreshes, history-traversal restores,
* server-action redirects, server patches) — uses this shared map
* directly, even while a lock is held.
*
* Binding at creation means a task queued before a lock scope begins never
* leaks entries into the scope's map (or reads out of it), and a scope task's
* late responses never leak into the shared map.
*/
export const segmentCacheMap: CacheMap<SegmentCacheEntry> = createCacheMap()
// All invalidation listeners for the whole cache are tracked in single set.
// Since we don't yet support tag or path-based invalidation, there's no point
......@@ -545,27 +568,12 @@ export function readRouteCacheEntry(
return null
}
export function readSegmentCacheEntry(
now: number,
varyPath: SegmentVaryPath
): SegmentCacheEntry | null {
const isRevalidation = false
return getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
varyPath,
isRevalidation,
false
)
}
/**
* Like `readSegmentCacheEntry`, but prefers a Fulfilled entry over a
* more-specific Pending or Rejected entry. Use this during a navigation, where
* a less-specific shell entry (e.g. params -> Fallback) should be rendered
* immediately rather than blocking on a more-specific Pending entry that may
* still be in-flight.
* Reads the cache entry for a segment during a navigation. Unlike a plain
* lookup, prefers a Fulfilled entry over a more-specific Pending or Rejected
* entry: during a navigation, a less-specific shell entry (e.g. params ->
* Fallback) should be rendered immediately rather than blocking on a
* more-specific Pending entry that may still be in-flight.
*
* Performs up to two lookups:
* 1. An `onlyMatchFulfilled` lookup that walks past Pending/Rejected entries
......@@ -576,60 +584,21 @@ export function readSegmentCacheEntry(
*/
export function readSegmentCacheEntryForNavigation(
now: number,
// The map the navigation is bound to: a locked navigation's driving-task
// map, or the shared map otherwise.
map: CacheMap<SegmentCacheEntry>,
varyPath: SegmentVaryPath,
restrictToShell: boolean = false
): SegmentCacheEntry | null {
const isRevalidation = false
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { getCurrentNavigationLock } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const lock = getCurrentNavigationLock()
if (lock !== null) {
// Instant Navigation Testing API
//
// Modify the lookup logic to simulate the behavior that we would expect
// to mostly realistically happen in a production environment with a
// warm prefetch cache.
// If restrictToShell is true, it means we're navigating to a link that
// 1) has Partial Prefetching enabled, and 2) does not have a prefetch
// prop set. We should only allow the shell to render, not anything that
// varies on concrete route params.
const lookupVaryPath = restrictToShell
? getShellSegmentVaryPath(varyPath)
: varyPath
// To prevent the test navigation from being "polluted" by earlier
// prefetches, we'll also only match entries that were created during
// the current lock scope. This is tracked by the `ownedEntries` set.
const ownedEntries = lock.ownedEntries
// Besides that, the rest of the logic is the same as production.
const fulfilled = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
lookupVaryPath,
isRevalidation,
true
)
if (fulfilled !== null && ownedEntries.has(fulfilled)) {
return fulfilled
}
const entry = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
lookupVaryPath,
isRevalidation,
false
)
if (entry !== null && ownedEntries.has(entry)) {
return entry
}
return null
}
let lookupVaryPath = varyPath
if (process.env.__NEXT_EXPOSE_TESTING_API && restrictToShell) {
// Instant Navigation Testing API: we're navigating to a link that 1) has
// Partial Prefetching enabled, and 2) does not have a prefetch prop set.
// Only the shell may render, not anything that varies on concrete route
// params.
lookupVaryPath = getShellSegmentVaryPath(varyPath)
}
// Prefer a Fulfilled entry (e.g. a cached shell) over a more-specific
......@@ -638,8 +607,8 @@ export function readSegmentCacheEntryForNavigation(
const fulfilled = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
varyPath,
map,
lookupVaryPath,
isRevalidation,
true
)
......@@ -649,8 +618,8 @@ export function readSegmentCacheEntryForNavigation(
return getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
varyPath,
map,
lookupVaryPath,
isRevalidation,
false
)
......@@ -658,13 +627,14 @@ export function readSegmentCacheEntryForNavigation(
function readRevalidatingSegmentCacheEntry(
now: number,
map: CacheMap<SegmentCacheEntry>,
varyPath: SegmentVaryPath
): SegmentCacheEntry | null {
const isRevalidation = true
return getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
map,
varyPath,
isRevalidation,
false
......@@ -929,72 +899,49 @@ function deprecated_createOptimisticRouteTree(
*/
export function readOrCreateSegmentCacheEntry(
now: number,
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`,
// captured when the task was scheduled).
map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>,
// Non-null when this read is part of a locked navigation's prefetch (Instant
// Navigation Testing API only; always null in production). See below.
navigationLockPrefetch: NavigationLockPrefetch | null
tree: RouteTree<RSCSegmentData | null>
): SegmentCacheEntry {
const existingEntry = readSegmentCacheEntry(now, tree.varyPath)
const existingEntry = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
map,
tree.varyPath,
false,
false
)
if (existingEntry !== null) {
if (
process.env.__NEXT_EXPOSE_TESTING_API &&
navigationLockPrefetch !== null
) {
// Locked navigation: ignore entries that predate the lock so each
// navigation reads only data (re)fetched within the lock scope — a
// "clean read." But an entry we already created within this scope is
// reused like normal; otherwise the prefetch would discard the entry it
// just fetched on every scheduler pass and refetch forever. See
// navigation-testing-lock.ts.
const { getCurrentNavigationLock, trackNavigationLockPrefetchEntry } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const lock = getCurrentNavigationLock()
if (lock !== null && lock.ownedEntries.has(existingEntry)) {
// Track-on-reuse: when this navigation reuses an in-flight (Pending)
// entry it didn't spawn — e.g. a runtime-prefetch (PPRRuntime) upgrade
// started by an earlier prefetch in the scope — register it on this
// navigation's prefetch so the navigation awaits it before reading.
// Without this, the navigation can read while that upgrade is still
// pending and fall back to a less-specific fulfilled entry (the shell),
// never surfacing the resolved value.
//
// This is content-neutral: the entry is found by the concrete vary-path
// (not by strategy), so it's whatever the navigation would read at this
// key anyway. Tracking only controls whether we await it now versus
// suspend on it during the render, so it can't surface an entry the
// navigation wouldn't otherwise read. Tracking is deduped, so it's a
// no-op if we already spawned/tracked this entry.
if (existingEntry.status === EntryStatus.Pending) {
trackNavigationLockPrefetchEntry(
navigationLockPrefetch,
existingEntry
)
}
return existingEntry
}
} else {
return existingEntry
}
return existingEntry
}
// No reusable entry, or a locked navigation discarding a pre-lock entry.
// Create a pending entry and add it to the cache. The stale time is set to a
// default value; the actual stale time will be set when the entry is
// fulfilled with data from the server response.
return insertEmptySegmentCacheEntry(now, map, fetchStrategy, tree)
}
/**
* Creates an empty segment cache entry and inserts it into the cache, keyed
* at the vary path a request made with the given fetch strategy is stored
* under. The stale time is set to a default value; the actual stale time will
* be set when the entry is fulfilled with data from the server response.
*/
function insertEmptySegmentCacheEntry(
now: number,
map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>
): EmptySegmentCacheEntry {
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const pendingEntry = createDetachedSegmentCacheEntry(now)
const emptyEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = false
setInCacheMap(
segmentCacheMap,
varyPathForRequest,
pendingEntry,
isRevalidation
)
return pendingEntry
setInCacheMap(map, varyPathForRequest, emptyEntry, isRevalidation)
return emptyEntry
}
export function readOrCreateRevalidatingSegmentEntry(
now: number,
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`).
map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>
): SegmentCacheEntry {
......@@ -1025,7 +972,11 @@ export function readOrCreateRevalidatingSegmentEntry(
// return a less generic entry upon revalidation. For now, though, this isn't
// a concern because the keypath is based solely on the prefetch strategy,
// not on data contained in the response.
const existingEntry = readRevalidatingSegmentCacheEntry(now, tree.varyPath)
const existingEntry = readRevalidatingSegmentCacheEntry(
now,
map,
tree.varyPath
)
if (existingEntry !== null) {
return existingEntry
}
......@@ -1035,17 +986,14 @@ export function readOrCreateRevalidatingSegmentEntry(
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const pendingEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = true
setInCacheMap(
segmentCacheMap,
varyPathForRequest,
pendingEntry,
isRevalidation
)
setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)
return pendingEntry
}
export function overwriteRevalidatingSegmentCacheEntry(
now: number,
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`).
map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>
) {
......@@ -1057,12 +1005,7 @@ export function overwriteRevalidatingSegmentCacheEntry(
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const pendingEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = true
setInCacheMap(
segmentCacheMap,
varyPathForRequest,
pendingEntry,
isRevalidation
)
setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)
return pendingEntry
}
......@@ -1100,6 +1043,12 @@ function isExistingSegmentEntryPreferred(
export function upsertSegmentEntry(
now: number,
// The map the whole upsert (existing-entry read, insert, shadow eviction)
// operates in. Prefetch response-write paths pass the spawning task's map
// (`PrefetchTask.segmentCacheMap`), so a response that lands after a
// testing-lock scope boundary still writes into the map its entries
// live in.
map: CacheMap<SegmentCacheEntry>,
varyPath: SegmentVaryPath,
candidateEntry: SegmentCacheEntry,
// The fully concrete vary path a read for this segment position resolves
......@@ -1123,7 +1072,14 @@ export function upsertSegmentEntry(
return null
}
const existingEntry = readSegmentCacheEntry(now, varyPath)
const existingEntry = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
map,
varyPath,
false,
false
)
if (existingEntry !== null) {
// Don't replace a more specific segment with a less-specific one. A case where this
// might happen is if the existing segment was fetched via
......@@ -1175,10 +1131,10 @@ export function upsertSegmentEntry(
}
const isRevalidation = false
setInCacheMap(segmentCacheMap, varyPath, candidateEntry, isRevalidation)
setInCacheMap(map, varyPath, candidateEntry, isRevalidation)
if (lookupVaryPath !== null) {
evictShadowingSegmentEntries(now, lookupVaryPath, candidateEntry)
evictShadowingSegmentEntries(now, map, lookupVaryPath, candidateEntry)
}
return candidateEntry
......@@ -1217,6 +1173,7 @@ export function upsertSegmentEntry(
*/
function evictShadowingSegmentEntries(
now: number,
map: CacheMap<SegmentCacheEntry>,
lookupVaryPath: SegmentVaryPath,
candidateEntry: SegmentCacheEntry
): void {
......@@ -1230,7 +1187,14 @@ function evictShadowingSegmentEntries(
// beyond any real fallback chain, which is bounded by the vary
// path's length.
for (let i = 0; i < 32; i++) {
const shadowEntry = readSegmentCacheEntry(now, lookupVaryPath)
const shadowEntry = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
map,
lookupVaryPath,
false,
false
)
if (shadowEntry === null || shadowEntry === candidateEntry) {
// The candidate is reachable from the lookup path (or the read missed
// entirely, e.g. because the candidate expired). Done.
......@@ -1282,21 +1246,12 @@ export function createDetachedSegmentCacheEntry(
staleAt,
version: 0,
}
if (process.env.__NEXT_EXPOSE_TESTING_API) {
// Instant Navigation Testing API: mark entries created during a lock scope
// as owned, so locked navigations match only data (re)fetched within the
// scope. No-op when no lock is held (always in production).
const { recordNavigationLockOwnedEntry } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
recordNavigationLockOwnedEntry(emptyEntry)
}
return emptyEntry
}
export function upgradeToPendingSegment(
emptyEntry: EmptySegmentCacheEntry,
fetchStrategy: FetchStrategy,
navigationLockPrefetch: NavigationLockPrefetch | null
fetchStrategy: FetchStrategy
): PendingSegmentCacheEntry {
const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any
pendingEntry.status = EntryStatus.Pending
......@@ -1316,22 +1271,6 @@ export function upgradeToPendingSegment(
// before the data is read on the server.
pendingEntry.version = getCurrentSegmentCacheVersion()
if (
process.env.__NEXT_EXPOSE_TESTING_API &&
// Instant Navigation Testing API only. Non-null when the requesting
// prefetch is driving a locked navigation, in which case the
// freshly-spawned pending entry is tracked against that navigation's
// prefetch state so the navigation waits for it to fulfill before reading
// it. Null at non-scheduler call sites (BFCache fulfillment, response
// processing), which don't spawn an in-flight request to wait on, and
// always in production.
navigationLockPrefetch !== null
) {
const { trackNavigationLockPrefetchEntry } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
trackNavigationLockPrefetchEntry(navigationLockPrefetch, pendingEntry)
}
return pendingEntry
}
......@@ -1365,13 +1304,7 @@ export function attemptToFulfillDynamicSegmentFromBFCache(
return null
}
const pendingSegment = upgradeToPendingSegment(
segment,
FetchStrategy.Full,
// Fulfilled synchronously from the BFCache; nothing for a locked
// navigation to wait on.
null
)
const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full)
const isPartial = false
return fulfillSegmentCacheEntry(
pendingSegment,
......@@ -1394,6 +1327,8 @@ export function attemptToFulfillDynamicSegmentFromBFCache(
*/
export function attemptToUpgradeSegmentFromBFCache(
now: number,
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`).
map: CacheMap<SegmentCacheEntry>,
tree: RouteTree<RSCSegmentData | null>
): FulfilledSegmentCacheEntry | null {
const varyPath = tree.varyPath
......@@ -1406,10 +1341,7 @@ export function attemptToUpgradeSegmentFromBFCache(
}
const pendingSegment = upgradeToPendingSegment(
createDetachedSegmentCacheEntry(now),
FetchStrategy.Full,
// Fulfilled synchronously from the BFCache; nothing for a locked
// navigation to wait on.
null
FetchStrategy.Full
)
const isPartial = false
const newEntry = fulfillSegmentCacheEntry(
......@@ -1427,6 +1359,7 @@ export function attemptToUpgradeSegmentFromBFCache(
)
const upserted = upsertSegmentEntry(
now,
map,
segmentVaryPath,
newEntry,
// The concrete lookup path this BFCache upgrade applies to. (In
......@@ -2031,7 +1964,10 @@ export function convertRouteTreeToFlightRouterState(
export async function fetchRouteOnCacheMiss(
entry: PendingRouteCacheEntry,
key: RouteCacheKey
key: RouteCacheKey,
// The spawning task's `PrefetchTask.segmentCacheMap`, for the legacy
// branch that writes segment data included in the tree response.
map: CacheMap<SegmentCacheEntry>
): Promise<PrefetchSubtaskResult<null> | null> {
// This function is allowed to use async/await because it contains the actual
// fetch that gets issued on a cache miss. Notice it writes the result to the
......@@ -2273,7 +2209,8 @@ export async function fetchRouteOnCacheMiss(
serverData.r ?? null,
pathname,
search,
nextUrl
nextUrl,
map
)
}
......@@ -2399,6 +2336,7 @@ export async function fetchSegmentsOnCacheMiss(
const now = Date.now()
writeSegmentBundleResponseVariants(
task.segmentCacheMap,
serverResponse,
shellResponse,
responseSize,
......@@ -2616,6 +2554,9 @@ async function fetchSegmentsOnCacheMissImpl(
* is a no-op (it only touches Pending entries).
*/
function writeSegmentBundleResponseVariants(
// The map the bundle's entries live in (pinned when the request was
// spawned).
map: CacheMap<SegmentCacheEntry>,
serverResponse: SegmentPrefetchResponse,
shellResponse: SegmentPrefetchResponse | null,
responseSize: number,
......@@ -2629,6 +2570,7 @@ function writeSegmentBundleResponseVariants(
if (fetchStrategy === FetchStrategy.StaticShell) {
if (shellResponse !== serverResponse) {
writeSegmentBundleResponse(
map,
serverResponse,
responseSize,
detachEntriesFromSegmentBundle(segments),
......@@ -2648,6 +2590,7 @@ function writeSegmentBundleResponseVariants(
rejectRemainingSegmentsInBundle(segments, now + 10 * 1000)
} else {
writeSegmentBundleResponse(
map,
shellResponse,
responseSize,
segments,
......@@ -2664,6 +2607,7 @@ function writeSegmentBundleResponseVariants(
}
} else {
writeSegmentBundleResponse(
map,
serverResponse,
responseSize,
segments,
......@@ -2674,6 +2618,7 @@ function writeSegmentBundleResponseVariants(
)
if (shellResponse !== null && shellResponse !== serverResponse) {
writeSegmentBundleResponse(
map,
shellResponse,
responseSize,
detachEntriesFromSegmentBundle(segments),
......@@ -2708,6 +2653,7 @@ function writeSegmentBundleResponseVariants(
* re-issues the same request and upserts the upgraded result here).
*/
function writeSegmentBundleResponse(
map: CacheMap<SegmentCacheEntry>,
serverResponse: SegmentPrefetchResponse,
responseSize: number,
segments: SegmentBundle,
......@@ -2860,6 +2806,7 @@ function writeSegmentBundleResponse(
// complete response already in this slot isn't downgraded.
upsertSegmentEntry(
now,
map,
payloadVaryPath,
fulfilledEntry,
node.tree.varyPath
......@@ -2869,12 +2816,7 @@ function writeSegmentBundleResponse(
// upsert it into this payload's slot.
const detachedEntry = createDetachedSegmentCacheEntry(now)
const fulfilledEntry = fulfillSegmentCacheEntry(
upgradeToPendingSegment(
detachedEntry,
fetchStrategy,
// Response-write path, not a locked-navigation prefetch.
null
),
upgradeToPendingSegment(detachedEntry, fetchStrategy),
data.rsc,
entryStaleAt,
isPartial,
......@@ -2883,6 +2825,7 @@ function writeSegmentBundleResponse(
)
upsertSegmentEntry(
now,
map,
payloadVaryPath,
fulfilledEntry,
node.tree.varyPath
......@@ -3089,6 +3032,7 @@ async function retryUpgradeableFallbackPrefetch(
const { serverResponse, shellResponse, responseSize } = result
const now = Date.now()
writeSegmentBundleResponseVariants(
task.segmentCacheMap,
serverResponse,
shellResponse,
responseSize,
......@@ -3309,7 +3253,8 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
staleAt,
dynamicRequestTree,
renderedSearch,
cacheData.isResponsePartial
cacheData.isResponsePartial,
task.segmentCacheMap
)
} else {
// This is _not_ a Shell prefetch, so the pending entries should be
......@@ -3334,7 +3279,8 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
shellStaleAt,
dynamicRequestTree,
renderedSearch,
isShellStagePartial
isShellStagePartial,
task.segmentCacheMap
)
}
}
......@@ -3386,7 +3332,8 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
rootVaryParamsIterable,
staleAtForSpawnedEntries,
navigationSeed,
spawnedEntries
spawnedEntries,
task.segmentCacheMap
)
// For buffered responses, update LRU sizes now that we know which
......@@ -3438,7 +3385,9 @@ function writeDynamicTreeResponseIntoCache(
rootVaryParamsIterable: VaryParamsIterable | null,
originalPathname: string,
originalSearch: NormalizedSearch,
nextUrl: string | null
nextUrl: string | null,
// The spawning task's `PrefetchTask.segmentCacheMap`.
map: CacheMap<SegmentCacheEntry>
): void {
const renderedSearch = getRenderedSearch(response)
......@@ -3528,7 +3477,8 @@ function writeDynamicTreeResponseIntoCache(
rootVaryParamsIterable,
getStaleAtFromHeader(now, response),
navigationSeed,
null
null,
map
)
}
......@@ -3561,7 +3511,13 @@ export function writeDynamicRenderResponseIntoCache(
rootVaryParamsIterable: VaryParamsIterable | null,
staleAt: number,
navigationSeed: NavigationSeed,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,
// The map the work that spawned this response's request is bound to: the
// spawning task's `PrefetchTask.segmentCacheMap` for prefetches, the
// navigation's map for navigation-side writes. Binding the write to the
// requesting work means a response that lands after a testing-lock scope
// boundary still writes into the map its entries live in.
map: CacheMap<SegmentCacheEntry>
): Array<FulfilledSegmentCacheEntry> | null {
if (buildId && buildId !== getNavigationBuildId()) {
// The server build does not match the client. Treat as a 404. During
......@@ -3583,6 +3539,7 @@ export function writeDynamicRenderResponseIntoCache(
// the cache.
writeSeedDataIntoCache(
now,
map,
fetchStrategy,
routeTree,
staleAt,
......@@ -3611,6 +3568,7 @@ export function writeDynamicRenderResponseIntoCache(
fulfillEntrySpawnedByRuntimePrefetch(
now,
map,
fetchStrategy,
head,
isHeadPartial,
......@@ -3642,6 +3600,7 @@ export function writeDynamicRenderResponseIntoCache(
function writeSeedDataIntoCache(
now: number,
map: CacheMap<SegmentCacheEntry>,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPR
......@@ -3677,6 +3636,7 @@ function writeSeedDataIntoCache(
const varyParams = readVaryParams(data.varyParams, rootVaryParamsIterable)
fulfillEntrySpawnedByRuntimePrefetch(
now,
map,
fetchStrategy,
rsc,
isPartial,
......@@ -3697,6 +3657,7 @@ function writeSeedDataIntoCache(
for (const childTree of slots.values()) {
writeSeedDataIntoCache(
now,
map,
fetchStrategy,
childTree,
staleAt,
......@@ -3710,6 +3671,7 @@ function writeSeedDataIntoCache(
function fulfillEntrySpawnedByRuntimePrefetch(
now: number,
map: CacheMap<SegmentCacheEntry>,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPR
......@@ -3791,12 +3753,7 @@ function fulfillEntrySpawnedByRuntimePrefetch(
: null
if (canonicalVaryPath !== null) {
const isRevalidation = false
setInCacheMap(
segmentCacheMap,
canonicalVaryPath,
fulfilledEntry,
isRevalidation
)
setInCacheMap(map, canonicalVaryPath, fulfilledEntry, isRevalidation)
// The re-key moved the entry to a more generic path (and, for a spawned
// revalidation, vacated its Revalidation slot). A stale settled entry
// at a more specific path — e.g. the partial entry that prompted the
......@@ -3804,23 +3761,31 @@ function fulfillEntrySpawnedByRuntimePrefetch(
// causing the scheduler to keep re-reading the stale entry and respawn
// the revalidation forever. Evict it so the fulfilled entry is
// reachable. See evictShadowingSegmentEntries.
evictShadowingSegmentEntries(now, tree.varyPath, fulfilledEntry)
evictShadowingSegmentEntries(now, map, tree.varyPath, fulfilledEntry)
}
} else {
// There's no matching entry. Attempt to create a new one. This is a
// response-write path, not a locked-navigation prefetch.
const possiblyNewEntry = readOrCreateSegmentCacheEntry(
// There's no matching entry. Attempt to create a new one.
let possiblyNewEntry: SegmentCacheEntry | null = getFromCacheMap(
now,
fetchStrategy,
tree,
null
getCurrentSegmentCacheVersion(),
map,
tree.varyPath,
false,
false
)
if (possiblyNewEntry === null) {
possiblyNewEntry = insertEmptySegmentCacheEntry(
now,
map,
fetchStrategy,
tree
)
}
if (possiblyNewEntry.status === EntryStatus.Empty) {
// Confirmed this is a new entry. We can fulfill it.
const newEntry = possiblyNewEntry
const fulfilledEntry = fulfillSegmentCacheEntry(
// Response-write path, not a locked-navigation prefetch.
upgradeToPendingSegment(newEntry, fetchStrategy, null),
upgradeToPendingSegment(newEntry, fetchStrategy),
rsc,
staleAt,
isPartial,
......@@ -3830,18 +3795,13 @@ function fulfillEntrySpawnedByRuntimePrefetch(
)
if (fulfilledVaryPath !== null) {
const isRevalidation = false
setInCacheMap(
segmentCacheMap,
fulfilledVaryPath,
fulfilledEntry,
isRevalidation
)
setInCacheMap(map, fulfilledVaryPath, fulfilledEntry, isRevalidation)
// Same as the owned-entry re-key above. Usually the entry really is
// new — the read a moment ago returned nothing at the concrete lookup
// path, so nothing can shadow it and this is a no-op — but this
// branch also claims a pre-existing Empty entry, and re-keying that
// away can expose a stale settled entry at an intermediate path.
evictShadowingSegmentEntries(now, tree.varyPath, fulfilledEntry)
evictShadowingSegmentEntries(now, map, tree.varyPath, fulfilledEntry)
}
} else {
// There was already an entry in the cache. But we may be able to
......@@ -3849,9 +3809,7 @@ function fulfillEntrySpawnedByRuntimePrefetch(
const newEntry = fulfillSegmentCacheEntry(
upgradeToPendingSegment(
createDetachedSegmentCacheEntry(now),
fetchStrategy,
// Response-write path, not a locked-navigation prefetch.
null
fetchStrategy
),
rsc,
staleAt,
......@@ -3868,7 +3826,7 @@ function fulfillEntrySpawnedByRuntimePrefetch(
// a more generic path, any stale settled entry at a more specific path
// that would shadow it is evicted (the upsert handles this; the other
// branches above call evictShadowingSegmentEntries themselves).
upsertSegmentEntry(now, varyPath, newEntry, tree.varyPath)
upsertSegmentEntry(now, map, varyPath, newEntry, tree.varyPath)
}
}
}
......@@ -4153,7 +4111,10 @@ export function writePrerenderResponseIntoCache(
staleAt: number,
baseTree: FlightRouterState,
renderedSearch: string,
isResponsePartial: boolean
isResponsePartial: boolean,
// The map the work that spawned this response's request is bound to. See
// writeDynamicRenderResponseIntoCache.
map: CacheMap<SegmentCacheEntry>
): void {
if (transportData === null) {
return
......@@ -4180,7 +4141,8 @@ export function writePrerenderResponseIntoCache(
rootVaryParamsIterable,
staleAt,
navigationSeed,
null // spawnedEntries — no pre-created entries; will create or upsert
null, // spawnedEntries — no pre-created entries; will create or upsert
map
)
}
......
......@@ -13,12 +13,10 @@
*/
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 {
NavigationLockPrefetch,
NavigationLockState,
} from './navigation-testing-lock'
import type { NavigationLockPrefetch } from './navigation-testing-lock'
export type {
NavigationLockPrefetch,
......@@ -33,16 +31,11 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
return null
}
export function recordNavigationLockOwnedEntry(
_entry: SegmentCacheEntry
): void {}
export function trackNavigationLockPrefetchEntry(
_prefetch: NavigationLockPrefetch,
_entry: PendingSegmentCacheEntry
): void {}
export function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {
return null
}
export function finishNavigationLockPrefetchSpawning(
export function resolveNavigationLockPrefetch(
_prefetch: NavigationLockPrefetch
): void {}
......@@ -57,10 +50,6 @@ export function isNavigationLocked(): boolean {
return false
}
export function getCurrentNavigationLock(): NavigationLockState | null {
return null
}
export function beginLockedNavigation(): Promise<void> | null {
return null
}
......
......@@ -26,11 +26,8 @@ import {
import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'
import { refreshOnInstantNavigationUnlock } from '../use-action-queue'
import { subtreeHasSpeculativePrefetch } from './scheduler'
import {
waitForSegmentCacheEntry,
type PendingSegmentCacheEntry,
type SegmentCacheEntry,
} from './cache'
import type { SegmentCacheEntry } from './cache'
import { createCacheMap, type CacheMap } from './cache-map'
import type { FetchStrategy } from './types'
type InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'
......@@ -100,22 +97,18 @@ function writeCookieValue(value: InstantCookie): void {
/**
* The "wait for the locked navigation's prefetch to fulfill" state for a single
* locked navigation. `promise` resolves once that prefetch has spawned every
* request and all of them have fulfilled, so the navigation reads present data
* rather than a still-in-flight entry. Owned by the prefetch task (one per
* navigation, so successive navigations in a scope resolve independently) and
* also tracked in `NavigationLockState.activePrefetches` so the lock can
* force-resolve any that are still pending when it's released.
*
* `pendingCount` holds one reference for the scheduler while it is still
* spawning, plus one per in-flight entry; `promise` resolves when it drains to
* 0. `trackedEntries` dedupes entry registration.
* locked navigation. `promise` resolves when the driving prefetch task
* completes — which the scheduler only allows after a full pass has observed
* every segment response it cares about (see `blockTaskOnPendingResponse` in
* scheduler.ts) — so the navigation reads present data rather than a
* still-in-flight entry. Owned by the prefetch task (one per navigation, so
* successive navigations in a scope resolve independently) and also tracked
* in `NavigationLockState.activePrefetches` so the lock can force-resolve any
* that are still pending when it's released.
*/
export type NavigationLockPrefetch = {
promise: Promise<void>
resolve: () => void
pendingCount: number
trackedEntries: Set<PendingSegmentCacheEntry>
}
export type NavigationLockState = {
......@@ -131,16 +124,19 @@ export type NavigationLockState = {
// during a lock scope.
fetch: typeof fetch
// 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
// force-resolved so no navigation hangs waiting on a prefetch that the scope
// ended before it could finish.
// A prefetch removes itself when its driving task completes; on release, any
// still here are force-resolved so no navigation hangs waiting on a prefetch
// that the scope ended before it could finish.
activePrefetches: Set<NavigationLockPrefetch>
// Every segment entry that was (re)fetched within this lock scope. Navigation
// reads are restricted to these, so each instant() navigation observes only
// data fetched under the lock — a "clean read" — and never matches a stale
// entry left in the cache by an earlier navigation or prefetch. See
// `readSegmentCacheEntryForNavigation`.
ownedEntries: Set<SegmentCacheEntry>
// The scope's private segment cache. Prefetch tasks scheduled while the
// lock is held are bound to this map instead of the shared one, and a
// locked navigation inherits the map of the task that drives it (see
// `segmentCacheMap` in cache.ts). It starts empty, so each instant()
// navigation observes only data fetched under the lock — a "clean read" —
// 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
// navigation's dynamic write waits on this rather than on the scope-wide
// `released`. Each navigation captures the promise when it begins (via
......@@ -167,12 +163,8 @@ export function getPreLockFetch(): typeof fetch | null {
* 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
* prefetch task and awaits `.promise`). Returns null if no lock is held.
*
* `pendingCount` starts at 1, representing the scheduler itself while it is
* 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.
* Resolved by the scheduler via `resolveNavigationLockPrefetch` when the
* driving prefetch task completes.
*/
export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
if (lockState !== null) {
......@@ -183,8 +175,6 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
const prefetch: NavigationLockPrefetch = {
promise,
resolve: resolve!,
pendingCount: 1,
trackedEntries: new Set(),
}
lockState.activePrefetches.add(prefetch)
return prefetch
......@@ -193,68 +183,28 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
}
/**
* Records a freshly-created segment entry as owned by the current lock scope, so
* navigation reads will match it — and only entries created within the scope
* (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.
* Returns the current lock scope's private segment cache map, or null when no
* lock is held. See `NavigationLockState.segmentCacheMap`.
*/
export function recordNavigationLockOwnedEntry(entry: SegmentCacheEntry): void {
if (lockState !== 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)
export function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {
return lockState !== null ? lockState.segmentCacheMap : null
}
/**
* Called once the scheduler has finished spawning every request for the
* locked-navigation prefetch, releasing the scheduler's reference from the ref
* count. The prefetch resolves here if every spawned entry already fulfilled.
* Called by the scheduler when the locked-navigation prefetch task completes.
* A task only completes after a full pass observed every segment response it
* 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(
prefetch: NavigationLockPrefetch
): void {
prefetch.pendingCount--
settleNavigationLockPrefetchIfDrained(prefetch)
}
function settleNavigationLockPrefetchIfDrained(
export function resolveNavigationLockPrefetch(
prefetch: NavigationLockPrefetch
): void {
if (prefetch.pendingCount === 0) {
// Unregister from the lock (if still held) and resolve. Resolving is
// idempotent, so it's safe even if the lock already force-resolved this on
// release.
if (lockState !== null) {
lockState.activePrefetches.delete(prefetch)
}
prefetch.resolve()
if (lockState !== null) {
lockState.activePrefetches.delete(prefetch)
}
prefetch.resolve()
}
function acquireLock(): void {
......@@ -274,7 +224,7 @@ function acquireLock(): void {
resolveReleased: resolveReleased!,
fetch: window.fetch,
activePrefetches: new Set(),
ownedEntries: new Set(),
segmentCacheMap: createCacheMap(),
currentNavigation,
resolveCurrentNavigation: resolveCurrentNavigation!,
}
......@@ -563,10 +513,6 @@ export function isNavigationLocked(): boolean {
return false
}
export function getCurrentNavigationLock(): NavigationLockState | null {
return lockState
}
/**
* Returns the current locked navigation's withheld-data gate — the same
* immutable promise `beginLockedNavigation` handed that navigation — or null
......
......@@ -17,6 +17,8 @@ import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import {
EntryStatus,
segmentCacheMap,
type SegmentCacheEntry,
readRouteCacheEntry,
deprecated_requestOptimisticRouteCacheEntry,
resolveStaleAt,
......@@ -27,6 +29,7 @@ import {
} from './cache'
import { discoverKnownRoute } from './optimistic-routes'
import { createCacheKey, type NormalizedSearch } from './cache-key'
import type { CacheMap } from './cache-map'
import { schedulePrefetchTask } from './scheduler'
import { PrefetchPriority, FetchStrategy } from './types'
import { getLinkForCurrentNavigation } from '../links'
......@@ -105,7 +108,9 @@ export function navigate(
freshnessPolicy,
scrollBehavior,
navigateType,
navigationLock
navigationLock,
// An unlocked navigation is bound to the shared map.
segmentCacheMap
)
}
......@@ -120,7 +125,10 @@ function navigateImpl(
freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior,
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> {
const now = Date.now()
const href = url.href
......@@ -142,7 +150,8 @@ function navigateImpl(
scrollBehavior,
navigateType,
route,
navigationLock
navigationLock,
map
)
}
......@@ -179,7 +188,8 @@ function navigateImpl(
scrollBehavior,
navigateType,
optimisticRoute,
navigationLock
navigationLock,
map
)
}
}
......@@ -202,7 +212,8 @@ function navigateImpl(
freshnessPolicy,
scrollBehavior,
navigateType,
navigationLock
navigationLock,
map
).catch(() => {
// If the navigation fails, return the current state
return state
......@@ -224,6 +235,9 @@ export function navigateToKnownRoute(
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
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,
// 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
......@@ -337,6 +351,7 @@ export function navigateToKnownRoute(
navigationSeed.dynamicStaleAt,
isSamePageNavigation,
accumulation,
map,
restrictToShell
)
if (task !== null) {
......@@ -350,6 +365,7 @@ export function navigateToKnownRoute(
routeCacheEntry,
navigateType,
navigationLock,
map,
signal
)
}
......@@ -384,7 +400,8 @@ function navigateUsingPrefetchedRouteTree(
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
route: FulfilledRouteCacheEntry,
navigationLock: NavigationLock | null
navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>
): AppRouterState {
const routeTree = route.tree
const canonicalUrl = route.canonicalUrl + url.hash
......@@ -413,6 +430,7 @@ function navigateUsingPrefetchedRouteTree(
scrollBehavior,
navigateType,
navigationLock,
map,
null,
route,
// Not an HMR refresh, so there's no request generation to cancel.
......@@ -444,7 +462,8 @@ async function navigateToUnknownRoute(
freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null
navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>
): 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
......@@ -559,7 +578,8 @@ async function navigateToUnknownRoute(
staleAt,
currentFlightRouterState,
renderedSearch,
isResponsePartial
isResponsePartial,
map
)
})
.catch(() => {
......@@ -586,7 +606,8 @@ async function navigateToUnknownRoute(
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
map
)
}
})
......@@ -627,6 +648,7 @@ async function navigateToUnknownRoute(
scrollBehavior,
navigateType,
navigationLock,
map,
debugInfo,
// Unknown route navigations don't use route prediction - the route tree
// came directly from the server. If a mismatch occurs during dynamic data
......@@ -870,13 +892,13 @@ async function ensurePrefetchThenNavigate(
// Create this navigation's "wait for prefetch to fulfill" state and schedule
// the prefetch as a locked-navigation prefetch. The prefetch's promise
// resolves once it has spawned every request and all of them have fulfilled,
// so the navigation below reads present data rather than a still-in-flight
// entry.
// resolves when the task completes — after every segment response the task
// cares about has settled — so the navigation below reads present data
// rather than a still-in-flight entry.
const { beginNavigationLockPrefetch } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const navigationLockPrefetch = beginNavigationLockPrefetch()
schedulePrefetchTask(
const prefetchTask = schedulePrefetchTask(
cacheKey,
currentFlightRouterState,
fetchStrategy,
......@@ -889,7 +911,10 @@ async function ensurePrefetchThenNavigate(
}
// 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(
state,
url,
......@@ -901,7 +926,8 @@ async function ensurePrefetchThenNavigate(
freshnessPolicy,
scrollBehavior,
navigateType,
navigationLock
navigationLock,
prefetchTask.segmentCacheMap
)
// Only transition to captured-SPA once the navigation is known to be an SPA.
......
......@@ -39,9 +39,11 @@ import {
PrefetchPriority,
} from './types'
import {
segmentCacheMap,
getCurrentRouteCacheVersion,
getCurrentSegmentCacheVersion,
} from './cache'
import type { CacheMap } from './cache-map'
import type { NavigationLockPrefetch } from './navigation-testing-lock'
import {
addSearchParamsIfPageSegment,
......@@ -81,6 +83,18 @@ export type PrefetchTask = {
routeCacheVersion: number
segmentCacheVersion: number
/**
* The segment cache map this task operates in, captured when the task was
* scheduled. Every segment read the task performs and every write its
* responses perform target this map. Almost always the shared map; a task
* scheduled while the Instant Navigation Testing lock is held gets the
* lock scope's private map instead. Binding the map to the task means
* tasks queued before a lock scope never leak entries into (or read out
* of) the scope's map, and a scope task's late responses never leak into
* the shared map. See `segmentCacheMap` in cache.ts.
*/
segmentCacheMap: CacheMap<SegmentCacheEntry>
/**
* Whether to prefetch dynamic data, in addition to static data. This is
* used by `<Link prefetch={true}>`.
......@@ -193,9 +207,8 @@ export type PrefetchTask = {
/**
* Instant Navigation Testing API only. Non-null when this prefetch task drives
* a locked navigation (the `ensurePrefetchThenNavigate` path). Holds that
* navigation's "wait for prefetch to fulfill" state: each spawned pending entry
* is tracked against it (see `upgradeToPendingSegment`), and the scheduler
* signals it when done spawning. See navigation-testing-lock.ts.
* navigation's "wait for prefetch to fulfill" state, resolved when the task
* completes. See navigation-testing-lock.ts.
*/
_navigationLockPrefetch?: NavigationLockPrefetch | null
}
......@@ -309,12 +322,28 @@ export function schedulePrefetchTask(
onInvalidate: null | (() => void),
navigationLockPrefetch: NavigationLockPrefetch | null
): PrefetchTask {
// Bind the task to the segment cache map that is active right now: the
// shared map, unless the Instant Navigation Testing lock is held, in which
// case the task gets the lock scope's private map. This is the single
// place work is bound to a map based on lock state — everything downstream
// receives the map explicitly. See `segmentCacheMap` in cache.ts.
let taskSegmentCacheMap = segmentCacheMap
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { getNavigationLockSegmentCacheMap } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const lockMap = getNavigationLockSegmentCacheMap()
if (lockMap !== null) {
taskSegmentCacheMap = lockMap
}
}
// Spawn a new prefetch task
const task: PrefetchTask = {
key,
treeAtTimeOfPrefetch,
routeCacheVersion: getCurrentRouteCacheVersion(),
segmentCacheVersion: getCurrentSegmentCacheVersion(),
segmentCacheMap: taskSegmentCacheMap,
priority,
phase: PrefetchPhase.RouteTree,
hasBackgroundWork: false,
......@@ -642,21 +671,15 @@ function processQueueInMicrotask() {
process.env.__NEXT_EXPOSE_TESTING_API &&
task._navigationLockPrefetch != null
) {
// The scheduler has spawned every request for this locked-navigation
// prefetch, so release its "still spawning" reference. The prefetch's
// promise (awaited by `ensurePrefetchThenNavigate`) resolves once the
// count reaches 0 — i.e. every spawned entry has also fulfilled, so
// the navigation reads present data rather than a still-in-flight
// entry. If everything already fulfilled, it resolves synchronously.
//
// TODO: Now that a task only completes after a full pass observes
// every segment response it spawned or found in flight, the
// navigation-testing lock's per-entry ref counting (pendingCount /
// trackNavigationLockPrefetchEntry) is redundant — a single resolve
// fired here would suffice.
const { finishNavigationLockPrefetchSpawning } =
// This locked-navigation prefetch is complete: the final pass
// observed every segment response it cares about, so the data the
// navigation will read has settled. Resolve the prefetch's
// promise (awaited by `ensurePrefetchThenNavigate`) so the
// navigation proceeds against present data rather than a
// still-in-flight entry.
const { resolveNavigationLockPrefetch } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
finishNavigationLockPrefetchSpawning(task._navigationLockPrefetch)
resolveNavigationLockPrefetch(task._navigationLockPrefetch)
// Release at most once per task: a stale registration from an
// earlier pass can re-ping a completed task (see above), so it can
// pass through here again.
......@@ -738,7 +761,11 @@ function pingRoute(
if (background(task)) {
routeWithoutSearch.status = EntryStatus.Pending
spawnPrefetchSubtask(
fetchRouteOnCacheMiss(routeWithoutSearch, keyWithoutSearch)
fetchRouteOnCacheMiss(
routeWithoutSearch,
keyWithoutSearch,
task.segmentCacheMap
)
)
}
break
......@@ -790,7 +817,9 @@ function pingRootRouteTree(
// behavior if PPR is disabled for a route (via the incremental opt-in).
//
// Those cases will be handled here.
spawnPrefetchSubtask(fetchRouteOnCacheMiss(route, task.key))
spawnPrefetchSubtask(
fetchRouteOnCacheMiss(route, task.key, task.segmentCacheMap)
)
// If the request takes longer than a minute, a subsequent request should
// retry instead of waiting for this one. When the response is received,
......@@ -1082,9 +1111,9 @@ function pingStaticHead(
tree: route.metadata,
entry: readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
route.metadata,
task._navigationLockPrefetch ?? null
route.metadata
),
parent: null,
}
......@@ -1672,9 +1701,9 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
const segment = readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
task.fetchStrategy,
tree,
task._navigationLockPrefetch ?? null
tree
)
switch (segment.status) {
case EntryStatus.Empty: {
......@@ -1692,8 +1721,7 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
// Set the fetch strategy to LoadingBoundary to indicate that the server
// might not include it in the pending response. If another route is able
// to issue a per-segment request, we'll do that in the background.
FetchStrategy.LoadingBoundary,
task._navigationLockPrefetch ?? null
FetchStrategy.LoadingBoundary
)
spawnedEntries.set(tree.requestKey, pendingSegment)
// The pass blocks on every request it spawns, not just requests it
......@@ -1825,14 +1853,14 @@ function pingRouteTreeAndIncludeDynamicData(
// entire subtree.
const segment = readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
// Note that `fetchStrategy` might be different from `task.fetchStrategy`,
// and we have to use the former here.
// We can have a task with `FetchStrategy.PPR` where some of its segments are configured to
// always use runtime prefetching (via `export const prefetch`), and those should check for
// entries that include search params.
fetchStrategy,
tree,
task._navigationLockPrefetch ?? null
tree
)
let spawnedSegment: PendingSegmentCacheEntry | null = null
......@@ -1853,11 +1881,7 @@ function pingRouteTreeAndIncludeDynamicData(
}
}
// Include it in the request.
spawnedSegment = upgradeToPendingSegment(
segment,
fetchStrategy,
task._navigationLockPrefetch ?? null
)
spawnedSegment = upgradeToPendingSegment(segment, fetchStrategy)
break
}
case EntryStatus.Fulfilled: {
......@@ -1880,7 +1904,11 @@ function pingRouteTreeAndIncludeDynamicData(
// entry from a previous navigation, prefer that over making a new
// request.
if (fetchStrategy === FetchStrategy.Full) {
const fulfilled = attemptToUpgradeSegmentFromBFCache(now, tree)
const fulfilled = attemptToUpgradeSegmentFromBFCache(
now,
task.segmentCacheMap,
tree
)
if (fulfilled !== null) {
break
}
......@@ -2080,11 +2108,7 @@ function pingSegmentBundle(
}
switch (nodeEntry.status) {
case EntryStatus.Empty:
upgradeToPendingSegment(
nodeEntry,
fetchStrategy,
task._navigationLockPrefetch ?? null
)
upgradeToPendingSegment(nodeEntry, fetchStrategy)
needsFetch = true
// The pass blocks on every request it spawns, not just requests it
// finds already in flight.
......@@ -2104,15 +2128,12 @@ function pingSegmentBundle(
) {
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now,
task.segmentCacheMap,
fetchStrategy,
nodeTree
)
if (revalidatingEntry.status === EntryStatus.Empty) {
upgradeToPendingSegment(
revalidatingEntry,
fetchStrategy,
task._navigationLockPrefetch ?? null
)
upgradeToPendingSegment(revalidatingEntry, fetchStrategy)
node.entry = revalidatingEntry
needsFetch = true
// Block on the revalidation request we just spawned, in
......@@ -2146,15 +2167,12 @@ function pingSegmentBundle(
) {
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now,
task.segmentCacheMap,
fetchStrategy,
nodeTree
)
if (revalidatingEntry.status === EntryStatus.Empty) {
upgradeToPendingSegment(
revalidatingEntry,
fetchStrategy,
task._navigationLockPrefetch ?? null
)
upgradeToPendingSegment(revalidatingEntry, fetchStrategy)
node.entry = revalidatingEntry
needsFetch = true
// Block on the retry revalidation we just spawned, like any
......@@ -2235,15 +2253,12 @@ function pingSegmentBundle(
) {
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now,
task.segmentCacheMap,
fetchStrategy,
nodeTree
)
if (revalidatingEntry.status === EntryStatus.Empty) {
upgradeToPendingSegment(
revalidatingEntry,
fetchStrategy,
task._navigationLockPrefetch ?? null
)
upgradeToPendingSegment(revalidatingEntry, fetchStrategy)
node.entry = revalidatingEntry
needsFetch = true
// The pass blocks on every request it spawns, including
......@@ -2329,15 +2344,24 @@ function accumulateSegmentBundle(
const segment = readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
tree,
task._navigationLockPrefetch ?? null
tree
)
if (
process.env.__NEXT_PREFETCH_INLINING &&
tree.prefetchHints & PrefetchHint.InlinedIntoChild
) {
if (segment.status === EntryStatus.Pending) {
// The chain this entry joins may be dropped before it's ever pinged
// (see the drop sites in pingNewPartOfCacheComponentsTree), and only
// the ping blocks on Pending entries. Register on the in-flight
// response at read time instead, so the pass observes it before the
// phase can complete even if the chain is dropped. When the chain does
// get pinged, the ping's own registration dedupes against this one.
blockTaskOnPendingResponse(task, segment)
}
return {
bundle: { tree, entry: segment, parent: parentBundle },
// No bundle ping happens here, but the node's own entry may already be
......@@ -2364,9 +2388,9 @@ function accumulateSegmentBundle(
tree: route.metadata,
entry: readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
route.metadata,
task._navigationLockPrefetch ?? null
route.metadata
),
parent: parentBundle,
}
......@@ -2445,6 +2469,7 @@ function pingFullSegmentRevalidation(
): PendingSegmentCacheEntry | null {
const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(
now,
task.segmentCacheMap,
fetchStrategy,
tree
)
......@@ -2456,8 +2481,7 @@ function pingFullSegmentRevalidation(
// the server.
const pendingSegment = upgradeToPendingSegment(
revalidatingSegment,
fetchStrategy,
task._navigationLockPrefetch ?? null
fetchStrategy
)
// The upsert is handled by fulfillEntrySpawnedByRuntimePrefetch
// when the dynamic prefetch response is written into the cache.
......@@ -2475,13 +2499,13 @@ function pingFullSegmentRevalidation(
// Reset it and start a new revalidation.
const emptySegment = overwriteRevalidatingSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
tree
)
const pendingSegment = upgradeToPendingSegment(
emptySegment,
fetchStrategy,
task._navigationLockPrefetch ?? null
fetchStrategy
)
// The upsert is handled by fulfillEntrySpawnedByRuntimePrefetch
// when the dynamic prefetch response is written into the cache.
......
......@@ -69,10 +69,11 @@ describe('instant-nav-panel', () => {
})
}
async function clickLink(browser: Playwright, href: string) {
await browser.eval((page) => {
document.querySelector<HTMLAnchorElement>(`[href="${page}"]`)!.click()
}, href)
async function clickLink(browser: Playwright, href: string, id?: string) {
const selector = id ? `#${id}` : `[href="${href}"]`
await browser.eval((selector) => {
document.querySelector<HTMLAnchorElement>(selector)!.click()
}, selector)
}
function getInstantNavPanel(browser: Playwright) {
......@@ -698,18 +699,54 @@ describe('instant-nav-panel', () => {
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
// The prefetch link shares its href with #link-to-target, so select it
// by id rather than by href.
await browser.eval(() => {
document
.querySelector<HTMLAnchorElement>('#link-to-target-prefetch')!
.click()
})
await clickLink(
browser,
'/target-page/my-post?search=foo',
'link-to-target-prefetch'
)
await expectSpaPanel(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 () => {
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