Skip to content

Commit 75548c9

Browse files
acdlitesamselikoff
andauthored
[backport] Fix Nav Inspector request loop on repeat captures (#97326)
Backports #97050 ("Fix Nav Inspector request loop on repeat captures") to `next-16-3`. With the Nav Inspector enabled, clicking a `<Link prefetch={true}>`, closing the inspector, navigating home, re-enabling it, and clicking the same link left the app hung in a pending "Compiling…" state while it fired 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. Because the segment cache resolves lookups by most-specific-match, 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 — so every scheduler pass discarded and refetched forever. Rather than patch the filter, the fix replaces the `ownedEntries` mechanism with a per-scope segment `CacheMap`. Each lock scope owns a private map that starts empty and is discarded at release, so a captured navigation structurally observes only data fetched under the lock. The map is bound to a unit of work when it 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, history-traversal restores, 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, so the non-testing paths are unchanged. ### Verification on this branch Cherry-picked from `5dc3ae1fe7`. Three files conflicted; each was resolved by keeping the release branch's existing code shape and applying only the fix's actual change — threading the segment `CacheMap` through as an explicit parameter. - **`refresh-reducer.ts`** and **`restore-reducer.ts`** — the conflicts were confined to the import block. Canary imports `convertServerPatchToFullTree` from `./segment-cache/decode-server-response`, a module that doesn't exist on this branch; `next-16-3` still imports it from `./segment-cache/navigation`. I kept the release branch's import source and added the new `segmentCacheMap` import alongside it. The function-body changes (passing `segmentCacheMap` as the shared map) applied cleanly, and the `startPPRNavigation`/`spawnDynamicRequests` argument order lines up with this branch's signatures. - **`cache.ts`** — the substantive one. `next-16-3` predates the post-16.3.0 segment-cache refactors, so three areas differ from canary and had to be adapted rather than taken verbatim from the patch: (1) `RouteTree` is still non-generic here (`RouteTree`, not `RouteTree<RSCSegmentData | null>` — this branch has no `RSCSegmentData` and the tree doesn't carry render data), so the three signatures the patch retyped were kept as plain `RouteTree`; (2) `writeSegmentBundleResponse` still has the older `StaticShell`/`else` re-key split guarded by `__NEXT_VARY_PARAMS`, versus canary's single `upsertSegmentEntry` — I kept the release-branch logic and threaded `map` into both of its `upsertSegmentEntry` calls; (3) `writeDynamicRenderResponseIntoCache` and `writeSeedDataIntoCache` still use the `flightDatas` + `CacheNodeSeedData` write model rather than canary's route-tree-carries-data model — I kept the release-branch traversal and threaded `map` into each `writeSeedDataIntoCache` / `fulfillEntrySpawnedByRuntimePrefetch` call. Everything else in `cache.ts` — the `ownedEntries` removal, the `segmentCacheMap` export, `insertEmptySegmentCacheEntry`, and the `map` parameter added to every read/write helper — applied cleanly and is identical to canary. I confirmed no stale references to the removed `ownedEntries` / `readSegmentCacheEntry` / `navigationLockPrefetch`-param APIs remain, and that every call site of the retyped helpers passes a map. The remaining files applied without conflict. `server-patch-reducer.ts`, `navigation-testing-lock.ts`, `navigation-testing-lock.disabled.ts`, and the `instant-navs-devtools` test are byte-identical to canary. `create-initial-router-state.ts`, `ppr-navigations.ts`, `server-action-reducer.ts`, `navigation.ts`, and `scheduler.ts` differ from canary only in pre-existing `next-16-3` divergence (the older transport-data / route-tree models); the fix's own hunks (the `segmentCacheMap` threading) applied to them cleanly. No local typecheck was run — this fresh worktree has no `node_modules` and installing it carries the known corepack/SWC-binary gotchas — so behavioral and type verification is left to CI on this branch, which carries the `instant-navs-devtools` regression test from #96692. **Reviewer, focus here:** the `writeSegmentBundleResponse` resolution in `cache.ts` (area 2 above) is the hunk I'd most like a second pair of eyes on. I preserved this branch's `StaticShell`/`else` re-key branch structure and only inserted the `map` argument into its two `upsertSegmentEntry` calls; please confirm that routing both branches' writes through the task's bound map (rather than the module-level `segmentCacheMap`) is the correct behavior for the older re-key logic. <!-- NEXT_JS_LLM --> Co-authored-by: Sam Selikoff <[email protected]>
1 parent f6bd714 commit 75548c9

12 files changed

Lines changed: 474 additions & 434 deletions

File tree

‎packages/next/src/client/components/router-reducer/create-initial-router-state.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
convertRootFlightRouterStateToRouteTree,
1111
resolveStaleAt,
1212
processRuntimePrefetchStream,
13+
segmentCacheMap,
1314
writeDynamicRenderResponseIntoCache,
1415
writePrerenderResponseIntoCache,
1516
} from '../segment-cache/cache'
@@ -154,7 +155,8 @@ export function createInitialRouterState({
154155
staleAt,
155156
initialTree,
156157
initialRenderedSearch,
157-
true // isResponsePartial
158+
true, // isResponsePartial
159+
segmentCacheMap // hydration writes are bound to the shared map
158160
)
159161
})
160162
.catch(() => {
@@ -181,7 +183,8 @@ export function createInitialRouterState({
181183
staleAt,
182184
initialTree,
183185
initialRenderedSearch,
184-
false // isResponsePartial
186+
false, // isResponsePartial
187+
segmentCacheMap // hydration writes are bound to the shared map
185188
)
186189
})
187190
.catch(() => {
@@ -220,7 +223,8 @@ export function createInitialRouterState({
220223
processed.rootVaryParamsIterable,
221224
processed.staleAt,
222225
processed.navigationSeed,
223-
null
226+
null,
227+
segmentCacheMap // hydration writes are bound to the shared map
224228
)
225229
}
226230
})

‎packages/next/src/client/components/router-reducer/ppr-navigations.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ import {
2626
type NavigationSeed,
2727
} from '../segment-cache/navigation'
2828
import {
29+
segmentCacheMap,
30+
type SegmentCacheEntry,
2931
type RouteTree,
3032
type RefreshState,
3133
type FulfilledRouteCacheEntry,
@@ -45,6 +47,7 @@ import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
4547
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
4648
import { urlSearchParamsToParsedUrlQuery } from '../../route-params'
4749
import type { NormalizedSearch } from '../segment-cache/cache-key'
50+
import type { CacheMap } from '../segment-cache/cache-map'
4851
import {
4952
getRenderedSearchFromVaryPath,
5053
type PageVaryPath,
@@ -180,6 +183,8 @@ export function createInitialCacheNodeForHydration(
180183
seedDynamicStaleAt,
181184
false,
182185
accumulation,
186+
// Hydration is bound to the shared map.
187+
segmentCacheMap,
183188
restrictToShell
184189
)
185190
return task
@@ -228,6 +233,9 @@ export function startPPRNavigation(
228233
seedDynamicStaleAt: number,
229234
isSamePageNavigation: boolean,
230235
accumulation: NavigationRequestAccumulation,
236+
// The segment cache map this navigation is bound to: a locked navigation's
237+
// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.
238+
map: CacheMap<SegmentCacheEntry>,
231239
// Instant Navigation Testing API only — restricts segment reads to shell
232240
// entries. Always false outside the testing API. See navigation-testing-lock.
233241
restrictToShell: boolean
@@ -254,6 +262,7 @@ export function startPPRNavigation(
254262
oldRootRefreshState,
255263
parentRefreshState,
256264
accumulation,
265+
map,
257266
restrictToShell
258267
)
259268
}
@@ -274,6 +283,7 @@ function updateCacheNodeOnNavigation(
274283
oldRootRefreshState: RefreshState,
275284
parentRefreshState: RefreshState | null,
276285
accumulation: NavigationRequestAccumulation,
286+
map: CacheMap<SegmentCacheEntry>,
277287
// Instant Navigation Testing API only — restricts segment reads to shell
278288
// entries. Always false outside the testing API. See navigation-testing-lock.
279289
restrictToShell: boolean
@@ -337,6 +347,7 @@ function updateCacheNodeOnNavigation(
337347
seedDynamicStaleAt,
338348
parentNeedsDynamicRequest,
339349
accumulation,
350+
map,
340351
restrictToShell
341352
)
342353
}
@@ -407,6 +418,7 @@ function updateCacheNodeOnNavigation(
407418
oldCacheNode !== undefined
408419
? oldCacheNode.bfcacheId
409420
: generateBFCacheId(freshness),
421+
map,
410422
restrictToShell
411423
)
412424
newCacheNode = result.cacheNode
@@ -551,6 +563,7 @@ function updateCacheNodeOnNavigation(
551563
oldRootRefreshState,
552564
refreshState,
553565
accumulation,
566+
map,
554567
restrictToShell
555568
)
556569

@@ -664,6 +677,7 @@ function createCacheNodeOnNavigation(
664677
seedDynamicStaleAt: number,
665678
parentNeedsDynamicRequest: boolean,
666679
accumulation: NavigationRequestAccumulation,
680+
map: CacheMap<SegmentCacheEntry>,
667681
// Instant Navigation Testing API only — restricts segment reads to shell
668682
// entries. Always false outside the testing API. See navigation-testing-lock.
669683
restrictToShell: boolean
@@ -695,6 +709,7 @@ function createCacheNodeOnNavigation(
695709
// This segment was not part of the previous route, so mint a fresh
696710
// bfcacheId.
697711
generateBFCacheId(freshness),
712+
map,
698713
restrictToShell
699714
)
700715
const newCacheNode = result.cacheNode
@@ -733,6 +748,7 @@ function createCacheNodeOnNavigation(
733748
seedDynamicStaleAt,
734749
parentNeedsDynamicRequest || needsDynamicRequest,
735750
accumulation,
751+
map,
736752
restrictToShell
737753
)
738754

@@ -959,6 +975,7 @@ function createCacheNodeForSegment(
959975
freshness: FreshnessPolicy,
960976
dynamicStaleAt: number,
961977
bfcacheId: number,
978+
map: CacheMap<SegmentCacheEntry>,
962979
// Instant Navigation Testing API only — restricts segment reads to shell
963980
// entries. Always false outside the testing API. See navigation-testing-lock.
964981
restrictToShell: boolean
@@ -1109,6 +1126,7 @@ function createCacheNodeForSegment(
11091126

11101127
const segmentEntry = readSegmentCacheEntryForNavigation(
11111128
now,
1129+
map,
11121130
tree.varyPath,
11131131
restrictToShell
11141132
)
@@ -1216,6 +1234,7 @@ function createCacheNodeForSegment(
12161234
if (metadataVaryPath !== null) {
12171235
const metadataEntry = readSegmentCacheEntryForNavigation(
12181236
now,
1237+
map,
12191238
metadataVaryPath,
12201239
restrictToShell
12211240
)
@@ -1425,6 +1444,9 @@ export function spawnDynamicRequests(
14251444
// transition hasn't committed yet.
14261445
navigateType: 'push' | 'replace',
14271446
navigationLock: NavigationLock | null,
1447+
// The segment cache map this navigation is bound to. See `segmentCacheMap`
1448+
// in cache.ts.
1449+
map: CacheMap<SegmentCacheEntry>,
14281450
signal: AbortSignal | undefined
14291451
): void {
14301452
const dynamicRequestTree = task.dynamicRequestTree
@@ -1451,6 +1473,7 @@ export function spawnDynamicRequests(
14511473
freshnessPolicy,
14521474
routeCacheEntry,
14531475
navigationLock,
1476+
map,
14541477
signal
14551478
)
14561479

@@ -1505,6 +1528,7 @@ export function spawnDynamicRequests(
15051528
freshnessPolicy,
15061529
routeCacheEntry,
15071530
navigationLock,
1531+
map,
15081532
signal
15091533
)
15101534
)
@@ -1783,6 +1807,7 @@ async function fetchMissingDynamicData(
17831807
freshnessPolicy: FreshnessPolicy,
17841808
routeCacheEntry: FulfilledRouteCacheEntry | null,
17851809
navigationLock: NavigationLock | null,
1810+
map: CacheMap<SegmentCacheEntry>,
17861811
signal: AbortSignal | undefined
17871812
): Promise<{
17881813
exitStatus: NavigationTaskExitStatus
@@ -1847,7 +1872,8 @@ async function fetchMissingDynamicData(
18471872
staleAt,
18481873
dynamicRequestTree,
18491874
result.renderedSearch,
1850-
isResponsePartial
1875+
isResponsePartial,
1876+
map
18511877
)
18521878
})
18531879
.catch(() => {
@@ -1875,7 +1901,8 @@ async function fetchMissingDynamicData(
18751901
processed.rootVaryParamsIterable,
18761902
processed.staleAt,
18771903
processed.navigationSeed,
1878-
null
1904+
null,
1905+
map
18791906
)
18801907
}
18811908
})

‎packages/next/src/client/components/router-reducer/reducers/refresh-reducer.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ import {
88
convertServerPatchToFullTree,
99
navigateToKnownRoute,
1010
} from '../../segment-cache/navigation'
11-
import { invalidateSegmentCacheEntries } from '../../segment-cache/cache'
11+
import {
12+
invalidateSegmentCacheEntries,
13+
segmentCacheMap,
14+
} from '../../segment-cache/cache'
1215
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
1316
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
1417
import {
@@ -100,6 +103,8 @@ export function refreshDynamicData(
100103
scrollBehavior,
101104
navigateType,
102105
navigationLock,
106+
// A refresh is bound to the shared map.
107+
segmentCacheMap,
103108
null,
104109
// Refresh navigations don't use route prediction, so there's no route
105110
// cache entry to mark as having a dynamic rewrite on mismatch. If a

‎packages/next/src/client/components/router-reducer/reducers/restore-reducer.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
completeTraverseNavigation,
1818
convertServerPatchToFullTree,
1919
} from '../../segment-cache/navigation'
20+
import { segmentCacheMap } from '../../segment-cache/cache'
2021
import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'
2122

2223
export function restoreReducer(
@@ -73,6 +74,8 @@ export function restoreReducer(
7374
restoreSeed.dynamicStaleAt,
7475
false,
7576
accumulation,
77+
// A history-traversal restore is bound to the shared map.
78+
segmentCacheMap,
7679
// A history-traversal restore never restricts to the shell.
7780
false
7881
)
@@ -97,6 +100,8 @@ export function restoreReducer(
97100
// dynamic requests ungated (null lock) so they render from cache or fetch
98101
// normally rather than being withheld behind the lock.
99102
null,
103+
// A history-traversal restore is bound to the shared map.
104+
segmentCacheMap,
100105
// Not an HMR refresh, so there's no request generation to cancel.
101106
undefined
102107
)

‎packages/next/src/client/components/router-reducer/reducers/server-action-reducer.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,10 @@ import {
4747
extractInfoFromServerReferenceId,
4848
omitUnusedArgs,
4949
} from '../../../../shared/lib/server-reference-info'
50-
import { invalidateEntirePrefetchCache } from '../../segment-cache/cache'
50+
import {
51+
invalidateEntirePrefetchCache,
52+
segmentCacheMap,
53+
} from '../../segment-cache/cache'
5154
import { startRevalidationCooldown } from '../../segment-cache/scheduler'
5255
import { getDeploymentId } from '../../../../shared/lib/deployment-id'
5356
import { getNavigationBuildId } from '../../../navigation-build-id'
@@ -513,6 +516,8 @@ export function serverActionReducer(
513516
scrollBehavior,
514517
navigateType,
515518
navigationLock,
519+
// A server-action redirect navigation is bound to the shared map.
520+
segmentCacheMap,
516521
null,
517522
// Server action redirects don't use route prediction - we already
518523
// have the route tree from the server response. If a mismatch occurs

‎packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
completeHardNavigation,
1111
navigateToKnownRoute,
1212
} from '../../segment-cache/navigation'
13+
import { segmentCacheMap } from '../../segment-cache/cache'
1314
import { refreshReducer } from './refresh-reducer'
1415
import { getCurrentNavigationLock } from '../ppr-navigations'
1516

@@ -65,6 +66,8 @@ export function serverPatchReducer(
6566
scrollBehavior,
6667
navigateType,
6768
navigationLock,
69+
// A server-patch retry navigation is bound to the shared map.
70+
segmentCacheMap,
6871
null,
6972
// Server patch (retry) navigations don't use route prediction. This is
7073
// typically a retry after a previous mismatch, so the route was already

0 commit comments

Comments
 (0)