Unverified Commit 0ca967b8 authored by Josh Story's avatar Josh Story Committed by GitHub

Add group depth tracking to instant validation boundary discovery (#91208)

The depth-based instant validation previously only iterated
URL-consuming segments as potential shared/new boundaries. Route groups
between URL segments were invisible — when a route group layout with
Suspense was shared in a client navigation, its Suspense appeared to
cover blocking code in the validation render even though it wouldn't in
reality.

This adds a second dimension to the validation iteration: group depth.
At each URL depth, we now also step through route group boundaries. A
new `discoverValidationDepths` function walks the LoaderTree and returns
an array where each entry represents the max group depth at that URL
depth. The validation loop iterates from deepest group depth to
shallowest within each URL depth, stopping on the first error.

Key design decisions:
- URL depth and group depth counters are advanced before the boundary
check, making the boundary condition a simple `nextUrlDepth > depth &&
currentGroupDepth >= groupDepth`
- The synthetic `(slot)` segment that Next.js inserts for parallel slots
is excluded from group depth counting since it doesn't represent a real
navigation boundary
- Group depths are discovered from the LoaderTree rather than the URL
pathname, making the tree the source of truth for validation bounds
parent a41bef94
...@@ -1264,7 +1264,7 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1264,7 +1264,7 @@ async fn directory_tree_to_loader_tree_internal(
let current_level_is_parallel_route = is_parallel_route(&directory_name); let current_level_is_parallel_route = is_parallel_route(&directory_name);
if current_level_is_parallel_route { if current_level_is_parallel_route {
tree.segment = rcstr!("(slot)"); tree.segment = rcstr!("(__SLOT__)");
} }
if let Some(page) = (app_path == for_app_path || app_path.is_catchall()) if let Some(page) = (app_path == for_app_path || app_path.is_catchall())
......
...@@ -429,7 +429,7 @@ async function createTreeCodeFromPath( ...@@ -429,7 +429,7 @@ async function createTreeCodeFromPath(
parallelSegmentKey = parallelSegmentKey =
parallelSegmentKey === PARALLEL_VIRTUAL_SEGMENT || parallelSegmentKey === PARALLEL_VIRTUAL_SEGMENT ||
parallelSegmentKey === PAGE_SEGMENT parallelSegmentKey === PAGE_SEGMENT
? '(slot)' ? '(__SLOT__)'
: parallelSegmentKey : parallelSegmentKey
const normalizedParallelKey = normalizeParallelKey(parallelKey) const normalizedParallelKey = normalizeParallelKey(parallelKey)
......
...@@ -877,9 +877,9 @@ function getBoundaryDebugNameFromSegment(segment: Segment): string | undefined { ...@@ -877,9 +877,9 @@ function getBoundaryDebugNameFromSegment(segment: Segment): string | undefined {
function isVirtualLayout(segment: string): boolean { function isVirtualLayout(segment: string): boolean {
return ( return (
// This is inserted by the loader. We should consider encoding these // This is inserted by the loader. Uses double-underscore convention
// in a more special way instead of checking the name, to distinguish them // (like __PAGE__ and __DEFAULT__) to avoid collisions with
// from app-defined groups. // user-defined route groups.
segment === '(slot)' segment === '(__SLOT__)'
) )
} }
...@@ -4662,6 +4662,7 @@ async function validateInstantConfigs( ...@@ -4662,6 +4662,7 @@ async function validateInstantConfigs(
createCombinedPayloadAtDepth, createCombinedPayloadAtDepth,
createCombinedPayloadStream, createCombinedPayloadStream,
collectStagedSegmentData, collectStagedSegmentData,
discoverValidationDepths,
} = ctx.componentMod.InstantValidation()! } = ctx.componentMod.InstantValidation()!
const { createValidationSampleTracking } = const { createValidationSampleTracking } =
...@@ -4707,13 +4708,15 @@ async function validateInstantConfigs( ...@@ -4707,13 +4708,15 @@ async function validateInstantConfigs(
* runtime and dynamic errors, returning the more specific result. * runtime and dynamic errors, returning the more specific result.
*/ */
async function validateAtDepth( async function validateAtDepth(
depth: number depth: number,
groupDepthForValidation: number
): Promise<Array<unknown> | null> { ): Promise<Array<unknown> | null> {
return validateAtDepthImpl(depth, null) return validateAtDepthImpl(depth, groupDepthForValidation, null)
} }
async function validateAtDepthImpl( async function validateAtDepthImpl(
depth: number, depth: number,
groupDepthForValidation: number,
previousBoundaryState: null | ValidationBoundaryTracking previousBoundaryState: null | ValidationBoundaryTracking
): Promise<null | Array<unknown>> { ): Promise<null | Array<unknown>> {
const extraChunksController = new AbortController() const extraChunksController = new AbortController()
...@@ -4735,6 +4738,7 @@ async function validateInstantConfigs( ...@@ -4735,6 +4738,7 @@ async function validateInstantConfigs(
ctx.getDynamicParamFromSegment, ctx.getDynamicParamFromSegment,
ctx.query, ctx.query,
depth, depth,
groupDepthForValidation,
extraChunksController.signal, extraChunksController.signal,
boundaryState, boundaryState,
clientReferenceManifest, clientReferenceManifest,
...@@ -4914,7 +4918,11 @@ async function validateInstantConfigs( ...@@ -4914,7 +4918,11 @@ async function validateInstantConfigs(
if (previousBoundaryState === null && payloadResult.hasAmbiguousErrors) { if (previousBoundaryState === null && payloadResult.hasAmbiguousErrors) {
// This is the first validation attempt. we prepared a payload where dynamic holes might be runtime data dependencies // This is the first validation attempt. we prepared a payload where dynamic holes might be runtime data dependencies
// or dynamic data dependencies. We do a followup validation using a payload with only Runtime segments to discriminate // or dynamic data dependencies. We do a followup validation using a payload with only Runtime segments to discriminate
const dynamicOnlyErrors = await validateAtDepthImpl(depth, boundaryState) const dynamicOnlyErrors = await validateAtDepthImpl(
depth,
groupDepthForValidation,
boundaryState
)
if (dynamicOnlyErrors !== null && dynamicOnlyErrors.length > 0) { if (dynamicOnlyErrors !== null && dynamicOnlyErrors.length > 0) {
// The dynamic errors only validation found errors to report so we favor those // The dynamic errors only validation found errors to report so we favor those
...@@ -4926,25 +4934,43 @@ async function validateInstantConfigs( ...@@ -4926,25 +4934,43 @@ async function validateInstantConfigs(
return errors return errors
} }
const urlSegments = ctx.url.pathname.split('/').filter(Boolean) // Discover validation depth bounds from the LoaderTree. The array
const maxDepth = urlSegments.length + 1 // +1 for root // length is the max URL depth; each entry is the max group depth
// (route group segments) between that URL depth and the next.
const groupDepthsByUrlDepth = discoverValidationDepths(loaderTree)
const maxDepth = groupDepthsByUrlDepth.length
for (let depth = maxDepth - 1; depth >= 0; depth--) { for (let depth = maxDepth - 1; depth >= 0; depth--) {
debug?.(`Trying depth ${depth}...`) const maxGroupDepth = groupDepthsByUrlDepth[depth]
const errors = await validateAtDepth(depth) for (
let currentGroupDepth = maxGroupDepth;
currentGroupDepth >= 0;
currentGroupDepth--
) {
debug?.(
`Trying depth ${depth}` +
(currentGroupDepth > 0
? ` + groupDepth ${currentGroupDepth}...`
: '...')
)
if (errors === null) { const errors = await validateAtDepth(depth, currentGroupDepth)
debug?.(` No config at depth ${depth}, skipping.`)
continue
}
if (errors.length > 0) { if (errors === null) {
debug?.(` Depth ${depth}: ❌ Failed (${errors.length} errors)`) debug?.(` No config at depth ${depth}+${currentGroupDepth}, skipping.`)
return errors continue
} }
if (errors.length > 0) {
debug?.(
` Depth ${depth}+${currentGroupDepth}: ❌ Failed (${errors.length} errors)`
)
return errors
}
debug?.(` Depth ${depth}: ✅ Passed`) debug?.(` Depth ${depth}+${currentGroupDepth}: ✅ Passed`)
}
} }
debug?.(`✅ All depths passed`) debug?.(`✅ All depths passed`)
......
...@@ -785,6 +785,86 @@ function segmentConsumesURLDepth(segment: Segment): boolean { ...@@ -785,6 +785,86 @@ function segmentConsumesURLDepth(segment: Segment): boolean {
return true return true
} }
/**
* Walks the LoaderTree to discover validation depth bounds.
*
* Each route group between URL segments represents a potential
* shared/new boundary in a client navigation. When a user navigates
* between sibling routes that share a route group layout, that
* layout is already mounted — its Suspense boundaries are revealed
* and don't cover new content below. By tracking the max group
* depth at each URL depth, we can iterate all possible group
* boundaries and validate that blocking code is always covered by
* Suspense in the new tree. This is conservative: some boundaries
* may not correspond to real navigations (e.g. a route group with
* no siblings), but it ensures we don't miss real violations.
*
* The max is taken across all parallel slots. When slots have
* different numbers of groups, the deepest slot determines the
* iteration range. Shallower slots simply stay entirely shared
* at group depths beyond their own group count — they run out
* of groups before reaching the boundary, so their content
* remains in the Dynamic stage.
*
* Returns an array where:
* - length = max URL depth (number of URL-consuming segments)
* - array[i] = max group depth at URL depth i (number of route group
* segments between this URL depth and the next)
*
* For example, a tree like:
* '' / (outer) / (inner) / dashboard / page
* returns [2, 0] — URL depth 0 (root) has 2 group layers before
* the next URL segment (dashboard), and URL depth 1 (dashboard) has
* 0 group layers before the leaf.
*/
export function discoverValidationDepths(loaderTree: LoaderTree): number[] {
const groupDepthsByUrlDepth: number[] = []
function recordGroupDepth(urlDepth: number, groupDepth: number): void {
while (groupDepthsByUrlDepth.length <= urlDepth) {
groupDepthsByUrlDepth.push(0)
}
if (groupDepth > groupDepthsByUrlDepth[urlDepth]) {
groupDepthsByUrlDepth[urlDepth] = groupDepth
}
}
// urlDepth tracks the index of the current URL-consuming segment.
// Groups accumulate at the same index. When the next URL segment
// is reached, it increments the index and resets the group counter.
// We start at -1 so the root segment '' increments to 0.
function walk(tree: LoaderTree, urlDepth: number, groupDepth: number): void {
const segment = tree[0]
const { parallelRoutes } = parseLoaderTree(tree)
const consumesDepth = segmentConsumesURLDepth(segment)
let nextUrlDepth = urlDepth
let nextGroupDepth = groupDepth
if (consumesDepth) {
nextUrlDepth = urlDepth + 1
nextGroupDepth = 0
recordGroupDepth(nextUrlDepth, 0)
} else if (
typeof segment === 'string' &&
isGroupSegment(segment) &&
segment !== '(__SLOT__)'
) {
// Count real route groups but not the synthetic '(__SLOT__)' segment
// that Next.js inserts for parallel slots. The synthetic group
// can't be a real navigation boundary.
nextGroupDepth++
recordGroupDepth(urlDepth, nextGroupDepth)
}
for (const key in parallelRoutes) {
walk(parallelRoutes[key], nextUrlDepth, nextGroupDepth)
}
}
walk(loaderTree, -1, 0)
return groupDepthsByUrlDepth
}
/** /**
* Builds a combined RSC payload for validation at a given URL depth. * Builds a combined RSC payload for validation at a given URL depth.
* *
...@@ -815,6 +895,7 @@ export async function createCombinedPayloadAtDepth( ...@@ -815,6 +895,7 @@ export async function createCombinedPayloadAtDepth(
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
query: NextParsedUrlQuery | null, query: NextParsedUrlQuery | null,
depth: number, depth: number,
groupDepth: number,
releaseSignal: AbortSignal, releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking, boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
...@@ -837,7 +918,8 @@ export async function createCombinedPayloadAtDepth( ...@@ -837,7 +918,8 @@ export async function createCombinedPayloadAtDepth(
loaderTree: LoaderTree, loaderTree: LoaderTree,
parentPath: SegmentPath | null, parentPath: SegmentPath | null,
key: string | null, key: string | null,
urlDepthConsumed: number urlDepthConsumed: number,
groupDepthConsumed: number
): Promise<TreeResult> { ): Promise<TreeResult> {
const { parallelRoutes } = parseLoaderTree(loaderTree) const { parallelRoutes } = parseLoaderTree(loaderTree)
...@@ -862,12 +944,35 @@ export async function createCombinedPayloadAtDepth( ...@@ -862,12 +944,35 @@ export async function createCombinedPayloadAtDepth(
null null
) )
const consumesDepth = segmentConsumesURLDepth(segment) const consumesUrlDepth = segmentConsumesURLDepth(segment)
const isGroup =
typeof segment === 'string' &&
isGroupSegment(segment) &&
segment !== '(__SLOT__)'
// Advance counters for this segment before the boundary check,
// mirroring how discoverValidationDepths counts. URL segments
// increment urlDepthConsumed, groups increment groupDepthConsumed.
// The synthetic '(__SLOT__)' segment is excluded — it can't be a
// real navigation boundary.
let nextUrlDepth = urlDepthConsumed
let currentGroupDepth = groupDepthConsumed
if (consumesUrlDepth) {
nextUrlDepth++
currentGroupDepth = 0
} else if (isGroup) {
currentGroupDepth++
}
const pastUrlBoundary = nextUrlDepth > depth
const isBoundary = pastUrlBoundary && currentGroupDepth >= groupDepth
if (consumesDepth && urlDepthConsumed === depth) { if (isBoundary) {
debug?.(` ['${path}' is the boundary]`) debug?.(
` ['${path}' is the boundary (url=${nextUrlDepth}, group=${currentGroupDepth})]`
)
boundaryState.expectedIds.add(path) boundaryState.expectedIds.add(path)
const wrappedSegmentData: SegmentData = { const finalSegmentData: SegmentData = {
...segmentData, ...segmentData,
node: ( node: (
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- bundled in the server layer // eslint-disable-next-line @next/internal/no-ambiguous-jsx -- bundled in the server layer
...@@ -876,6 +981,7 @@ export async function createCombinedPayloadAtDepth( ...@@ -876,6 +981,7 @@ export async function createCombinedPayloadAtDepth(
</PlaceValidationBoundaryBelowThisLevel> </PlaceValidationBoundaryBelowThisLevel>
), ),
} }
const slots: CacheNodeSeedDataSlots = {} const slots: CacheNodeSeedDataSlots = {}
let requiresInstantUI = false let requiresInstantUI = false
let createInstantStack: (() => Error) | null = null let createInstantStack: (() => Error) | null = null
...@@ -895,13 +1001,13 @@ export async function createCombinedPayloadAtDepth( ...@@ -895,13 +1001,13 @@ export async function createCombinedPayloadAtDepth(
} }
} }
return { return {
seedData: getCacheNodeSeedDataFromSegment(wrappedSegmentData, slots), seedData: getCacheNodeSeedDataFromSegment(finalSegmentData, slots),
requiresInstantUI, requiresInstantUI,
createInstantStack, createInstantStack,
} }
} }
// Not the boundary yet — keep walking the shared tree. // Not at the boundary yet — keep walking as shared.
const slots: CacheNodeSeedDataSlots = {} const slots: CacheNodeSeedDataSlots = {}
let requiresInstantUI = false let requiresInstantUI = false
let createInstantStack: (() => Error) | null = null let createInstantStack: (() => Error) | null = null
...@@ -910,7 +1016,8 @@ export async function createCombinedPayloadAtDepth( ...@@ -910,7 +1016,8 @@ export async function createCombinedPayloadAtDepth(
parallelRoutes[parallelRouteKey], parallelRoutes[parallelRouteKey],
path, path,
parallelRouteKey, parallelRouteKey,
consumesDepth ? urlDepthConsumed + 1 : urlDepthConsumed nextUrlDepth,
currentGroupDepth
) )
slots[parallelRouteKey] = result.seedData slots[parallelRouteKey] = result.seedData
if (result.requiresInstantUI) { if (result.requiresInstantUI) {
...@@ -947,7 +1054,6 @@ export async function createCombinedPayloadAtDepth( ...@@ -947,7 +1054,6 @@ export async function createCombinedPayloadAtDepth(
if (layoutOrPageMod !== undefined) { if (layoutOrPageMod !== undefined) {
instantConfig = instantConfig =
(layoutOrPageMod as AppSegmentConfig).unstable_instant ?? null (layoutOrPageMod as AppSegmentConfig).unstable_instant ?? null
if (instantConfig && typeof instantConfig === 'object') { if (instantConfig && typeof instantConfig === 'object') {
const rawFactory: unknown = (layoutOrPageMod as any) const rawFactory: unknown = (layoutOrPageMod as any)
.__debugCreateInstantConfigStack .__debugCreateInstantConfigStack
...@@ -1042,7 +1148,8 @@ export async function createCombinedPayloadAtDepth( ...@@ -1042,7 +1148,8 @@ export async function createCombinedPayloadAtDepth(
initialLoaderTree, initialLoaderTree,
null /* parentPath */, null /* parentPath */,
null /* key */, null /* key */,
0 /* urlDepthConsumed */ 0 /* urlDepthConsumed */,
0 /* groupDepthConsumed */
) )
if (!requiresInstantUI) { if (!requiresInstantUI) {
......
...@@ -91,7 +91,7 @@ export default async function Page() { ...@@ -91,7 +91,7 @@ export default async function Page() {
<DebugLinks href="/suspense-in-root/static/valid-only-loading-around-dynamic" /> <DebugLinks href="/suspense-in-root/static/valid-only-loading-around-dynamic" />
</li> </li>
<li> <li>
<DebugLinks href="/suspense-in-root/static/valid-only-loading-around-dynamic-higher" /> <DebugLinks href="/suspense-in-root/static/invalid-loading-above-route-group" />
</li> </li>
<li> <li>
<DebugLinks href="/suspense-in-root/static/invalid-dynamic-layout-with-loading" /> <DebugLinks href="/suspense-in-root/static/invalid-dynamic-layout-with-loading" />
...@@ -185,6 +185,12 @@ export default async function Page() { ...@@ -185,6 +185,12 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/static/route-group-shared-boundary" /> <DebugLinks href="/suspense-in-root/static/route-group-shared-boundary" />
</li> </li>
<li>
<DebugLinks href="/suspense-in-root/static/parallel-group-depths-deep-slot-hole" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/parallel-group-depths-shallow-slot-hole" />
</li>
<li> <li>
<DebugLinks href="/suspense-in-root/static/route-group-shared-boundary/foo" /> <DebugLinks href="/suspense-in-root/static/route-group-shared-boundary/foo" />
</li> </li>
......
...@@ -11,8 +11,12 @@ export default async function Page() { ...@@ -11,8 +11,12 @@ export default async function Page() {
<main> <main>
<p> <p>
This page doesn't wrap runtime/dynamic components in suspense, but it This page doesn't wrap runtime/dynamic components in suspense, but it
has a loading.tsx above it. a self-navigation with a different search has a loading.tsx above it. However, the page is inside a route group
param value would block, but we accept that. and the loading.tsx is on the parent URL segment. Validation considers
the route group as a potential shared boundary where the loading.tsx
Suspense would already be revealed. In a more advanced system we would
analyze siblings of the route group to determine if such a navigation is
actually possible, but for now we conservatively report an error.
</p> </p>
<div> <div>
<Runtime /> <Runtime />
......
import { cookies } from 'next/headers'
import { ReactNode } from 'react'
export default async function B2Layout({ children }: { children: ReactNode }) {
await cookies()
return <div>{children}</div>
}
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return (
<main>
<p>Children page inside 2 nested route groups</p>
</main>
)
}
import { cookies } from 'next/headers'
import { ReactNode } from 'react'
// Hole in the 3rd (deepest) group of @slot. Detected at groupDepth=2
// where g2 is the boundary and g3 is in the new tree.
export default async function G3Layout({ children }: { children: ReactNode }) {
await cookies()
return <div>{children}</div>
}
export const unstable_instant = { prefetch: 'static' }
export default function SlotPage() {
return <p>Slot A page inside 3 nested route groups</p>
}
import { ReactNode } from 'react'
export default function Layout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div>
<div style={{ border: '1px solid blue', padding: '1em' }}>{slot}</div>
{children}
</div>
)
}
import { cookies } from 'next/headers'
import { ReactNode } from 'react'
export default async function B2Layout({ children }: { children: ReactNode }) {
await cookies()
return <div>{children}</div>
}
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return (
<main>
<p>Children page inside 2 nested route groups</p>
</main>
)
}
export const unstable_instant = { prefetch: 'static' }
export default function SlotPage() {
return <p>Slot A page inside 3 nested route groups</p>
}
import { cookies } from 'next/headers'
import { ReactNode } from 'react'
// Hole in the 1st (shallowest) group of @slot. Not detected before
// the children slot's b2 hole because at groupDepth=1, g1 is the
// boundary (shared) and b1 is the boundary with b2 new.
export default async function G1Layout({ children }: { children: ReactNode }) {
await cookies()
return <div>{children}</div>
}
import { ReactNode } from 'react'
export default function Layout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div>
<div style={{ border: '1px solid blue', padding: '1em' }}>{slot}</div>
{children}
</div>
)
}
import Link from 'next/link' import Link from 'next/link'
// The instant config is on the page. When (outer) is shared and
// (inner) is the boundary, this page is in the new tree where
// buildNewTreeSeedData finds the config and triggers validation.
export const unstable_instant = { prefetch: 'static' }
export default function Page() { export default function Page() {
return ( return (
<main> <main>
......
import { ReactNode, Suspense } from 'react' import { ReactNode, Suspense } from 'react'
// The unstable_instant config makes this route eligible for validation. // This layout has Suspense around children. When both (outer) and (inner)
// The Suspense here covers children in the validation render (where both // are in the new tree (groupDepth=0), the Suspense covers (inner)'s
// (outer) and (inner) are in the new tree), but in a real /foo → / client // blocking cookies() call. But when (outer) is shared (groupDepth=1),
// navigation, (outer)/layout is shared and its Suspense doesn't apply. // the Suspense is already mounted and doesn't cover the new tree.
export const unstable_instant = { prefetch: 'static' }
export default function OuterLayout({ children }: { children: ReactNode }) { export default function OuterLayout({ children }: { children: ReactNode }) {
return ( return (
<div> <div>
......
...@@ -175,7 +175,7 @@ describe('prefetch inlining', () => { ...@@ -175,7 +175,7 @@ describe('prefetch inlining', () => {
⇣ root ⇣ root
⇣ └── "test-parallel" ⇣ └── "test-parallel"
outlined ■ ├── "__PAGE__" outlined ■ ├── "__PAGE__"
⇣ └── @sidebar/"(slot)" ⇣ └── @sidebar/"(__SLOT__)"
outlined ■ └── "__PAGE__" outlined ■ └── "__PAGE__"
" "
`) `)
...@@ -184,7 +184,7 @@ describe('prefetch inlining', () => { ...@@ -184,7 +184,7 @@ describe('prefetch inlining', () => {
" "
⇣ root ⇣ root
⇣ └── "test-parallel" ⇣ └── "test-parallel"
⇣ ├── @sidebar/"(slot)" ⇣ ├── @sidebar/"(__SLOT__)"
outlined ■ │ └── "__PAGE__" outlined ■ │ └── "__PAGE__"
outlined ■ └── "__PAGE__" outlined ■ └── "__PAGE__"
" "
......
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