Unverified Commit 4e75a9c3 authored by Josh Story's avatar Josh Story Committed by GitHub

Instant Insights: only report non-validatable if dev render is error free (#93858)

When an error prevents validation from happening that same error likely
shows up in the main dev render. To avoid double reporting in dev we
silence notices about validation being incomplete if the main render has
errors to report to the user. If no user facing errors exist then we
will report the lack of validation as it's own issue to confront.
parent 30421ba1
......@@ -1469,7 +1469,9 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
isBuildTimePrerendering = false,
} = renderOpts
let didErrorObservably = false
function onFlightDataRenderError(err: DigestedError, silenceLog: boolean) {
didErrorObservably = true
return onInstrumentationRequestError?.(
err,
req,
......@@ -1579,7 +1581,8 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
ctx,
finalRequestStore,
fallbackParams,
validationDebugChannelClient
validationDebugChannelClient,
didErrorObservably
)
} else {
logValidationSkipped(ctx)
......@@ -3401,7 +3404,11 @@ async function renderToStream(
return getTracer().withSpan(renderSpan, async () => {
// MARK: renderToStream errorHandlers
const { reactServerErrorsByDigest } = workStore
// We use this to determine if we should suppress other derivative errors
let didErrorObservably = false
function onHTMLRenderRSCError(err: DigestedError, silenceLog: boolean) {
didErrorObservably = true
return onInstrumentationRequestError?.(
err,
req,
......@@ -3533,7 +3540,8 @@ async function renderToStream(
ctx,
finalRequestStore,
fallbackParams,
validationDebugChannelClient
validationDebugChannelClient,
didErrorObservably
)
reactServerResult = new ReactServerResult(serverStream)
......@@ -3652,7 +3660,8 @@ async function renderToStream(
ctx,
finalRequestStore,
fallbackParams,
validationDebugChannelClient
validationDebugChannelClient,
didErrorObservably
)
reactServerResult = new ReactServerResult(serverStream)
......@@ -5604,7 +5613,8 @@ async function spawnStaticShellValidationInDevImpl(
ctx: AppRenderContext,
requestStore: RequestStore,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
debugChannelClient: AnyStream | undefined
debugChannelClient: AnyStream | undefined,
devRenderDidError: boolean
): Promise<void> {
const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
......@@ -5735,7 +5745,8 @@ async function spawnStaticShellValidationInDevImpl(
fallbackRouteParams,
ctx,
hmrRefreshHash,
validationSamples
validationSamples,
devRenderDidError
)
if (instantConfigsResult.length > 0) {
......@@ -6093,7 +6104,8 @@ async function validateInstantConfigs(
fallbackRouteParams: OpaqueFallbackRouteParams | null,
ctx: AppRenderContext,
hmrRefreshHash: string | undefined,
validationSamples: ValidationStoreClient['validationSamples'] | null
validationSamples: ValidationStoreClient['validationSamples'] | null,
devRenderDidError: boolean
): Promise<Array<unknown>> {
const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
......@@ -6340,7 +6352,8 @@ async function validateInstantConfigs(
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
instantValidationState,
validationSampleTracking,
boundaryState
boundaryState,
devRenderDidError
)
} catch (thrownValue) {
result = getNavigationDisallowedDynamicReasons(
......@@ -6348,7 +6361,8 @@ async function validateInstantConfigs(
PreludeState.Errored,
instantValidationState,
validationSampleTracking,
boundaryState
boundaryState,
devRenderDidError
)
}
......@@ -7109,7 +7123,8 @@ async function validateInstantConfigInBuildWithSample(
fallbackRouteParams,
validationCtx,
undefined, // hmrRefreshHash,
validationSamples
validationSamples,
false // build has no shared dev render that would surface errors
)
})
}
......
......@@ -1390,7 +1390,8 @@ export function getNavigationDisallowedDynamicReasons(
prelude: PreludeState,
dynamicValidation: InstantValidationState,
validationSampleTracking: InstantValidationSampleTracking | null,
boundaryState: ValidationBoundaryTracking
boundaryState: ValidationBoundaryTracking,
devRenderDidError: boolean
): NavigationValidationResult {
// If we have errors related to missing samples, those should take precedence over everything else.
if (validationSampleTracking) {
......@@ -1402,6 +1403,12 @@ export function getNavigationDisallowedDynamicReasons(
const { validationPreventingErrors } = dynamicValidation
if (validationPreventingErrors.length > 0) {
if (process.env.__NEXT_DEV_SERVER && devRenderDidError) {
// The dev render already surfaced server errors to the user.
// The same errors likely caused validation to be inconclusive,
// so reporting them again as validation failures would be noisy.
return []
}
return validationPreventingErrors
}
......@@ -1480,6 +1487,11 @@ export function getNavigationDisallowedDynamicReasons(
}
const error = new Error(message)
return error
} else if (process.env.__NEXT_DEV_SERVER && devRenderDidError) {
// Errors outside the boundary likely blocked it from rendering,
// but they're already being reported to the user via the dev
// render. Suppress the validation failure to avoid noise.
return []
} 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 error = rootInstantStack !== null ? rootInstantStack() : new Error()
......
......@@ -141,6 +141,12 @@ export default async function Page() {
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-error-in-parent-does-not-block-validation" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/server-error-blocks-children" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/server-error-inside-boundary" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/false-below-static" />
</li>
......
import { Suspense, type ReactNode } from 'react'
import { connection } from 'next/server'
export const unstable_instant = false
function ServerError() {
throw new Error('Server component error')
}
export default async function Layout({ children }: { children: ReactNode }) {
await connection()
return (
<>
<p>
This layout renders a server component that throws. The error is caught
by a Suspense boundary but wraps the children slot, preventing the
instant page from rendering.
</p>
<Suspense>
<ServerError />
{children}
</Suspense>
</>
)
}
export const unstable_instant = { level: 'experimental-error' }
export default function Page() {
return (
<main>
<p>
This page has instant validation but a server error in the parent layout
blocks it from rendering.
</p>
</main>
)
}
import { type ReactNode } from 'react'
import { connection } from 'next/server'
export const unstable_instant = false
function ServerError() {
throw new Error('Server component error inside boundary')
}
export default async function Layout({ children }: { children: ReactNode }) {
await connection()
return (
<>
<p>
This layout renders a server component that throws without a Suspense
boundary. The error is inside the validation boundary so it prevents
validation from completing.
</p>
<ServerError />
{children}
</>
)
}
export const unstable_instant = { level: 'experimental-error' }
export default function Page() {
return (
<main>
<p>
This page has instant validation but a server error in the parent layout
is inside the boundary without a Suspense guard.
</p>
</main>
)
}
import { nextTestSetup } from 'e2e-utils'
import {
extractBuildValidationError,
waitForValidation,
} from 'e2e-utils/instant-validation'
import { retry, waitForRedbox } from '../../../lib/next-test-utils'
import { createRedboxSnapshot } from '../../../lib/add-redbox-matchers'
import { Playwright } from '../../../lib/next-webdriver'
describe('instant validation - server errors', () => {
const { next, skipped, isNextDev, isNextStart, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
env: {
NEXT_TEST_LOG_VALIDATION: '1',
},
})
if (skipped) return
if (isNextStart && !isTurbopack) {
it.skip('TODO: snapshot tests for webpack', () => {})
return
}
if (isNextStart) {
beforeAll(async () => {
await next.build({ args: ['--experimental-build-mode', 'compile'] })
})
afterEach(async () => {
await next.stop()
})
} else {
beforeAll(async () => {
await next.start()
})
}
let currentCliOutputIndex = 0
beforeEach(() => {
currentCliOutputIndex = next.cliOutput.length
})
function getCliOutputSinceMark(): string {
if (next.cliOutput.length < currentCliOutputIndex) {
currentCliOutputIndex = 0
}
return next.cliOutput.slice(currentCliOutputIndex)
}
const prerender = async (pathname: string) => {
const args = [
'--experimental-build-mode',
'generate',
'--debug-build-paths',
`app${pathname}/page.tsx`,
]
return await next.build({ args })
}
const cases = isNextDev
? [
{ isClientNav: false, description: 'dev - initial load' },
{ isClientNav: true, description: 'dev - client navigation' },
]
: [{ isClientNav: false, description: 'build' }]
describe.each(cases)('$description', ({ isClientNav }) => {
it('server error blocks children - validation suppressed', async () => {
if (isNextDev) {
const browser = isClientNav
? await navigateViaClientNav(
'/suspense-in-root/static/server-error-blocks-children'
)
: await next.browser(
'/suspense-in-root/static/server-error-blocks-children'
)
await waitForRedbox(browser)
await waitForValidation(await browser.url(), getCliOutputSinceMark)
const errors = await createRedboxSnapshot(browser, next)
expect(errors).toMatchInlineSnapshot(`
{
"description": "Server component error",
"environmentLabel": "Server",
"label": "Runtime Error",
"source": "app/suspense-in-root/static/server-error-blocks-children/layout.tsx (7:9) @ ServerError
> 7 | throw new Error('Server component error')
| ^",
"stack": [
"ServerError app/suspense-in-root/static/server-error-blocks-children/layout.tsx (7:9)",
],
}
`)
} else {
const result = await prerender(
'/suspense-in-root/static/server-error-blocks-children'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/suspense-in-root/static/server-error-blocks-children": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to the following error.
at ignore-listed frames
Error: An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.
at a (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
at b (<anonymous>) {
[cause]: Error: Server component error
at c (app/suspense-in-root/static/server-error-blocks-children/layout.tsx:7:9)
at d (<anonymous>)
5 |
6 | function ServerError() {
> 7 | throw new Error('Server component error')
| ^
8 | }
9 |
10 | export default async function Layout({ children }: { children: ReactNode }) { {
digest: '<error-digest>'
}
}
Build-time instant validation failed for route "/suspense-in-root/static/server-error-blocks-children".
To get a more detailed stack trace and pinpoint the issue, try one of the following:
- Start the app in development mode by running \`next dev\`, then open "/suspense-in-root/static/server-error-blocks-children" in your browser to investigate the error.
- Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
}
})
it('server error inside boundary - validation suppressed', async () => {
if (isNextDev) {
const browser = isClientNav
? await navigateViaClientNav(
'/suspense-in-root/static/server-error-inside-boundary'
)
: await next.browser(
'/suspense-in-root/static/server-error-inside-boundary'
)
await waitForRedbox(browser)
await waitForValidation(await browser.url(), getCliOutputSinceMark)
const errors = await createRedboxSnapshot(browser, next)
expect(errors).toMatchInlineSnapshot(`
{
"description": "Server component error inside boundary",
"environmentLabel": "Server",
"label": "Runtime Error",
"source": "app/suspense-in-root/static/server-error-inside-boundary/layout.tsx (7:9) @ ServerError
> 7 | throw new Error('Server component error inside boundary')
| ^",
"stack": [
"ServerError app/suspense-in-root/static/server-error-inside-boundary/layout.tsx (7:9)",
],
}
`)
} else {
const result = await prerender(
'/suspense-in-root/static/server-error-inside-boundary'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/suspense-in-root/static/server-error-inside-boundary": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to the following error.
at ignore-listed frames
Error: An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.
at body (<anonymous>)
at html (<anonymous>)
at a (<anonymous>) {
[cause]: Error: Server component error inside boundary
at b (app/suspense-in-root/static/server-error-inside-boundary/layout.tsx:7:9)
at c (<anonymous>)
5 |
6 | function ServerError() {
> 7 | throw new Error('Server component error inside boundary')
| ^
8 | }
9 |
10 | export default async function Layout({ children }: { children: ReactNode }) { {
digest: '<error-digest>'
}
}
Build-time instant validation failed for route "/suspense-in-root/static/server-error-inside-boundary".
To get a more detailed stack trace and pinpoint the issue, try one of the following:
- Start the app in development mode by running \`next dev\`, then open "/suspense-in-root/static/server-error-inside-boundary" in your browser to investigate the error.
- Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
}
})
})
async function navigateViaClientNav(href: string): Promise<Playwright> {
const browser = await next.browser('/suspense-in-root')
await browser
.elementByCss(`[data-link-type="soft"][href="${href}"]`)
.click()
await retry(
async () => {
expect(await browser.url()).toContain(href)
},
undefined,
100,
'wait for url to change'
)
return browser
}
})
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