Unverified Commit ee0d02ad authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix `'use cache'` bail-out under `unstable_instant = false` (#94198)

This fixes a bug where pages exporting `unstable_instant = false` cause
their `'use cache'` reads to be incorrectly treated as dynamic, so the
build emits an empty static shell where it should contain the cached
content.

The root cause sits in the cache wrapper's Resume Data Cache (RDC) miss
bail-out. When prerendering a fallback shell whose RDC is the prefilled,
read-only seed from a phase-1 prerender of a more-specific sibling
route, a `'use cache'` miss is short-circuited to a dynamic hole — under
that contract a miss means the cache key depends on a fallback param.
That bail was gated on `workUnitStore.allowEmptyStaticShell`, which
originally coincided with "we have a read-only seed" because the
fallback-shell flow was the only thing setting the flag. #89077 widened
the flag to also cover `unstable_instant = false`, which has no seed, so
the bail started firing for routes that should be allowed to fill their
caches normally.

To fix this, we're replacing the proxy condition with the structural
check `workUnitStore.resumeDataCache?.mutable === false`, which
precisely matches the case the bail is for: a prerender whose RDC is the
immutable, prefilled seed. This avoids the false positive for when
`unstable_instant = false` is set and we're doing a prospective
prerender with an empty mutable RDC. The check is type-narrowed via the
discriminated union introduced in #94194, which is why that PR landed
first. With the cache wrapper no longer the consumer,
`workUnitStore.allowEmptyStaticShell` is removed from the prerender
store — the flag survives only as `renderOpts.allowEmptyStaticShell` and
a local parameter feeding the "shell may be empty for any reason" check
in `dynamic-rendering.ts`.
parent 8c661813
...@@ -5644,7 +5644,6 @@ async function spawnStaticShellValidationInDevImpl( ...@@ -5644,7 +5644,6 @@ async function spawnStaticShellValidationInDevImpl(
dynamicChunks, dynamicChunks,
rootParams, rootParams,
fallbackRouteParams, fallbackRouteParams,
allowEmptyStaticShell,
ctx, ctx,
validationSamples, validationSamples,
validationSampleTracking validationSampleTracking
...@@ -5718,7 +5717,6 @@ async function warmupClientModulesForStagedValidation( ...@@ -5718,7 +5717,6 @@ async function warmupClientModulesForStagedValidation(
allServerChunks: Array<Uint8Array>, allServerChunks: Array<Uint8Array>,
rootParams: Params, rootParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null, fallbackRouteParams: OpaqueFallbackRouteParams | null,
allowEmptyStaticShell: boolean,
ctx: AppRenderContext, ctx: AppRenderContext,
validationSamples: ValidationStoreClient['validationSamples'], validationSamples: ValidationStoreClient['validationSamples'],
validationSampleTracking: ValidationStoreClient['validationSampleTracking'] validationSampleTracking: ValidationStoreClient['validationSampleTracking']
...@@ -5747,7 +5745,6 @@ async function warmupClientModulesForStagedValidation( ...@@ -5747,7 +5745,6 @@ async function warmupClientModulesForStagedValidation(
// is module loading, which has it's own cache signal // is module loading, which has it's own cache signal
cacheSignal: null, cacheSignal: null,
dynamicTracking: null, dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -5920,7 +5917,6 @@ async function validateStagedShell( ...@@ -5920,7 +5917,6 @@ async function validateStagedShell(
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender // No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null, cacheSignal: null,
dynamicTracking: clientDynamicTracking, dynamicTracking: clientDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -7033,10 +7029,6 @@ async function validateInstantConfigInBuildWithSample( ...@@ -7033,10 +7029,6 @@ async function validateInstantConfigInBuildWithSample(
return [stageController.syncInterruptReason] return [stageController.syncInterruptReason]
} }
const allowEmptyStaticShell =
(validationCtx.renderOpts.allowEmptyStaticShell ?? false) ||
(await isPageAllowedToBlock(loaderTree))
// Now we the chunks of a fully rendered page, just like in dev. // Now we the chunks of a fully rendered page, just like in dev.
// We can use them to validate all the navigations required by `instant` configs. // We can use them to validate all the navigations required by `instant` configs.
// Note that we're not performing static shell validation here -- that happens // Note that we're not performing static shell validation here -- that happens
...@@ -7056,7 +7048,6 @@ async function validateInstantConfigInBuildWithSample( ...@@ -7056,7 +7048,6 @@ async function validateInstantConfigInBuildWithSample(
accumulatedChunks.dynamicChunks, accumulatedChunks.dynamicChunks,
sampleRootParams, sampleRootParams,
fallbackRouteParams, fallbackRouteParams,
allowEmptyStaticShell,
validationCtx, validationCtx,
validationSamples, validationSamples,
warmupValidationSamplesTracking warmupValidationSamplesTracking
...@@ -7407,7 +7398,6 @@ async function prerenderToStream( ...@@ -7407,7 +7398,6 @@ async function prerenderToStream(
// the final prerender. // the final prerender.
cacheSignal, cacheSignal,
dynamicTracking: null, dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -7441,7 +7431,6 @@ async function prerenderToStream( ...@@ -7441,7 +7431,6 @@ async function prerenderToStream(
// the final prerender. // the final prerender.
cacheSignal, cacheSignal,
dynamicTracking: null, dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -7563,7 +7552,6 @@ async function prerenderToStream( ...@@ -7563,7 +7552,6 @@ async function prerenderToStream(
// is module loading, which has it's own cache signal // is module loading, which has it's own cache signal
cacheSignal: null, cacheSignal: null,
dynamicTracking: null, dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -7680,7 +7668,6 @@ async function prerenderToStream( ...@@ -7680,7 +7668,6 @@ async function prerenderToStream(
// All caches we could read must already be filled so no tracking is necessary // All caches we could read must already be filled so no tracking is necessary
cacheSignal: null, cacheSignal: null,
dynamicTracking: null, dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -7720,7 +7707,6 @@ async function prerenderToStream( ...@@ -7720,7 +7707,6 @@ async function prerenderToStream(
// All caches we could read must already be filled so no tracking is necessary // All caches we could read must already be filled so no tracking is necessary
cacheSignal: null, cacheSignal: null,
dynamicTracking: serverDynamicTracking, dynamicTracking: serverDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -7871,7 +7857,6 @@ async function prerenderToStream( ...@@ -7871,7 +7857,6 @@ async function prerenderToStream(
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender // No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null, cacheSignal: null,
dynamicTracking: clientDynamicTracking, dynamicTracking: clientDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -8546,7 +8531,6 @@ async function prerenderToStream( ...@@ -8546,7 +8531,6 @@ async function prerenderToStream(
controller: errorServerReactController, controller: errorServerReactController,
cacheSignal: null, cacheSignal: null,
dynamicTracking: errorServerDynamicTracking, dynamicTracking: errorServerDynamicTracking,
allowEmptyStaticShell,
revalidate: revalidate:
typeof prerenderStore?.revalidate !== 'undefined' typeof prerenderStore?.revalidate !== 'undefined'
? prerenderStore.revalidate ? prerenderStore.revalidate
...@@ -8630,7 +8614,6 @@ async function prerenderToStream( ...@@ -8630,7 +8614,6 @@ async function prerenderToStream(
controller: errorClientReactController, controller: errorClientReactController,
cacheSignal: null, cacheSignal: null,
dynamicTracking: errorClientDynamicTracking, dynamicTracking: errorClientDynamicTracking,
allowEmptyStaticShell,
revalidate: errorPrerenderStore.revalidate, revalidate: errorPrerenderStore.revalidate,
expire: errorPrerenderStore.expire, expire: errorPrerenderStore.expire,
stale: errorPrerenderStore.stale, stale: errorPrerenderStore.stale,
......
...@@ -284,14 +284,6 @@ interface StaticPrerenderStoreCommon { ...@@ -284,14 +284,6 @@ interface StaticPrerenderStoreCommon {
* a dynamic access. * a dynamic access.
*/ */
readonly fallbackRouteParams: OpaqueFallbackRouteParams | null readonly fallbackRouteParams: OpaqueFallbackRouteParams | null
/**
* When true, the page is prerendered as a fallback shell, while allowing any
* dynamic accesses to result in an empty shell. This is the case when there
* are also routes prerendered with a more complete set of params.
* Prerendering those routes would catch any invalid dynamic accesses.
*/
readonly allowEmptyStaticShell: boolean
} }
export interface PrerenderStorePPR export interface PrerenderStorePPR
......
...@@ -513,7 +513,6 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -513,7 +513,6 @@ export class AppRouteRouteModule extends RouteModule<
// During prospective render we don't use a controller // During prospective render we don't use a controller
// because we need to let all caches fill. // because we need to let all caches fill.
dynamicTracking, dynamicTracking,
allowEmptyStaticShell: false,
revalidate: defaultRevalidate, revalidate: defaultRevalidate,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
...@@ -609,7 +608,6 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -609,7 +608,6 @@ export class AppRouteRouteModule extends RouteModule<
controller: finalController, controller: finalController,
cacheSignal: null, cacheSignal: null,
dynamicTracking, dynamicTracking,
allowEmptyStaticShell: false,
revalidate: defaultRevalidate, revalidate: defaultRevalidate,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
......
...@@ -2255,24 +2255,18 @@ export async function cache( ...@@ -2255,24 +2255,18 @@ export async function cache(
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
// If `allowEmptyStaticShell` is true, and thus a prefilled resume if (resumeDataCache?.mutable === false) {
// data cache was provided, then a cache miss means that params were // We're prerendering a fallback shell whose Resume Data Cache is
// part of the cache key. In this case, we can make this cache // the prefilled, read-only seed from a phase-1 prerender of a more-
// function a dynamic hole in the shell (or produce an empty shell if // specific sibling route. A miss here means the cache key depends
// there's no parent suspense boundary). Currently, this also includes // on a fallback param. We short-circuit to a dynamic hole (which
// layouts and pages that don't read params, which will be improved // may produce an empty shell if there's no parent Suspense
// when we implement NAR-136. Otherwise, we assume that if params are // boundary). Currently this also catches layouts and pages that
// passed explicitly into a "use cache" function, that the params are // don't read params, which will be improved when we implement
// also accessed. This allows us to abort early, and treat the // NAR-136. Compared to the instrumentation-based params bailout we
// function as dynamic, instead of waiting for the timeout to be // also do here, this covers the case where params are transformed
// reached. Compared to the instrumentation-based params bailout we do // with an async function before being passed into the "use cache"
// here, this also covers the case where params are transformed with // function, which escapes the instrumentation.
// an async function, before being passed into the "use cache"
// function, which escapes the instrumentation.
if (workUnitStore.allowEmptyStaticShell) {
if (resumeDataCache?.mutable) {
resumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
}
return makeHangingPromise( return makeHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
......
import { ReactNode } from 'react'
export const unstable_instant = false
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default async function Page() {
'use cache'
return <p>{new Date().toISOString()}</p>
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { import {
expectBuildValidationSkipped,
expectNoBuildValidationErrors, expectNoBuildValidationErrors,
extractBuildValidationError, extractBuildValidationError,
parseValidationMessages, parseValidationMessages,
...@@ -951,5 +952,13 @@ describe('instant-validation-build', () => { ...@@ -951,5 +952,13 @@ describe('instant-validation-build', () => {
) )
expectNoBuildValidationErrors(result) expectNoBuildValidationErrors(result)
}) })
it('valid - a page with "use cache" and `unstable_instant = false` still prerenders as a fully static shell', async () => {
const result = await prerender('/(instant-false-static)/use-cache')
expectBuildValidationSkipped(result)
// A fully static shell is non-empty and contains the closing </html> tag.
const html = await next.readFile('.next/server/app/use-cache.html')
expect(html).toContain('</html>')
})
}) })
}) })
...@@ -16,6 +16,7 @@ import { ...@@ -16,6 +16,7 @@ import {
ErrorSnapshot, ErrorSnapshot,
RedboxSnapshot, RedboxSnapshot,
} from '../../../lib/add-redbox-matchers' } from '../../../lib/add-redbox-matchers'
import { getDeterministicOutput } from '../cache-components-errors/utils'
describe('instant validation', () => { describe('instant validation', () => {
const { next, skipped, isNextDev, isNextStart, isTurbopack } = nextTestSetup({ const { next, skipped, isNextDev, isNextStart, isTurbopack } = nextTestSetup({
...@@ -941,24 +942,45 @@ describe('instant validation', () => { ...@@ -941,24 +942,45 @@ describe('instant validation', () => {
const result = await prerender( const result = await prerender(
'/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input' '/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input'
) )
expect(extractBuildValidationError(result.cliOutput)) // TODO: This currently fails with the static-prerender sync-IO error on
.toMatchInlineSnapshot(` // Date.now(), not the instant-validation sync-IO error described above.
"Error: Route "/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input" accessed cookie "testCookie" which is not defined in the \`unstable_samples\` of \`unstable_instant\`. Add it to the sample's \`cookies\` array, or \`{ name: "testCookie", value: null }\` if it should be absent. // The cookies() promise hangs during the static shell, but the cache
at <unknown> (app/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input/page.tsx:26:49) // body doesn't read it, so the cache resolves with 'cached result'
24 | // regardless and Date.now() runs before instant validation gets a
25 | export default async function Page() { // chance. When we add staged rendering to static prerendering too,
> 26 | const cookiePromise = cookies().then((c) => c.get('testCookie')?.value ?? '') // cookies should resolve at the runtime stage and the cache call should
| ^ // defer until its args serialize, so the cache function (and the
// Date.now() that follows) lands in the runtime stage.
expect(
getDeterministicOutput(result.cliOutput, {
isMinified: true,
startingLineMatch: 'Collecting page data',
})
).toMatchInlineSnapshot(`
"Error: Route "/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input": Next.js encountered the unstable value \`Date.now()\` while prerendering.
This value can change between renders, so it must be either prerendered or computed later.
Ways to fix this:
- Render at request time by adding a dynamic data access (e.g. \`await connection()\`) before this call
- Prerender and cache the value with \`"use cache"\`
- Render the value on the client with \`"use client"\`
- If the value is for telemetry, use a timing API such as \`performance.now()\`
Learn more: https://nextjs.org/docs/messages/next-prerender-current-time
at a (app/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input/page.tsx:28:20)
26 | const cookiePromise = cookies().then((c) => c.get('testCookie')?.value ?? '')
27 | await cachedFn(cookiePromise) 27 | await cachedFn(cookiePromise)
28 | const now = Date.now() > 28 | const now = Date.now()
29 | return ( { | ^
digest: 'INSTANT_VALIDATION_ERROR' 29 | return (
} 30 | <main>
Build-time instant validation failed for route "/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input". 31 | <p>Runtime page with sync IO after cache with cookie input: {now}</p>
To get a more detailed stack trace and pinpoint the issue, try one of the following: 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/runtime/invalid-sync-io-after-cache-with-cookie-input" in your browser to investigate the error. - Start the app in development mode by running \`next dev\`, then open "/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input" in your browser to investigate the error.
- Rerun the production build with \`next build --debug-prerender\` to generate better stack traces. - Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.
Stopping prerender due to instant validation errors." Error occurred prerendering page "/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input/page: /suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input, exiting the build."
`) `)
expect(result.exitCode).toBe(1) expect(result.exitCode).toBe(1)
} }
......
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