Skip to content

Commit 74cdcad

Browse files
committed
fix(cache): require matching integrity to serve stale
1 parent d4eea12 commit 74cdcad

3 files changed

Lines changed: 34 additions & 3 deletions

File tree

‎.agents/cache.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ Rule: **never write an entry that has neither an expiry nor a storage TTL** (fin
2828
- `{ swr: true, maxAge: 60 }` **has** an expiry in `entry.expires` but has no TTL. Storage retains it after it becomes stale. This retention provides ISR. The cache serves the last good value while a background refresh replaces it. If refresh fails, the cache continues to serve the last success. Next's `revalidate` marks a page as eligible for regeneration and does not delete it. Vercel limits ISR by capacity, not by a timer. `x-cache` mirrors `x-nextjs-cache` values HIT, STALE, and MISS. This case is **allowed**. Finding 14.3 proposed a default TTL of `maxAge`. That proposal was **rejected**. Such a TTL would delete the entry as soon as it became stale. It would turn SWR into foreground revalidation and make `docs/1.guide/9.isr.md` impossible. Backend **capacity** limits this case. Since finding 14.1, the built-in backend has a capacity limit. See `.agents/storage.md`.
2929
- `{ maxAge: 0 }`, including a `getMaxAge` value clamped to zero, has no usable fresh period and no reclaim rule. Storage would create a permanent HIT. The cache **refuses** this case and evicts any previous entry for the key. This also removes entries written by older ocache versions. A nullish `maxAge` is also refused. Both defaults merges supply `maxAge: 1`, and explicit `undefined` no longer removes it. Therefore, the nullish case is reachable only through standalone `expireCache`, which does not merge defaults.
3030

31+
## Freshness vs. validity
32+
33+
`expired` mixes two kinds of condition, and only one of them may serve a stale value.
34+
35+
- **Freshness**: `entry.stale === true` (from `expire`), an elapsed `maxAge`, `readMaxAge === 0`, and `shouldInvalidateCache`. The stored value is this function's own output and is merely unwanted. SWR serves it while a background refresh runs.
36+
- **Validity**: an `integrity` mismatch and a failing `validate`. The stored value does not belong to this function at all. It must never reach a caller. These force foreground revalidation, so the status is `revalidated`, never `stale`.
37+
38+
`validate` was already excluded from the stale branch. `integrity` was not. Two functions that shared `storage`, `name`, and key but hashed differently reproduced the defect: the second function's first call returned the first function's value, and the background refresh corrected only later calls. This is cross-handler disclosure wherever storage-key namespaces collide, and it also serves a pre-deploy value after the function source or options change. Both serve decisions — the `status` expression and the SWR early return — read one captured `isMatched`. Do not read `entry.integrity` at the second site: the background `resolveEntry` reassigns that field, so the check would race.
39+
3140
## Hooks
3241

3342
- `getMaxAge(entry)` sets a dynamic per-entry TTL after the resolver runs. It returns seconds as shorthand for `maxAge`, or `{ maxAge?, staleMaxAge? }`. The cache stores the result on the entry. It controls read freshness, storage TTL, and the `Cache-Control` value that `defineCachedHandler` creates (finding 10.2). It runs before `serialize`, so `entry.value` is still live. Do not consume a one-use body. `serialize` reads that body exactly once. `http/index.ts` always installs a wrapper. A handler entry therefore always has both fields. `undefined` means "no override," not "hook not called." This distinction makes the finding 10.2 advertisement correct.

‎src/cache.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,13 @@ export function defineCachedFunction<T, ArgsT extends unknown[] = any[]>(
155155
// Run asynchronous validation once per read.
156156
const _isValid = (await validate(entry, validateCtx)) !== false;
157157

158+
// A mismatch means the entry belongs to another function, so it is unusable, not stale.
159+
const isMatched = entry.integrity === integrity;
160+
158161
const expired =
159162
shouldInvalidateCache ||
160163
entry.stale === true ||
161-
entry.integrity !== integrity ||
164+
!isMatched ||
162165
readMaxAge === 0 ||
163166
(ttl > 0 && Date.now() - (entry.mtime || 0) > ttl) ||
164167
!_isValid;
@@ -177,7 +180,7 @@ export function defineCachedFunction<T, ArgsT extends unknown[] = any[]>(
177180
? "miss"
178181
: !expired
179182
? "hit"
180-
: swr && _isValid
183+
: swr && _isValid && isMatched
181184
? "stale"
182185
: "revalidated";
183186

@@ -314,7 +317,7 @@ export function defineCachedFunction<T, ArgsT extends unknown[] = any[]>(
314317
configurable: true,
315318
});
316319

317-
if (swr && (await validate(entry, validateCtx)) !== false) {
320+
if (swr && isMatched && (await validate(entry, validateCtx)) !== false) {
318321
_resolvePromise.catch((error) => {
319322
onError("[cache] SWR handler error.", error);
320323
});

‎test/index.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,25 @@ describe("cachedFunction", () => {
180180
expect(statuses).toEqual(["miss", "hit", "revalidated"]);
181181
});
182182

183+
it("never serves an entry with a foreign integrity as stale under SWR", async () => {
184+
const statuses: (string | undefined)[] = [];
185+
const fn = defineCachedFunction(() => "mine", {
186+
maxAge: 100,
187+
swr: true,
188+
getKey: () => "k",
189+
transform: (entry) => {
190+
statuses.push(entry.status);
191+
return entry.value;
192+
},
193+
});
194+
const [key] = await fn.resolveKeys();
195+
// Another function's value under the same key: unusable, not merely stale.
196+
await testStorage.set(key!, { value: "theirs", mtime: Date.now(), integrity: "foreign" });
197+
198+
expect(await fn()).toBe("mine");
199+
expect(statuses).toEqual(["revalidated"]);
200+
});
201+
183202
it("does not persist per-call status to storage (incl. on a hit)", async () => {
184203
const fn = defineCachedFunction(() => "v", { maxAge: 100, getKey: () => "k" });
185204
await fn(); // miss (writes entry)

0 commit comments

Comments
 (0)