crbench//

← all cases

Image optimizer hardcodes max-age=0, discarding the upstream cache TTL

Tier 2 hard typescript · local · real merged PR from vercel/next.js #34075

Ground-truth defects

d1 · correctness · medium
The image-optimizer move to response-cache dropped the maxAge argument to sendResponse and hardcoded the cached-image header to `public, max-age=0, must-revalidate` instead of `max-age=${maxAge}`. The computed upstream/minimumCacheTTL maxAge is no longer propagated, so every optimized image returns max-age=0 and CDNs/browsers in front of a single instance stop caching, inflating origin load. (Large-diff stress case: ~3.6k lines, 15 files.)
d2 · correctness · high
In the standalone-without-sharp guard inside imageOptimizer's Squoosh-fallback branch, the deliberate `throw new ImageError(500, 'internal server error')` (meant to hard-fail when 'sharp' isn't installed in standalone mode) is caught by the enclosing try/catch, which returns { buffer: upstreamBuffer, contentType: upstreamType!, maxAge } instead of propagating the error. The old code sent a real 500 directly (`req.statusCode = 500; res.end(...); return { finished: true }`); this diff's rewrite routes the same guardrail through a throw that gets silently swallowed, so standalone mode without sharp serves a 200 with the original, unoptimized image instead of failing loudly.
d3 · correctness · medium
In imageOptimizer's internal-request path, `if (!mockRes.statusCode)` can never be true for any real HTTP status code (`mockRes.statusCode` starts at 200 and is only ever set to other truthy numbers like 404/500 by `handleRequest`), so the intended check for a failed internal response never fires. The old code additionally forwarded the upstream status via `res.statusCode = mockRes.statusCode`; this diff removes that forwarding entirely, so an internal 404/500 is masked behind an eventual 200 (until a secondary content-type check happens to catch it).
d4 · correctness · medium
`unstable_revalidate`'s new try/catch around the revalidation fetch discards the real error entirely: both a network failure and a non-OK HTTP response from the revalidation endpoint are collapsed into an identical, opaque `Failed to revalidate ${urlPath}` error with no status code, so callers can no longer distinguish a network outage from a 404/500 returned by the endpoint being revalidated.

The change under review

diff (truncated — full diff)
diff --git a/packages/next/server/api-utils.ts b/packages/next/server/api-utils.ts
index d5244556a431..a4e5706173c4 100644
--- a/packages/next/server/api-utils.ts
+++ b/packages/next/server/api-utils.ts
@@ -365,15 +365,29 @@ async function unstable_revalidate(
     )
   }
 
+  if (typeof urlPath !== 'string' || !urlPath.startsWith('/')) {
+    throw new Error(
+      `Invalid urlPath provided to revalidate(), must be a path e.g. /blog/post-1, received ${urlPath}`
+    )
+  }
+
   const baseUrl = context.trustHostHeader
     ? `https://${req.headers.host}`
     : `http://${context.hostname}:${context.port}`
 
-  return fetch(`${baseUrl}${urlPath}`, {
-    headers: {
-      [PRERENDER_REVALIDATE_HEADER]: context.previewModeId,
-    },
-  })
+  try {
+    const res = await fetch(`${baseUrl}${urlPath}`, {
+      headers: {
+        [PRERENDER_REVALIDATE_HEADER]: context.previewModeId,
+      },
+    })
+
+    if (!res.ok) {
+      throw new Error(`Invalid response ${res.status}`)
+    }
+  } catch (err) {
+    throw new Error(`Failed to revalidate ${urlPath}`)
+  }
 }
 
 const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`
diff --git a/packages/next/server/base-server.ts b/packages/next/server/base-server.ts
index 4f7fc2b510ca..d2848d502c0c 100644
--- a/packages/next/server/base-server.ts
+++ b/packages/next/server/base-server.ts
@@ -1545,6 +1545,8 @@ export default abstract class Server {
         await handleRedirect(cachedData.props)
         return null
       }
+    } else if (cachedData.kind === 'IMAGE') {
+      throw new Error('invariant SSG should not return an image cache value')
     } else {
       return {
         type: isDataReq ? 'json' : 'html',
diff --git a/packages/next/server/config-shared.ts b/packages/next/server/config-shared.ts
index 2d28f9dc553a..c7f4037e6a80 100644
--- a/packages/next/server/config-shared.ts
+++ b/packages/next/server/config-shared.ts
@@ -8,7 +8,7 @@ import {
 } from './image-config'
 
 export type NextConfigComplete = Required<NextConfig> & {
-  images: ImageConfigComplete
+  images: Required<ImageConfigComplete>
   typescript: Required<TypeScriptConfig>
   configOrigin?: string
   configFile?: string
diff --git a/packages/next/server/image-optimizer.ts b/packages/next/server/image-optimizer.ts
index 8363070892c6..2d5c73b6dc41 100644
--- a/packages/next/server/image-optimizer.ts
+++ b/packages/next/server/image-optimizer.ts
@@ -1,6 +1,6 @@
 import { mediaType } from 'next/dist/compiled/@hapi/accept'
 import { createHash } from 'crypto'
-import { createReadStream, promises } from 'fs'
+import { promises } from 'fs'
 import { getOrientation, Orientation } from 'next/dist/compiled/get-orientation'
 import imageSizeOf from 'next/dist/compiled/image-size'
 import { IncomingMessage, ServerResponse } from 'http'
@@ -10,14 +10,13 @@ import contentDisposition from 'next/dist/compiled/content-disposition'
 import { join } from 'path'
 import Stream from 'stream'
 import nodeUrl, { UrlWithParsedQuery } from 'url'
-import { NextConfig } from './config-shared'
-import { fileExists } from '../lib/file-exists'
-import { ImageConfig, imageConfigDefault } from './image-config'
+import { NextConfigComplete } from './config-shared'
 import { processBuffer, decodeBuffer, Operation } from './lib/squoosh/main'
 import { sendEtagResponse } from './send-payload'
 import { getContentType, getExtension } from './serve-static'
 import chalk from 'next/dist/compiled/chalk'
 import { NextUrlWithParsedQuery } from './request-meta'
+import { IncrementalCacheEntry, IncrementalCacheValue } from './response-cache'
 
 type XCacheHeader = 'MISS' | 'HIT' | 'STALE'
 
@@ -31,7 +30,6 @@ const CACHE_VERSION = 3
 const ANIMATABLE_TYPES = [WEBP, PNG, GIF]
 const VECTOR_TYPES = [SVG]
 const BLUR_IMG_SIZE = 8 // should match `next-image-loader`
-const inflightRequests = new Map<string, Promise<void>>()
 
 let sharp:
   | ((
@@ -48,489 +46,505 @@ try {
 
 let showSharpMissingWarning = process.env.NODE_ENV === 'production'
 
-export async function imageOptimizer(
-  req: IncomingMessage,
-  res: ServerResponse,
-  parsedUrl: UrlWithParsedQuery,
-  nextConfig: NextConfig,
-  distDir: string,
-  render404: () => Promise<void>,
-  handleRequest: (
-    newReq: IncomingMessage,
-    newRes: ServerResponse,
-    newParsedUrl?: NextUrlWithParsedQuery
-  ) => Promise<void>,
-  isDev = false
-) {
-  const imageData: ImageConfig = nextConfig.images || imageConfigDefault
-  const {
-    deviceSizes = [],
-    imageSizes = [],
-    domains = [],
-    loader,
-    minimumCacheTTL = 60,
-    formats = ['image/webp'],
-  } = imageData
-
-  if (loader !== 'default') {
-    await render404()
-    return { finished: true }
-  }
+export interface ImageParamsResult {
+  href: string
+  isAbsolute: boolean
+  isStatic: boolean
+  width: number
+  quality: number
+  mimeType: string
+  sizes: number[]
+  minimumCacheTTL: number
+}
 
-  const { headers } = req
-  const { url, w, q } = parsedUrl.query
-  const mimeType = getSupportedMimeType(formats, headers.accept)
-  let href: string
+export class ImageOptimizerCache {
+  private cacheDir: string
+  private nextConfig: NextConfigComplete
+
+  static validateParams(
+    req: IncomingMessage,
+    query: UrlWithParsedQuery['query'],
+    nextConfig: NextConfigComplete,
+    isDev: boolean
+  ): ImageParamsResult | { errorMessage: string } {
+    const imageData = nextConfig.images
+    const {
+      deviceSizes = [],
+      imageSizes = [],
+      domains = [],
+      minimumCacheTTL = 60,
+      formats = ['image/webp'],
+    } = imageData
+    const { url, w, q } = query
+    let href: string
+
+    if (!url) {
+      return { errorMessage: '"url" parameter is required' }
+    } else if (Array.isArray(url)) {
+      return { errorMessage: '"url" parameter cannot be an array' }
+    }
 
-  if (!url) {
-    res.statusCode = 400
-    res.end('"url" parameter is required')
-    return { finished: true }
-  } else if (Array.isArray(url)) {
-    res.statusCode = 400
-    res.end('"url" parameter cannot be an array')
-    return { finished: true }
-  }
+    let isAbsolute: boolean
 
-  let isAbsolute: boolean
+    if (url.startsWith('/')) {
+      href = url
+      isAbsolute = false
+    } else {
+      let hrefParsed: URL
 
-  if (url.startsWith('/')) {
-    href = url
-    isAbsolute = false
-  } else {
-    let hrefParsed: URL
+      try {
+        hrefParsed = new URL(url)
+        href = hrefParsed.toString()
+        isAbsolute = true
+      } catch (_error) {
+        return { errorMessage: '"url" parameter is invalid' }
+      }
 
-    try {
-      hrefParsed = new URL(url)
-      href = hrefParsed.toString()
-      isAbsolute = true
-    } catch (_error) {
-      res.statusCode = 400
-      res.end('"url" parameter is invalid')
-      return { finished: true }
+      if (!['http:', 'https:'].includes(hrefParsed.protocol)) {
+        return { errorMessage: '"url" parameter is invalid' }
+      }
+
+      if (!domains || !domains.includes(hrefParsed.hostname)) {
+        return { errorMessage: '"url" parameter is not allowed' }
+      }
     }
 
-    if (!['http:', 'https:'].includes(hrefParsed.protocol)) {
-      res.statusCode = 400
-      res.end('"url" parameter is invalid')
-      return { finished: true }
+    if (!w) {
+      return { errorMessage: '"w" parameter (width) is required' }
+    } else if (Array.isArray(w)) {
+      return { errorMessage: '"w" parameter (width) cannot be an array' }
     }
 
-    if (!domains.includes(hrefParsed.hostname)) {
-      res.statusCode = 400
-      res.end('"url" parameter is not allowed')
-      return { finished: true }
+    if (!q) {
+      return { errorMessage: '"q" parameter (quality) is required' }
+    } else if (Array.isArray(q)) {
+      return { errorMessage: '"q" parameter (quality) cannot be an array' }
     }
-  }
 
-  if (!w) {
-    res.statusCode = 400
-    res.end('"w" parameter (width) is required')
-    return { finished: true }
-  } else if (Array.isArray(w)) {
-    res.statusCode = 400
-    res.end('"w" parameter (width) cannot be an array')
-    return { finished: true }
-  }
+    const width = parseInt(w, 10)
 
-  if (!q) {
-    res.statusCode = 400
-    res.end('"q" parameter (quality) is required')
-    return { finished: true }
-  } else if (Array.isArray(q)) {
-    res.statusCode = 400
-    res.end('"q" parameter (quality) cannot be an array')
-    return { finished: true }
-  }
+    if (!width || isNaN(width)) {
+      return {
+        errorMessage: '"w" parameter (width) must be a number greater than 0',
+      }
+    }
 
-  // Should match output from next-image-loader
-  const isStatic = url.startsWith(
-    `${nextConfig.basePath || ''}/_next/static/media`
-  )
+    const sizes = [...(deviceSizes || []), ...(imageSizes || [])]
 
-  const width = parseInt(w, 10)
+    if (isDev) {
+      sizes.push(BLUR_IMG_SIZE)
+    }
 
-  if (!width || isNaN(width)) {
-    res.statusCode = 400
-    res.end('"w" parameter (width) must be a number greater than 0')
-    return { finished: true }
-  }
+    if (!sizes.includes(width)) {
+      return {
+        errorMessage: `"w" parameter (width) of ${width} is not allowed`,
+      }
+    }
 
-  const sizes = [...deviceSizes, ...imageSizes]
+    const quality = parseInt(q)
 
-  if (isDev) {
-    sizes.push(BLUR_IMG_SIZE)
-  }
+    if (isNaN(quality) || quality < 1 || quality > 100) {
+      return {
+        errorMessage:
+          '"q" parameter (quality) must be a number between 1 and 100',
+      }
+    }
 
-  if (!sizes.includes(width)) {
-    res.statusCode = 400
-    res.end(`"w" parameter (width) of ${width} is not allowed`)
-    return { finished: true }
-  }
+    const mimeType = getSupportedMimeType(formats || [], req.headers['accept'])
 
-  const quality = parseInt(q)
+    const isStatic = url.startsWith(
+      `${nextConfig.basePath || ''}/_next/static/media`
+    )
 
-  if (isNaN(quality) || quality < 1 || quality > 100) {
-    res.statusCode = 400
-    res.end('"q" parameter (quality) must be a number between 1 and 100')
-    return { finished: true }
+    return {
+      href,
+      sizes,
+      isAbsolute,
+      isStatic,
+      width,
+      quality,
+      mimeType,
+      minimumCacheTTL,
+    }
   }
 
-  const hash = getHash([CACHE_VERSION, href, width, quality, mimeType])
-  const imagesDir = join(distDir, 'cache', 'images')
-  const hashDir = join(imagesDir, hash)
-  const now = Date.now()
-  let xCache: XCacheHeader = 'MISS'
+  static getCacheKey({
+    href,
+    width,
+    quality,
+    mimeType,
+  }: {
+    href: string
+    width: number
+    quality: number
+    mimeType: string
+  }): string {
+    return getHash([CACHE_VERSION, href, width, quality, mimeType])
+  }
 
-  // If there're concurrent requests hitting the same resource and it's still
-  // being optimized, wait before accessing the cache.
-  if (inflightRequests.has(hash)) {
-    await inflightRequests.get(hash)
+  constructor({
+    distDir,
+    nextConfig,
+  }: {
+    distDir: string
+    nextConfig: NextConfigComplete
+  }) {
+    this.cacheDir = join(distDir, 'cache', 'images')
+    this.nextConfig = nextConfig
   }
-  const dedupe = new Deferred<void>()
-  inflightRequests.set(hash, dedupe.promise)
 
-  try {
-    if (await fileExists(hashDir, 'directory')) {
-      const files = await promises.readdir(hashDir)
-      for (let file of files) {
-        const [maxAgeStr, expireAtSt, etag, extension] = file.split('.')
-        const maxAge = Number(maxAgeStr)
+  async get(cacheKey: string): Promise<IncrementalCacheEntry | null> {
+    try {
+      const cacheDir = join(this.cacheDir, cacheKey)
+      const files = await promises.readdir(cacheDir)
+      const now = Date.now()
+
+      for (const file of files) {
+        const [maxAgeSt, expireAtSt, etag, extension] = file.split('.')
+        const buffer = await promises.readFile(join(cacheDir, file))
         const expireAt = Number(expireAtSt)
-        const contentType = getContentType(extension)
-        const fsPath = join(hashDir, file)
-        xCache = now < expireAt ? 'HIT' : 'STALE'
-        const result = setResponseHeaders(
-          req,
-          res,
-          url,
-          etag,
-          maxAge,
-          contentType,
-          isStatic,
-          isDev,
-          xCache
-        )
-        if (!result.finished) {
-          await new Promise<void>((resolve, reject) => {
-            createReadStream(fsPath)
-              .on('end', resolve)
-              .on('error', reject)
-              .pipe(res)
-          })
-        }
-        if (xCache === 'HIT') {
-          return { finished: true }
-        } else {
-          await promises.unlink(fsPath)
+        const maxAge = Number(maxAgeSt)
+
+        return {
+          value: {
+            kind: 'IMAGE',
+            etag,
+            buffer,
+            extension,
+          },
+          revalidateAfter:
+            Math.max(maxAge, this.nextConfig.images.minimumCacheTTL) * 1000 +
+            Date.now(),
+          curRevalidate: maxAge,
+          isStale: now > expireAt,
         }
       }
+    } catch (_) {
+      // failed to read from cache dir, treat as cache miss
+    }
+    return null
+  }
+  async set(
+    cacheKey: string,
+    value: IncrementalCacheValue | null,
+    revalidate?: number | false
+  ) {
+    if (value?.kind !== 'IMAGE') {
+      throw new Error('invariant attempted to set non-image to image-cache')
     }
 
-    let upstreamBuffer: Buffer
-    let upstreamType: string | null
-    let maxAge: number
-
-    if (isAbsolute) {
-      const upstreamRes = await fetch(href)
+    if (typeof revalidate !== 'number') {
+      throw new Error('invariant revalidate must be a number for image-cache')
+    }
+    const expireAt =
+      Math.max(revalidate, this.nextConfig.images.minimumCacheTTL) * 1000 +
+      Date.now()
+
+    await writeToCacheDir(
+      join(this.cacheDir, cacheKey),
+      value.extension,
+      revalidate,
+      expireAt,
+      value.buffer,
+      value.etag
+    )
+  }
+}
+export class ImageError extends Error {
+  statusCode: number
 
-      if (!upstreamRes.ok) {
-        res.statusCode = upstreamRes.status
-        res.end('"url" parameter is valid but upstream response is invalid')
-        return { finished: true }
-      }
+  constructor(statusCode: number, message: string) {
+    super(message)
+    this.statusCode = statusCode
+  }
+}
 
-      res.statusCode = upstreamRes.status
-      upstreamBuffer = Buffer.from(await upstreamRes.arrayBuffer())
-      upstreamType =
-        detectContentType(upstreamBuffer) ||
-        upstreamRes.headers.get('Content-Type')
-      maxAge = getMaxAge(upstreamRes.headers.get('Cache-Control'))
-    } else {
-      try {
-        const resBuffers: Buffer[] = []
-        const mockRes: any = new Stream.Writable()
+export async function imageOptimizer(
+  _req: IncomingMessage,
+  _res: ServerResponse,
+  paramsResult: ImageParamsResult,
+  nextConfig: NextConfigComplete,
+  handleRequest: (
+    newReq: IncomingMessage,
+    newRes: ServerResponse,
+    newParsedUrl?: NextUrlWithParsedQuery
+  ) => Promise<void>
+): Promise<{ buffer: Buffer; contentType: string; maxAge: number }> {

Leaderboard for this case

hard · 1 of 9 bots fully caught it (11% solve rate) · 58% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 Drape (Review) solved 4/4 100.0% 11 1
2 Drape (Deep Review) partial 3/4 80.0% 7 0
3 qodo partial 3/4 80.0% 5 0
4 cursor partial 2/4 60.0% 2 0
5 greptile partial 2/4 60.0% 4 0
6 Claude Code (Opus 5.5) partial 3/4 60.0% 6 1
7 Cubic partial 2/4 60.0% 6 1
8 Mjolnir (Opus 5.5) partial 1/4 40.0% 4 0
9 Mjolnir (Sonnet 5.5) partial 1/4 40.0% 2 0

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ exact
d2 high ✗ —
d3 medium ✓ exact
d4 medium ✓ off by one
valid · impact high
The new writeToCacheDir calls rmdir with recursive before mkdir. On Node 16+, a recursive rmdir on a path that doesn't exist throws ENOENT. The first set for a key therefore fails, and ResponseCache only logs that error after it has already resolved the response. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d1 · impact medium
valid · matches d3 · impact medium
valid · impact low
upstreamType can be null when detection fails and there is no Content-Type header. If optimization then fails, the catch path returns null, and next-server passes it to getExtension, which gives an undefined extension. That result now gets cached; the old code never cached the fallback. [grounded: diff] [consensus 3/3: valid=3]
invalid
ResponseCache only compares revalidateAfter to false. Staleness comes from isStale, which is computed from the stored expireAt. A revalidateAfter that drifts forward on each read therefore doesn't change behavior. [invalid: contradiction] [consensus 3/3: invalid=3]
valid · matches d4 · impact medium
raw comments (6)
packages/next/server/image-optimizer.ts:563
`writeToCacheDir` now calls `promises.rmdir(dir, { recursive: true })` before `mkdir`. The first time an image is cached, that directory doesn't exist yet. Since Node 16, a recursive `rmdir` on a missing path throws ENOENT, so `ImageOptimizerCache.set` fails on every first write. ResponseCache runs the write after it has already resolved the response, so the error is only logged and nothing is ever saved to disk. Every request then re-optimizes the image. `rmdir` with `recursive` is also deprecated; use `rm(dir, { recursive: true, force: true })`. Separately, deleting and recreating the directory without a lock can race with a concurrent `get` or `set` on the same key, for example across processes.
packages/next/server/image-optimizer.ts:580
The Cache-Control header for non-static images is now hardcoded to `public, max-age=0, must-revalidate`. Before, production used the upstream max-age (clamped to `minimumCacheTTL`). Browsers and CDNs now revalidate on every request, even when the upstream response or `minimumCacheTTL` allows caching. That is a real loss of caching and extra load on the server.
packages/next/server/image-optimizer.ts:347
For internal (relative) images, the new check `if (!mockRes.statusCode)` is effectively never true, because the mock's statusCode defaults to 200 and real statuses are never 0. The old code passed the internal status through. Now a 404 or 500 internal response is processed as if it were an image. If its body looks like an image, or the error is HTML caught by the content-type check, it gets the wrong status (400), or a broken body gets optimized and cached. The intended check is probably `statusCode >= 400`. Also, any ImageError thrown inside this try block is caught and rethrown as a generic 500, which hides the real status.
packages/next/server/image-optimizer.ts:535
When optimization fails, the catch block returns `{ buffer: upstreamBuffer, contentType: upstreamType!, maxAge }`. `upstreamType` can be null when the type can't be detected and there is no Content-Type header. The caller then runs `getExtension(null)`, which gives an `undefined` extension. That value is written into the cache filename (`...undefined`) and passed to `getContentType`, so the response has no valid content type. The unoptimized fallback is also now cached on disk as if it were optimized, so one transient optimizer failure keeps the original image cached for the whole TTL.
packages/next/server/image-optimizer.ts:271
`revalidateAfter` in `ImageOptimizerCache.get` is computed as `Date.now() + maxAge`, not from the stored `expireAt`. It moves forward on every read, so the value doesn't reflect when the entry actually expires.
packages/next/server/api-utils.ts:388
The catch block replaces every error, including the `Invalid response ${res.status}` thrown just above it, with a generic `Failed to revalidate ${urlPath}`. The status code and the underlying network error are lost, which makes failures hard to diagnose. Changing the return type from `Promise<Response>` to `Promise<void>` also breaks any callers that read the response.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 high ✓ off by one
d3 medium ✗ —
d4 medium ✓ exact
valid · impact high
On Node 16+, recursive fs.rmdir on a path that doesn't exist throws ENOENT. That means set() rejects on the first write for every cache key. ResponseCache catches and logs the error after resolving, so the image is never written to the cache. [grounded: diff] [consensus 5/5: valid=5]
valid · matches d4 · impact medium
valid · impact low
When optimization fails, the fallback returns upstreamType!, which can be an unregistered MIME type or null. In that case getExtension returns null and the cast doesn't change it. A null extension then gets cached and passed to getContentType. Before this change the content type itself was kept. [grounded: diff] [consensus 5/5: valid=5]
valid · matches d2 · impact high
invalid
The fixture really is text.txt, but the old test already requested '/test.txt'. The code was moved, not introduced by this change. [invalid: contradiction] [consensus 5/5: invalid=5]
valid · impact low
The new test helper calls server.close() without waiting for it, and afterAll doesn't await stop(). This is a minor test-hygiene issue that could leave handles open. [grounded: diff] [consensus 5/5: valid=5]
raw comments (7)
packages/next/server/image-optimizer.ts:546
<!-- cubic:v=d55268f4-7a9d-4919-a55d-a178eb74c851 --> <!-- cubic:review-run=63c5a198-8677-5bd9-8c81-77c980255a1a --> <!-- metadata:{"confidence":10} --> P1: On the first request for every cache key, `writeToCacheDir` rejects before creating the directory because recursive `rmdir` fails with `ENOENT` when `dir` is absent. Ignore that missing-directory error or use a forced recursive removal so generated images are actually cached. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At packages/next/server/image-optimizer.ts, line 546: <comment>On the first request for every cache key, `writeToCacheDir` rejects before creating the directory because recursive `rmdir` fails with `ENOENT` when `dir` is absent. Ignore that missing-directory error or use a forced recursive removal so generated images are actually cached.</comment> <file context> @@ -48,489 +46,505 @@ try { - const extension = getExtension(contentType) - const etag = getHash([buffer]) const filename = join(dir, `${maxAge}.${expireAt}.${etag}.${extension}`) + await promises.rmdir(dir, { recursive: true }) + await promises.mkdir(dir, { recursive: true }) await promises.writeFile(filename, buffer) </file context> ``` </details> ```suggestion try { await promises.rmdir(dir, { recursive: true }) } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') { throw err } } ```
packages/next/server/api-utils.ts:389
<!-- cubic:v=1a7e451a-10c9-4390-beeb-61e8a0b994c9 --> <!-- cubic:review-run=63c5a198-8677-5bd9-8c81-77c980255a1a --> <!-- metadata:{"confidence":9} --> P2: When the revalidation response is non-2xx, the `Invalid response ${res.status}` error thrown above is caught here and discarded. Preserve the original error or include its status so callers and server logs can distinguish an HTTP failure from a network failure. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At packages/next/server/api-utils.ts, line 389: <comment>When the revalidation response is non-2xx, the `Invalid response ${res.status}` error thrown above is caught here and discarded. Preserve the original error or include its status so callers and server logs can distinguish an HTTP failure from a network failure.</comment> <file context> @@ -365,15 +365,29 @@ async function unstable_revalidate( + throw new Error(`Invalid response ${res.status}`) + } + } catch (err) { + throw new Error(`Failed to revalidate ${urlPath}`) + } } </file context> ``` </details>
packages/next/server/next-server.ts:225
<!-- cubic:v=5b516f6a-f973-4ca0-ad8c-3369adcc3c76 --> <!-- cubic:review-run=63c5a198-8677-5bd9-8c81-77c980255a1a --> <!-- metadata:{"confidence":7} --> P2: When optimization falls back for an image whose MIME type has no registered extension, `getExtension(contentType)` returns `null`; the `as string` cast does not change that runtime value. Preserve the MIME type in the cached value or ensure the optimizer returns a supported extension before caching. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At packages/next/server/next-server.ts, line 225: <comment>When optimization falls back for an image whose MIME type has no registered extension, `getExtension(contentType)` returns `null`; the `as string` cast does not change that runtime value. Preserve the MIME type in the cached value or ensure the optimizer returns a supported extension before caching.</comment> <file context> @@ -157,25 +170,92 @@ export default class NextNodeServer extends BaseServer { + kind: 'IMAGE', + buffer, + etag, + extension: getExtension(contentType) as string, + }, + revalidate: maxAge, </file context> ``` </details>
packages/next/server/image-optimizer.ts:528
<!-- cubic:v=e93fabb8-8de8-4786-9af1-cdbde5f22594 --> <!-- cubic:review-run=63c5a198-8677-5bd9-8c81-77c980255a1a --> <!-- metadata:{"confidence":10} --> P2: When standalone mode lacks Sharp, the thrown `ImageError(500, ...)` is swallowed by this catch and the original image is returned with 200. Re-throw `ImageError` instances before applying the optimization-failure fallback. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At packages/next/server/image-optimizer.ts, line 528: <comment>When standalone mode lacks Sharp, the thrown `ImageError(500, ...)` is swallowed by this catch and the original image is returned with 200. Re-throw `ImageError` instances before applying the optimization-failure fallback.</comment> <file context> @@ -48,489 +46,505 @@ try { + } else { + throw new ImageError(500, 'Unable to optimize buffer') + } + } catch (error) { + return { + buffer: upstreamBuffer, </file context> ``` </details> ```suggestion } catch (error) { if (error instanceof ImageError) { throw error } ```
test/integration/image-optimizer/test/util.js:1005
<!-- cubic:v=4b26e236-1b9f-4efb-be24-3203c62bd384 --> <!-- cubic:review-run=63c5a198-8677-5bd9-8c81-77c980255a1a --> <!-- metadata:{"confidence":7} --> P3: The "should error if the resource isn't a valid image" test requests `/test.txt`, but the app's `public` directory contains `text.txt`, not `test.txt`. The test only passes by accident: the missing-file 404 response is coerced to the same 400 message by the optimizer's internal mock handling. Point the test at the real fixture (`/text.txt`) so it actually exercises a non-image resource; otherwise a change to 404 handling silently alters what this test covers. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At test/integration/image-optimizer/test/util.js, line 1005: <comment>The "should error if the resource isn't a valid image" test requests `/test.txt`, but the app's `public` directory contains `text.txt`, not `test.txt`. The test only passes by accident: the missing-file 404 response is coerced to the same 400 message by the optimizer's internal mock handling. Point the test at the real fixture (`/text.txt`) so it actually exercises a non-image resource; otherwise a change to 404 handling silently alters what this test covers.</comment> <file context> @@ -0,0 +1,1259 @@ + }) + + it("should error if the resource isn't a valid image", async () => { + const query = { url: '/test.txt', w: ctx.w, q: 80 } + const opts = { headers: { accept: 'image/webp' } } + const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) </file context> ``` </details> ```suggestion const query = { url: '/text.txt', w: ctx.w, q: 80 } ```
test/integration/image-optimizer/test/util.js:126
<!-- cubic:v=87d29071-bf2c-4606-a03a-502d0c3fe83d --> <!-- cubic:review-run=63c5a198-8677-5bd9-8c81-77c980255a1a --> <!-- metadata:{"confidence":8} --> P3: In `afterAll`, `slowImageServer.stop()` is not awaited, and `stop()` calls `server.close()` synchronously without returning a promise. `server.close()` only stops accepting new connections and drains existing ones asynchronously, so Jest may proceed (and later detect open handles) while the server is still bound; `runTests` is invoked once per describe across four test files, each starting its own server, so unclosed listeners can accumulate. Make `stop()` return a promise (e.g. `server.close()` wrapped in a `new Promise`) and `await` it in `afterAll`. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At test/integration/image-optimizer/test/util.js, line 126: <comment>In `afterAll`, `slowImageServer.stop()` is not awaited, and `stop()` calls `server.close()` synchronously without returning a promise. `server.close()` only stops accepting new connections and drains existing ones asynchronously, so Jest may proceed (and later detect open handles) while the server is still bound; `runTests` is invoked once per describe across four test files, each starting its own server, so unclosed listeners can accumulate. Make `stop()` return a promise (e.g. `server.close()` wrapped in a `new Promise`) and `await` it in `afterAll`.</comment> <file context> @@ -0,0 +1,1259 @@ + beforeAll(async () => { + slowImageServer = await serveSlowImage() + }) + afterAll(async () => { + slowImageServer.stop() + }) </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **6 issues found** across 15 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="packages/next/server/api-utils.ts"> <violation number="1" location="packages/next/server/api-utils.ts:389"> P2: When the revalidation response is non-2xx, the `Invalid response ${res.status}` error thrown above is caught here and discarded. Preserve the original error or include its status so callers and server logs can distinguish an HTTP failure from a network failure.</violation> </file> <file name="packages/next/server/next-server.ts"> <violation number="1" location="packages/next/server/next-server.ts:225"> P2: When optimization falls back for an image whose MIME type has no registered extension, `getExtension(contentType)` returns `null`; the `as string` cast does not change that runtime value. Preserve the MIME type in the cached value or ensure the optimizer returns a supported extension before caching.</violation> </file> <file name="packages/next/server/image-optimizer.ts"> <violation number="1" location="packages/next/server/image-optimizer.ts:528"> P2: When standalone mode lacks Sharp, the thrown `ImageError(500, ...)` is swallowed by this catch and the original image is returned with 200. Re-throw `ImageError` instances before applying the optimization-failure fallback.</violation> <violation number="2" location="packages/next/server/image-optimizer.ts:546"> P1: On the first request for every cache key, `writeToCacheDir` rejects before creating the directory because recursive `rmdir` fails with `ENOENT` when `dir` is absent. Ignore that missing-directory error or use a forced recursive removal so generated images are actually cached.</violation> </file> <file name="test/integration/image-optimizer/test/util.js"> <violation number="1" location="test/integration/image-optimizer/test/util.js:126"> P3: In `afterAll`, `slowImageServer.stop()` is not awaited, and `stop()` calls `server.close()` synchronously without returning a promise. `server.close()` only stops accepting new connections and drains existing ones asynchronously, so Jest may proceed (and later detect open handles) while the server is still bound; `runTests` is invoked once per describe across four test files, each starting its own server, so unclosed listeners can accumulate. Make `stop()` return a promise (e.g. `server.close()` wrapped in a `new Promise`) and `await` it in `afterAll`.</violation> <violation number="2" location="test/integration/image-optimizer/test/util.js:1005"> P3: The "should error if the resource isn't a valid image" test requests `/test.txt`, but the app's `public` directory contains `text.txt`, not `test.txt`. The test only passes by accident: the missing-file 404 response is coerced to the same 400 message by the optimizer's internal mock handling. Point the test at the real fixture (`/text.txt`) so it actually exercises a non-image resource; otherwise a change to 404 handling silently alters what this test covers.</violation> </file> ``` </details> <sub>**Tip**: cubic can generate docs of your entire codebase and keep them up to date. Try it [here](https://docs.cubic.dev/wiki/ai-wiki?utm_source=github).<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/61/ai_pr_review_github_delivery_bbb0e03e25e07c68a9c0fe0a5c5fe4a9cee6299e7c886af81154db328cddf77a?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F61)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_bbb0e03e25e07c68a9c0fe0a5c5fe4a9cee6299e7c886af81154db328cddf77a:a8c614d0831390e0df069bfff7a32e5ae1ed60d2:63c5a198-8677-5bd9-8c81-77c980255a1a -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 high ✓ off by one
d3 medium ✓ off by one
d4 medium ✗ —
valid · matches d2 · impact high
valid · matches d3 · impact medium
raw comments (3)
packages/next/server/image-optimizer.ts:533
### Standalone sharp error is swallowed **Medium Severity** <!-- DESCRIPTION START --> Throwing `ImageError` when `sharp` is missing in `outputStandalone` is caught by the surrounding optimization `catch`, which returns the original buffer as a successful result. That response is then cached, so standalone deployments without `sharp` serve unoptimized images with 200 instead of failing with 500. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 54dc867f-3c35-4e3f-a61f-6ea7932ae0d2 --> <!-- LOCATIONS START packages/next/server/image-optimizer.ts#L527-L533 packages/next/server/image-optimizer.ts#L446-L457 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`packages/next/server/image-optimizer.ts#L446-L457`](https://github.com/drape-io/crbench-cursor-2026-09/blob/8e7f533bdedc033b856e7d69cdfb47010166ed82/packages/next/server/image-optimizer.ts#L446-L457) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjE1MTg5ZWJhLTNhMzUtNGI3MC04MDQzLThlMjE0NjViN2Y1OCIsImVuY3J5cHRpb25LZXkiOiJUSjhVMzhxMEhTdl8zVVBqZ1FQcl9KTTlmZ0hEUFFXdGtIMVd0WkFHNEdrIiwiYnJhbmNoIjoidDItbmV4dGpzLTM0MDc1IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjE1MTg5ZWJhLTNhMzUtNGI3MC04MDQzLThlMjE0NjViN2Y1OCIsImVuY3J5cHRpb25LZXkiOiJUSjhVMzhxMEhTdl8zVVBqZ1FQcl9KTTlmZ0hEUFFXdGtIMVd0WkFHNEdrIiwiYnJhbmNoIjoidDItbmV4dGpzLTM0MDc1IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6NjMsImNvbW1pdFNoYSI6IjhlN2Y1MzNiZGVkYzAzM2I4NTZlN2Q2OWNkZmI0NzAxMDE2NmVkODIiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 8e7f533bdedc033b856e7d69cdfb47010166ed82. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
packages/next/server/image-optimizer.ts:375
### Internal image status check ineffective **Low Severity** <!-- DESCRIPTION START --> The new internal-upstream guard uses `if (!mockRes.statusCode)`, which is false for real failures like 404 or 500 because those values are truthy and `statusCode` defaults to 200. A thrown `ImageError` here is also remapped to 500 by the inner `catch`, so failed internal image fetches are not surfaced with their actual status. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 48f0c768-0c64-4fcc-b11a-4ea7c7ab85ab --> <!-- LOCATIONS START packages/next/server/image-optimizer.ts#L357-L375 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmVjZGVhMThjLWRkNDktNGI5MS1hNDdlLWE5YzE2MTM1MzFkYyIsImVuY3J5cHRpb25LZXkiOiJTcUlxbVJ4dEZ3eGtwOW9ySWdIaTNrODF3eW90NG04MXBXZE8ybXFBUGVjIiwiYnJhbmNoIjoidDItbmV4dGpzLTM0MDc1IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmVjZGVhMThjLWRkNDktNGI5MS1hNDdlLWE5YzE2MTM1MzFkYyIsImVuY3J5cHRpb25LZXkiOiJTcUlxbVJ4dEZ3eGtwOW9ySWdIaTNrODF3eW90NG04MXBXZE8ybXFBUGVjIiwiYnJhbmNoIjoidDItbmV4dGpzLTM0MDc1IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6NjMsImNvbW1pdFNoYSI6IjhlN2Y1MzNiZGVkYzAzM2I4NTZlN2Q2OWNkZmI0NzAxMDE2NmVkODIiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 8e7f533bdedc033b856e7d69cdfb47010166ed82. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTo1ZDExZGJjZi1hMjY5LTRlOWMtODI2Mi00YjZjYWQ1YTQ1OTkiLCJlbmNyeXB0aW9uS2V5IjoidTQ0cHNjZTV6WjRKRC1QbnFBdWYtT1EzdUptendOY3RaaUZWa3QzVFRUNCIsImJyYW5jaCI6InQyLW5leHRqcy0zNDA3NSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 8e7f533bdedc033b856e7d69cdfb47010166ed82. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ exact
d2 high ✓ off by one
d3 medium ✓ off by one
d4 medium ✗ —
valid · impact low
sendResponse now hashes the full buffer on every request including cache hits, whereas before hits used the etag from the filename; cacheEntry.value.etag is available but unused. Minor perf regression. [grounded: tree packages/next/server/image-optimizer.ts] [consensus 3/3: valid=3]
valid · impact high
Node 16 changed fsPromises.rmdir with recursive:true on a nonexistent path to throw ENOENT; on first write the dir doesn't exist, so set() throws (logged in background by ResponseCache) and nothing is cached. [grounded: tree packages/next/server/image-optimizer.ts] [consensus 3/3: valid=3]
valid · matches d2 · impact high
valid · impact low
Previously render404 was passed parsedUrl; now it's omitted so render404 re-parses raw req.url (with basePath). Real but low-impact behavior change. [grounded: tree packages/next/server/next-server.ts] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · impact medium
When upstreamType is null and optimization throws, the fallback returns null contentType; next-server calls getExtension(contentType) which in mime 1.x calls .match on null and throws a non-ImageError TypeError, yielding a 500. Previously sendResponse tolerated null contentType. [grounded: tree packages/next/server/image-optimizer.ts] [consensus 3/3: valid=3]
valid · matches d1 · impact medium
raw comments (7)
packages/next/server/image-optimizer.ts:614
**ETag rehashed from full image on every hit** `sendResponse` runs `getHash([buffer])` on every request, including cache hits, even though the cache entry already carries `etag`. Before this change, hits read the ETag from the filename. Pass `cacheEntry.value.etag` into `sendResponse` instead of hashing the buffer again. ``` packages/next/server/image-optimizer.ts:604 export function sendResponse( packages/next/server/image-optimizer.ts:605 req: IncomingMessage, packages/next/server/image-optimizer.ts:606 res: ServerResponse, packages/next/server/image-optimizer.ts:607 url: string, packages/next/server/image-optimizer.ts:268 newReq: IncomingMessage, packages/next/server/image-optimizer.ts:269 newRes: ServerResponse, packages/next/server/image-optimizer.ts:270 newParsedUrl?: NextUrlWithParsedQuery packages/next/server/image-optimizer.ts:271 ) => Promise<void> packages/next/server/image-optimizer.ts:272 ): Promise<{ buffer: Buffer; contentType: string; maxAge: number }> { packages/next/server/image-optimizer.ts:273 let upstreamBuffer: Buffer ```
packages/next/server/image-optimizer.ts:548
**Images never cached on Node 16+** `writeToCacheDir` calls `promises.rmdir(dir, { recursive: true })` before the directory exists. Node 16+ throws ENOENT for that, so nothing gets written and every request optimizes the image again. Use `promises.rm(dir, { recursive: true, force: true })`, or ignore ENOENT. ``` packages/next/server/image-optimizer.ts:546 await promises.rmdir(dir, { recursive: true }) packages/next/server/image-optimizer.ts:547 await promises.mkdir(dir, { recursive: true }) packages/next/server/image-optimizer.ts:548 await promises.writeFile(filename, buffer) packages/next/server/image-optimizer.ts:549 } packages/next/package.json:278 "node": ">=12.22.0" ```
packages/next/server/image-optimizer.ts:360
**Standalone missing-sharp 500 is silently swallowed** The standalone "sharp is required" `ImageError(500)` is now thrown inside the `try`. The final `catch` in `imageOptimizer` catches it and returns the unoptimized upstream image, which then gets cached. Rethrow `ImageError` from the final catch, or move the standalone check above the try. ``` packages/next/server/image-optimizer.ts:352 mockReq.url = href packages/next/server/image-optimizer.ts:353 mockReq.connection = _req.connection packages/next/server/image-optimizer.ts:355 await handleRequest(mockReq, mockRes, nodeUrl.parse(href, true)) packages/next/server/image-optimizer.ts:356 await isStreamFinished packages/next/server/image-optimizer.ts:430 (base) const orientation = await getOrientation(upstreamBuffer) packages/next/server/image-optimizer.ts:432 (base) const operations: Operation[] = [] packages/next/server/image-optimizer.ts:434 (base) if (orientation === Orientation.RIGHT_TOP) { packages/next/server/image-optimizer.ts:435 (base) operations.push({ type: 'rotate', numRotations: 1 }) packages/next/server/image-optimizer.ts:436 (base) } else if (orientation === Orientation.BOTTOM_RIGHT) { packages/next/server/image-optimizer.ts:437 (base) operations.push({ type: 'rotate', numRotations: 2 }) ```
packages/next/server/next-server.ts:191
**Image 404 page ignores the normalized URL** When the loader isn't `default`, `render404` gets no `parsedUrl`, so it re-reads the raw `req.url`. That path still has the basePath and lacks the router's locale query. Pass `parsedUrl` as the third argument, like the other callers. ``` packages/next/server/next-server.ts:188 const imagesConfig = this.nextConfig.images packages/next/server/next-server.ts:190 if (imagesConfig.loader !== 'default') { packages/next/server/next-server.ts:191 await this.render404(req, res) packages/next/server/next-server.ts:192 return { finished: true } packages/next/server/base-server.ts:1829 const { pathname, query }: NextUrlWithParsedQuery = parsedUrl packages/next/server/base-server.ts:1830 ? parsedUrl packages/next/server/base-server.ts:1831 : parseUrl(req.url!, true) packages/next/server/base-server.ts:1833 if (this.nextConfig.i18n) { packages/next/server/base-server.ts:1834 query.__nextLocale = packages/next/server/base-server.ts:1835 query.__nextLocale || this.nextConfig.i18n.defaultLocale ```
packages/next/server/image-optimizer.ts:420
**Internal error responses cached as images** The new check `!mockRes.statusCode` never fires, because statusCode starts at 200 and is always set. So a non-2xx internal response with an image body is cached and served with 200. Before, the upstream status was passed through. Throw an `ImageError` when `mockRes.statusCode` is not 2xx. ``` packages/next/server/image-optimizer.ts:418 transformer.resize(width) packages/next/server/image-optimizer.ts:419 } packages/next/server/image-optimizer.ts:421 if (contentType === AVIF) { packages/next/server/image-optimizer.ts:422 if (transformer.avif) { packages/next/server/image-optimizer.ts:271 (base) // will not be emitted. packages/next/server/image-optimizer.ts:272 (base) // https://nodejs.org/docs/latest-v16.x/api/stream.html#writable_writechunk-encoding-callback ```
packages/next/server/image-optimizer.ts:531
**Unknown upstream type crashes with a TypeError (500)** When optimization fails and the upstream type couldn't be detected, imageOptimizer's fallback returns `contentType: upstreamType!` (null). getExtension(null) then throws in mime's `extension`, so the request ends in an unhandled 500. Throw an ImageError(400) for unknown types instead of returning null. ``` packages/next/server/image-optimizer.ts:527 } packages/next/server/image-optimizer.ts:528 } catch (error) { packages/next/server/image-optimizer.ts:529 return { packages/next/server/image-optimizer.ts:530 buffer: upstreamBuffer, packages/next/server/serve-static.ts:37 export function getExtension(contentType: string): string | null { packages/next/server/serve-static.ts:38 if (contentType === 'image/avif') { packages/next/server/serve-static.ts:39 // TODO: update "mime" package packages/next/server/serve-static.ts:40 return 'avif' packages/next/server/serve-static.ts:41 } packages/next/server/serve-static.ts:42 const { mime } = send ```
packages/next/server/image-optimizer.ts:580
**Optimized images no longer cacheable by browsers/CDNs** `setResponseHeaders` now always sends `max-age=0, must-revalidate` for non-static images, even in production, and ignores the upstream max-age. Browsers and CDNs then revalidate on every view. Pass the cached revalidate/maxAge to `sendResponse` and keep `max-age=${isDev ? 0 : maxAge}`. ``` packages/next/server/image-optimizer.ts:580 : `public, max-age=0, must-revalidate` packages/next/server/image-optimizer.ts:604 export function sendResponse( packages/next/server/image-optimizer.ts:605 req: IncomingMessage, packages/next/server/image-optimizer.ts:606 res: ServerResponse, packages/next/server/image-optimizer.ts:565 (base) 'Cache-Control', packages/next/server/image-optimizer.ts:566 (base) isStatic packages/next/server/image-optimizer.ts:567 (base) ? 'public, max-age=315360000, immutable' packages/next/server/image-optimizer.ts:568 (base) : `public, max-age=${isDev ? 0 : maxAge}, must-revalidate` packages/next/server/image-optimizer.ts:569 (base) ) ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ exact
d2 high ✓ off by one
d3 medium ✓ off by one
d4 medium ✓ off by one
valid · impact medium
Since Node 16, fsPromises.rmdir(path, {recursive:true}) rejects with ENOENT when the path does not exist. On a cache miss the directory is missing, so the write fails before mkdir and the error is only logged by ResponseCache. The new writeToCacheDir introduces this. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · impact low
The catch fallback can return a null contentType. The route then calls getExtension(contentType), and the compiled mime 1.x extension() calls e.match(...) without a null guard, so it throws. That error is not an ImageError and gets rethrown, where before the original buffer was served. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The constructor now requires image-optimizer unconditionally. That module requires sharp and squoosh at top level, so they load at startup even in minimal mode or with a non-default loader. Before, this was lazy inside imageOptimizer(). [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
Before, the call was render404(req, res, parsedUrl). Now parsedUrl is dropped, so render404 re-parses req.url and loses routed query state such as __nextLocale. [grounded: diff] [consensus 3/3: valid=3]
valid · impact high
When hasNextSupport is set, the build trace excludes image-optimizer.js. The constructor now requires it unconditionally, even in minimal mode, so server startup fails when the file is missing. Before, it was required only lazily in the image route. [grounded: tree packages/next/build/index.ts] [consensus 3/3: valid=3]
valid · matches d4 · impact medium
valid · impact low
Before, the cache-hit path took the etag from the filename and streamed the file. Now sendResponse hashes the whole buffer on every response, including hits, even though cacheEntry.value.etag is available. This is a performance regression. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d1 · impact medium
invalid
The new test asserts that all concurrent requests report MISS, with a comment explaining that they share the blocking first response. That makes it intended behaviour, not a defect. [invalid: contradiction] [consensus 3/3: invalid=3]
valid · matches d2 · impact high
raw comments (11)
packages/next/server/image-optimizer.ts:546
**Image cache write fails on first write** `writeToCacheDir` calls `promises.rmdir(dir, { recursive: true })` before `mkdir`. On Node 16+ this rejects with ENOENT when the directory doesn't exist, as on every cache miss. Nothing reaches disk; the error is only logged. Use `promises.rm(dir, { recursive: true, force: true })`, or ignore the error, before `mkdir`. ``` packages/next/server/image-optimizer.ts:540 maxAge: number, packages/next/server/image-optimizer.ts:541 expireAt: number, packages/next/server/image-optimizer.ts:542 buffer: Buffer, packages/next/server/image-optimizer.ts:543 etag: string packages/next/server/response-cache.ts:175 } catch (err) { packages/next/server/response-cache.ts:176 // while revalidating in the background we can't reject as packages/next/server/response-cache.ts:177 // we already resolved the cache entry so log the error here packages/next/server/response-cache.ts:178 if (resolved) { packages/next/server/response-cache.ts:179 console.error(err) packages/next/server/response-cache.ts:180 } else { ```
packages/next/server/image-optimizer.ts:455
**Internal image error status is ignored** `!mockRes.statusCode` never fires, because the mock starts at 200 and handlers set 4xx/5xx. An internal route answering 500/404 with an image body is optimized, cached and served as 200, where it used to propagate the status. Check `mockRes.statusCode >= 400` instead. ``` packages/next/server/image-optimizer.ts:452 // recommend it be used in production and this is a production feature packages/next/server/image-optimizer.ts:453 console.error( packages/next/server/image-optimizer.ts:454 `Error: 'sharp' is required to be installed in standalone mode for the image optimization to function correctly` packages/next/server/image-optimizer.ts:455 ) ```
packages/next/server/image-optimizer.ts:551
**Image request errors when upstream type is unknown** If optimization fails and the upstream type is null, the fallback returns `contentType: null`. `getExtension(null)` in the route generator then throws (mime's `extension` calls `.match` on it), so the request errors instead of serving the original image as before. Guard null before calling getExtension. ``` packages/next/server/image-optimizer.ts:545 const filename = join(dir, `${maxAge}.${expireAt}.${etag}.${extension}`) packages/next/server/image-optimizer.ts:546 await promises.rmdir(dir, { recursive: true }) packages/next/server/image-optimizer.ts:547 await promises.mkdir(dir, { recursive: true }) packages/next/server/image-optimizer.ts:548 await promises.writeFile(filename, buffer) ```
packages/next/server/next-server.ts:120
**Image optimizer loaded eagerly at server start** The constructor now requires `./image-optimizer` unconditionally, which loads sharp and squoosh. It runs even when images are unused, the loader is non-default, or the server is in minimal mode. This used to be loaded lazily on the first image request. Create the image ResponseCache lazily on the first image request. ``` packages/next/server/next-server.ts:120 const { ImageOptimizerCache } = packages/next/server/next-server.ts:121 require('./image-optimizer') as typeof import('./image-optimizer') packages/next/server/next-server.ts:123 this.imageResponseCache = new ResponseCache( packages/next/server/next-server.ts:124 new ImageOptimizerCache({ ```
packages/next/server/next-server.ts:191
**Image 404 drops parsed URL, losing detected locale** The new non-default-loader branch calls `render404(req, res)` without `parsedUrl`, so `render404` re-parses `req.url` instead of using the routed `parsedUrl`. That `parsedUrl.query` carries `__nextLocale` set during request handling; the fresh parse lacks it. Call `this.render404(req, res, parsedUrl)`. ``` packages/next/server/next-server.ts:190 if (imagesConfig.loader !== 'default') { packages/next/server/next-server.ts:191 await this.render404(req, res) packages/next/server/next-server.ts:192 return { finished: true } ```
packages/next/server/next-server.ts:120
**Server crashes when image-optimizer is traced out** The constructor and `generateImageRoutes` now `require('./image-optimizer')` unconditionally. `build/index.ts` excludes `image-optimizer.js` (and sharp) from the traced server files when `ciEnvironment.hasNextSupport` is set, since images are handled outside next-server. In that build the require fails at startup. Require the image optimizer lazily inside the image route handler, as before. ``` packages/next/server/next-server.ts:120 const { ImageOptimizerCache } = packages/next/server/next-server.ts:121 require('./image-optimizer') as typeof import('./image-optimizer') packages/next/server/next-server.ts:123 this.imageResponseCache = new ResponseCache( packages/next/server/next-server.ts:124 new ImageOptimizerCache({ packages/next/build/index.ts:1258 // only ignore image-optimizer code when packages/next/build/index.ts:1259 // this is being handled outside of next-server packages/next/build/index.ts:1260 '**/next/dist/server/image-optimizer.js', packages/next/build/index.ts:1261 '**/node_modules/sharp/**/*', ```
packages/next/server/api-utils.ts:386
**Revalidate error hides the real cause** The `catch` in `unstable_revalidate` catches its own `Invalid response ${res.status}` error, as well as fetch errors, and throws a generic `Failed to revalidate`. The status code or network error is discarded, so users cannot tell why revalidation failed. Include `err.message` in the thrown error, or pass it as `cause`. ``` packages/next/server/api-utils.ts:378 try { packages/next/server/api-utils.ts:379 const res = await fetch(`${baseUrl}${urlPath}`, { packages/next/server/api-utils.ts:380 headers: { packages/next/server/api-utils.ts:381 [PRERENDER_REVALIDATE_HEADER]: context.previewModeId, ```
packages/next/server/image-optimizer.ts:611
**Image ETag re-hashed on every cache hit** `sendResponse` runs `getHash([buffer])` (sha256 over the whole image) on every response, even though the cache entry already carries `etag`, and the route in `next-server.ts` doesn't pass it. Every HIT now costs a full hash of the image. Pass cacheEntry.value.etag into sendResponse. ``` packages/next/server/image-optimizer.ts:604 export function sendResponse( packages/next/server/image-optimizer.ts:605 req: IncomingMessage, packages/next/server/image-optimizer.ts:606 res: ServerResponse, packages/next/server/image-optimizer.ts:607 url: string, ```
packages/next/server/image-optimizer.ts:580
**Image Cache-Control max-age always 0 in production** `setResponseHeaders` no longer receives `maxAge`, so non-static optimized images always get `max-age=0, must-revalidate`, in production too. Browsers and CDNs revalidate every image instead of caching for the TTL. Pass maxAge through to sendResponse and use `isDev ? 0 : maxAge` as before. ``` packages/next/server/image-optimizer.ts:576 res.setHeader( packages/next/server/image-optimizer.ts:577 'Cache-Control', packages/next/server/image-optimizer.ts:578 isStatic packages/next/server/image-optimizer.ts:579 ? 'public, max-age=315360000, immutable' ```
packages/next/server/response-cache.ts:158
**Concurrent image requests all reported as MISS** `isMiss` is set from the first caller's cache lookup and stored in the shared pending promise. Requests that arrive while the image is being generated reuse that entry and also get `isMiss: true`. Don't share isMiss across waiters; only the generating request should see MISS. ``` packages/next/server/response-cache.ts:153 resolve( packages/next/server/response-cache.ts:154 cacheEntry === null packages/next/server/response-cache.ts:155 ? null packages/next/server/response-cache.ts:156 : { ```
packages/next/server/image-optimizer.ts:456
**Standalone missing-sharp error is swallowed and cached** The `throw new ImageError(500, ...)` for standalone mode without sharp sits inside the `try` whose `catch` returns the upstream buffer. The 500 never reaches the client; the unoptimized image is served with 200 and cached. Move the sharp check outside the try, or rethrow ImageError in the catch. ``` packages/next/server/image-optimizer.ts:407 try { packages/next/server/image-optimizer.ts:456 throw new ImageError(500, 'internal server error') packages/next/server/image-optimizer.ts:528 } catch (error) { packages/next/server/image-optimizer.ts:529 return { ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 high ✓ exact
d3 medium ✓ off by one
d4 medium ✗ —
valid · matches d2 · impact high
valid · matches d3 · impact medium
valid · impact low
Before this change, cache hits streamed the file with createReadStream(...).pipe(res). Now ImageOptimizerCache.get reads the whole file into a Buffer on every hit, so concurrent hits on large cached images each hold a full in-memory buffer. That is a real regression in memory use. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
Previously the optimization-failure fallback only sent the response and did not write it to disk; the old test was 'should proxy-pass unsupported image types and should not cache file'. Now the fallback result goes through ResponseCache.set and is written to disk, and the replacement test 'should maintain bmp' expects the cache directory to change. The cache has no eviction, so the new behavior adds to unbounded disk growth, though origins are limited by the domains allowlist. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
packages/next/server/image-optimizer.ts:456
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Standalone Error Is Swallowed** In standalone production without `sharp`, this throws an `ImageError`, but the unconditional catch at lines 528–533 turns it into a successful pass-through result. The route-level error handler never runs, so the server serves and caches the unoptimized source instead of returning the intended HTTP 500.
packages/next/server/image-optimizer.ts:358
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Internal Errors Become Successes** An internal image handler can return image bytes with a non-2xx status, but statuses such as 404 and 500 are truthy and therefore pass this check. Because the internal status is no longer copied to the outer response, the body is optimized, cached, and returned as HTTP 200, hiding the origin failure.
packages/next/server/image-optimizer.ts:204
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Cache Hits Amplify Memory** Every cache hit now reads the entire image into a new `Buffer` before responding. Animated and vector assets can retain their original size, and no encoded-byte limit is enforced, so concurrent requests for large cached assets allocate one full buffer each instead of streaming the file. This can cause avoidable memory pressure under load.
packages/next/server/next-server.ts:227
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Fallback Payloads Accumulate** This now persists every successful optimizer result, including original payloads returned after optimization failures. That removes the previous no-cache behavior for unsupported fallback formats, while the disk cache has no size or entry-count eviction. Many distinct allowed-origin URLs or variants can therefore accumulate large fallback payloads and eventually exhaust cache storage.
PR-level
<h3>Greptile Summary</h3> This PR refactors image optimization around the shared response-cache mechanism and changes manual revalidation to await completion rather than expose the internal fetch response. - Introduces a filesystem-backed `ImageOptimizerCache` with stale-while-revalidate behavior. - Moves image-route validation, response generation, and persistence into `NextNodeServer`. - Extends response-cache value types to include image buffers. - Splits image-optimizer coverage across Sharp, old-Sharp, and Squoosh suites. - Contains two blocking image-response regressions plus memory and disk-cache concerns. <h3>Confidence Score: 3/5</h3> The PR is not safe to merge until standalone missing-Sharp failures escape correctly and non-2xx statuses from internal image handlers are preserved or rejected. The broad transformation catch turns an explicitly intended standalone failure into a successful cached image, while the internal-image path accepts and hides non-2xx origin statuses; the new cache design also introduces non-blocking memory and disk-growth concerns. **Files Needing Attention:** packages/next/server/image-optimizer.ts, packages/next/server/next-server.ts <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | packages/next/server/image-optimizer.ts | Adds image parameter validation and filesystem caching, but swallows the standalone missing-Sharp failure, loses internal response statuses, and buffers complete cache hits. | | packages/next/server/next-server.ts | Integrates image responses with ResponseCache but unconditionally persists optimization-fallback payloads and omits internal origin status propagation. | | packages/next/server/response-cache.ts | Generalizes stale-while-revalidate cache entries to support images and exposes miss/stale metadata. | | packages/next/server/api-utils.ts | Validates manual revalidation paths, awaits the internal request, and reports non-successful responses as failures. | | test/integration/image-optimizer/test/util.js | Consolidates image-optimizer coverage and adds stale/concurrency tests, though some new assertions codify the broadened fallback caching behavior. | </details> <details open><summary><h3>Flowchart</h3></summary> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A["/_next/image request"] --> B["Validate URL, width, quality, and format"] B --> C["ResponseCache lookup"] C -->|Hit or stale| D["Read cached file into Buffer"] C -->|Miss or revalidate| E["Fetch internal or external origin"] E --> F["Optimize or return original payload"] F --> G["Persist through ImageOptimizerCache"] D --> H["Set image headers and send response"] G --> H ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update packages/next/server/api-utils.ts..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/ce0bad407f7b82407869ca437cc82d46625937a5) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284698)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 high ✓ off by one
d3 medium ✗ —
d4 medium ✗ —
valid · impact high
Node >=16 rejects recursive rmdir on a nonexistent path with ENOENT; on a cache miss the key dir doesn't exist, so set() rejects. ResponseCache has already resolved, so the error is only logged and the image is never cached. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d2 · impact high
valid · impact high
Same issue as finding 0: unguarded recursive rmdir on a missing dir throws ENOENT on Node 16+, so the cache write fails silently and every request is a MISS that re-optimizes. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
The throw sits inside the optimization try, whose catch returns the upstream buffer. The intended 500 is swallowed and the unoptimized image is served and cached. The old code ended the response with 'internal server error' instead. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
packages/next/server/image-optimizer.ts:546
[P1] First cache write fails on Node 16+, so optimized images are never cached `writeToCacheDir` now calls `promises.rmdir(dir, { recursive: true })` before `mkdir`, with nothing to catch an error. On a cache miss the directory for that cache key doesn't exist yet. Starting with Node 16, `fs.rmdir` with `recursive: true` throws `ENOENT` when the path doesn't exist; Node 12–15 ignored that case. Because `ResponseCache.get` calls `incrementalCache.set` after it has already resolved the response, the error only reaches `console.error` and the file is never written. On Node 16+ (allowed by `engines: ›=12.22.0`), every request to `/_next/image` re-runs the optimization and logs an error. Ignoring `ENOENT` (or using `fs.rm` with `force: true` where it exists) would avoid this.
packages/next/server/image-optimizer.ts:456
[P2] Missing sharp in standalone mode now returns the unoptimized image with a 200 The check for sharp being missing in standalone mode now throws `ImageError(500, 'internal server error')`. That throw sits inside the `try` whose `catch (error)` (line 528) returns the original upstream buffer as a successful result. The old code ended the response with a 500. Now, in standalone mode without `sharp`, the error is swallowed and the user gets the unoptimized image with a 200. `showSharpMissingWarning` is also never reset on this path, so the error is logged on every request. The 500 isn't returned anymore unless the `catch` re-throws `ImageError`s or the check moves outside the `try`.
packages/next/server/image-optimizer.ts:545
[P1] Image cache is never written on first optimization under Node 16+ · `writeToCacheDir` now calls `await promises.rmdir(dir, { recursive: true })` before `mkdir`. On a cache miss, the per-key directory doesn't exist yet. On Node 16 and later, a recursive `rmdir` on a missing path rejects with ENOENT (I checked this locally with Node 22). Node 12–15 ignored the missing path, which is why this can go unnoticed. When `rmdir` rejects, `ImageOptimizerCache.set` rejects too. `ResponseCache` has already resolved the entry at that point, so it only `console.error`s the failure and moves on. As a result, on Node 16+ nothing is written to `.next/cache/images` for a new key. Every later request is another MISS that re-optimizes the image and logs an error. To fix it, ignore ENOENT, for example `promises.rm(dir, { recursive: true, force: true })` with an `rmdir(...).catch(() =› {})` fallback for older Node.
packages/next/server/image-optimizer.ts:427
[P2] Missing `sharp` in standalone mode no longer returns a 500 · The `outputStandalone`-without-sharp check used to set a 500 and return early. It now throws `ImageError(500, 'internal server error')`, but the throw is inside the `try` whose `catch (error)` returns `{ buffer: upstreamBuffer, contentType: upstreamType!, maxAge }`. That catch swallows the error. Standalone deployments without `sharp` now quietly serve the unoptimized original image, and the response cache stores it, instead of failing with the intended 500. `showSharpMissingWarning` is never cleared on this path, so the error line is logged on every request. Throw this error outside the optimization `try`, or rethrow `ImageError` from the catch.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 high ✓ off by one
d3 medium ✗ —
d4 medium ✗ —
valid · impact high
The change added an unguarded `promises.rmdir(dir, { recursive: true })` call before `mkdir` in writeToCacheDir. The first time a cache key is written, that directory does not exist yet. Since Node 16.0.0, `fs.rmdir` with `recursive: true` rejects with ENOENT when the path does not exist, so `ImageOptimizerCache.set` throws before `writeFile` runs. ResponseCache has already resolved the response by then, so the error is only logged with `console.error`, and no image is ever written to the cache. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d2 · impact high
raw comments (2)
PR-level
[P1] rmdir on a missing cache dir throws on Node 16+, so images are never cached — packages/next/server/image-optimizer.ts:~(writeToCacheDir) `await promises.rmdir(dir, { recursive: true })` `writeToCacheDir` now calls `promises.rmdir(dir, { recursive: true })` before `mkdir`. On the first write for a cache key the directory doesn't exist. Since Node 16, `fs.rmdir(..., { recursive: true })` on a nonexistent path rejects with ENOENT instead of silently succeeding. Next 12 also supports Node 16. So `ImageOptimizerCache.set` throws before the file is written. `ResponseCache` has already resolved at that point, so the error is only logged with `console.error`. The result is that on Node 16+ nothing is persisted to `.next/cache/images`. Every request re-optimizes the image, and the cache-dir integration tests would fail. Use `rm` with `force: true`, or catch and ignore the error, so a missing directory is tolerated.
PR-level
[P2] Standalone-mode missing-sharp error is swallowed by the fallback catch — packages/next/server/image-optimizer.ts:~(the `throw new ImageError(500, 'internal server error')` inside the `try`) Before this change, standalone output without `sharp` ended the response with a 500 ('internal server error'). The new code instead throws `ImageError(500, ...)` inside the same `try` block whose `catch (error)` returns `{ buffer: upstreamBuffer, contentType: upstreamType! }`. The catch handles every error, including this `ImageError`. When `experimental.outputStandalone` is set and `sharp` isn't installed, the server now silently serves the unoptimized upstream image with a 200 and caches it. It no longer returns the intended 500. The catch should rethrow `ImageError` or the check should move outside the `try`.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 high ✓ exact
d3 medium ✓ off by one
d4 medium ✓ exact
valid · matches d2 · impact high
valid · impact low
If upstreamType is null, the `if (upstreamType)` validation is skipped. When optimization then fails, the catch returns `contentType: upstreamType!`, which is null at runtime. next-server passes that to `getExtension(contentType) as string`, so a null/bogus extension gets cached and served. The old code also sent the raw bytes without a content type, but it never pushed null into the new cache path, so this change introduces it. Real but small. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The new writeToCacheDir does a recursive rmdir, then mkdir, then writeFile, with no lock and no atomic rename. ResponseCache only dedupes requests inside one process. Separate processes sharing distDir can interleave these steps: one deletes the other's directory, causing an ENOENT on write or a lost entry. The only cost is redundant re-optimization, so the impact is low. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d4 · impact medium
valid · matches d3 · impact medium
raw comments (7)
packages/next/server/image-optimizer.ts:531
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Standalone images are served unoptimized <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>imageOptimizer</i></b> throws an <b><i>ImageError</i></b> when Sharp is unavailable in standalone mode, but the surrounding catch converts every optimization exception into the original upstream image. This path now returns and caches an unoptimized response instead of preserving the intended 500 failure when standalone deployments omit Sharp. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description `imageOptimizer` catches the intentional standalone-mode `ImageError` and serves the original image instead of returning the required failure. ## Fix Focus Areas - packages/next/server/image-optimizer.ts[447-456] - packages/next/server/image-optimizer.ts[528-533] ## Recommended Fix In the optimization catch block, rethrow `ImageError` instances before applying the fallback to the upstream buffer. Keep the fallback only for ordinary transformation failures. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
packages/next/server/image-optimizer.ts:532
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 2\. Untyped responses break image requests <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> <b><i>imageOptimizer</i></b> skips validation when <b><i>upstreamType</i></b> is null and its transformation catch returns that runtime null through a non-null assertion. A successful upstream response without detectable image bytes or a <b><i>Content-Type</i></b> header consequently reaches cache-key extension handling without a valid string instead of producing a controlled invalid-image response. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Upstream responses with no detected or declared content type can escape validation and return a null content type into the image cache path. ## Fix Focus Areas - packages/next/server/image-optimizer.ts[293-297] - packages/next/server/image-optimizer.ts[379-405] - packages/next/server/image-optimizer.ts[528-533] - packages/next/server/next-server.ts[218-226] ## Recommended Fix Validate that `upstreamType` exists and represents an image before optimization or fallback. Throw a controlled `ImageError` for missing types, and remove the non-null assertion so an invalid type cannot reach `getExtension`. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
packages/next/server/image-optimizer.ts:548
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 4\. Concurrent workers can lose cache writes <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> <b><i>writeToCacheDir</i></b> recursively deletes the shared key directory before recreating it and writing the generated image, without an atomic replacement or cross-process lock. Separate server instances optimizing the same key can interleave those operations so one worker removes another worker&#x27;s newly created directory, causing failed persistence and repeated optimization. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Concurrent server processes can race while deleting and recreating the same image-cache directory, losing or failing cache writes. ## Fix Focus Areas - packages/next/server/image-optimizer.ts[537-548] - packages/next/server/response-cache.ts[79-107] ## Recommended Fix Write each generated image to a unique temporary path and atomically rename it into place. Avoid recursively removing the destination directory during each write, and tolerate another worker completing the same cache entry first. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
packages/next/server/api-utils.ts:389
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 5\. Revalidation failures hide their cause <code>🐞 Bug</code> <code>◔ Observability</code> <pre> <b><i>unstable_revalidate</i></b> catches every fetch or status failure and replaces it with a new error containing only the requested path. DNS, connection, TLS, and non-success HTTP failures therefore expose neither their original message nor the response status to application logs and error handlers. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Revalidation replaces all underlying fetch and HTTP errors with a generic message, removing the details needed to diagnose failures. ## Fix Focus Areas - packages/next/server/api-utils.ts[378-390] ## Recommended Fix Include the original error as the new error's cause, or preserve its message and non-success status in the thrown error while retaining the requested path for context. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
packages/next/server/image-optimizer.ts:364
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 3\. Internal image errors return success <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>imageOptimizer</i></b> initializes the local-image mock status to 200, ignores the status passed to <b><i>writeHead</i></b>, and rejects only a falsy <b><i>mockRes.statusCode</i></b> rather than ordinary 4xx or 5xx responses. When an internal route returns image-looking bytes with a non-2xx status, those bytes are optimized, cached, and sent by the outer image route without copying the status, so processing reaches the client as a 200 response. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description `imageOptimizer` discards statuses supplied through the local mock response's `writeHead` and accepts every truthy status after the internal request completes. Because the outer image route sends the generated buffer without copying that status, internal non-2xx image responses can be optimized, cached, and served as successful responses, unlike absolute image fetching, which rejects non-2xx upstream responses. ## Fix Focus Areas - packages/next/server/image-optimizer.ts[327-340] - packages/next/server/image-optimizer.ts[355-375] ## Recommended Fix Make the mock `writeHead` assign its status argument to `mockRes.statusCode`, then reject statuses outside the 2xx range after the internal request completes, using the same success criteria as the external-fetch path. In the enclosing catch, preserve an existing `ImageError` so its original status reaches the image route, and wrap only unexpected internal failures as a 500 error. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Unify image optimization caching and harden on-demand revalidation <code>✨ Enhancement</code> <code>🐞 Bug fix</code> <code>🧪 Tests</code> <code>🕐 40+ Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Integrates image optimization with the shared stale-while-revalidate response cache. >• Validates on-demand revalidation paths and converts failed responses into errors. >• Expands concurrent image-cache coverage across Sharp and Squoosh configurations. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD A["Image Request"] --> B["Image Route"] --> C["Parameter Validation"] --> D["Response Cache"] D --> E[("Image Disk Cache")] D --> F["Image Optimizer"] --> G["Image Source"] F --> D ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The selected approach is appropriate: adapting image persistence to the existing ResponseCache centralizes request deduplication and stale-while-revalidate behavior instead of maintaining a separate inflight-request implementation. A standalone image-specific coordinator was considered, but it would duplicate cache lifecycle logic and increase concurrency risk. </dd> </dl> </details> <details> <summary> Files changed (15) <code> +2030 / -1569 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (3) <code> +588 / -445 </code></summary> <dl> <dd> <details> <summary>image-optimizer.ts<code>Separate image validation, optimization, caching, and response delivery</code> <code>+434/-428</code></summary> <br/> >Separate image validation, optimization, caching, and response delivery > ><pre> >• Introduces parameter validation, typed image errors, cache-key generation, and an ImageOptimizerCache adapter for ResponseCache. The optimizer now returns image data instead of directly managing HTTP responses and inflight requests, while disk entries retain TTL, expiry, ETag, and extension metadata. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-a3946331c576661316d56e5451a449433371bff26e53937d45f3efbb5b472c02'>packages/next/server/image-optimizer.ts</a> </details> <details> <summary>next-server.ts<code>Route image requests through the shared response cache</code> <code>+90/-13</code></summary> <br/> >Route image requests through the shared response cache > ><pre> >• Creates an image-specific ResponseCache backed by ImageOptimizerCache. The image route now validates parameters, deduplicates generation, serves hit/miss/stale responses, and maps typed optimizer failures to HTTP errors. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-ea09101c272788873ce720075e4839f0254179af0a07259a107752cafb193949'>packages/next/server/next-server.ts</a> </details> <details> <summary>response-cache.ts<code>Extend response caching to image values</code> <code>+64/-4</code></summary> <br/> >Extend response caching to image values > ><pre> >• Adds image cache value types and a generic incremental-cache contract. Cache results now expose stale and miss state so image responses can emit accurate cache headers. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-8a37414c87fd57ba569599997e14b886f252f36c3d039db45c22b9d55c4f55bb'>packages/next/server/response-cache.ts</a> </details> </dd> </dl> </details> <details> <summary>Bug fix (3) <code> +22 / -6 </code></summary> <dl> <dd> <details> <summary>api-utils.ts<code>Validate paths and surface revalidation failures</code> <code>+19/-5</code></summary> <br/> >Validate paths and surface revalidation failures > ><pre> >• Requires revalidation targets to be absolute paths beginning with &#x27;/&#x27;. Failed fetches and non-success responses now reject with a revalidation error instead of returning the raw response. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-098f0eca63ed374378d9984a17c485bcfb01793e8f8b5bb82af4d15a28c2127b'>packages/next/server/api-utils.ts</a> </details> <details> <summary>base-server.ts<code>Reject image values in the SSG response path</code> <code>+2/-0</code></summary> <br/> >Reject image values in the SSG response path > ><pre> >• Adds an invariant preventing image cache entries from being processed as page or redirect SSG results. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-2b8e3503c1bebf856610a5551d9c5996435b99f45db389d4eeac1b671518875e'>packages/next/server/base-server.ts</a> </details> <details> <summary>utils.ts<code>Correct the revalidation API return type</code> <code>+1/-1</code></summary> <br/> >Correct the revalidation API return type > ><pre> >• Changes &#x27;unstable_revalidate&#x27; from returning a Response to returning Promise&lt;void&gt;, matching its success-or-throw behavior. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-6baca52abe9d42b03dcf64d4ace2097a526c9b7519cdab7597f98b654f7b693d'>packages/next/shared/lib/utils.ts</a> </details> </dd> </dl> </details> <details> <summary>Refactor (2) <code> +9 / -23 </code></summary> <dl> <dd> <details> <summary>config-shared.ts<code>Require complete image configuration fields</code> <code>+1/-1</code></summary> <br/> >Require complete image configuration fields > ><pre> >• Changes the completed Next.js configuration type so all image configuration properties are required after configuration normalization. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-1ce54af4c1a0166a265bebae9ba304b24816ebe9cbb92f90b9707379b0680e97'>packages/next/server/config-shared.ts</a> </details> <details> <summary>incremental-cache.ts<code>Share cache value types and guard against image entries</code> <code>+8/-22</code></summary> <br/> >Share cache value types and guard against image entries > ><pre> >• Imports common cache entry types from response-cache, improves redirect size accounting, and asserts that image values never enter the page incremental cache. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-aaa872d6d11669ea197d0696981330f0e98185690946f335a08326f52a004401'>packages/next/server/incremental-cache.ts</a> </details> </dd> </dl> </details> <details> <summary>Tests (7) <code> +1411 / -1095 </code></summary> <dl> <dd> <details> <summary>prerender.test.ts<code>Assert boolean on-demand revalidation outcomes</code> <code>+4/-12</code></summary> <br/> >Assert boolean on-demand revalidation outcomes > ><pre> >• Updates prerender scenarios to verify the API fixture&#x27;s revalidated flag instead of inspecting the internal revalidation response body and status. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-3a8ce3244cc0ab37fa9ea56f5134f1cb77f7f01fa5b23f453a23a56f718be48a'>test/e2e/prerender.test.ts</a> </details> <details> <summary>manual-revalidate.js<code>Report revalidation success through exception handling</code> <code>+8/-4</code></summary> <br/> >Report revalidation success through exception handling > ><pre> >• Wraps on-demand revalidation in a try/catch and reports a boolean result, reflecting the new void-returning API contract. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-348b2608cd4cb7b0620400a504c0931764f85c3eed48656d6a3d82f1ecd5da12'>test/e2e/prerender/pages/api/manual-revalidate.js</a> </details> <details> <summary>index.test.js<code>Delegate optimizer scenarios to shared test utilities</code> <code>+77/-1079</code></summary> <br/> >Delegate optimizer scenarios to shared test utilities > ><pre> >• Moves the common optimizer matrix into reusable utilities and retains configuration-specific integration cases. Expectations now reflect zero browser max-age while verifying upstream TTL metadata in disk cache files. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-1890717f6402a731fae651e8b3de439ee96a06aae4b28db9612b4960f0d41fa0'>test/integration/image-optimizer/test/index.test.js</a> </details> <details> <summary>old-sharp.test.js<code>Isolate outdated Sharp integration coverage</code> <code>+27/-0</code></summary> <br/> >Isolate outdated Sharp integration coverage > ><pre> >• Adds a dedicated suite that installs Sharp 0.26.3 and runs the shared image optimizer scenarios, including compatibility warnings. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-b47f2ca6a995f958a7a5ef132bd570fca40715ebc9460c3eb97aa69cc49093bf'>test/integration/image-optimizer/test/old-sharp.test.js</a> </details> <details> <summary>sharp.test.js<code>Isolate current Sharp integration coverage</code> <code>+27/-0</code></summary> <br/> >Isolate current Sharp integration coverage > ><pre> >• Adds a dedicated suite that installs the latest Sharp release and runs the shared image optimizer scenarios. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-c229f642e724a1829ba37c957c99092f17406809ea3af5ee99ce9dd66c26c9a2'>test/integration/image-optimizer/test/sharp.test.js</a> </details> <details> <summary>squoosh.test.js<code>Add dedicated Squoosh optimizer suite</code> <code>+9/-0</code></summary> <br/> >Add dedicated Squoosh optimizer suite > ><pre> >• Runs the shared image optimizer scenarios without Sharp to cover the Squoosh transformation path. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-aa84ff40621ca2728fe23cb138946b817dd4a59de962e540415781c3c1194202'>test/integration/image-optimizer/test/squoosh.test.js</a> </details> <details> <summary>util.js<code>Centralize optimizer tests and add cache concurrency coverage</code> <code>+1259/-0</code></summary> <br/> >Centralize optimizer tests and add cache concurrency coverage > ><pre> >• Extracts reusable setup, filesystem, image-dimension, and optimizer test helpers. Adds a controllable slow image server and verifies request deduplication, non-blocking stale responses, background regeneration, cache metadata, and backend-specific behavior. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-ad4f0b1d2b2d4ff2aed61077e2d63851562f938c1cbbb818632af66b8d91372e'>test/integration/image-optimizer/test/util.js</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (5)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Standalone images are served unoptimized <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>imageOptimizer</i></b> throws an <b><i>ImageError</i></b> when Sharp is unavailable in standalone mode, but the >surrounding catch converts every optimization exception into the original upstream image. This path >now returns and caches an unoptimized response instead of preserving the intended 500 failure when >standalone deployments omit Sharp. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[packages/next/server/image-optimizer.ts[R528-531]](https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-a3946331c576661316d56e5451a449433371bff26e53937d45f3efbb5b472c02R528-R531)</code> > >```diff >+ } catch (error) { >+ return { >+ buffer: upstreamBuffer, >+ contentType: upstreamType!, >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Standalone mode explicitly throws when Sharp is absent, but that throw occurs inside the broad >transformation try block and is immediately converted into a successful upstream-buffer result. ></pre> > > <code>[packages/next/server/image-optimizer.ts[447-456]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L447-L456)</code> > <code>[packages/next/server/image-optimizer.ts[519-533]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L519-L533)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >`imageOptimizer` catches the intentional standalone-mode `ImageError` and serves the original image instead of returning the required failure. > >## Fix Focus Areas >- packages/next/server/image-optimizer.ts[447-456] >- packages/next/server/image-optimizer.ts[528-533] > >## Recommended Fix >In the optimization catch block, rethrow `ImageError` instances before applying the fallback to the upstream buffer. Keep the fallback only for ordinary transformation failures. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 2. Untyped responses break image requests <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>imageOptimizer</i></b> skips validation when <b><i>upstreamType</i></b> is null and its transformation catch returns >that runtime null through a non-null assertion. A successful upstream response without detectable >image bytes or a <b><i>Content-Type</i></b> header consequently reaches cache-key extension handling without a >valid string instead of producing a controlled invalid-image response. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[packages/next/server/image-optimizer.ts[R528-532]](https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-a3946331c576661316d56e5451a449433371bff26e53937d45f3efbb5b472c02R528-R532)</code> > >```diff >+ } catch (error) { >+ return { >+ buffer: upstreamBuffer, >+ contentType: upstreamType!, >+ maxAge, >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Both upstream paths can assign null to <b><i>upstreamType</i></b>; validation is conditional on that value being >truthy, while the fallback returns it as a string and the route passes it to <b><i>getExtension</i></b>, whose >signature requires a string. ></pre> > > <code>[packages/next/server/image-optimizer.ts[293-297]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L293-L297)</code> > <code>[packages/next/server/image-optimizer.ts[366-395]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L366-L395)</code> > <code>[packages/next/server/image-optimizer.ts[528-533]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L528-L533)</code> > <code>[packages/next/server/next-server.ts[218-226]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/next-server.ts/#L218-L226)</code> > <code>[packages/next/server/serve-static.ts[37-48]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/serve-static.ts/#L37-L48)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Upstream responses with no detected or declared content type can escape validation and return a null content type into the image cache path. > >## Fix Focus Areas >- packages/next/server/image-optimizer.ts[293-297] >- packages/next/server/image-optimizer.ts[379-405] >- packages/next/server/image-optimizer.ts[528-533] >- packages/next/server/next-server.ts[218-226] > >## Recommended Fix >Validate that `upstreamType` exists and represents an image before optimization or fallback. Throw a controlled `ImageError` for missing types, and remove the non-null assertion so an invalid type cannot reach `getExtension`. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 3. Internal image errors return success <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>imageOptimizer</i></b> initializes the local-image mock status to 200, ignores the status passed to ><b><i>writeHead</i></b>, and rejects only a falsy <b><i>mockRes.statusCode</i></b> rather than ordinary 4xx or 5xx >responses. When an internal route returns image-looking bytes with a non-2xx status, those bytes are >optimized, cached, and sent by the outer image route without copying the status, so processing >reaches the client as a 200 response. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[packages/next/server/image-optimizer.ts[R358-364]](https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-a3946331c576661316d56e5451a449433371bff26e53937d45f3efbb5b472c02R358-R364)</code> > >```diff >+ if (!mockRes.statusCode) { >+ console.error('image response failed for', href, mockRes.statusCode) >+ throw new ImageError( >+ mockRes.statusCode, >+ '"url" parameter is valid but internal response is invalid' > ) >- return { finished: true } >- } >- if (!upstreamType.startsWith('image/')) { >- res.statusCode = 400 >- res.end("The requested resource isn't a valid image.") >- return { finished: true } > } >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The mock response starts with <b><i>statusCode</i></b> set to 200, while its <b><i>writeHead</i></b> implementation copies >only headers and discards the supplied status; the subsequent falsy-status check therefore cannot >reject normal 4xx or 5xx values after the mock has passed through the full request handler. The >outer route then sends the generated or cached buffer without applying the mock response status, >whereas the absolute-image path correctly checks <b><i>upstreamRes.ok</i></b> before serving any buffer. ></pre> > > <code>[packages/next/server/image-optimizer.ts[278-290]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L278-L290)</code> > <code>[packages/next/server/image-optimizer.ts[327-340]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L327-L340)</code> > <code>[packages/next/server/image-optimizer.ts[355-375]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L355-L375)</code> > <code>[packages/next/server/next-server.ts[239-247]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/next-server.ts/#L239-L247)</code> > <code>[packages/next/server/base-server.ts[1652-1653]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/base-server.ts/#L1652-L1653)</code> > <code>[packages/next/server/image-optimizer.ts[278-291]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L278-L291)</code> > <code>[packages/next/server/image-optimizer.ts[325-340]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L325-L340)</code> > <code>[packages/next/server/image-optimizer.ts[355-369]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L355-L369)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >`imageOptimizer` discards statuses supplied through the local mock response's `writeHead` and accepts every truthy status after the internal request completes. Because the outer image route sends the generated buffer without copying that status, internal non-2xx image responses can be optimized, cached, and served as successful responses, unlike absolute image fetching, which rejects non-2xx upstream responses. > >## Fix Focus Areas >- packages/next/server/image-optimizer.ts[327-340] >- packages/next/server/image-optimizer.ts[355-375] > >## Recommended Fix >Make the mock `writeHead` assign its status argument to `mockRes.statusCode`, then reject statuses outside the 2xx range after the internal request completes, using the same success criteria as the external-fetch path. In the enclosing catch, preserve an existing `ImageError` so its original status reaches the image route, and wrap only unexpected internal failures as a 500 error. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <br/> <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> <details> <summary> 4. Concurrent workers can lose cache writes <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>writeToCacheDir</i></b> recursively deletes the shared key directory before recreating it and writing the >generated image, without an atomic replacement or cross-process lock. Separate server instances >optimizing the same key can interleave those operations so one worker removes another worker&#x27;s newly >created directory, causing failed persistence and repeated optimization. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[packages/next/server/image-optimizer.ts[R545-548]](https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-a3946331c576661316d56e5451a449433371bff26e53937d45f3efbb5b472c02R545-R548)</code> > >```diff > const filename = join(dir, `${maxAge}.${expireAt}.${etag}.${extension}`) >+ await promises.rmdir(dir, { recursive: true }) >+ await promises.mkdir(dir, { recursive: true }) > await promises.writeFile(filename, buffer) >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Deduplication is held in an instance-local map, while every server instance owns a separate response >cache and all instances write through the same delete-create-write sequence under the distribution >cache directory. ></pre> > > <code>[packages/next/server/next-server.ts[98-128]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/next-server.ts/#L98-L128)</code> > <code>[packages/next/server/response-cache.ts[79-107]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/response-cache.ts/#L79-L107)</code> > <code>[packages/next/server/image-optimizer.ts[537-548]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/image-optimizer.ts/#L537-L548)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Concurrent server processes can race while deleting and recreating the same image-cache directory, losing or failing cache writes. > >## Fix Focus Areas >- packages/next/server/image-optimizer.ts[537-548] >- packages/next/server/response-cache.ts[79-107] > >## Recommended Fix >Write each generated image to a unique temporary path and atomically rename it into place. Avoid recursively removing the destination directory during each write, and tolerate another worker completing the same cache entry first. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 5. Revalidation failures hide their cause <code>🐞 Bug</code> <code>◔ Observability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>unstable_revalidate</i></b> catches every fetch or status failure and replaces it with a new error >containing only the requested path. DNS, connection, TLS, and non-success HTTP failures therefore >expose neither their original message nor the response status to application logs and error >handlers. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[packages/next/server/api-utils.ts[R388-389]](https://github.com/drape-io/crbench-qodo-2026-09/pull/58/files#diff-098f0eca63ed374378d9984a17c485bcfb01793e8f8b5bb82af4d15a28c2127bR388-R389)</code> > >```diff >+ } catch (err) { >+ throw new Error(`Failed to revalidate ${urlPath}`) >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The non-success branch creates a status-bearing error, but the unconditional catch immediately >discards it along with any native fetch error and throws a detail-free replacement. ></pre> > > <code>[packages/next/server/api-utils.ts[378-390]](https://github.com/drape-io/crbench-qodo-2026-09/blob/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7/packages/next/server/api-utils.ts/#L378-L390)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Revalidation replaces all underlying fetch and HTTP errors with a generic message, removing the details needed to diagnose failures. > >## Fix Focus Areas >- packages/next/server/api-utils.ts[378-390] > >## Recommended Fix >Include the original error as the new error's cause, or preserve its message and non-success status in the thrown error while retaining the requested path for context. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>🧠 Deep</code>: This is a broad, high-risk image optimization and cache redesign spanning multiple server paths, APIs, concurrency behavior, validation, and extensive test refactoring, with many independent logic sites where redundant review is materially valuable.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/6465b94993d9ac8b2d7ee4a8533d355f3e1efae7 --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>