Unverified Commit 6fbd61c1 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Do not mark complete shell requests as partial (#97503)

The router code did not respect the isPartial byte for runtime app
shells for some reason, potentially leading to unnecessary speculative
prefetch requests even if the shell was in fact complete.

The comments say that the byte on those can't be trusted:

https://github.com/vercel/next.js/blob/d00eb6b6c471c9c51ef997f643b049210d9940a5/packages/next/src/client/components/segment-cache/cache.ts#L2694-L2696
which is not true -- the byte is definitely set to partial when a shell
contains holes (due to URL data or link data).
 
Updates some tests that now no longer trigger a speculative prefetch
because the shell is complete.
(note that our tests use `prefetch = 'partial'` a lot, so some of them
were triggering speculative prefetches even when they shouldn't have.
see #97469 for more)
parent 844c62e1
...@@ -2689,11 +2689,7 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest( ...@@ -2689,11 +2689,7 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest(
// Runtime prefetch responses (PPRRuntime and RuntimeShell requests) are // Runtime prefetch responses (PPRRuntime and RuntimeShell requests) are
// partial when the server marks the response as '~' (Partial). // partial when the server marks the response as '~' (Partial).
// Full/LoadingBoundary prefetch responses are always complete. This only // Full/LoadingBoundary prefetch responses are always complete.
// describes the FULL payload: shell-tier writes don't consume it — a
// shell is partial by construction (RuntimeShell responses omit every
// dynamic suspense boundary below the shell stage, regardless of what
// the server marker says); see writeResponsePayloadsIntoCache.
const isFullResponsePartial = const isFullResponsePartial =
(fetchStrategy === FetchStrategy.PPRRuntime || (fetchStrategy === FetchStrategy.PPRRuntime ||
fetchStrategy === FetchStrategy.RuntimeShell) && fetchStrategy === FetchStrategy.RuntimeShell) &&
...@@ -2866,12 +2862,11 @@ function writeResponsePayloadsIntoCache( ...@@ -2866,12 +2862,11 @@ function writeResponsePayloadsIntoCache(
} }
return null return null
} }
// No shell exists, and the request wasn't a static shell walk. The full // This request either:
// payload fulfills the spawned entries at the request's own keying — // - didn't allow recovering a shell (no staged rendering),
// including for a RuntimeShell request (shell staging not enabled, or // - or was a (runtime) shell request, so we already have a shell without recovering anything.
// the render wasn't staged), whose response is then conservatively treated // In either case, we don't have anything to consider other than the request itself,
// as the shell it asked for: keyed at the shell tier and partial // so the payload simply fulfills the spawned entries at the request's own keying.
// by construction.
fulfilledEntries = writeServerResponseIntoCache( fulfilledEntries = writeServerResponseIntoCache(
now, now,
fetchStrategy, fetchStrategy,
...@@ -2882,9 +2877,7 @@ function writeResponsePayloadsIntoCache( ...@@ -2882,9 +2877,7 @@ function writeResponsePayloadsIntoCache(
renderedSearch, renderedSearch,
buildId, buildId,
staleAt, staleAt,
fetchStrategy === FetchStrategy.RuntimeShell isFullResponsePartial,
? true
: isFullResponsePartial,
metadataVaryPath, metadataVaryPath,
spawnedEntries, spawnedEntries,
null, null,
...@@ -2909,7 +2902,7 @@ function writeResponsePayloadsIntoCache( ...@@ -2909,7 +2902,7 @@ function writeResponsePayloadsIntoCache(
renderedSearch, renderedSearch,
buildId, buildId,
staleAt, staleAt,
shellWasRequested ? true : isFullResponsePartial, isFullResponsePartial,
metadataVaryPath, metadataVaryPath,
spawnedEntries, spawnedEntries,
// The full payload's tier: PPR for a static response, PPRRuntime for // The full payload's tier: PPR for a static response, PPRRuntime for
......
...@@ -127,6 +127,15 @@ export default function Page() { ...@@ -127,6 +127,15 @@ export default function Page() {
</LinkAccordion> </LinkAccordion>
</li> </li>
</ul> </ul>
<h2>Complete shell</h2>
<ul>
<li>
<LinkAccordion href="/runtime-shell-complete">
Complete runtime shell
</LinkAccordion>
</li>
</ul>
</main> </main>
) )
} }
import { Suspense } from 'react'
import { cookies } from 'next/headers'
export const prefetch = 'partial'
export default function Page() {
return (
<main>
<Suspense fallback={<p id="cookie-loading">Loading cookie...</p>}>
<CookieDependent />
</Suspense>
</main>
)
}
async function CookieDependent() {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
return <p id="cookie-value">{`Cookie: ${value}`}</p>
}
...@@ -70,6 +70,33 @@ describe('App Shell prefetching', () => { ...@@ -70,6 +70,33 @@ describe('App Shell prefetching', () => {
) )
}) })
it('can navigate without extra requests if a runtime app shell is complete', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal the link and fetch the shell. The route uses cookies, so this will be
// a runtime shell.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/runtime-shell-complete"]')
.click()
}, [{ includes: 'Cookie: none', kind: 'runtime' }])
// Navigate. The shell is complete, so this shouldn't require fetching anything else.
await act(async () => {
await browser.elementByCss('a[href="/runtime-shell-complete"]').click()
}, 'no-requests')
expect(await browser.elementById('cookie-value').text()).toEqual(
'Cookie: none'
)
})
it('runtime-prefetches per-link content of a dynamic route whose static-attempt hint is unset', async () => { it('runtime-prefetches per-link content of a dynamic route whose static-attempt hint is unset', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
......
...@@ -71,12 +71,12 @@ export default function Page() { ...@@ -71,12 +71,12 @@ export default function Page() {
</LinkAccordion> </LinkAccordion>
</li> </li>
<li> <li>
<LinkAccordion href="/test-independent-head/a"> <LinkAccordion href="/test-independent-head/a" prefetch={true}>
Independent head A Independent head A
</LinkAccordion> </LinkAccordion>
</li> </li>
<li> <li>
<LinkAccordion href="/test-independent-head/b"> <LinkAccordion href="/test-independent-head/b" prefetch={true}>
Independent head B Independent head B
</LinkAccordion> </LinkAccordion>
</li> </li>
......
...@@ -636,13 +636,13 @@ describe('prefetch inlining', () => { ...@@ -636,13 +636,13 @@ describe('prefetch inlining', () => {
page = p page = p
}, },
}) })
const act = createRouterAct(page!) const act = createRouterAct(page!, { includeAppShellRequests: true })
// Reveal a default (auto) link to the route. The route is a Partial // Reveal a default (auto) link to the route. The route is a Partial
// Prefetching route (the page is partial), so every segment the // Prefetching route (the page is partial), so every segment the
// prefetch walks is held to the runtime-completeness contract — and the // prefetch walks is held to the runtime-completeness contract — and the
// route's static-attempt hint is unset because the page reads cookies, // route's static-attempt hint is unset because the page reads cookies,
// so the walked layout deopts directly to the batched runtime prefetch, // so the walked layout deopts directly to the batched runtime shell,
// which serves its whole subtree. The inlined layout content arrives in // which serves its whole subtree. The inlined layout content arrives in
// that runtime response. (No static bundle request fires: the Shell // that runtime response. (No static bundle request fires: the Shell
// phase already runtime-cached every entry in the bundle chain, and a // phase already runtime-cached every entry in the bundle chain, and a
...@@ -659,9 +659,8 @@ describe('prefetch inlining', () => { ...@@ -659,9 +659,8 @@ describe('prefetch inlining', () => {
{ includes: 'Static layout content', kind: 'runtime' } { includes: 'Static layout content', kind: 'runtime' }
) )
// Reveal a prefetch={true} link to the same route. Everything is // Reveal a prefetch={true} link to the same route. The shell is complete,
// already runtime-cached at the per-link tier by the prefetch above, so // so a runtime prefetch will not give us any more data and should be skipped.
// opting in has nothing left to fetch.
await act(async () => { await act(async () => {
await browser await browser
.elementByCss( .elementByCss(
...@@ -709,7 +708,7 @@ describe('prefetch inlining', () => { ...@@ -709,7 +708,7 @@ describe('prefetch inlining', () => {
page = p page = p
}, },
}) })
const act = createRouterAct(page!) const act = createRouterAct(page!, { includeAppShellRequests: true })
await act( await act(
async () => { async () => {
...@@ -810,7 +809,7 @@ describe('prefetch inlining', () => { ...@@ -810,7 +809,7 @@ describe('prefetch inlining', () => {
page = p page = p
}, },
}) })
const act = createRouterAct(page!) const act = createRouterAct(page!, { includeAppShellRequests: true })
await act( await act(
async () => { async () => {
......
...@@ -510,18 +510,20 @@ describe('runtime prefetching', () => { ...@@ -510,18 +510,20 @@ describe('runtime prefetching', () => {
// Clear cookies after the test. This currently doesn't happen automatically. // Clear cookies after the test. This currently doesn't happen automatically.
await using _ = defer(() => browser.deleteCookies()) await using _ = defer(() => browser.deleteCookies())
const act = createRouterAct(page) const act = createRouterAct(page, { includeAppShellRequests: true })
await browser.addCookie({ name: 'testCookie', value: 'initialValue' }) await browser.addCookie({ name: 'testCookie', value: 'initialValue' })
// Reveal the link to trigger a runtime prefetch for the initial cookie value // Reveal the link.
// We won't actually perform a runtime prefetch, because the request is
// satisfied by the app shell.
await act(async () => { await act(async () => {
const linkToggle = await browser.elementByCss( const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/${prefix}/cookies-only"]` `input[data-link-accordion="/${prefix}/cookies-only"]`
) )
await linkToggle.click() await linkToggle.click()
}, [ }, [
// Should allow reading cookies // Should allow reading cookies in the app shell
{ {
includes: 'Cookie: initialValue', includes: 'Cookie: initialValue',
}, },
...@@ -561,11 +563,14 @@ describe('runtime prefetching', () => { ...@@ -561,11 +563,14 @@ describe('runtime prefetching', () => {
// Clear cookies after the test. This currently doesn't happen automatically. // Clear cookies after the test. This currently doesn't happen automatically.
await using _ = defer(() => browser.deleteCookies()) await using _ = defer(() => browser.deleteCookies())
const act = createRouterAct(page) const act = createRouterAct(page, { includeAppShellRequests: true })
await browser.addCookie({ name: 'testCookie', value: 'initialValue' }) await browser.addCookie({ name: 'testCookie', value: 'initialValue' })
// Reveal the link to trigger a runtime prefetch for the initial cookie value // Reveal the link.
// We won't actually perform a runtime prefetch, because the request is
// satisfied by the app shell.
await act(async () => { await act(async () => {
const linkToggle = await browser.elementByCss( const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/${prefix}/cookies-only"]` `input[data-link-accordion="/${prefix}/cookies-only"]`
...@@ -1056,11 +1061,13 @@ describe('runtime prefetching', () => { ...@@ -1056,11 +1061,13 @@ describe('runtime prefetching', () => {
page = p page = p
}, },
}) })
const act = createRouterAct(page) const act = createRouterAct(page, { includeAppShellRequests: true })
const STATIC_CONTENT = 'This page errors after a cookies call' const STATIC_CONTENT = 'This page errors after a cookies call'
// Reveal the link to trigger a runtime prefetch // Reveal the link.
// We won't actually perform a runtime prefetch, because the request is
// satisfied by the app shell.
await act(async () => { await act(async () => {
const linkToggle = await browser.elementByCss( const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/errors/error-after-cookies"]` `input[data-link-accordion="/errors/error-after-cookies"]`
...@@ -1077,7 +1084,7 @@ describe('runtime prefetching', () => { ...@@ -1077,7 +1084,7 @@ describe('runtime prefetching', () => {
expect(getCliOutput()).toContain('Error: Kaboom') expect(getCliOutput()).toContain('Error: Kaboom')
} }
// Navigate to the page. We already have the paged cached. // Navigate to the page. We already have the page cached.
// Even though the render errored, we shouldn't fetch it again. // Even though the render errored, we shouldn't fetch it again.
await act(async () => { await act(async () => {
await browser await browser
......
...@@ -7,20 +7,16 @@ import { cookies } from 'next/headers' ...@@ -7,20 +7,16 @@ import { cookies } from 'next/headers'
// Prefetching segment, the page requires runtime-completeness during the // Prefetching segment, the page requires runtime-completeness during the
// Speculative phase (which the consuming test enters via a `prefetch={true}` // Speculative phase (which the consuming test enters via a `prefetch={true}`
// link), and with the hint unset the scheduler skips the static attempt // link), and with the hint unset the scheduler skips the static attempt
// entirely and issues the runtime prefetch directly. Unlike the uses-cookies // entirely and issues the runtime prefetch directly.
// fixture, the Speculative runtime prefetch RESOLVES the cookies() read, so // It also awaits searchParams so that a speculative prefetch has non-shell
// the cookie-derived content itself arrives in the runtime response. // contents to resolve.
export const prefetch = 'partial' export const prefetch = 'partial'
async function CookieContent() { type PageProps = {
const cookieStore = await cookies() searchParams: Promise<SearchParams>
const value = cookieStore.get('testCookie')?.value ?? 'none'
return (
<div id="speculative-cookie-content">{`Speculative-cookies cookie: ${value}`}</div>
)
} }
export default function Page() { export default function Page(props: PageProps) {
return ( return (
<main> <main>
<p id="page-content">Speculative-cookies page shell text</p> <p id="page-content">Speculative-cookies page shell text</p>
...@@ -29,8 +25,34 @@ export default function Page() { ...@@ -29,8 +25,34 @@ export default function Page() {
<p id="speculative-cookie-loading">Loading speculative cookie...</p> <p id="speculative-cookie-loading">Loading speculative cookie...</p>
} }
> >
<CookieContent /> <CookieContent {...props} />
</Suspense> </Suspense>
</main> </main>
) )
} }
async function CookieContent(props: PageProps) {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
return (
<>
<div id="speculative-cookie-content">{`Speculative-cookies cookie: ${value}`}</div>
<Suspense
fallback={
<p id="speculative-search-params-loading">Loading search params...</p>
}
>
<SearchParamsContent {...props} />
</Suspense>
</>
)
}
type SearchParams = Record<string, string | string[]>
async function SearchParamsContent(props: PageProps) {
const searchCount = Object.keys(await props.searchParams).length
return (
<div id="search-params-content">{`Search params count: ${searchCount}`}</div>
)
}
...@@ -123,11 +123,8 @@ describe('static App Shell prefetch attempt', () => { ...@@ -123,11 +123,8 @@ describe('static App Shell prefetch attempt', () => {
.elementByCss('input[data-link-accordion="/uses-cookies"]') .elementByCss('input[data-link-accordion="/uses-cookies"]')
.click() .click()
}, [ }, [
// The page (the new part) arrives in the runtime shell response. // Cookies are included in the runtime shell.
// (The bare cookies() read itself isn't resolved by the runtime { includes: 'cookie-content', kind: 'runtime' },
// prerender — it stays a hole for the navigation-time dynamic
// request — so we only assert on the shell text.)
{ includes: 'Cookies page shell text', kind: 'runtime' },
// No static attempt for the new part: the page content must not // No static attempt for the new part: the page content must not
// arrive in a static per-segment response. (The route tree prefetch // arrive in a static per-segment response. (The route tree prefetch
// is also `kind: 'static'`, but its response doesn't contain rendered // is also `kind: 'static'`, but its response doesn't contain rendered
...@@ -382,29 +379,15 @@ describe('static App Shell prefetch attempt', () => { ...@@ -382,29 +379,15 @@ describe('static App Shell prefetch attempt', () => {
.elementByCss('input[data-link-accordion="/speculative-cookies"]') .elementByCss('input[data-link-accordion="/speculative-cookies"]')
.click() .click()
}, [ }, [
// Two runtime responses arrive, in order, and each resolves the // 1. Runtime shell (includes cookies)
// cookies() read (a runtime prefetch renders with the request's
// cookies):
//
// 1. The Shell phase's runtime shell request — the same direct
// runtime shell behavior the hint-unset tests above exercise,
// except that here the session content resolves instead of
// remaining a hole.
{ includes: 'Speculative-cookies page shell text', kind: 'runtime' },
{ includes: 'Speculative-cookies cookie: none', kind: 'runtime' },
// 2. The Speculative phase's runtime prefetch of the page segment,
// which re-delivers the page content. (It fires on top of the
// runtime shell entry because a per-URL runtime prefetch can
// provide content a URL-independent shell response cannot.)
{ includes: 'Speculative-cookies page shell text', kind: 'runtime' },
{ includes: 'Speculative-cookies cookie: none', kind: 'runtime' }, { includes: 'Speculative-cookies cookie: none', kind: 'runtime' },
// 2. Runtime prefetch (includes cookies and search params)
{ includes: 'Search params count: 0', kind: 'runtime' },
// No static attempt in either phase: the page content must not // No static attempt in either phase: the page content must not
// arrive in ANY static per-segment response. (The server does emit // arrive in ANY static per-segment response. (The server does emit
// static data for the segment — the shell text is in it — but with // static data for the segment — the shell text is in it — but with
// the hint unset nothing fetches it: this blanket rejection // the hint unset nothing fetches it.
// was verified empirically against the full request log. The route
// tree prefetch is also kind: 'static', but its response doesn't
// contain rendered page content, so it can't match this.)
{ {
includes: 'Speculative-cookies page shell text', includes: 'Speculative-cookies page shell text',
kind: 'static', kind: 'static',
......
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