Unverified Commit f4dc7c82 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

[backport] Fix catch-all index page being served for every other slug (#97416)

Backports [Fix catch-all index page being served for every other
slug](https://github.com/vercel/next.js/pull/96553) to `next-16-3`.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarAndrew Clark <git@andrewclark.io>
parent eba236b5
...@@ -2566,11 +2566,8 @@ function writeSegmentBundleResponseVariants( ...@@ -2566,11 +2566,8 @@ function writeSegmentBundleResponseVariants(
now, now,
FetchStrategy.StaticShell, FetchStrategy.StaticShell,
// When the shell IS the full response (no shell/full split), the // When the shell IS the full response (no shell/full split), the
// entries this write fulfills carry full-tier content, so PPR is // entries this write fulfills carry full-tier content, so PPR is the
// the strategy that describes it. They're still keyed at the shell // strategy that describes it.
// vary path: that's the reusable slot, and it serves concrete
// fallback reads correctly precisely because the shell and concrete
// variants coincide.
shellResponse === serverResponse shellResponse === serverResponse
? FetchStrategy.PPR ? FetchStrategy.PPR
: FetchStrategy.StaticShell : FetchStrategy.StaticShell
...@@ -2740,15 +2737,18 @@ function writeSegmentBundleResponse( ...@@ -2740,15 +2737,18 @@ function writeSegmentBundleResponse(
: FetchStrategy.PPRRuntime : FetchStrategy.PPRRuntime
: fetchStrategy : fetchStrategy
// Determine the vary path to key the segment at. For the full payload, // Key the entry by which params the server said this segment depends on.
// re-key to a more generic path if the server tells us which params the // Reusing one copy across param values is the point of the shell, but it
// segment varies by. // requires knowing the content doesn't depend on those params, and the
// server's report is the direct evidence of that.
//
// Without that report, assume every param varies. The exception is a
// shell variant, which reduces param-dependent content to param
// fallbacks, so it really is good for any value of them.
const payloadVaryPath = const payloadVaryPath =
fetchStrategy === FetchStrategy.StaticShell process.env.__NEXT_VARY_PARAMS && varyParams !== null
? node.tree.shellVaryPath ? getFulfilledSegmentVaryPath(node.tree.varyPath, varyParams)
: process.env.__NEXT_VARY_PARAMS && varyParams !== null : getSegmentVaryPathForRequest(payloadFetchStrategy, node.tree)
? getFulfilledSegmentVaryPath(node.tree.varyPath, varyParams)
: getSegmentVaryPathForRequest(FetchStrategy.PPR, node.tree)
const nodeEntry = node.entry const nodeEntry = node.entry
if (nodeEntry !== null && nodeEntry.status === EntryStatus.Pending) { if (nodeEntry !== null && nodeEntry.status === EntryStatus.Pending) {
...@@ -2761,43 +2761,24 @@ function writeSegmentBundleResponse( ...@@ -2761,43 +2761,24 @@ function writeSegmentBundleResponse(
responseIsUpgradeableISRFallback, responseIsUpgradeableISRFallback,
recordedFetchStrategy recordedFetchStrategy
) )
if (fetchStrategy === FetchStrategy.StaticShell) { // Move the entry to that key. This is load-bearing rather than a no-op:
// Re-key at the shell vary path, mirroring the RuntimeShell re-key // a task spawns its entries before it knows what the response will
// in fulfillEntrySpawnedByRuntimePrefetch. Usually the entry already // contain, so the key it guessed can be more reusable than the response
// lives there, but the scheduler can also upgrade a pre-existing // turned out to deserve.
// Empty entry at a more concrete path in place, so the re-key is //
// load-bearing. The shadow eviction keeps a stale settled entry at // Pass the concrete lookup path — the most specific path a read for
// a more specific path from hiding the shell entry (the just-written // this segment position would use — so that if the entry lands at a
// full payload's entry is preferred and survives it). Routed through // more generic key, a stale entry at a more specific one can't shadow
// the upsert rather than a bare set so the usual precedence rules // it. See evictShadowingSegmentEntries. The upsert (rather than a bare
// apply: a concurrent task's response (e.g. a RuntimeShell entry) // set) applies the usual precedence rules, so a concurrent task's more
// can land in the shell slot first, and this write must not // complete response already in this slot isn't downgraded.
// downgrade it. (In the common case the slot already holds this upsertSegmentEntry(
// very entry, which the upsert replaces in place.) now,
if (process.env.__NEXT_VARY_PARAMS) { map,
upsertSegmentEntry( payloadVaryPath,
now, fulfilledEntry,
map, node.tree.varyPath
node.tree.shellVaryPath, )
fulfilledEntry,
node.tree.varyPath
)
}
} else {
// Set the fulfilled entry into the canonical cache slot. Pass the
// concrete lookup path — the most specific path a read for this
// segment position would use — so that if the canonical path is more
// generic (i.e. the server re-keyed the segment), any stale settled
// entry at a more specific path (e.g. a partial shell entry) that
// would shadow this one is evicted. See evictShadowingSegmentEntries.
upsertSegmentEntry(
now,
map,
payloadVaryPath,
fulfilledEntry,
node.tree.varyPath
)
}
} else { } else {
// We don't own this entry. Create a detached entry and attempt to // We don't own this entry. Create a detached entry and attempt to
// upsert it into this payload's slot. // upsert it into this payload's slot.
......
import { LinkAccordion } from '../../../components/link-accordion'
type Params = { slug?: string[] }
export function generateStaticParams(): Params[] {
return [{ slug: [] }, { slug: ['alpha'] }, { slug: ['beta'] }]
}
/**
* An optional catch-all where the index (empty slug) and the named pages are
* the same route. The page reads `params`, so every one of these segments
* varies by `slug` — the server reports that in the response's vary params.
*/
export default async function DocsPage({
params,
}: {
params: Promise<Params>
}) {
const { slug } = await params
const name = slug && slug.length > 0 ? slug.join('/') : 'index'
return (
<div>
{/*
The id is slug-specific so a test can wait for the navigation to
actually commit — an id shared by every slug would match the
pre-navigation DOM and read stale content.
One interpolated string so the text is a single node in the RSC
payload, which lets the test assert on response contents.
*/}
<div id={`docs-page-${name}`}>{`Docs: ${name}`}</div>
<LinkAccordion href="/docs/alpha">alpha</LinkAccordion>
<LinkAccordion href="/docs/beta">beta</LinkAccordion>
</div>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function HomePage() {
return (
<div>
<div id="home-page">Home</div>
{/*
Revealing this link prefetches /docs — the fully static index of the
optional catch-all route. That prefetch is what used to poison the
param-wildcard slot for every other slug.
*/}
<LinkAccordion href="/docs">Docs index</LinkAccordion>
</div>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
}: {
href: string
children: React.ReactNode
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
// Partial Prefetching enables the Shell prefetch phase, where the bug lived.
partialPrefetching: true,
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('segment cache - static shell vary params regression', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
// Depends on build-time prerenders, which don't exist in dev.
test('skipped in dev mode', () => {})
return
}
// Regression test for a segment cache keying bug.
//
// During the Shell prefetch phase the client walks at the StaticShell
// strategy, and it used to key whatever came back at `tree.shellVaryPath`,
// which replaces every non-root param with Fallback. That's only correct
// when the payload really is the param-independent shell.
//
// When a route renders with no dynamic hole, the response has no shell/full
// split — the "shell" payload IS the concrete render for the params that
// were requested. Keying it at the wildcard path published one param's page
// as the answer for every other param value, and recorded it at the highest
// tier, so later navigations rendered the wrong page and skipped the network
// entirely.
//
// On an optional catch-all, the index (empty slug) is the case that hits
// this: prefetching /docs poisoned /docs/alpha and /docs/beta.
//
// The fix makes the server-reported vary params authoritative, so the shell
// path is used exactly when the segment really is param-independent.
it('does not serve the catch-all index page for a different slug', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Prefetch the fully static index of the optional catch-all route. Its
// response has no shell/full split, so this is the write that used to land
// in the param-wildcard slot.
await act(
async () => {
await browser.elementByCss('input[data-link-accordion="/docs"]').click()
},
{ includes: 'Docs: index' }
)
// Navigate there. Fully prefetched, so nothing should be requested.
await act(async () => {
await browser.elementByCss('a[href="/docs"]').click()
expect(await browser.elementById('docs-page-index').text()).toBe(
'Docs: index'
)
}, 'no-requests')
// Now prefetch a different slug on the same route. Before the fix the
// index's page segment was sitting in the wildcard slot marked complete,
// so this fired no request at all for the page content and this
// expectation would time out.
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/docs/alpha"]')
.click()
},
{ includes: 'Docs: alpha' }
)
await act(async () => {
await browser.elementByCss('a[href="/docs/alpha"]').click()
expect(await browser.elementById('docs-page-alpha').text()).toBe(
'Docs: alpha'
)
}, 'no-requests')
})
})
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