Unverified Commit 6302e6a9 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Don't re-request the App Shell to upgrade an ISR fallback (#94808)

When a page hasn't been prerendered with concrete params yet, the server
answers a per-segment prefetch with the fallback shell and flags it as
upgradeable, and the client records that on the cache entries so a later
prefetch of the same route can retry and pick up the concrete prerender
once the server has generated it. The scheduler runs that retry from its
Fulfilled-entry branch: any prefetch task that finds an
upgradeable-fallback entry and hasn't retried yet spawns a revalidation
for its own URL.

That's right for the concrete static walk, where the retry can bring
back the param-dependent content the fallback omitted. It's wrong for
the Shell-phase walk under Partial Prefetching. A shell request asks for
shell-stage content, and the fallback render already produced all of it:
a concrete prerender's shell stage omits the same param-dependent
content the fallback omitted, so the retry can only return the shell the
cache already has.

This shows up with root params. The shell varies only on the root params
it reads, so a shell fetched for `/en/uk/posts/1` whose root layout
reads `lang` but not `region` is keyed with `region` as a fallback, and
a link to `/en/gb/posts/1` finds it in the cache. With the retry gate
on, revealing that link re-requested the identical shell, once per link
whose root params the shell doesn't read.

The fix gates the ISR fallback retry on the walk's strategy, next to the
Pending and Rejected branches that already skip revalidations during a
static shell attempt. The per-task retry loop that the original fallback
response starts is unchanged.

The included test reveals three links from `/en/us`: `/en/uk/posts/1`
fetches the shell, `/en/gb/posts/1` (same `lang`, different `region`)
fetches nothing, and `/fr/uk/posts/1` (different `lang`) fetches a new
shell.

This PR originally narrowed the shell's cache key to the root params the
server reported. That change landed separately in "Convert per-segment
prefetches to NavigationFlightResponse format" (#96877); rebasing onto
it left the test, which then caught this.

<!-- NEXT_JS_LLM_PR -->
parent a10b283d
...@@ -2326,17 +2326,20 @@ function pingSegmentBundle( ...@@ -2326,17 +2326,20 @@ function pingSegmentBundle(
} }
} }
// If this is the speculative phase (not the shell phase), check if we
// should attempt to upgrade a fallback ISR response to a concrete
// version.
//
// For entries below this phase's tier, upgrade during the phase // For entries below this phase's tier, upgrade during the phase
// itself — no background deferral, since the whole point of the // itself — no background deferral, since the whole point of the
// Speculative phase is to bring the cache up to the // Speculative phase is to bring the cache up to the
// per-link-concrete tier. `isPartial` ensures a complete entry isn't // per-link-concrete tier. `isPartial` ensures a complete entry isn't
// re-fetched. // re-fetched.
//
// If we can use runtime requests and a runtime request would provide more // If we can use runtime requests and a runtime request would provide more
// data, we also skip the upgrade (see `willBeSupersededByRuntimeRequest`) // data, we also skip the upgrade (see `willBeSupersededByRuntimeRequest`)
// Check if we should attempt to upgrade a fallback ISR response to
// a concrete version.
const isUpgradeableISRFallbackRetry = const isUpgradeableISRFallbackRetry =
fetchStrategy === FetchStrategy.PPR &&
nodeEntry.isUpgradeableISRFallback && nodeEntry.isUpgradeableISRFallback &&
// If the status is empty, then we haven't yet attempted to upgrade // If the status is empty, then we haven't yet attempted to upgrade
// the fallback. // the fallback.
......
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
// The App Shell is keyed by root params so that a locale-aware (etc.) shell can
// still be reused across navigations. But a shell should only vary on the root
// params it actually reads — keying it on root params it never touches stores
// redundant copies and misses cache hits.
//
// This fixture's root layout reads only `lang`; `region` is a root param that
// is read only below the shell boundary. So the shell for
// /[lang]/[region]/posts varies on `lang` but is identical across `region`.
//
// The app uses Partial Prefetching, so revealing a link prefetches only the
// shared shell — no per-link Speculative prefetch. Each reveal is therefore
// exactly one shell prefetch (when the shell isn't already cached) or no
// requests at all. We pass `{ includeAppShellRequests: true }` so router-act
// asserts on App Shell requests (next-router-prefetch: '3') instead of ignoring
// them.
describe('App Shell varies only on the root params it reads', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('is skipped in dev (prefetching is disabled)', () => {})
return
}
it('reuses the shell across an unread root param, but refetches across a read one', async () => {
let page: Playwright.Page
// Start on the one statically-generated route.
const browser = await next.browser('/en/us', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Prime the shared shell for /en/uk/posts. The shell render reads `lang`
// ('en') but not `region`.
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/en/uk/posts/1"]')
.click()
},
{ includes: 'App shell for posts' }
)
// Reveal /en/gb/posts/1 — SAME lang, DIFFERENT region. The shell does not
// read `region`, so the shell cached for /en/uk is reusable: this reveal
// should prefetch nothing.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/en/gb/posts/1"]')
.click()
}, 'no-requests')
// Reveal /fr/uk/posts/1 — DIFFERENT lang. The shell DOES read `lang`, so it
// must NOT be reused: a fresh shell prefetch fires. This guards against
// over-narrowing (dropping a root param the shell actually reads).
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/fr/uk/posts/1"]')
.click()
},
{ includes: 'App shell for posts' }
)
})
})
import { lang } from 'next/root-params'
import { ReactNode } from 'react'
// This is the topmost layout in the route tree (there is no app/layout.tsx
// above it), so both `lang` and `region` are "root params" (params at or above
// the root layout), accessible via next/root-params.
//
// Crucially, the layout — which is part of the App Shell — reads ONLY `lang`,
// never `region`. So the shell varies on `lang` but is identical across
// `region` values.
export default async function RootLayout({
children,
}: {
children: ReactNode
}) {
const currentLang = await lang()
return (
<html lang={currentLang}>
<body>
<div id="shell-lang">{`Shell lang: ${currentLang}`}</div>
{children}
</body>
</html>
)
}
// Only one combo is statically generated — just enough to give the app a
// buildable start page (/en/us).
export function generateStaticParams() {
return [{ lang: 'en', region: 'us' }]
}
import { LinkAccordion } from '../../../components/link-accordion'
// Home page for a (lang, region) pair, e.g. /en/us. It renders accordion links
// to the same posts route under several (lang, region) combinations so the test
// can prime and probe the shell cache without navigating.
export default function Page() {
return (
<main>
<h1>Home</h1>
<ul>
<li>
<LinkAccordion href="/en/uk/posts/1">en/uk post 1</LinkAccordion>
</li>
<li>
<LinkAccordion href="/en/gb/posts/1">en/gb post 1</LinkAccordion>
</li>
<li>
<LinkAccordion href="/fr/uk/posts/1">fr/uk post 1</LinkAccordion>
</li>
</ul>
</main>
)
}
import { Suspense } from 'react'
import { region } from 'next/root-params'
type Params = { id: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
{/* The fallback is the App Shell — the part of the page that doesn't
depend on the dynamic params. Nothing above this boundary reads the
`region` root param, so the shell does not vary on `region`. */}
<Suspense fallback={<p id="shell">App shell for posts</p>}>
<ParamsDependent params={params} />
</Suspense>
</main>
)
}
async function ParamsDependent({ params }: { params: Promise<Params> }) {
'use cache'
const { id } = await params
// `region` is a root param, but it's only read here — below the shell
// boundary, in the dynamic content — so it's not part of the shell.
const currentRegion = await region()
return <p id="dynamic-content">{`Post ${id} for region ${currentRegion}`}</p>
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
// Opt the whole app into Partial Prefetching (non-eager). Under App Shells
// this skips the per-link Speculative phase, so revealing a link prefetches
// ONLY the shared shell. That makes each reveal observable as exactly "one
// shell prefetch, or no requests at all" — which is what the assertions rely
// on.
partialPrefetching: true,
experimental: {
prefetchInlining: true,
optimisticRouting: true,
cachedNavigations: true,
varyParams: true,
},
}
export default nextConfig
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