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(
dynamicChunks,
rootParams,
fallbackRouteParams,
allowEmptyStaticShell,
ctx,
validationSamples,
validationSampleTracking
......@@ -5718,7 +5717,6 @@ async function warmupClientModulesForStagedValidation(
allServerChunks: Array<Uint8Array>,
rootParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
allowEmptyStaticShell: boolean,
ctx: AppRenderContext,
validationSamples: ValidationStoreClient['validationSamples'],
validationSampleTracking: ValidationStoreClient['validationSampleTracking']
......@@ -5747,7 +5745,6 @@ async function warmupClientModulesForStagedValidation(
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -5920,7 +5917,6 @@ async function validateStagedShell(
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null,
dynamicTracking: clientDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -7033,10 +7029,6 @@ async function validateInstantConfigInBuildWithSample(
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.
// 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
......@@ -7056,7 +7048,6 @@ async function validateInstantConfigInBuildWithSample(
accumulatedChunks.dynamicChunks,
sampleRootParams,
fallbackRouteParams,
allowEmptyStaticShell,
validationCtx,
validationSamples,
warmupValidationSamplesTracking
......@@ -7407,7 +7398,6 @@ async function prerenderToStream(
// the final prerender.
cacheSignal,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -7441,7 +7431,6 @@ async function prerenderToStream(
// the final prerender.
cacheSignal,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -7563,7 +7552,6 @@ async function prerenderToStream(
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -7680,7 +7668,6 @@ async function prerenderToStream(
// All caches we could read must already be filled so no tracking is necessary
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -7720,7 +7707,6 @@ async function prerenderToStream(
// All caches we could read must already be filled so no tracking is necessary
cacheSignal: null,
dynamicTracking: serverDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -7871,7 +7857,6 @@ async function prerenderToStream(
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null,
dynamicTracking: clientDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -8546,7 +8531,6 @@ async function prerenderToStream(
controller: errorServerReactController,
cacheSignal: null,
dynamicTracking: errorServerDynamicTracking,
allowEmptyStaticShell,
revalidate:
typeof prerenderStore?.revalidate !== 'undefined'
? prerenderStore.revalidate
......@@ -8630,7 +8614,6 @@ async function prerenderToStream(
controller: errorClientReactController,
cacheSignal: null,
dynamicTracking: errorClientDynamicTracking,
allowEmptyStaticShell,
revalidate: errorPrerenderStore.revalidate,
expire: errorPrerenderStore.expire,
stale: errorPrerenderStore.stale,
......
......@@ -284,14 +284,6 @@ interface StaticPrerenderStoreCommon {
* a dynamic access.
*/
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
......
......@@ -513,7 +513,6 @@ export class AppRouteRouteModule extends RouteModule<
// During prospective render we don't use a controller
// because we need to let all caches fill.
dynamicTracking,
allowEmptyStaticShell: false,
revalidate: defaultRevalidate,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......@@ -609,7 +608,6 @@ export class AppRouteRouteModule extends RouteModule<
controller: finalController,
cacheSignal: null,
dynamicTracking,
allowEmptyStaticShell: false,
revalidate: defaultRevalidate,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......
......@@ -2255,24 +2255,18 @@ export async function cache(
switch (workUnitStore.type) {
case 'prerender':
// If `allowEmptyStaticShell` is true, and thus a prefilled resume
// data cache was provided, then a cache miss means that params were
// part of the cache key. In this case, we can make this cache
// function a dynamic hole in the shell (or produce an empty shell if
// there's no parent suspense boundary). Currently, this also includes
// layouts and pages that don't read params, which will be improved
// when we implement NAR-136. Otherwise, we assume that if params are
// passed explicitly into a "use cache" function, that the params are
// also accessed. This allows us to abort early, and treat the
// function as dynamic, instead of waiting for the timeout to be
// reached. Compared to the instrumentation-based params bailout we do
// here, this also covers the case where params are transformed with
// 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)
}
if (resumeDataCache?.mutable === false) {
// We're prerendering a fallback shell whose Resume Data Cache is
// the prefilled, read-only seed from a phase-1 prerender of a more-
// specific sibling route. A miss here means the cache key depends
// on a fallback param. We short-circuit to a dynamic hole (which
// may produce an empty shell if there's no parent Suspense
// boundary). Currently this also catches layouts and pages that
// don't read params, which will be improved when we implement
// NAR-136. Compared to the instrumentation-based params bailout we
// also do here, this covers the case where params are transformed
// with an async function before being passed into the "use cache"
// function, which escapes the instrumentation.
return makeHangingPromise(
workUnitStore.renderSignal,
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 {
expectBuildValidationSkipped,
expectNoBuildValidationErrors,
extractBuildValidationError,
parseValidationMessages,
......@@ -951,5 +952,13 @@ describe('instant-validation-build', () => {
)
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 {
ErrorSnapshot,
RedboxSnapshot,
} from '../../../lib/add-redbox-matchers'
import { getDeterministicOutput } from '../cache-components-errors/utils'
describe('instant validation', () => {
const { next, skipped, isNextDev, isNextStart, isTurbopack } = nextTestSetup({
......@@ -941,24 +942,45 @@ describe('instant validation', () => {
const result = await prerender(
'/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"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.
at <unknown> (app/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input/page.tsx:26:49)
24 |
25 | export default async function Page() {
> 26 | const cookiePromise = cookies().then((c) => c.get('testCookie')?.value ?? '')
| ^
// TODO: This currently fails with the static-prerender sync-IO error on
// Date.now(), not the instant-validation sync-IO error described above.
// The cookies() promise hangs during the static shell, but the cache
// body doesn't read it, so the cache resolves with 'cached result'
// regardless and Date.now() runs before instant validation gets a
// chance. When we add staged rendering to static prerendering too,
// 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)
28 | const now = Date.now()
29 | return ( {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input".
> 28 | const now = Date.now()
| ^
29 | return (
30 | <main>
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:
- 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.
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)
}
......
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