Files
next.js/test/e2e/app-dir/use-cache-hanging-inputs/use-cache-hanging-inputs.test.ts
Hendrik LiebauandGitHub 6f4d94ac88 Stream Cache Components dev render instead of restarting on cache miss (#94457)
When Cache Components is enabled, `next dev` previously simulated a
production loading experience on every cold request. The render did a
prospective pass to detect cache misses, and on any miss it waited for
every cache to fill via `cacheSignal.cacheReady()` and then restarted
the render with warm caches before streaming anything, so the browser
saw nothing until the slowest cache had filled. Every cold load blocked
on cache population.

This change replaces the restart-on-cache-miss flow with a single
non-abandoning staged render that streams immediately and fills caches
as a side effect. On a cold load the Suspense fallbacks stream right
away and the cached content resolves as its cache fills; on a warm
reload the staged progression matches the previous no-cache-miss path.
The render is split into clearly owned pieces: `setUpStagedDevRender`
builds the staged controller, cache signal, and resume cache;
`streamStagedRenderInDev{Node,Web}` runs the streaming render and
reports a result once the stream has fully finished; and
`stagedRenderWithCachesInDev{Node,Web}` returns the stream and leaves
the validation follow-up detached so it never blocks the response.

The render advances its stages in sequential tasks, and the stream is
not handed back the instant it exists: it is held until the render has
advanced through the stage whose content belongs in the shell. That is
the static stage for initial loads, HMR refreshes, and plain
navigations, or the runtime stage for client navigations to a route with
a runtime prefetch config, whose runtime-prefetchable content the
navigation's prefetch would have settled. It never waits for the dynamic
stage. Buffering the shell before the first flush keeps the streaming
renderer from emitting a premature Suspense fallback for content that
belongs in the shell, and it mirrors production, where the static shell
(plus runtime-prefetchable content where configured) is served and the
remaining holes stream in as fallbacks.

Two internal reads that would otherwise register as synchronous IO and
wrongly force the render to the dynamic stage, the cache handler's
tag-expiry clock check and the hot reloader's module-scope dev client
id, are now read untracked: via `performance.timeOrigin +
performance.now()` like the `'use cache'` handler, and only in the
browser where the HMR connection reads it, respectively.

Cache Components rules validation now runs in that background follow-up,
once the streamed render has fully settled. `planDevValidation` inspects
the finished render and picks one of three paths: forward an invalid
dynamic usage error the streamed render already recorded and stop (for
example a request API used inside `'use cache'`); validate the streamed
render's own chunks when it neither missed caches nor hit sync IO; or,
when it did either, validate a dedicated warm-cache render instead.
Because that warm render reads the filled caches back rather than
filling them, it can surface an invalid dynamic usage error the cold
streamed render cannot, such as a nested dynamic `use cache` cache life
that propagated to a parent with no explicit `cacheLife`; that error is
forwarded and validation is skipped, just as one recorded by the
streamed render is.

Since cold loads no longer block on cache fills, the transient
cache-status indicator that reflected that wait is no longer emitted; a
follow-up will instead add an indicator that tells the user whether a
render streamed with cache misses, and so wasn't representative of
production.
2026-06-09 10:38:12 +00:00

196 lines
6.7 KiB
TypeScript

import { nextTestSetup } from 'e2e-utils'
import escapeStringRegexp from 'escape-string-regexp'
import {
getRedboxDescription,
getRedboxSource,
openRedbox,
waitForRedbox,
getRedboxTitle,
getRedboxTotalErrorCount,
} from 'next-test-utils'
import stripAnsi from 'strip-ansi'
const expectedTimeoutErrorMessage =
'Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".'
describe('use-cache-hanging-inputs', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: process.env.NEXT_TEST_MODE !== 'dev',
})
if (skipped) {
return
}
if (isNextDev) {
// TODO(restart-on-cache-miss): reenable when fixed
describe.skip('when an uncached promise is used inside of "use cache"', () => {
it('should show an error toast after a timeout', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/uncached-promise')
// The request is pending while we stall on the hanging inputs, and
// playwright will wait for the load even before continuing. So we don't
// need to wait for the "use cache" timeout of 50 seconds here.
await openRedbox(browser)
const errorCount = await getRedboxTotalErrorCount(browser)
const errorDescription = await getRedboxDescription(browser)
const errorSource = await getRedboxSource(browser)
expect(errorCount).toBe(1)
expect(errorDescription).toBe(expectedTimeoutErrorMessage)
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(errorSource).toMatchInlineSnapshot(`
"app/uncached-promise/page.tsx (10:13) @ Foo
8 | }
9 |
> 10 | const Foo = async ({ promise }) => {
| ^
11 | 'use cache'
12 |
13 | return ("
`)
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
at Foo (app/uncached-promise/page.tsx:10:13)`)
}, 180_000)
})
// TODO(restart-on-cache-miss): reenable when fixed
describe.skip('when an uncached promise is used inside of a nested "use cache"', () => {
it('should show an error toast after a timeout', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/uncached-promise-nested')
// The request is pending while we stall on the hanging inputs, and
// playwright will wait for the load even before continuing. So we don't
// need to wait for the "use cache" timeout of 50 seconds here.
await openRedbox(browser)
const errorCount = await getRedboxTotalErrorCount(browser)
const errorDescription = await getRedboxDescription(browser)
const errorSource = await getRedboxSource(browser)
expect(errorCount).toBe(1)
expect(errorDescription).toBe(expectedTimeoutErrorMessage)
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(errorSource).toMatchInlineSnapshot(`
"app/uncached-promise-nested/page.tsx (16:1) @ indirection
14 | }
15 |
> 16 | async function indirection(promise: Promise<number>) {
| ^
17 | 'use cache'
18 |
19 | return getCachedData(promise)"
`)
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
at indirection (app/uncached-promise-nested/page.tsx:16:1)
at Page (app/uncached-promise-nested/page.tsx:23:22)`)
}, 180_000)
})
// TODO(restart-on-cache-miss): reenable when fixed
describe.skip('when a "use cache" function is closing over an uncached promise', () => {
it('should show an error toast after a timeout', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/bound-args')
// The request is pending while we stall on the hanging inputs, and
// playwright will wait for the load even before continuing. So we don't
// need to wait for the "use cache" timeout of 50 seconds here.
await openRedbox(browser)
const errorCount = await getRedboxTotalErrorCount(browser)
const errorDescription = await getRedboxDescription(browser)
const errorSource = await getRedboxSource(browser)
expect(errorCount).toBe(1)
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(errorDescription).toBe(expectedTimeoutErrorMessage)
expect(errorSource).toMatchInlineSnapshot(`
"app/bound-args/page.tsx (13:15) @ Foo
11 | const uncachedDataPromise = fetchUncachedData()
12 |
> 13 | const Foo = async () => {
| ^
14 | 'use cache'
15 |
16 | return ("
`)
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
at Foo (app/bound-args/page.tsx:13:15)`)
}, 180_000)
})
describe('when an error is thrown', () => {
it('should show an error overlay with only one error', async () => {
const browser = await next.browser('/error')
await waitForRedbox(browser)
const count = await getRedboxTotalErrorCount(browser)
const title = await getRedboxTitle(browser)
const description = await getRedboxDescription(browser)
expect({ count, title, description }).toEqual({
count: 1,
title: 'Runtime Error\nCache',
description: 'kaputt!',
})
})
})
} else {
// TODO: Be more precise about the expected error messages and stacks.
it('should fail the build with errors after a timeout', async () => {
const { cliOutput } = await next.build()
expect(cliOutput).toInclude(createExpectedBuildErrorMessage('/error'))
expect(cliOutput).toInclude('Error: kaputt!')
expect(cliOutput).toIncludeRepeated(
escapeStringRegexp(expectedTimeoutErrorMessage),
4
)
expect(cliOutput).toInclude(
createExpectedBuildErrorMessage('/bound-args')
)
expect(cliOutput).toInclude(
createExpectedBuildErrorMessage('/transformed-params/[slug]')
)
expect(cliOutput).toInclude(
createExpectedBuildErrorMessage('/uncached-promise')
)
expect(cliOutput).toInclude(
createExpectedBuildErrorMessage('/uncached-promise-nested')
)
}, 180_000)
}
})
function createExpectedBuildErrorMessage(pathname: string) {
return `Error occurred prerendering page "${pathname}". Read more: https://nextjs.org/docs/messages/prerender-error`
}