Unverified Commit 59ad3de6 authored by Josh Story's avatar Josh Story Committed by GitHub

Preserve closed-parameter restrictions in client route prediction (#98889)

## Summary

Preserve the restrictions of `dynamicParams = false` in client route
prediction, independently of the proposed parameter-matching API.

For `/products/[slug]` with only `allowed` generated during the build,
learning `/products/allowed` must not imply that `/products/rejected`
exists. This remains true when the page never reads `slug`. The
transport-tree builder now attaches `PrefetchHint.IsClosedParam` to the
affected dynamic node, rather than putting a route-level bit on the
response root or copying it to every prefetch node. Live rendering,
error trees, and prefetch-hint collection preserve that placement.

Legacy `dynamicParams = false` closes the entire parameter tuple. For
`/catalog/[lang]/products/[slug]/details`, both `[lang]` and `[slug]`
receive the hint; the static segments do not. Shared ancestors refresh
their hints even when their UI is reused: navigating between open and
closed pages under the same `[slug]` must add or clear the restriction.

Client behavior remains conservative: optimistic route prediction
declines a tree containing any closed parameter and asks the server to
resolve the destination. Existing apps combining `dynamicParams = false`
with `experimental.optimisticRouting` therefore lose prediction for
those routes. Sending allowed parameter values to the client and
predicting valid destinations from that list is future work, not part of
this change.

This PR is an independent prerequisite extracted from #97393. It does
not enable Cache Components, introduce parameter-matching configuration,
or change which parameter values are allowed. The later API layer
supplies exact closed-parameter names for routes with a closed prefix
and an open suffix.

## Verification

- The legacy routing/navigation fixture runs with Cache Components
disabled. Revised node-placement assertions fail against the old
response-root representation. The shared-sibling navigation test also
reproduced stale hints before the skipped-ancestor refresh was added.
- Initial documents and live client navigations with `prefetch={false}`
place the hint on `[slug]`; open routes carry no closure hint. A nested
legacy route marks both dynamic parameters, and open/closed sibling
navigation updates a reused ancestor.
- Five tests pass in development with both Turbopack and Webpack. The
three existing prefetch-dependent scenarios retain their production-only
gates; all eight tests pass in production with both bundlers.
- The seven production scenarios present before adding shared-sibling
navigation also passed with optimistic routing disabled in the Webpack
axis-A configuration.
- Existing config and transport-tree helper unit suites pass (22 tests
and one snapshot), and repository TypeScript checks pass.
- The eight-test legacy fixture also passes on the integrated API head.

An exploratory dev run of the combined routing-404 scenario encountered
an intermittent Turbopack `NoFallbackError`/500; a subsequent run
returned the expected 404. This PR does not fix that observation or
claim dev coverage for that production-only scenario.

<!-- NEXT_JS_LLM -->
parent 75b9f201
......@@ -155,7 +155,10 @@ import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { recursiveCopy } from '../lib/recursive-copy'
import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { installBindings } from './swc/install-bindings'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import {
getNamedRouteRegex,
getRouteRegex,
} from '../shared/lib/router/utils/route-regex'
import { getFilesInDir } from '../lib/get-files-in-dir'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import {
......@@ -3178,6 +3181,13 @@ export default async function build(
sortedStaticPaths.forEach(([originalAppPath, routes]) => {
const appConfig = appDefaultConfigs.get(originalAppPath)
const isDynamicError = appConfig?.dynamic === 'error'
// Legacy dynamicParams=false closes the entire route tuple.
const notFoundParams =
fallbackModes.get(originalAppPath) === FallbackMode.NOT_FOUND
? Object.keys(
getRouteRegex(normalizeAppPath(originalAppPath)).groups
)
: undefined
const isRoutePPREnabled: boolean = appConfig
? isAppCacheComponentsEnabled
......@@ -3205,6 +3215,7 @@ export default async function build(
page: originalAppPath,
_ssgPath: route.encodedPathname,
_fallbackRouteParams: route.fallbackRouteParams,
_notFoundParams: notFoundParams,
_isDynamicError: isDynamicError,
_isAppDir: true,
_isRoutePPREnabled: isRoutePPREnabled,
......
......@@ -42,6 +42,7 @@ import {
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' with { 'turbopack-transition': 'next-server-utility' }
import { shouldServeStreamingMetadata } from '../../server/lib/streaming-metadata' with { 'turbopack-transition': 'next-server-utility' }
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' with { 'turbopack-transition': 'next-server-utility' }
import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app' with { 'turbopack-transition': 'next-server-utility' }
import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta' with { 'turbopack-transition': 'next-server-utility' }
import {
RSC_HEADER,
......@@ -194,6 +195,13 @@ export function createAppPageEntrypoint({
const normalizedSrcPage = normalizeAppPath(srcPage)
// The legacy prerender manifest says whether unmatched values return 404,
// but does not list all of the route's parameter names. Read them from the
// route pattern once, since the names do not depend on the request.
const routeParamNames = parseNormalizedAppRoute(
normalizedSrcPage
).dynamicSegments.map((segment) => segment.param.paramName)
async function handler(
req: IncomingMessage,
res: ServerResponse,
......@@ -906,6 +914,15 @@ export function createAppPageEntrypoint({
multiZoneDraftMode,
prefetchHints: prefetchHintsManifest,
// With dynamicParams = false, every parameter is restricted to the
// paths generated at build time. Advertise this even for allowed
// URLs. Read the current manifest here because dev updates it as
// routes compile.
notFoundParams:
prerenderManifest.dynamicRoutes[normalizedSrcPage]?.fallback ===
false
? routeParamNames
: undefined,
incrementalCache,
cacheLifeProfiles: nextConfig.cacheLife,
staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,
......
......@@ -765,6 +765,16 @@ export function matchKnownRoute(
return null
}
// Closed parameters affect whether the route exists, even when none of its
// components read them. Resolve the target URL on the server instead of
// combining a predicted tree with UI cached for an allowed parameter value.
if (
pattern.tree.prefetchHints &
(PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)
) {
return null
}
// "Reify" the pattern: clone the template tree with concrete param values.
// This substitutes resolved params (e.g., slug: "hello") into dynamic
// segments and recomputes vary paths for correct segment cache keying.
......
......@@ -102,6 +102,8 @@ async function exportPageImpl(
// The parameters that are currently unknown.
_fallbackRouteParams = [],
_notFoundParams: notFoundParams,
// Check if this is an `app/` page.
_isAppDir: isAppDir = false,
......@@ -279,6 +281,7 @@ async function exportPageImpl(
allowEmptyStaticShell,
runInstantValidation,
isFallbackUpgradeable,
notFoundParams,
experimental: {
...commonRenderOpts.experimental,
isRoutePPREnabled,
......
......@@ -2398,7 +2398,8 @@ async function getErrorRSCPayload(
ctx.missingPrefetchHintPolicy,
Boolean(ctx.renderOpts.partialPrefetching),
getDynamicParamFromSegment,
query
query,
ctx.renderOpts.notFoundParams
)
// Attach the error shell as the root's render output. Vary params are not
// tracked for error pages.
......
......@@ -601,6 +601,7 @@ async function createComponentTreeInternal(
partialPrefetching,
getDynamicParamFromSegment,
query,
ctx.renderOpts.notFoundParams,
rootLayoutIncludedAtThisLevelOrAbove
)
} else {
......@@ -741,7 +742,8 @@ async function createComponentTreeInternal(
prefetchInliningEnabled,
ctx.missingPrefetchHintPolicy,
partialPrefetching,
!rootLayoutIncluded
!rootLayoutIncluded,
ctx.renderOpts.notFoundParams
)
// Convert the parallel route map into an object after all promises have been resolved.
......
......@@ -15,6 +15,7 @@ import {
import type { GetDynamicParamFromSegment } from './app-render'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param'
export type MissingPrefetchHintPolicy =
| 'mark-stale'
......@@ -64,7 +65,8 @@ export async function computeSegmentPrefetchHints(
partialPrefetching: boolean,
// Whether this segment is at or above the root layout (no layout was found
// above it).
isRootLayoutOrAbove: boolean
isRootLayoutOrAbove: boolean,
notFoundParams: readonly string[] | undefined
): Promise<number> {
const { layout, loading, page } = loaderTree[2]
......@@ -119,6 +121,13 @@ export async function computeSegmentPrefetchHints(
prefetchHints |= PrefetchHint.IsRootLayoutOrAbove
}
if (notFoundParams?.length) {
const param = getSegmentParam(loaderTree[0])
if (param !== null && notFoundParams.includes(param.paramName)) {
prefetchHints |= PrefetchHint.IsClosedParam
}
}
if (instantConfig === false) {
// The segment explicitly opts out of Partial Prefetching. We don't change
// the prefetch behavior, but we record it so the dev-time
......@@ -160,7 +169,8 @@ async function createTransportTreeFromLoaderTreeImpl(
partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
didFindRootLayout: boolean
didFindRootLayout: boolean,
notFoundParams: readonly string[] | undefined
): Promise<PartialTransportNode> {
const [segment, parallelRoutes, { layout }] = loaderTree
const dynamicParam = getDynamicParamFromSegment(loaderTree)
......@@ -172,7 +182,8 @@ async function createTransportTreeFromLoaderTreeImpl(
prefetchInliningEnabled,
missingPrefetchHintPolicy,
partialPrefetching,
!didFindRootLayout
!didFindRootLayout,
notFoundParams
)
if (!didFindRootLayout && typeof layout !== 'undefined') {
......@@ -195,7 +206,8 @@ async function createTransportTreeFromLoaderTreeImpl(
partialPrefetching,
getDynamicParamFromSegment,
searchParams,
didFindRootLayout
didFindRootLayout,
notFoundParams
)
// Propagate subtree flags from children
if (child.h !== undefined) {
......@@ -238,6 +250,7 @@ export async function createTransportTreeFromLoaderTree(
partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
notFoundParams: readonly string[] | undefined,
// Whether a root layout was already found above this loader tree slice, so a
// slice that starts below the root layout doesn't mark a sub-layout as the
// root layout.
......@@ -252,7 +265,8 @@ export async function createTransportTreeFromLoaderTree(
partialPrefetching,
getDynamicParamFromSegment,
searchParams,
didFindRootLayout
didFindRootLayout,
notFoundParams
)
}
......@@ -268,7 +282,8 @@ export async function createFullTransportTreeFromLoaderTree(
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any
searchParams: any,
notFoundParams: readonly string[] | undefined
): Promise<FullTransportNode> {
// With emitSkippedData, every node carries data, which is what
// FullTransportNode requires. TypeScript can't see through the flag,
......@@ -282,7 +297,8 @@ export async function createFullTransportTreeFromLoaderTree(
partialPrefetching,
getDynamicParamFromSegment,
searchParams,
false
false,
notFoundParams
) as Promise<FullTransportNode>
}
......@@ -297,6 +313,7 @@ export async function createRouteTreePrefetch(
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
notFoundParams: readonly string[] | undefined,
// See note on createTransportTreeFromLoaderTree's didFindRootLayout.
didFindRootLayout: boolean = false
): Promise<PartialTransportNode> {
......@@ -313,6 +330,7 @@ export async function createRouteTreePrefetch(
partialPrefetching,
getDynamicParamFromSegment,
searchParams,
didFindRootLayout
didFindRootLayout,
notFoundParams
)
}
......@@ -221,6 +221,9 @@ export interface RenderOptsPartial {
*/
prefetchHints?: Record<string, PrefetchHints>
/** Parameters whose novel values are rejected by routing. */
notFoundParams?: readonly string[]
/**
* When true, the page is prerendered as a fallback shell, while allowing any
* dynamic accesses to result in an empty shell. This is the case when there
......
......@@ -15,6 +15,7 @@ import type { LoaderTree } from '../lib/app-dir-module'
import { getLinkAndScriptTags } from './get-css-inlined-link-tags'
import { getPreloadableFonts } from './get-preloadable-fonts'
import {
computeSegmentPrefetchHints,
createTransportTreeFromLoaderTree,
createRouteTreePrefetch,
} from './create-transport-tree-from-loader-tree'
......@@ -171,6 +172,7 @@ export async function walkTreeWithFlightRouterState({
ctx.missingPrefetchHintPolicy,
partialPrefetching,
getDynamicParamFromSegment,
ctx.renderOpts.notFoundParams,
rootLayoutIncluded
)
: await createTransportTreeFromLoaderTree(
......@@ -181,6 +183,7 @@ export async function walkTreeWithFlightRouterState({
partialPrefetching,
getDynamicParamFromSegment,
query,
ctx.renderOpts.notFoundParams,
rootLayoutIncluded
)
......@@ -201,7 +204,8 @@ export async function walkTreeWithFlightRouterState({
prefetchInliningEnabled,
ctx.missingPrefetchHintPolicy,
partialPrefetching,
getDynamicParamFromSegment
getDynamicParamFromSegment,
ctx.renderOpts.notFoundParams
)
: await createTransportTreeFromLoaderTree(
loaderTreeToFilter,
......@@ -211,6 +215,7 @@ export async function walkTreeWithFlightRouterState({
partialPrefetching,
getDynamicParamFromSegment,
query,
ctx.renderOpts.notFoundParams,
rootLayoutIncluded
)
return {
......@@ -322,6 +327,17 @@ export async function walkTreeWithFlightRouterState({
// rendered subtrees, so the client is expected to already have it.
tree: {
s: segmentToTransportSegment(actualSegment),
// The UI is shared, but route-specific restrictions may have changed
// (e.g. an open sibling navigating to a dynamicParams=false page).
h: await computeSegmentPrefetchHints(
loaderTreeToFilter,
hintTree,
prefetchInliningEnabled,
ctx.missingPrefetchHintPolicy,
partialPrefetching,
!rootLayoutIncluded,
ctx.renderOpts.notFoundParams
),
d: createSkippedSegmentData(),
c: children,
},
......
......@@ -39,6 +39,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
// private optional properties
_fallbackRouteParams: z.array(z.any()).optional(),
_notFoundParams: z.array(z.string()).optional(),
_isAppDir: z.boolean().optional(),
_isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(),
......
......@@ -1645,6 +1645,9 @@ export type ExportPathMap = {
*/
_fallbackRouteParams?: readonly FallbackRouteParam[]
/** Parameters whose novel values are rejected by routing. @internal */
_notFoundParams?: readonly string[]
/**
* @internal
*/
......
......@@ -278,6 +278,14 @@ export const enum PrefetchHint {
// fallbacks — simply never carry it.) Set on every node of the tree, but
// does not propagate.
ShouldAttemptStaticPrefetch = 0b100000000000000,
// This dynamic segment only accepts build-time parameter values. Kept on
// the affected node, without propagating or copying it to other segments.
// Until the client knows the allowed values, any such node prevents route
// prediction, even when the route's components never read the parameter.
IsClosedParam = 0b1000000000000000,
// A descendant segment (but not this one) has a closed parameter. Propagates
// upward so route prediction can check the root instead of walking the tree.
SubtreeHasClosedParams = 0b10000000000000000,
}
/**
......@@ -309,7 +317,8 @@ export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled
export const SubtreePrefetchHints =
PrefetchHint.SubtreeHasPartialPrefetching |
PrefetchHint.SubtreeHasLoadingBoundary |
PrefetchHint.SubtreeHasInstantFalse
PrefetchHint.SubtreeHasInstantFalse |
PrefetchHint.SubtreeHasClosedParams
/**
* Folds a child segment's prefetch hints into its parent's, propagating the
......@@ -344,6 +353,12 @@ export function propagateSubtreeBits(
if (childHints & PrefetchHint.SubtreeHasInstantFalse) {
parentHints |= PrefetchHint.SubtreeHasInstantFalse
}
if (
childHints &
(PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)
) {
parentHints |= PrefetchHint.SubtreeHasClosedParams
}
return parentHints
}
......
export const dynamicParams = false
export function generateStaticParams() {
return [{ lang: 'en', slug: 'allowed' }]
}
export default function Page() {
return <p id="catalog-page">Allowed catalog page</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function NotFound() {
return <p id="root-not-found">Route not found</p>
}
import Link from 'next/link'
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return (
<>
<p id="open-product-page">Open product page</p>
<Link href="/products/allowed" prefetch={false} id="navigate-allowed">
Navigate to an allowed product without prefetching
</Link>
</>
)
}
import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<h1>Prefetch closed parameters</h1>
<LinkAccordion href="/products/allowed">Allowed product</LinkAccordion>
<LinkAccordion href="/products/rejected">Rejected product</LinkAccordion>
<Link href="/products/rejected" prefetch={false} id="navigate-rejected">
Navigate without prefetching
</Link>
</main>
)
}
export const dynamicParams = false
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return <p id="product-page">Allowed product page</p>
}
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<section id="products-layout">
<h1>Product catalog</h1>
{children}
</section>
)
}
export default function NotFound() {
return <p id="nested-not-found">Product not found</p>
}
import Link from 'next/link'
export const dynamicParams = false
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return (
<>
<p id="shared-closed-page">Closed sibling</p>
<Link id="open-sibling" href="/shared/allowed/open" prefetch={false}>
Open sibling
</Link>
</>
)
}
import Link from 'next/link'
export function generateStaticParams() {
return [{ slug: 'allowed' }]
}
export default function Page() {
return (
<>
<p id="shared-open-page">Open sibling</p>
<Link id="closed-sibling" href="/shared/allowed/closed" prefetch={false}>
Closed sibling
</Link>
</>
)
}
'use client'
import Link from 'next/link'
import { useState, type ReactNode } from 'react'
export function LinkAccordion({
href,
children,
}: {
href: string
children: ReactNode
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<div>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? <Link href={href}>{children}</Link> : children}
</div>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: false,
partialPrefetching: false,
experimental: {
// Keep this legacy fixture independent of the CC CI job's defaults.
cachedNavigations: false,
optimisticRouting: process.env.__NEXT_TEST_AXIS !== 'A',
varyParams: true,
prefetchInlining: 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