Unverified Commit 15cd0274 authored by Josh Story's avatar Josh Story Committed by GitHub

Add per-slot error attribution for instant validation using slot markers and…

Add per-slot error attribution for instant validation using slot markers and config depth preference (#91610)

When a validation boundary spans multiple parallel slots, errors were
previously attributed to whichever unstable_instant config was found
first during tree iteration — which varied between turbopack and
webpack. This made the "Caused by: Instant Validation" source
non-deterministic and sometimes pointed to the wrong slot's config.

This adds a SlotMarker client component that wraps each slot's content
at fork points (where parallel routes > 1). The marker's
dynamically-named inner function appears in the SSR component stack,
allowing resolveInstantStack to identify which slot an error belongs to
and look up that slot's config. When a slot has no config, it falls back
to slotStacks[0] (the root config).

The root config is now selected by config depth preference rather than
first-found. configDepth tracks how many URL-consuming segments deep a
config was found, with deeper configs preferred as more specific. At
equal depth, the children slot is preferred over named slots. This
ensures deterministic attribution regardless of bundler iteration order.

Key changes:
- SlotMarker component in boundary-impl.tsx takes a name prop and lazily
creates named inner functions cached by name
- slotStacks array replaces the singleton createInstantStack on
InstantValidationState (index 0 = root config, 1+ = per-slot)
- configDepth on TreeResult only counts URL-consuming segments —
synthetic segments like (__SLOT__), __PAGE__, and route groups don't
contribute
- resolveInstantStack parses component stacks for slot markers and maps
to the correct config
- wrapSlotsWithMarkers called at every fork in both
buildSharedTreeSeedData and buildNewTreeSeedData
parent d57459c3
...@@ -13,6 +13,7 @@ const { ...@@ -13,6 +13,7 @@ const {
InstantValidationBoundaryContext, InstantValidationBoundaryContext,
PlaceValidationBoundaryBelowThisLevel, PlaceValidationBoundaryBelowThisLevel,
RenderValidationBoundaryAtThisLevel, RenderValidationBoundaryAtThisLevel,
SlotMarker,
} = } =
typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS
? (require('../../../server/app-render/instant-validation/boundary-impl') as typeof import('../../../server/app-render/instant-validation/boundary-impl')) ? (require('../../../server/app-render/instant-validation/boundary-impl') as typeof import('../../../server/app-render/instant-validation/boundary-impl'))
...@@ -22,4 +23,5 @@ export { ...@@ -22,4 +23,5 @@ export {
InstantValidationBoundaryContext, InstantValidationBoundaryContext,
PlaceValidationBoundaryBelowThisLevel, PlaceValidationBoundaryBelowThisLevel,
RenderValidationBoundaryAtThisLevel, RenderValidationBoundaryAtThisLevel,
SlotMarker,
} }
...@@ -4766,7 +4766,7 @@ async function validateInstantConfigs( ...@@ -4766,7 +4766,7 @@ async function validateInstantConfigs(
) )
const instantValidationState = createInstantValidationState( const instantValidationState = createInstantValidationState(
payloadResult.createInstantStack payloadResult.slotStacks
) )
const validationSampleTracking = const validationSampleTracking =
......
...@@ -48,7 +48,11 @@ import { ...@@ -48,7 +48,11 @@ import {
import { scheduleOnNextTick } from '../../lib/scheduler' import { scheduleOnNextTick } from '../../lib/scheduler'
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants' import {
INSTANT_VALIDATION_BOUNDARY_NAME,
INSTANT_SLOT_MARKER_PREFIX,
INSTANT_SLOT_MARKER_SUFFIX,
} from './instant-validation/boundary-constants'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking' import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples' import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
...@@ -742,6 +746,34 @@ const hasOutletRegex = new RegExp(`\\n\\s+at ${OUTLET_BOUNDARY_NAME}[\\n\\s]`) ...@@ -742,6 +746,34 @@ const hasOutletRegex = new RegExp(`\\n\\s+at ${OUTLET_BOUNDARY_NAME}[\\n\\s]`)
const hasInstantValidationBoundaryRegex = new RegExp( const hasInstantValidationBoundaryRegex = new RegExp(
`\\n\\s+at ${INSTANT_VALIDATION_BOUNDARY_NAME}[\\n\\s]` `\\n\\s+at ${INSTANT_VALIDATION_BOUNDARY_NAME}[\\n\\s]`
) )
const slotMarkerRegex = new RegExp(
`\\n\\s+at ${INSTANT_SLOT_MARKER_PREFIX}(\\d+)${INSTANT_SLOT_MARKER_SUFFIX}[\\n\\s]`
)
/** Look up the config factory for the slot this error belongs to.
* Checks the component stack for a slot marker (__next_instant_slot_N__)
* and returns the config at that index. Falls back to index 0 (root
* config) when no slot marker is found or the slot has no config. */
function resolveInstantStack(
componentStack: string,
dynamicValidation: InstantValidationState
): (() => Error) | null {
const { slotStacks } = dynamicValidation
if (slotStacks.length > 1) {
const match = slotMarkerRegex.exec(componentStack)
if (match) {
// Slot markers are 0-indexed in the component name but
// slotStacks is 1-indexed (index 0 is the root config).
const slotIndex = parseInt(match[1], 10) + 1
const slotStack = slotStacks[slotIndex]
if (slotStack != null) {
return slotStack
}
}
}
// Fall back to root config (index 0)
return slotStacks[0] ?? null
}
export function trackAllowedDynamicAccess( export function trackAllowedDynamicAccess(
workStore: WorkStore, workStore: WorkStore,
...@@ -809,11 +841,13 @@ export type InstantValidationState = { ...@@ -809,11 +841,13 @@ export type InstantValidationState = {
dynamicErrors: Array<Error> dynamicErrors: Array<Error>
validationPreventingErrors: Array<Error> validationPreventingErrors: Array<Error>
thrownErrorsOutsideBoundary: Array<unknown> thrownErrorsOutsideBoundary: Array<unknown>
createInstantStack: (() => Error) | null /** Per-slot config factories. Index 0 is the root config (fallback).
* Indices 1+ correspond to slot marker components in the tree. */
slotStacks: Array<(() => Error) | null>
} }
export function createInstantValidationState( export function createInstantValidationState(
createInstantStack: (() => Error) | null slotStacks: Array<(() => Error) | null>
): InstantValidationState { ): InstantValidationState {
return { return {
hasDynamicMetadata: false, hasDynamicMetadata: false,
...@@ -824,7 +858,7 @@ export function createInstantValidationState( ...@@ -824,7 +858,7 @@ export function createInstantValidationState(
dynamicErrors: [], dynamicErrors: [],
validationPreventingErrors: [], validationPreventingErrors: [],
thrownErrorsOutsideBoundary: [], thrownErrorsOutsideBoundary: [],
createInstantStack, slotStacks,
} }
} }
...@@ -840,6 +874,14 @@ export function trackDynamicHoleInNavigation( ...@@ -840,6 +874,14 @@ export function trackDynamicHoleInNavigation(
// We don't need to track that this is dynamic. It is only so when something else is also dynamic. // We don't need to track that this is dynamic. It is only so when something else is also dynamic.
return return
} }
// Resolve the config stack for this specific error. If the error
// is inside a slot marker, use that slot's config. Otherwise fall
// back to the default.
const effectiveCreateInstantStack = resolveInstantStack(
componentStack,
dynamicValidation
)
if (hasMetadataRegex.test(componentStack)) { if (hasMetadataRegex.test(componentStack)) {
const usageDescription = const usageDescription =
kind === DynamicHoleKind.Runtime kind === DynamicHoleKind.Runtime
...@@ -849,7 +891,7 @@ export function trackDynamicHoleInNavigation( ...@@ -849,7 +891,7 @@ export function trackDynamicHoleInNavigation(
const error = addErrorContext( const error = addErrorContext(
new Error(message), new Error(message),
componentStack, componentStack,
dynamicValidation.createInstantStack effectiveCreateInstantStack
) )
dynamicValidation.dynamicMetadata = error dynamicValidation.dynamicMetadata = error
return return
...@@ -863,7 +905,7 @@ export function trackDynamicHoleInNavigation( ...@@ -863,7 +905,7 @@ export function trackDynamicHoleInNavigation(
const error = addErrorContext( const error = addErrorContext(
new Error(message), new Error(message),
componentStack, componentStack,
dynamicValidation.createInstantStack effectiveCreateInstantStack
) )
dynamicValidation.dynamicErrors.push(error) dynamicValidation.dynamicErrors.push(error)
return return
...@@ -893,7 +935,7 @@ export function trackDynamicHoleInNavigation( ...@@ -893,7 +935,7 @@ export function trackDynamicHoleInNavigation(
const error = addErrorContext( const error = addErrorContext(
new Error(message), new Error(message),
componentStack, componentStack,
dynamicValidation.createInstantStack effectiveCreateInstantStack
) )
dynamicValidation.validationPreventingErrors.push(error) dynamicValidation.validationPreventingErrors.push(error)
return return
...@@ -933,11 +975,8 @@ export function trackDynamicHoleInNavigation( ...@@ -933,11 +975,8 @@ export function trackDynamicHoleInNavigation(
if (clientDynamic.syncDynamicErrorWithStack) { if (clientDynamic.syncDynamicErrorWithStack) {
// This task was the task that called the sync error. // This task was the task that called the sync error.
const syncError = clientDynamic.syncDynamicErrorWithStack const syncError = clientDynamic.syncDynamicErrorWithStack
if ( if (effectiveCreateInstantStack !== null && syncError.cause === undefined) {
dynamicValidation.createInstantStack !== null && syncError.cause = effectiveCreateInstantStack()
syncError.cause === undefined
) {
syncError.cause = dynamicValidation.createInstantStack()
} }
dynamicValidation.dynamicErrors.push(syncError) dynamicValidation.dynamicErrors.push(syncError)
return return
...@@ -951,7 +990,7 @@ export function trackDynamicHoleInNavigation( ...@@ -951,7 +990,7 @@ export function trackDynamicHoleInNavigation(
const error = addErrorContext( const error = addErrorContext(
new Error(message), new Error(message),
componentStack, componentStack,
dynamicValidation.createInstantStack effectiveCreateInstantStack
) )
dynamicValidation.dynamicErrors.push(error) dynamicValidation.dynamicErrors.push(error)
return return
...@@ -1294,26 +1333,23 @@ export function getNavigationDisallowedDynamicReasons( ...@@ -1294,26 +1333,23 @@ export function getNavigationDisallowedDynamicReasons(
} }
if (boundaryState.renderedIds.size < boundaryState.expectedIds.size) { if (boundaryState.renderedIds.size < boundaryState.expectedIds.size) {
const { thrownErrorsOutsideBoundary, createInstantStack } = const { thrownErrorsOutsideBoundary } = dynamicValidation
dynamicValidation const rootInstantStack = dynamicValidation.slotStacks[0]
if (thrownErrorsOutsideBoundary.length === 0) { if (thrownErrorsOutsideBoundary.length === 0) {
const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.` const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.`
const error = const error = rootInstantStack !== null ? rootInstantStack() : new Error()
createInstantStack !== null ? createInstantStack() : new Error()
error.name = 'Error' error.name = 'Error'
error.message = message error.message = message
return [error] return [error]
} else if (thrownErrorsOutsideBoundary.length === 1) { } else if (thrownErrorsOutsideBoundary.length === 1) {
const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to the following error.` const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to the following error.`
const error = const error = rootInstantStack !== null ? rootInstantStack() : new Error()
createInstantStack !== null ? createInstantStack() : new Error()
error.name = 'Error' error.name = 'Error'
error.message = message error.message = message
return [error, thrownErrorsOutsideBoundary[0] as Error] return [error, thrownErrorsOutsideBoundary[0] as Error]
} else { } else {
const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to one of the following errors.` const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to one of the following errors.`
const error = const error = rootInstantStack !== null ? rootInstantStack() : new Error()
createInstantStack !== null ? createInstantStack() : new Error()
error.name = 'Error' error.name = 'Error'
error.message = message error.message = message
return [error, ...(thrownErrorsOutsideBoundary as Error[])] return [error, ...(thrownErrorsOutsideBoundary as Error[])]
......
export const INSTANT_VALIDATION_BOUNDARY_NAME = export const INSTANT_VALIDATION_BOUNDARY_NAME =
'__next_instant_validation_boundary__' '__next_instant_validation_boundary__'
export const INSTANT_SLOT_MARKER_PREFIX = '__next_instant_slot_'
export const INSTANT_SLOT_MARKER_SUFFIX = '__'
...@@ -107,3 +107,32 @@ const InstantValidationBoundary = ...@@ -107,3 +107,32 @@ const InstantValidationBoundary =
0 0
) as typeof INSTANT_VALIDATION_BOUNDARY_NAME ) as typeof INSTANT_VALIDATION_BOUNDARY_NAME
] ]
// Slot marker component for attributing validation errors to the
// correct config when a boundary spans multiple parallel slots.
// Renders a dynamically-named inner component so the slot index
// appears in the SSR component stack (__next_instant_slot_N__).
const slotMarkerCache = new Map<
string,
(props: { children: ReactNode }) => ReactNode
>()
export function SlotMarker({
name,
children,
}: {
name: string
children: ReactNode
}) {
let Marker = slotMarkerCache.get(name)
if (!Marker) {
const ns = {
[name]: function ({ children: c }: { children: ReactNode }) {
return c
},
}
Marker = ns[name]
slotMarkerCache.set(name, Marker)
}
return <Marker>{children}</Marker>
}
...@@ -17,9 +17,14 @@ import { ...@@ -17,9 +17,14 @@ import {
} from '../prospective-render-utils' } from '../prospective-render-utils'
import { getDigestForWellKnownError } from '../create-error-handler' import { getDigestForWellKnownError } from '../create-error-handler'
import { import {
// NOTE: we're in the server layer, so this is a client reference // NOTE: we're in the server layer, so these are client references
PlaceValidationBoundaryBelowThisLevel, PlaceValidationBoundaryBelowThisLevel,
SlotMarker,
} from '../../../client/components/instant-validation/boundary' } from '../../../client/components/instant-validation/boundary'
import {
INSTANT_SLOT_MARKER_PREFIX,
INSTANT_SLOT_MARKER_SUFFIX,
} from './boundary-constants'
import type { ValidationBoundaryTracking } from './boundary-tracking' import type { ValidationBoundaryTracking } from './boundary-tracking'
import { import {
getLayoutOrPageModule, getLayoutOrPageModule,
...@@ -758,6 +763,10 @@ type TreeResult = { ...@@ -758,6 +763,10 @@ type TreeResult = {
seedData: CacheNodeSeedData seedData: CacheNodeSeedData
requiresInstantUI: boolean requiresInstantUI: boolean
createInstantStack: (() => Error) | null createInstantStack: (() => Error) | null
/** How deep in the tree the config was found. Higher = more specific.
* Used to prefer deeper configs over shallower ones when multiple
* slots have configs. */
configDepth: number
} }
/** /**
...@@ -885,7 +894,11 @@ export type ValidationPayloadResult = { ...@@ -885,7 +894,11 @@ export type ValidationPayloadResult = {
* True when some segments used Static stage. False when all segments * True when some segments used Static stage. False when all segments
* used Runtime stage and errors are definitively from uncached IO. */ * used Runtime stage and errors are definitively from uncached IO. */
hasAmbiguousErrors: boolean hasAmbiguousErrors: boolean
createInstantStack: (() => Error) | null /** Per-slot config factories indexed by slot marker index. When a
* boundary spans multiple parallel slots, each slot gets a marker
* component in the tree. The marker's index maps to this array to
* find the right config for error attribution. */
slotStacks: Array<(() => Error) | null>
} }
export async function createCombinedPayloadAtDepth( export async function createCombinedPayloadAtDepth(
...@@ -904,6 +917,43 @@ export async function createCombinedPayloadAtDepth( ...@@ -904,6 +917,43 @@ export async function createCombinedPayloadAtDepth(
): Promise<ValidationPayloadResult | null> { ): Promise<ValidationPayloadResult | null> {
let hasStaticSegments = false let hasStaticSegments = false
let hasRuntimeSegments = false let hasRuntimeSegments = false
// Index 0 is reserved for the root config. Slot markers start at 1.
const slotStacks: Array<(() => Error) | null> = [null]
/**
* When a segment has multiple parallel routes (a fork), wrap each
* slot's seed data with a slot marker component. The marker's index
* in the component stack maps to `slotStacks` for per-slot error
* attribution. Slot markers start at index 1 (index 0 is root).
*/
function wrapSlotsWithMarkers(
slots: CacheNodeSeedDataSlots,
results: Map<string, TreeResult>
): void {
const keys = Object.keys(slots)
if (keys.length <= 1) return
for (const key of keys) {
const slotSeedData = slots[key]
if (slotSeedData === null) continue
const result = results.get(key)
const markerIndex = slotStacks.length
slotStacks.push(result?.createInstantStack ?? null)
const markerName = `${INSTANT_SLOT_MARKER_PREFIX}${markerIndex - 1}${INSTANT_SLOT_MARKER_SUFFIX}`
const [node, parallelRoutesData, unused, isPartial, varyParams] =
slotSeedData
slots[key] = [
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- bundled in the server layer
<SlotMarker name={markerName} key="sm">
{node}
</SlotMarker>,
parallelRoutesData,
unused,
isPartial,
varyParams,
]
}
}
function getSegment(loaderTree: LoaderTree): Segment { function getSegment(loaderTree: LoaderTree): Segment {
const dynamicParam = getDynamicParamFromSegment(loaderTree) const dynamicParam = getDynamicParamFromSegment(loaderTree)
...@@ -983,34 +1033,50 @@ export async function createCombinedPayloadAtDepth( ...@@ -983,34 +1033,50 @@ export async function createCombinedPayloadAtDepth(
} }
const slots: CacheNodeSeedDataSlots = {} const slots: CacheNodeSeedDataSlots = {}
const slotResults = new Map<string, TreeResult>()
let requiresInstantUI = false let requiresInstantUI = false
let createInstantStack: (() => Error) | null = null let createInstantStack: (() => Error) | null = null
let bestConfigDepth = -1
for (const parallelRouteKey in parallelRoutes) { for (const parallelRouteKey in parallelRoutes) {
const result = await buildNewTreeSeedData( const result = await buildNewTreeSeedData(
parallelRoutes[parallelRouteKey], parallelRoutes[parallelRouteKey],
path, path,
parallelRouteKey, parallelRouteKey,
false /* isInsideRuntimePrefetch */ false /* isInsideRuntimePrefetch */,
0 /* segmentDepth */
) )
slotResults.set(parallelRouteKey, result)
slots[parallelRouteKey] = result.seedData slots[parallelRouteKey] = result.seedData
if (result.requiresInstantUI) { if (result.requiresInstantUI) {
requiresInstantUI = true requiresInstantUI = true
if (createInstantStack === null) { if (
result.configDepth > bestConfigDepth ||
(result.configDepth === bestConfigDepth &&
parallelRouteKey === 'children')
) {
bestConfigDepth = result.configDepth
createInstantStack = result.createInstantStack createInstantStack = result.createInstantStack
} }
} }
} }
wrapSlotsWithMarkers(slots, slotResults)
return { return {
seedData: getCacheNodeSeedDataFromSegment(finalSegmentData, slots), seedData: getCacheNodeSeedDataFromSegment(finalSegmentData, slots),
requiresInstantUI, requiresInstantUI,
createInstantStack, createInstantStack,
configDepth: bestConfigDepth,
} }
} }
// Not at the boundary yet — keep walking as shared. // Not at the boundary yet — keep walking as shared.
const slots: CacheNodeSeedDataSlots = {} const slots: CacheNodeSeedDataSlots = {}
const slotResults = new Map<string, TreeResult>()
let requiresInstantUI = false let requiresInstantUI = false
let createInstantStack: (() => Error) | null = null let createInstantStack: (() => Error) | null = null
let bestConfigDepth = -1
for (const parallelRouteKey in parallelRoutes) { for (const parallelRouteKey in parallelRoutes) {
const result = await buildSharedTreeSeedData( const result = await buildSharedTreeSeedData(
parallelRoutes[parallelRouteKey], parallelRoutes[parallelRouteKey],
...@@ -1019,18 +1085,28 @@ export async function createCombinedPayloadAtDepth( ...@@ -1019,18 +1085,28 @@ export async function createCombinedPayloadAtDepth(
nextUrlDepth, nextUrlDepth,
currentGroupDepth currentGroupDepth
) )
slotResults.set(parallelRouteKey, result)
slots[parallelRouteKey] = result.seedData slots[parallelRouteKey] = result.seedData
if (result.requiresInstantUI) { if (result.requiresInstantUI) {
requiresInstantUI = true requiresInstantUI = true
if (createInstantStack === null) { if (
result.configDepth > bestConfigDepth ||
(result.configDepth === bestConfigDepth &&
parallelRouteKey === 'children')
) {
bestConfigDepth = result.configDepth
createInstantStack = result.createInstantStack createInstantStack = result.createInstantStack
} }
} }
} }
wrapSlotsWithMarkers(slots, slotResults)
return { return {
seedData: getCacheNodeSeedDataFromSegment(segmentData, slots), seedData: getCacheNodeSeedDataFromSegment(segmentData, slots),
requiresInstantUI, requiresInstantUI,
createInstantStack, createInstantStack,
configDepth: bestConfigDepth,
} }
} }
...@@ -1038,7 +1114,8 @@ export async function createCombinedPayloadAtDepth( ...@@ -1038,7 +1114,8 @@ export async function createCombinedPayloadAtDepth(
lt: LoaderTree, lt: LoaderTree,
parentPath: SegmentPath | null, parentPath: SegmentPath | null,
key: string | null, key: string | null,
isInsideRuntimePrefetch: boolean isInsideRuntimePrefetch: boolean,
segmentDepth: number
): Promise<TreeResult> { ): Promise<TreeResult> {
const { parallelRoutes } = parseLoaderTree(lt) const { parallelRoutes } = parseLoaderTree(lt)
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(lt) const { mod: layoutOrPageMod } = await getLayoutOrPageModule(lt)
...@@ -1104,42 +1181,61 @@ export async function createCombinedPayloadAtDepth( ...@@ -1104,42 +1181,61 @@ export async function createCombinedPayloadAtDepth(
// Build children first, then determine requiresInstantUI. // Build children first, then determine requiresInstantUI.
const slots: CacheNodeSeedDataSlots = {} const slots: CacheNodeSeedDataSlots = {}
const slotResults = new Map<string, TreeResult>()
let childrenRequireInstantUI = false let childrenRequireInstantUI = false
let childCreateInstantStack: (() => Error) | null = null let childCreateInstantStack: (() => Error) | null = null
let bestChildConfigDepth = -1
for (const parallelRouteKey in parallelRoutes) { for (const parallelRouteKey in parallelRoutes) {
const childSegmentDepth = segmentConsumesURLDepth(segment)
? segmentDepth + 1
: segmentDepth
const result = await buildNewTreeSeedData( const result = await buildNewTreeSeedData(
parallelRoutes[parallelRouteKey], parallelRoutes[parallelRouteKey],
path, path,
parallelRouteKey, parallelRouteKey,
childIsInsideRuntimePrefetch childIsInsideRuntimePrefetch,
childSegmentDepth
) )
slotResults.set(parallelRouteKey, result)
slots[parallelRouteKey] = result.seedData slots[parallelRouteKey] = result.seedData
if (result.requiresInstantUI) { if (result.requiresInstantUI) {
childrenRequireInstantUI = true childrenRequireInstantUI = true
if (childCreateInstantStack === null) { if (
result.configDepth > bestChildConfigDepth ||
(result.configDepth === bestChildConfigDepth &&
parallelRouteKey === 'children')
) {
bestChildConfigDepth = result.configDepth
childCreateInstantStack = result.createInstantStack childCreateInstantStack = result.createInstantStack
} }
} }
} }
wrapSlotsWithMarkers(slots, slotResults)
// Local config takes precedence over children. // Local config takes precedence over children.
let requiresInstantUI: boolean let requiresInstantUI: boolean
let createInstantStack: (() => Error) | null let createInstantStack: (() => Error) | null
let configDepth: number
if (instantConfig === false) { if (instantConfig === false) {
requiresInstantUI = false requiresInstantUI = false
createInstantStack = null createInstantStack = null
configDepth = -1
} else if (instantConfig && typeof instantConfig === 'object') { } else if (instantConfig && typeof instantConfig === 'object') {
requiresInstantUI = true requiresInstantUI = true
createInstantStack = localCreateInstantStack createInstantStack = localCreateInstantStack
configDepth = segmentDepth
} else { } else {
requiresInstantUI = childrenRequireInstantUI requiresInstantUI = childrenRequireInstantUI
createInstantStack = childCreateInstantStack createInstantStack = childCreateInstantStack
configDepth = bestChildConfigDepth
} }
return { return {
seedData: getCacheNodeSeedDataFromSegment(segmentData, slots), seedData: getCacheNodeSeedDataFromSegment(segmentData, slots),
requiresInstantUI, requiresInstantUI,
createInstantStack, createInstantStack,
configDepth,
} }
} }
...@@ -1156,6 +1252,10 @@ export async function createCombinedPayloadAtDepth( ...@@ -1156,6 +1252,10 @@ export async function createCombinedPayloadAtDepth(
return null return null
} }
// Set the root config at index 0. This is the fallback for errors
// that occur above any fork (no slot marker in the component stack).
slotStacks[0] = createInstantStack
const { flightRouterState } = getRootDataFromPayload(initialRSCPayload) const { flightRouterState } = getRootDataFromPayload(initialRSCPayload)
const headStage = hasRuntimeSegments const headStage = hasRuntimeSegments
...@@ -1178,6 +1278,6 @@ export async function createCombinedPayloadAtDepth( ...@@ -1178,6 +1278,6 @@ export async function createCombinedPayloadAtDepth(
return { return {
payload, payload,
hasAmbiguousErrors: hasStaticSegments, hasAmbiguousErrors: hasStaticSegments,
createInstantStack, slotStacks,
} }
} }
...@@ -50,6 +50,9 @@ export default async function Page() { ...@@ -50,6 +50,9 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io-in-generate-metadata" /> <DebugLinks href="/suspense-in-root/runtime/invalid-sync-io-in-generate-metadata" />
</li> </li>
<li>
<DebugLinks href="/suspense-in-root/runtime/static-layout-above-runtime-config/inner" />
</li>
<li> <li>
<DebugLinks href="/suspense-in-root/runtime/valid-sync-io-in-generate-metadata-static-page" /> <DebugLinks href="/suspense-in-root/runtime/valid-sync-io-in-generate-metadata-static-page" />
</li> </li>
...@@ -138,6 +141,9 @@ export default async function Page() { ...@@ -138,6 +141,9 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/static/valid-client-error-in-parent-does-not-block-validation" /> <DebugLinks href="/suspense-in-root/static/valid-client-error-in-parent-does-not-block-validation" />
</li> </li>
<li>
<DebugLinks href="/suspense-in-root/static/false-below-static" />
</li>
</ul> </ul>
<h2>Head</h2> <h2>Head</h2>
...@@ -191,9 +197,24 @@ export default async function Page() { ...@@ -191,9 +197,24 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/static/parallel-group-depths-shallow-slot-hole" /> <DebugLinks href="/suspense-in-root/static/parallel-group-depths-shallow-slot-hole" />
</li> </li>
<li>
<DebugLinks href="/suspense-in-root/static/parallel-nested-forks" />
</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>
<li>
<DebugLinks href="/suspense-in-root/static/config-depth-preference/deeper/still/deep" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/config-depth-preference-slot-wins/deeper/still/deep" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/config-children-preferred" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/cross-slot-blocking/inner/deep" />
</li>
</ul> </ul>
<h2>Disable Validation</h2> <h2>Disable Validation</h2>
......
import { ReactNode } from 'react'
// This layout has the runtime prefetch config. The developer expects
// runtime prefetching to handle dynamic data, but the parent layout
// above this one gets static prefetching by default and blocks.
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default function InnerLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>Inner layout with runtime prefetch config</em>
{children}
</div>
)
}
export default function Page() {
return (
<main>
<p>Page inside inner layout with runtime prefetch config</p>
</main>
)
}
import { cookies } from 'next/headers'
import { ReactNode } from 'react'
// This layout calls cookies() without Suspense and has no instant
// config. It sits above a deeper layout with runtime prefetch config.
// From the developer's perspective, they configured runtime prefetching
// deeper in the tree, so cookies() should be fine. But this layout
// gets static prefetching by default (since the config is below it),
// making the cookies() call a blocking violation.
export default async function StaticLayout({
children,
}: {
children: ReactNode
}) {
await cookies()
return (
<div>
<em>Static layout above runtime config (calls cookies)</em>
{children}
</div>
)
}
// @other has config at the same depth as children's page.
// Children's config should be preferred for the root cause
// because children wins at equal depth.
export const unstable_instant = { prefetch: 'static' }
export default function OtherPage() {
return <p>Other slot page — same-depth config, no blocking</p>
}
import { cookies } from 'next/headers'
// @slot has NO config but blocks. The root config should be
// children's config (not some other named slot's) because
// children is preferred at equal depth.
export default async function SlotPage() {
await cookies()
return <p>Slot page — no config, blocks with cookies()</p>
}
import { ReactNode } from 'react'
export default function Layout({
children,
slot,
other,
}: {
children: ReactNode
slot: ReactNode
other: ReactNode
}) {
return (
<div>
<div style={{ border: '1px solid blue', padding: '1em' }}>{slot}</div>
<div style={{ border: '1px solid green', padding: '1em' }}>{other}</div>
{children}
</div>
)
}
// Children and @other both have config at the same depth (page level).
// Children's config should be preferred as the root cause when the
// error is in @slot (which has no config).
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return (
<main>
<p>Children page — same-depth config, no blocking</p>
</main>
)
}
import { cookies } from 'next/headers'
// @slot has NO config but blocks with cookies(). The cause must
// come from the deepest config — @anotherSlot/still/deep/page.tsx,
// not children's shallower catchall config.
export default async function CatchallSlotPage() {
await cookies()
return <p>Slot catchall page — no config, blocks with cookies()</p>
}
// Deepest config — in @anotherSlot, deeper than children's catchall.
// Should be preferred as the root cause because depth wins.
export const unstable_instant = { prefetch: 'static' }
export default function AnotherSlotDeepPage() {
return <p>Another slot deep page — deepest config, no blocking</p>
}
// Children's config via catchall — shallower than @anotherSlot's
// deep config. Should NOT be preferred as root cause.
export const unstable_instant = { prefetch: 'static' }
export default function ChildrenCatchallPage() {
return (
<main>
<p>Children catchall page — shallow config, no blocking</p>
</main>
)
}
import { ReactNode } from 'react'
export default function DeeperLayout({
children,
anotherSlot,
}: {
children: ReactNode
anotherSlot: ReactNode
}) {
return (
<div>
<div style={{ border: '1px solid green', padding: '0.5em' }}>
{anotherSlot}
</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 { cookies } from 'next/headers'
// @slot has NO config but blocks with cookies(). The cause must
// come from the children slot's configs. The deepest config
// (still/deep/page.tsx) should be preferred over the shallower
// one (@anotherSlot/page.tsx).
export default async function CatchallSlotPage() {
await cookies()
return <p>Slot catchall page — no config, blocks with cookies()</p>
}
export default function AnotherSlotDefault() {
return <p>Another slot default</p>
}
// Shallow config in a named slot. The deeper config in
// still/deep/page.tsx should be preferred over this one.
export const unstable_instant = { prefetch: 'static' }
export default function AnotherSlotPage() {
return <p>Another slot page — shallow config, no blocking</p>
}
import { ReactNode } from 'react'
export default function DeeperLayout({
children,
anotherSlot,
}: {
children: ReactNode
anotherSlot: ReactNode
}) {
return (
<div>
<div style={{ border: '1px solid green', padding: '0.5em' }}>
{anotherSlot}
</div>
{children}
</div>
)
}
// Deepest config — should be preferred as the root cause when
// the error is in @slot (which has no config).
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return (
<main>
<p>Deepest children page — deep config, no blocking</p>
</main>
)
}
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'
// @slot has NO instant config but calls cookies() without Suspense.
// This blocks the navigation, violating the instant config that's
// deep in the children slot (inner/deep/page.tsx) behind a second
// fork point. The cause should fall back to the root config.
export default async function CatchallSlotPage() {
await cookies()
return <p>Slot catchall page — blocks with cookies(), no config</p>
}
export default function PanelPage() {
return <p>Panel page — no config, no blocking</p>
}
// The instant config is deep in the children slot, behind a
// second fork point (inner/layout.tsx has @panel). The blocking
// code is in @slot at the outer fork. The slot marker for @slot
// has no config, so the cause must fall back to the root config.
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return (
<main>
<p>Deep children page with instant config (does not block)</p>
</main>
)
}
import { ReactNode } from 'react'
export default function InnerLayout({
children,
panel,
}: {
children: ReactNode
panel: ReactNode
}) {
return (
<div>
<div style={{ border: '1px solid green', padding: '0.5em' }}>{panel}</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 { ReactNode } from 'react'
// This layout requires instant UI with static prefetching.
// Even though the page below opts out with `false`, this layout's
// config still triggers validation at depths where both the layout
// and the page are in the new tree.
export const unstable_instant = { prefetch: 'static' }
export default function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
import { cookies } from 'next/headers'
// This page opts out with `false`, but the parent layout has a
// static config. At depths where both are in the new tree, the
// layout's config wins and validation still catches this page's
// blocking cookies() call without Suspense.
export const unstable_instant = false
export default async function Page() {
await cookies()
return (
<main>
<p>
This page has unstable_instant = false but the parent layout has
prefetch: 'static'. The layout's config still triggers validation.
</p>
</main>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export default async function Slot2aPage() {
await cookies()
return <p>Slot 2a — blocks with cookies()</p>
}
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export default async function Slot2bPage() {
await cookies()
return <p>Slot 2b — blocks with cookies()</p>
}
import { ReactNode } from 'react'
// This layout has no children slot — only named slots slot2a and slot2b.
export default function Slot1Layout({
slot2a,
slot2b,
}: {
slot2a: ReactNode
slot2b: ReactNode
}) {
return (
<div>
<div style={{ border: '1px solid green', padding: '0.5em' }}>
{slot2a}
</div>
<div style={{ border: '1px solid red', padding: '0.5em' }}>{slot2b}</div>
</div>
)
}
import { ReactNode } from 'react'
export default function Layout({
children,
slot1,
}: {
children: ReactNode
slot1: ReactNode
}) {
return (
<div>
<div style={{ border: '1px solid blue', padding: '1em' }}>{slot1}</div>
{children}
</div>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
await cookies()
return (
<main>
<p>Children page — blocks with cookies()</p>
</main>
)
}
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