Repository: vercel/next.js
Pull request: [ppr] Handle failed resume data cache entries

When a cache entry rejects, or can't be serialized, today it fails to write the cache entirely. This changes the flow so that failed cache writes are ignored, preserving the valid cache writes instead. This ensures that the Resume Data Cache is an incremental improvement rather than an all-or-nothing cache.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Changed files:
filename: packages/next/src/server/resume-data-cache/cache-store.ts
patch: @@ -32,7 +32,7 @@ export type DecryptedBoundArgsCacheStore = CacheStore<string>
 /**
  * Serialized format for "use cache" entries
  */
-interface UseCacheCacheStoreSerialized {
+export interface UseCacheCacheStoreSerialized {
   value: string
   tags: string[]
   stale: number
@@ -93,35 +93,41 @@ export function parseUseCacheCacheStore(
  */
 export async function serializeUseCacheCacheStore(
   entries: IterableIterator<[string, Promise<CacheEntry>]>
-): Promise<[string, UseCacheCacheStoreSerialized][]> {
+): Promise<Array<[string, UseCacheCacheStoreSerialized] | null>> {
   return Promise.all(
     Array.from(entries).map(([key, value]) => {
-      return value.then(async (entry) => {
-        const [left, right] = entry.value.tee()
-        entry.value = right
+      return value
+        .then(async (entry) => {
+          const [left, right] = entry.value.tee()
+          entry.value = right
 
-        let binaryString: string = ''
+          let binaryString: string = ''
 
-        // We want to encode the value as a string, but we aren't sure if the
-        // value is a a stream of UTF-8 bytes or not, so let's just encode it
-        // as a string using base64.
-        for await (const chunk of left) {
-          binaryString += arrayBufferToString(chunk)
-        }
+          // We want to encode the value as a string, but we aren't sure if the
+          // value is a a stream of UTF-8 bytes or not, so let's just encode it
+          // as a string using base64.
+          for await (const chunk of left) {
+            binaryString += arrayBufferToString(chunk)
+          }
 
-        return [
-          key,
-          {
-            // Encode the value as a base64 string.
-            value: btoa(binaryString),
-            tags: entry.tags,
-            stale: entry.stale,
-            timestamp: entry.timestamp,
-            expire: entry.expire,
-            revalidate: entry.revalidate,
-          },
-        ] satisfies [string, UseCacheCacheStoreSerialized]
-      })
+          return [
+            key,
+            {
+              // Encode the value as a base64 string.
+              value: btoa(binaryString),
+              tags: entry.tags,
+              stale: entry.stale,
+              timestamp: entry.timestamp,
+              expire: entry.expire,
+              revalidate: entry.revalidate,
+            },
+          ] satisfies [string, UseCacheCacheStoreSerialized]
+        })
+        .catch(() => {
+          // Any failed cache writes should be ignored as to not discard the
+          // entire cache.
+          return null
+        })
     })
   )
 }

filename: packages/next/src/server/resume-data-cache/resume-data-cache.test.ts
patch: @@ -9,7 +9,7 @@ import { inflateSync } from 'node:zlib'
 function createCacheWithSingleEntry() {
   const cache = createPrerenderResumeDataCache()
   cache.cache.set(
-    'key',
+    'success',
     Promise.resolve({
       value: streamFromString('value'),
       tags: [],
@@ -23,6 +23,13 @@ function createCacheWithSingleEntry() {
   return cache
 }
 
+function createCacheWithSingleEntryThatFails() {
+  const cache = createCacheWithSingleEntry()
+  cache.cache.set('fail', Promise.reject(new Error('Failed to serialize')))
+
+  return cache
+}
+
 describe('stringifyResumeDataCache', () => {
   it('serializes an empty cache', async () => {
     const cache = createPrerenderResumeDataCache()
@@ -41,7 +48,25 @@ describe('stringifyResumeDataCache', () => {
     ).toString('utf-8')
 
     expect(decompressed).toMatchInlineSnapshot(
-      `"{"store":{"fetch":{},"cache":{"key":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":0,"revalidate":0}},"encryptedBoundArgs":{}}}"`
+      `"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":0,"revalidate":0}},"encryptedBoundArgs":{}}}"`
+    )
+  })
+
+  it('serializes a cache with a single entry that fails', async () => {
+    const cache = createCacheWithSingleEntryThatFails()
+    const compressed = await stringifyResumeDataCache(cache)
+
+    // We have to decompress the output because the compressed string is not
+    // deterministic. If it fails here it's because the compressed string is
+    // different.
+    const decompressed = inflateSync(
+      Buffer.from(compressed, 'base64')
+    ).toString('utf-8')
+
+    // We expect that the cache will still contain the successful entry but the
+    // failed entry will be ignored and omitted from the output.
+    expect(decompressed).toMatchInlineSnapshot(
+      `"{"store":{"fetch":{},"cache":{"success":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":0,"revalidate":0}},"encryptedBoundArgs":{}}}"`
     )
   })
 })

filename: packages/next/src/server/resume-data-cache/resume-data-cache.ts
patch: @@ -6,6 +6,7 @@ import {
   serializeUseCacheCacheStore,
   parseUseCacheCacheStore,
   type DecryptedBoundArgsCacheStore,
+  type UseCacheCacheStoreSerialized,
 } from './cache-store'
 
 /**
@@ -114,7 +115,12 @@ export async function stringifyResumeDataCache(
       store: {
         fetch: Object.fromEntries(Array.from(resumeDataCache.fetch.entries())),
         cache: Object.fromEntries(
-          await serializeUseCacheCacheStore(resumeDataCache.cache.entries())
+          (
+            await serializeUseCacheCacheStore(resumeDataCache.cache.entries())
+          ).filter(
+            (entry): entry is [string, UseCacheCacheStoreSerialized] =>
+              entry !== null
+          )
         ),
         encryptedBoundArgs: Object.fromEntries(
           Array.from(resumeDataCache.encryptedBoundArgs.entries())