File size: 17,404 Bytes
94786da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
diff --git a/packages/next/src/server/lib/cache-handlers/default.ts b/packages/next/src/server/lib/cache-handlers/default.ts
index 5a215994fe..0270c24b62 100644
--- a/packages/next/src/server/lib/cache-handlers/default.ts
+++ b/packages/next/src/server/lib/cache-handlers/default.ts
@@ -20,6 +20,7 @@ import {
   tagsManifest,
   type TagManifestEntry,
 } from '../incremental-cache/tags-manifest.external'
+import { MIN_PRERENDERABLE_EXPIRE } from '../../use-cache/constants'
 
 type PrivateCacheEntry = {
   entry: CacheEntry
@@ -83,10 +84,30 @@ export function createDefaultCacheHandler(maxSize: number): CacheHandler {
 
       const entry = privateEntry.entry
 
+      // A negative `expire` is an eviction sentinel: the tiered cache handler
+      // (dev-only) marks a front entry for deletion by overwriting it with a
+      // negative `expire`, since the cache-handler interface has no per-key
+      // delete. Treat it as missing here, independently of the minimum
+      // retention below (which would otherwise keep it alive). This is distinct
+      // from `revalidate = -1` below, which keeps serving the entry but forces
+      // a revalidation.
+      if (entry.expire < 0) {
+        debug?.('get', cacheKey, 'evicted')
+        return undefined
+      }
+
       // The dev server serves stale entries until they expire (see the file
-      // overview); production drops them once past the revalidate time.
+      // overview); production drops them once past the revalidate time. In dev,
+      // an entry is retained for at least `MIN_PRERENDERABLE_EXPIRE` so that
+      // entries with a short `expire` (for example a `cacheLife({ expire: 0 })`
+      // client-only cache) still linger long enough that a reload hits the
+      // cache. That minimum is the same threshold below which the "use cache"
+      // wrapper treats an entry as dynamic, so it only extends the retention of
+      // entries that are dynamic anyway. It affects retention only; the
+      // returned entry keeps its real `expire`, so staging decisions are
+      // unchanged.
       const maxAgeSeconds = process.env.__NEXT_DEV_SERVER
-        ? entry.expire
+        ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)
         : entry.revalidate
 
       if (
diff --git a/packages/next/src/server/use-cache/handlers.ts b/packages/next/src/server/use-cache/handlers.ts
index 8217c381ee..d9edb00284 100644
--- a/packages/next/src/server/use-cache/handlers.ts
+++ b/packages/next/src/server/use-cache/handlers.ts
@@ -107,26 +107,25 @@ export function initializeCacheHandlers(cacheMaxMemorySize: number): boolean {
   // Create a set of the cache handlers.
   reference[handlersSetSymbol] = new Set(handlersMap.values())
 
-  // In development we add dedicated built-in in-memory handlers so that warm
-  // reloads are fast. These are always built-in handlers, never a
-  // user-configured one, and are gated on the dev server so production behaves
-  // exactly as configured.
+  // In development we add dedicated built-in in-memory handlers so that reloads
+  // are fast. These are always built-in handlers, never a user-configured one,
+  // and are gated on the dev server so production behaves exactly as
+  // configured.
   if (process.env.__NEXT_DEV_SERVER) {
     reference[memoryCacheDisabledSymbol] = cacheMaxMemorySize === 0
 
-    // Private caches are persisted here so warm reloads are fast. Private
-    // entries can hold data specific to the incoming request (for example,
-    // derived from its cookies or headers), so this is never the
-    // user-configured `default` alias. Sized so it still caches under
-    // `cacheMaxMemorySize: 0` (otherwise it would become the no-op stub and
-    // private reloads would miss).
+    // Private caches are persisted here so reloads are fast. Private entries
+    // can hold data specific to the incoming request (for example, derived from
+    // its cookies or headers), so this is never the user-configured `default`
+    // alias. Sized so it still caches under `cacheMaxMemorySize: 0` (otherwise
+    // it would become the no-op stub and private reloads would miss).
     reference[privateHandlerSymbol] = createDefaultCacheHandler(
       DEV_MEMORY_CACHE_SIZE
     )
 
     // Built-in front handlers, one per custom kind, and the tiered handlers
     // that place a front in front of a (possibly slow or remote) backing
-    // handler so warm reads resolve in a microtask, are both created per kind
+    // handler so cache hits resolve in a microtask, are both created per kind
     // in `setCacheHandler`.
     reference[devFrontHandlersSymbol] = new Map()
     reference[devTieredHandlersSymbol] = new Map()
@@ -178,7 +177,7 @@ export function isMemoryCacheDisabled(): boolean {
  * Whether `kind` is backed by a real user-configured handler rather than the
  * built-in in-memory default. Such a handler may be slow or remote, so in
  * development a built-in front handler is placed in front of it (see
- * `getDevTieredCacheHandler`) to keep warm reads microtask-fast. The presence
+ * `getDevTieredCacheHandler`) to keep cache hits microtask-fast. The presence
  * of a dev front handler is the signal, since front handlers are created
  * exactly for user-registered kinds. Always `false` in production.
  */
@@ -193,7 +192,7 @@ export function isCustomCacheHandler(kind: string): boolean {
 /**
  * Get the dev-only tiered cache handler for a custom `kind`: a fast built-in
  * in-memory front handler in front of the user-configured backing handler, so
- * warm reads resolve in a microtask. Returns `undefined` if there is none (a
+ * cache hits resolve in a microtask. Returns `undefined` if there is none (a
  * built-in kind, or production).
  */
 export function getDevTieredCacheHandler(
@@ -307,11 +306,14 @@ export function setCacheHandler(
   reference[handlersSetSymbol].add(cacheHandler)
 
   // A user-configured handler may be slow or remote. In development, give it a
-  // dedicated built-in in-memory front handler so warm reads resolve in a
+  // dedicated built-in in-memory front handler so cache hits resolve in a
   // microtask, and pair the two into a tiered handler the wrapper reads
   // through. Both are created alongside registration so their lifecycle matches
   // the backing handler's, and the front handler's presence is the signal that
-  // this kind is backed by a real handler (see `isCustomCacheHandler`).
+  // this kind is backed by a real handler (see `isCustomCacheHandler`). Being a
+  // built-in default handler, the front inherits the dev minimum retention, so
+  // a short-`expire` value still hits the front instead of falling through to
+  // the slow backing on every read.
   if (process.env.__NEXT_DEV_SERVER) {
     const frontHandler = createDefaultCacheHandler(DEV_MEMORY_CACHE_SIZE)
     reference[devFrontHandlersSymbol]?.set(kind, frontHandler)
diff --git a/packages/next/src/server/use-cache/tiered-cache-handler.ts b/packages/next/src/server/use-cache/tiered-cache-handler.ts
index a73ba7e920..a5e8b3eeac 100644
--- a/packages/next/src/server/use-cache/tiered-cache-handler.ts
+++ b/packages/next/src/server/use-cache/tiered-cache-handler.ts
@@ -14,7 +14,7 @@ export type CacheReadWriteHandler = Pick<CacheHandler, 'get' | 'set'>
 /**
  * Development-only. Puts a fast built-in in-memory `front` handler in front of
  * a slower or persistent user-configured `backing` handler. Its only job is to
- * guarantee that warm reads resolve in a microtask (so they aren't counted as
+ * guarantee that cache hits resolve in a microtask (so they aren't counted as
  * cache misses at a staged-render boundary, which would otherwise surface a
  * cold cache indicator), while keeping the front in sync with the backing.
  *
@@ -76,9 +76,9 @@ export function createTieredCacheHandler(
       const frontEntry = await front.get(cacheKey, softTags)
 
       if (frontEntry) {
-        // Warm hit: serve immediately (in a microtask). A background reconcile
+        // Cache hit: serve immediately (in a microtask). A background reconcile
         // keeps the front in sync with the backing for the next read;
-        // reconciles for the same key are serialized, so concurrent warm reads
+        // reconciles for the same key are serialized, so concurrent cache hits
         // don't hit the backing in parallel.
         scheduleBackgroundSync(cacheKey, () =>
           reconcileFrontFromBacking(
@@ -104,7 +104,7 @@ export function createTieredCacheHandler(
       }
 
       // Mirror this freshly read backing entry into the front so the next read
-      // is warm. The mirror is serialized per key: if a sync is already
+      // hits it. The mirror is serialized per key: if a sync is already
       // running, this chains after it, so the front converges to this read even
       // if the backing changed since that sync started.
       const [servedEntry, mirroredEntry] = cloneCacheEntry(backingEntry)
@@ -130,9 +130,9 @@ export function createTieredCacheHandler(
 }
 
 /**
- * After serving a warm front hit, consult the backing and mirror a newer entry
- * into the front for the next read. Runs in the background; failures are
- * non-fatal.
+ * After serving a cache hit from the front, consult the backing and mirror a
+ * newer entry into the front for the next read. Runs in the background;
+ * failures are non-fatal.
  */
 async function reconcileFrontFromBacking(
   front: CacheHandler,
@@ -186,17 +186,18 @@ async function mirrorIntoFront(
 
 /**
  * Build an already-expired copy of an entry, used to evict it from the front
- * handler (which has no per-key delete) once the backing no longer has it. In
- * dev the default handler treats an entry as missing once `now > timestamp +
- * expire * 1000`, so `expire: 0` against the original (past) timestamp makes
- * the next read a miss. The value is never read once the entry is expired, but
- * it must carry at least one byte because the built-in LRU cache refuses to
- * store size-0 entries.
+ * handler (which has no per-key delete) once the backing no longer has it. The
+ * default handler treats a negative `expire` as an eviction sentinel and
+ * reports the entry as missing on the next read. A negative `expire` is used
+ * rather than `0` because the dev front handler enforces a minimum retention,
+ * so a `0` `expire` would be kept alive by that minimum instead of evicted. The
+ * value is never read once the entry is evicted, but it must carry at least one
+ * byte because the built-in LRU cache refuses to store size-0 entries.
  */
 function toExpiredEntry(entry: CacheEntry): CacheEntry {
   return {
     ...entry,
-    expire: 0,
+    expire: -1,
     value: new ReadableStream({
       start(controller) {
         controller.enqueue(new Uint8Array(1))
diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts
index 9dfddda9d4..3ca4a061e8 100644
--- a/packages/next/src/server/use-cache/use-cache-wrapper.ts
+++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts
@@ -1092,12 +1092,17 @@ async function collectResult(
   // `MIN_PRERENDERABLE_EXPIRE` (5 minutes) caps how long an entry lingers in
   // the dedicated in-memory private handler. It is the shortest `expire` that
   // isn't treated as dynamic; a smaller `expire` would exclude the entry from
-  // prerenders. The size-0 case (`cacheMaxMemorySize: 0`) deliberately does NOT
-  // force this: it keeps its resolved cache life so that the cache entry can be
-  // considered prerenderable instead of being misread as a dynamic hole, and a
-  // separate dev revalidation (see the cache-hit path below) keeps its reloads
-  // showing a fresh value. Custom kinds keep their real cache life too, since
-  // their backing handler owns it.
+  // prerenders. Two other cases deliberately do NOT force this and keep their
+  // resolved cache life, relying instead on the dev handler's minimum retention
+  // and a dev revalidation (see the cache-hit path below) to keep reloads fast
+  // and fresh. The size-0 case (`cacheMaxMemorySize: 0`) keeps its life so the
+  // entry can be considered prerenderable instead of being misread as a dynamic
+  // hole. An explicit short-`expire` public cache (e.g. `cacheLife({ expire: 0
+  // })`) keeps its life so it stays correctly excluded from static prerenders
+  // via its real `expire` while a reload still hits the cache; forcing
+  // `revalidate: 0` here would instead corrupt the cache life propagated to an
+  // enclosing cache and trigger the nested-dynamic error. A cache backed by a
+  // custom handler keeps its real cache life too, since that handler owns it.
   const forceDynamicCacheLifeInDev = isPrivateCacheInDev
 
   // If cacheLife() was used to set an explicit revalidate/expire/stale time we
@@ -1640,7 +1645,7 @@ export async function cache(
     if (isPrivate) {
       // Private caches normally go to the Resume Data Cache (RDC), not a cache
       // handler. In development we additionally persist them in a dedicated
-      // built-in in-memory handler so that warm reloads are fast.
+      // built-in in-memory handler so that reloads are fast.
       if (process.env.__NEXT_DEV_SERVER) {
         cacheHandler = getPrivateCacheHandler()
       }
@@ -1652,7 +1657,7 @@ export async function cache(
 
       // In development, a user-configured (custom) handler may be slow or
       // remote, so we read through a tiered handler that puts a built-in
-      // in-memory front in front of it to keep warm reads microtask-fast.
+      // in-memory front in front of it to keep cache hits microtask-fast.
       // Built-in handlers (the default handler, and its size-0 replacement) are
       // already in-memory and used directly.
       if (process.env.__NEXT_DEV_SERVER && isCustomCacheHandler(kind)) {
@@ -2188,7 +2193,7 @@ export async function cache(
 
   let stream: undefined | ReadableStream = undefined
 
-  // Set when a short-lived warm hit ends its cache read up front (dev only) so
+  // Set when a short-lived cache hit ends its cache read up front (dev only) so
   // the static-shell boundary doesn't count it as a phantom miss. Once set, the
   // cache signal read is balanced, so serving must use a plain stream and skip
   // any trailing cacheSignal.endRead() call.
@@ -2945,7 +2950,19 @@ export async function cache(
 
         if (
           entry === undefined ||
-          currentTime > entry.timestamp + entry.expire * 1000 ||
+          // In dev, the built-in default handler retains a short-`expire` entry
+          // for at least `MIN_PRERENDERABLE_EXPIRE`, both when used directly
+          // and when fronting a custom cache handler. Apply that same minimum
+          // here so the retained entry is served and re-warmed in the
+          // background (below), rather than blocking to regenerate it on every
+          // read. The entry's real `expire` is untouched, so staging still
+          // treats it as dynamic.
+          currentTime >
+            entry.timestamp +
+              (process.env.__NEXT_DEV_SERVER
+                ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)
+                : entry.expire) *
+                1000 ||
           (workStore.isStaticGeneration &&
             currentTime > entry.timestamp + entry.revalidate * 1000)
         ) {
@@ -3134,19 +3151,24 @@ export async function cache(
 
           // Trigger a background revalidation when the entry is stale (past its
           // `revalidate`), so the next read gets a fresh value without blocking
-          // this one. In development with the in-memory cache disabled
-          // (`cacheMaxMemorySize: 0`), built-in entries keep their resolved
-          // (potentially non-dynamic) cache life, so an entry read back from
-          // the dev in-memory cache is normally still fresh and wouldn't
-          // revalidate on its own; revalidate those on every dynamic request
-          // render too, so each reload still shows a fresh value.
+          // this one. Development additionally re-warms on every dynamic
+          // request render in two cases where the dev in-memory entry would
+          // otherwise read back as fresh, so a subsequent reload still shows a
+          // fresh value. The first is with the in-memory cache disabled
+          // (`cacheMaxMemorySize: 0`), where built-in entries keep their
+          // resolved (potentially non-dynamic) cache life. The second is a
+          // short-`expire` entry (an explicit dynamic or client-only cache,
+          // e.g. `cacheLife({ expire: 0 })`), which is retained for at least
+          // `MIN_PRERENDERABLE_EXPIRE` so it is served from the cache; this
+          // also covers custom handlers, re-executing and writing through to
+          // the backing.
           let shouldTriggerBackgroundRevalidation =
             currentTime > entry.timestamp + entry.revalidate * 1000
           if (
             !shouldTriggerBackgroundRevalidation &&
             process.env.__NEXT_DEV_SERVER &&
-            isMemoryCacheDisabled() &&
-            !isCustomCacheHandler(kind)
+            (entry.expire < MIN_PRERENDERABLE_EXPIRE ||
+              (isMemoryCacheDisabled() && !isCustomCacheHandler(kind)))
           ) {
             switch (workUnitStore.type) {
               case 'request':