Unverified Commit 35d91fca authored by Josh Story's avatar Josh Story Committed by GitHub

Model prerenders as render candidates (#97431)

## Summary

This is the behavior-preserving base of a four-PR stack that introduces
explicit prerender matching policy without coupling the foundational
refactor to the proposed API.

The build currently uses `PrerenderedRoute` values for two related but
distinct concepts:

- a logical request matcher that says which parameterized URL shapes the
route can handle
- a build-time render candidate that may or may not become a persisted
prerender artifact

A candidate is not guaranteed to be an output. It can be rendered only
to validate a shell, discarded, and still leave behind a matcher that
tells future requests to block.

The new relationship is:

```text
logical pathname matcher
  -> zero or more render candidates
    -> zero or more persisted artifacts
```

## Concrete example

Consider `/[top]/items/[bottom]`:

```ts
export function generateStaticParams() {
  return [{ top: 't1', bottom: 'b1' }]
}
```

Static-path generation may consider three shapes:

| Shape | Purpose |
| --- | --- |
| `/[top]/items/[bottom]` | A generic shell candidate and logical
matcher |
| `/t1/items/[bottom]` | A shell after resolving `top` |
| `/t1/items/b1` | A concrete build-time prerender |

Suppose the generic candidate renders an allowed empty shell. The build
should discard that candidate artifact and use blocking behavior for the
generic matcher. It should not remove `/[top]/items/[bottom]` from the
valid matcher set, and it should not discard the concrete `/t1/items/b1`
artifact.

This is why the build needs two sets:

- route matchers, which describe valid request shapes
- prerender candidates, whose render results determine whether an
artifact is retained and can refine inferred fallback behavior

## Variants compatibility

Variants will make pathname-only candidate maps insufficient. Several
variant combinations can share `/t1/items/b1` as their logical pathname
while writing distinct artifacts under variant-specific output paths.

This PR keeps the route matcher keyed by logical pathname but retains
every candidate associated with it. Candidate finalization can therefore
evaluate each variant artifact independently without changing the route
tree's matcher set.

## Behavior preservation

This PR does not add a user-facing API or change `generateStaticParams`
semantics:

- a usable static shell remains a fallback prerender
- an allowed empty shell is discarded and represented by a blocking
matcher
- a route that requires a non-empty shell still fails validation
- unresolved matchers remain gated by route-level PPR support
- the most-specific shell continues to supply first-writer-wins metadata
such as prefetch hints

Render results can decide whether a candidate artifact is published and
can refine inferred matcher behavior, but they do not remove the logical
route matcher itself.

## Stack plan

1. **#97431 — model prerenders as render candidates:** land the
behavior-preserving matcher/candidate separation and post-render
finalization first.
2. **#97393 — add the experimental matcher API:** add `unstable_matcher`
and `unstable_generateMatcher`, policy aggregation, validation, and
local diagnostics.
3. **#97426 — test complex route shapes:** add test-only coverage for
catch-alls, optional catch-alls, root parameters, and parallel slots.
4. **#97427 — test foreground policy behavior:** add test-only coverage
showing blocking misses generate before responding while fallback misses
return the shared shell immediately.

This layering lets the internal model be reviewed and landed
independently of the API design. The upper test PRs validate the final
behavior without increasing the implementation diff.

## Verification

- `pnpm --filter=next types`
- `pnpm test-start-turbo
test/e2e/app-dir/sub-shell-generation/sub-shell-generation.test.ts`
- `pnpm test-start-turbo
test/e2e/app-dir/segment-cache/prefetch-inlining/prefetch-inlining.test.ts`

<!-- NEXT_JS_LLM -->
parent 9dfbc938
......@@ -138,7 +138,11 @@ import {
pageToRoute,
} from './utils'
import type { DynamicManifestRoute, PageInfo, PageInfos } from './utils'
import type { FallbackRouteParam, PrerenderedRoute } from './static-paths/types'
import type {
FallbackRouteParam,
PrerenderRouteMatcher,
PrerenderedRoute,
} from './static-paths/types'
import type { AppSegmentConfig } from './segment-config/app/app-segment-config'
import { writeBuildId } from './write-build-id'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
......@@ -2168,6 +2172,7 @@ export default async function build(
const serverPropsPages = new Set<string>()
const additionalPaths = new Map<string, PrerenderedRoute[]>()
const staticPaths = new Map<string, PrerenderedRoute[]>()
const prerenderRouteMatchers = new Map<string, PrerenderRouteMatcher[]>()
const appNormalizedPaths = new Map<string, string>()
const fallbackModes = new Map<string, FallbackMode>()
const appDefaultConfigs = new Map<string, AppSegmentConfig>()
......@@ -2569,6 +2574,13 @@ export default async function build(
isSSG = true
}
if (workerResult.prerenderRouteMatchers) {
prerenderRouteMatchers.set(
originalAppPath,
workerResult.prerenderRouteMatchers
)
}
const appConfig = workerResult.appConfig || {}
if (appConfig.revalidate !== 0) {
const hasGenerateStaticParams =
......@@ -3226,29 +3238,30 @@ export default async function build(
// If there was no result, there's nothing more to do.
if (!exportResult) return
const getFallbackMode = (route: PrerenderedRoute) => {
const hasEmptyStaticShell = exportResult.byPath.get(
route.pathname
)?.hasEmptyStaticShell
const resolveFallbackMode = (
matcher: PrerenderRouteMatcher,
prerenderCandidate: PrerenderedRoute | undefined,
hasEmptyStaticShell: boolean | undefined
) => {
// If the route has an empty static shell and is not configured to
// throw on empty static shell, then we should use the blocking
// static render mode.
if (
prerenderCandidate &&
hasEmptyStaticShell &&
!route.throwOnEmptyStaticShell &&
route.fallbackMode === FallbackMode.PRERENDER
!prerenderCandidate.throwOnEmptyStaticShell &&
matcher.fallbackMode === FallbackMode.PRERENDER
) {
return FallbackMode.BLOCKING_STATIC_RENDER
}
// If the route has no fallback mode, then we should use the
// `NOT_FOUND` fallback mode.
if (!route.fallbackMode) {
if (!matcher.fallbackMode) {
return FallbackMode.NOT_FOUND
}
return route.fallbackMode
return matcher.fallbackMode
}
const getCacheControl = (
......@@ -3311,6 +3324,15 @@ export default async function build(
if (!appConfig) throw new InvariantError('App config not found')
const ssgPageRoutesSet = new Set(pageInfos.get(page)?.ssgPageRoutes)
// Preserve the specificity order that unknown prerender routes had
// before matchers were modeled separately. Some metadata, such as
// prefetch hints, is collected using first-writer-wins semantics.
const dynamicRouteMatchers = [
...sortPageObjects(
prerenderRouteMatchers.get(originalAppPath) ?? [],
(route) => route.pathname
),
]
let hasRevalidateZero =
appConfig.revalidate === 0 ||
......@@ -3367,13 +3389,10 @@ export default async function build(
: []),
]
// We should collect all the dynamic routes into a single array for
// this page. Including the full fallback route (the original
// route), any routes that were generated with unknown route params
// should be collected and included in the dynamic routes part
// of the manifest instead.
const staticPrerenderedRoutes: PrerenderedRoute[] = []
const dynamicPrerenderedRoutes: PrerenderedRoute[] = []
// Candidates without unknown params can become concrete static
// outputs. Candidates with unknown params are finalized alongside
// the logical matcher directives collected above.
const concretePrerenderCandidates: PrerenderedRoute[] = []
// Sort the outputted routes to ensure consistent output. Any route
// though that has unknown route params will be pulled and sorted
......@@ -3439,18 +3458,17 @@ export default async function build(
prerenderedRoute.fallbackRouteParams &&
prerenderedRoute.fallbackRouteParams.length > 0
) {
// If the route has unknown params, then we need to add it to
// the list of dynamic routes.
dynamicPrerenderedRoutes.push(prerenderedRoute)
// Partial candidates have a corresponding matcher directive
// and are finalized below after inspecting their render.
} else {
// If the route doesn't have unknown params, then we need to
// add it to the list of static routes.
staticPrerenderedRoutes.push(prerenderedRoute)
concretePrerenderCandidates.push(prerenderedRoute)
}
}
// Handle all the static routes.
for (const route of staticPrerenderedRoutes) {
for (const route of concretePrerenderCandidates) {
if (isDynamicRoute(page) && route.pathname === page) continue
const pageInfo = pageInfos.get(page) as PageInfo
......@@ -3602,20 +3620,59 @@ export default async function build(
// they are enabled, then it'll already be included in the
// prerendered routes.
if (!isRoutePPREnabled) {
dynamicPrerenderedRoutes.push({
params: {},
dynamicRouteMatchers.push({
pathname: page,
encodedPathname: page,
fallbackRouteParams: [],
fallbackMode:
fallbackModes.get(originalAppPath) ??
FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
})
}
for (const route of dynamicPrerenderedRoutes) {
// A logical matcher can have zero or more render candidates.
// Today generateStaticParams produces at most one candidate per
// pathname. Variants can multiply that into several artifacts
// without changing the logical matcher, so retain every
// candidate instead of letting pathname select whichever one was
// inserted last.
const prerenderCandidatesByPathname = new Map<
string,
PrerenderedRoute[]
>()
for (const candidate of prerenderedRoutes) {
const candidates = prerenderCandidatesByPathname.get(
candidate.pathname
)
if (candidates) {
candidates.push(candidate)
} else {
prerenderCandidatesByPathname.set(candidate.pathname, [
candidate,
])
}
}
const dynamicRouteEntries: Array<{
matcher: PrerenderRouteMatcher
prerenderCandidate: PrerenderedRoute | undefined
}> = []
for (const matcher of dynamicRouteMatchers) {
const candidates = prerenderCandidatesByPathname.get(
matcher.pathname
) ?? [undefined]
for (const prerenderCandidate of candidates) {
dynamicRouteEntries.push({
matcher,
prerenderCandidate,
})
}
}
for (const {
matcher: route,
prerenderCandidate,
} of dynamicRouteEntries) {
// Static metadata files are rewritten above into the known
// static bucket under their `-`-placeholder pathname, so any
// entry that slips through here (e.g. an unexpected fallback
......@@ -3626,13 +3683,24 @@ export default async function build(
continue
}
const normalizedRoute = normalizePagePath(route.pathname)
// This is the artifact associated with this matcher entry. It
// currently has the same pathname as the logical matcher, but
// that is not an invariant: variants can write several
// artifacts for one matcher under distinct output paths.
const prerenderOutputPathname =
prerenderCandidate?.pathname ?? route.pathname
const normalizedRoute = normalizePagePath(
prerenderOutputPathname
)
const parentPageInfo = pageInfos.get(page) as PageInfo
const routeResult = exportResult.byPath.get(route.pathname)
const routeResult = exportResult.byPath.get(
prerenderOutputPathname
)
const metadata = routeResult?.metadata
const cacheControl = getCacheControl(route.pathname)
const cacheControl = getCacheControl(prerenderOutputPathname)
let dataRoute: string | null = null
if (!isAppRouteHandler) {
......@@ -3720,10 +3788,10 @@ export default async function build(
if (route.pathname === page) {
// The route pattern entry (for example `/blog/[slug]`) is
// also present in `dynamicPrerenderedRoutes`. Keep updating
// the parent entry in place so it retains its `ssgPageRoutes`
// subtree; if we rewrote it like a concrete child route we
// would lose the generated child paths from the build output.
// also present in `dynamicRouteMatchers`. Keep updating the
// parent entry in place so it retains its `ssgPageRoutes`
// subtree; rewriting it like a concrete child route would
// lose the generated child paths from the build output.
pageInfos.set(page, {
...(pageInfos.get(page) as PageInfo),
initialCacheControl: cacheControl,
......@@ -3751,7 +3819,11 @@ export default async function build(
})
}
const fallbackMode = getFallbackMode(route)
const fallbackMode = resolveFallbackMode(
route,
prerenderCandidate,
routeResult?.hasEmptyStaticShell
)
// When the route is configured to serve a prerender, we should
// use the cache control from the export result. If it can't be
......@@ -3795,7 +3867,7 @@ export default async function build(
}
}
prerenderManifest.dynamicRoutes[route.pathname] = {
prerenderManifest.dynamicRoutes[prerenderOutputPathname] = {
experimentalPPR: isRoutePPREnabled,
remainingPrerenderableParams:
route.remainingPrerenderableParams,
......@@ -3807,7 +3879,7 @@ export default async function build(
...classification,
experimentalBypassFor: bypassFor,
routeRegex: normalizeRouteRegex(
getNamedRouteRegex(route.pathname, {
getNamedRouteRegex(prerenderOutputPathname, {
prefixRouteKeys: false,
}).re.source
),
......
......@@ -3,6 +3,7 @@ import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type { AppSegment } from '../segment-config/app/app-segments'
import type {
FallbackRouteParam,
PrerenderRouteMatcher,
PrerenderedRoute,
StaticPathsResult,
} from './types'
......@@ -1175,5 +1176,28 @@ export async function buildAppStaticPaths({
assignStaticShellMetadata(prerenderedRoutes, prerenderablePathSegments)
}
return { fallbackMode, prerenderedRoutes }
const prerenderRouteMatchersByPathname = new Map<
string,
PrerenderRouteMatcher
>()
if (prerenderedRoutes && isRoutePPREnabled) {
for (const prerenderCandidate of prerenderedRoutes) {
if (!prerenderCandidate.fallbackRouteParams?.length) continue
prerenderRouteMatchersByPathname.set(prerenderCandidate.pathname, {
pathname: prerenderCandidate.pathname,
fallbackRouteParams: prerenderCandidate.fallbackRouteParams,
fallbackMode: prerenderCandidate.fallbackMode,
fallbackRootParams: prerenderCandidate.fallbackRootParams,
remainingPrerenderableParams:
prerenderCandidate.remainingPrerenderableParams,
})
}
}
const prerenderRouteMatchers =
prerenderRouteMatchersByPathname.size > 0
? [...prerenderRouteMatchersByPathname.values()]
: undefined
return { fallbackMode, prerenderedRoutes, prerenderRouteMatchers }
}
......@@ -52,9 +52,40 @@ type FallbackPrerenderedRoute = {
throwOnEmptyStaticShell: boolean
}
/**
* A route the build plans to prerender. Rendering decides whether the result
* becomes a published output: for example, an allowed empty fallback shell is
* discarded and its matcher becomes blocking instead.
*
* The historical name is retained because this type is used throughout static
* path generation, but values of this type are prerender candidates rather
* than guaranteed outputs.
*/
export type PrerenderedRoute = StaticPrerenderedRoute | FallbackPrerenderedRoute
/**
* Describes how a dynamic pathname is matched when no concrete build-time
* output matches it. It describes the logical route independently of any
* artifacts produced for it, and is not itself something to render.
*
* Zero or more prerender candidates may share this pathname. In particular,
* variants can produce several artifacts for one logical matcher, so consumers
* must not assume pathname identifies a single candidate or render result.
*/
export type PrerenderRouteMatcher = {
readonly pathname: string
readonly fallbackRouteParams: readonly FallbackRouteParam[]
readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: readonly string[]
readonly remainingPrerenderableParams?: readonly FallbackRouteParam[]
}
export type StaticPathsResult = {
fallbackMode: FallbackMode | undefined
/** Planned renders, some of which may be discarded after rendering. */
prerenderedRoutes: PrerenderedRoute[] | undefined
/** Logical request matchers, independent of the artifacts rendered for them. */
prerenderRouteMatchers?: PrerenderRouteMatcher[]
}
......@@ -69,7 +69,10 @@ import { createIncrementalCache } from '../export/helpers/create-incremental-cac
import { collectRootParamKeys } from './segment-config/app/collect-root-param-keys'
import { buildAppStaticPaths } from './static-paths/app'
import { buildPagesStaticPaths } from './static-paths/pages'
import type { PrerenderedRoute } from './static-paths/types'
import type {
PrerenderRouteMatcher,
PrerenderedRoute,
} from './static-paths/types'
import type { CacheControl } from '../server/lib/cache-control'
import { formatExpire, formatRevalidate } from './output/format'
import type {
......@@ -672,6 +675,7 @@ type PageIsStaticResult = {
hasServerProps?: boolean
hasStaticProps?: boolean
prerenderedRoutes: PrerenderedRoute[] | undefined
prerenderRouteMatchers: PrerenderRouteMatcher[] | undefined
prerenderFallbackMode: FallbackMode | undefined
rootParamKeys: readonly string[] | undefined
isNextImageImported?: boolean
......@@ -742,6 +746,7 @@ export async function isPageStatic({
isRoutePPREnabled: false,
prerenderFallbackMode: undefined,
prerenderedRoutes: undefined,
prerenderRouteMatchers: undefined,
rootParamKeys: undefined,
hasStaticProps: false,
hasServerProps: false,
......@@ -768,6 +773,7 @@ export async function isPageStatic({
let componentsResult: LoadComponentsReturnType
let prerenderedRoutes: PrerenderedRoute[] | undefined
let prerenderRouteMatchers: PrerenderRouteMatcher[] | undefined
let prerenderFallbackMode: FallbackMode | undefined
let appConfig: AppSegmentConfig = {}
let rootParamKeys: readonly string[] | undefined
......@@ -887,29 +893,32 @@ export async function isPageStatic({
;({ prerenderedRoutes, fallbackMode: prerenderFallbackMode } =
buildStaticMetadataStaticPaths(page))
} else {
;({ prerenderedRoutes, fallbackMode: prerenderFallbackMode } =
await buildAppStaticPaths({
dir,
page,
route,
cacheComponents,
authInterrupts,
useCacheTimeout,
staticPageGenerationTimeout,
segments,
distDir,
requestHeaders: {},
isrFlushToDisk,
cacheMaxMemorySize,
cacheHandler,
cacheLifeProfiles,
ComponentMod,
nextConfigOutput,
isRoutePPREnabled,
buildId,
deploymentId,
rootParamKeys,
}))
;({
prerenderedRoutes,
prerenderRouteMatchers,
fallbackMode: prerenderFallbackMode,
} = await buildAppStaticPaths({
dir,
page,
route,
cacheComponents,
authInterrupts,
useCacheTimeout,
staticPageGenerationTimeout,
segments,
distDir,
requestHeaders: {},
isrFlushToDisk,
cacheMaxMemorySize,
cacheHandler,
cacheLifeProfiles,
ComponentMod,
nextConfigOutput,
isRoutePPREnabled,
buildId,
deploymentId,
rootParamKeys,
}))
}
}
} else {
......@@ -982,6 +991,7 @@ export async function isPageStatic({
isRoutePPREnabled,
prerenderFallbackMode,
prerenderedRoutes,
prerenderRouteMatchers,
rootParamKeys,
hasStaticProps,
hasServerProps,
......
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p>{`Dynamic page: ${top}/${bottom}`}</p>
}
import { Suspense, type ReactNode } from 'react'
import { NoInline } from '../../../components/no-inline'
export function generateStaticParams() {
return [{ top: 't1' }]
}
export default async function Layout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return (
<div>
<NoInline />
<p>{`Top: ${top}`}</p>
<Suspense fallback={<p>Loading bottom...</p>}>{children}</Suspense>
</div>
)
}
import type { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return (
<div>
<p>Static parent</p>
{children}
</div>
)
}
......@@ -185,7 +185,7 @@ async function getRouteTreeFromHistory(
}
describe('prefetch inlining', () => {
const { next, isNextDev, isTurbopack } = nextTestSetup({
const { next, isNextDev, isNextStart, isTurbopack } = nextTestSetup({
files: __dirname,
})
......@@ -533,6 +533,40 @@ describe('prefetch inlining', () => {
)
})
if (isNextStart) {
it('partially generated dynamic route: build hints use the most specific shell', async () => {
const hints = await next.readJSON('.next/server/prefetch-hints.json')
expect(hints['/test-dynamic-partial/[top]/[bottom]'])
.toMatchInlineSnapshot(`
{
"hints": 64,
"slots": {
"children": {
"hints": 96,
"slots": {
"children": {
"hints": 32,
"slots": {
"children": {
"hints": 64,
"slots": {
"children": {
"hints": 160,
"slots": null,
},
},
},
},
},
},
},
},
}
`)
})
}
// TODO: Add a test for stale hints (InliningHintsStale). The stale hints
// mechanism expires the route cache entry so the next prefetch re-fetches
// the correct tree. This is hard to test reliably with act() because the
......
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