Skip to content

Commit 05d64e7

Browse files
committed
fix(router): handler-invoked loaders under cache() throw on header writes (closes #725 gap)
The cached-scope header guard (#725) exempted every loader body under a cache() boundary via isInsideAnyLoaderScope(). That let a handler-invoked loader — await ctx.use(Loader) from a handler, never registered with loader() — write a cookie/header on the MISS. On a HIT the handler is skipped and only DSL-registered loaders re-run, so that loader never executes and its write silently vanishes — the exact MISS/HIT divergence #725 was built to eliminate. Narrow the exemption to isInsideLoaderScope() (DSL scope only): registered loaders re-run on every HIT and merge into every response, so their writes stay allowed; a handler-invoked loader now throws deterministically like a handler write. The DSL scope ALS survives nested ctx.use bodies, so a handler-invoked loader nested under a DSL loader stays exempt (its parent re-runs it every HIT). The broad predicate is deferred to the throw path for the error label so the PPR handler-invoked-loader message stays "loader", and the throw reason keys on scope.kind so the cache() case explains the handler-skip cause. Re-ground the neighbouring read-purity guard comment, which this change makes contradictory: reads stay on the broad predicate under the consumption-lane baked-copy tradeoff (#672/#674), only writes narrow to DSL scope. Unit (cached-header-guard.test.ts): DSL-allowed pin, handler-invoked-throws pin (red before this change, green after), nested-under-DSL-allowed pin. E2e (cache-scope-guard, dev + production): /handler-loader-cookie-blocked asserts the error boundary renders and the cookie never reaches the wire; the DSL /loader-cookie-allowed control stays green in both modes.
1 parent 95f5648 commit 05d64e7

8 files changed

Lines changed: 175 additions & 19 deletions

File tree

‎packages/rangojs-router/docs/design/ppr-shell-resume.md‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,10 +1015,29 @@ at TTFB before any loader settles, so loader writes are dead letters on HITs
10151015
by physics. Middleware is THE header lane: it wraps the commit point, runs on
10161016
every request including HITs, and its stub-response writes merge into every
10171017
response (`createResponseWithMergedHeaders` -> `applyStubHeaders`,
1018-
`src/rsc/helpers.ts`). One deliberate asymmetry survives: loader writes inside
1019-
a plain `cache()` boundary stay ALLOWED — those loaders re-run and merge into
1020-
every response (no divergence exists; pinned by the cache-scope-guard e2e and
1021-
vite-rsc-demo's shop cart), while ppr loader writes throw.
1018+
`src/rsc/helpers.ts`). One deliberate asymmetry survives, and it is loader-KIND
1019+
specific (#725): a DSL (registered) loader's writes inside a plain `cache()`
1020+
boundary stay ALLOWED — a registered loader re-runs on every HIT
1021+
(`runInsideLoaderScope` in `fresh.ts` -> `resolveLoadersOnly` on the cache-hit
1022+
path) and merges into every response, so no divergence exists (pinned by the
1023+
`/loader-cookie-allowed` cache-scope-guard e2e and vite-rsc-demo's shop cart).
1024+
A **handler-invoked** loader body (`await ctx.use(Loader)` from a handler,
1025+
never registered with `loader()`) does NOT get the exemption: on a HIT the
1026+
handler is skipped, so that loader never re-runs and its Set-Cookie/header
1027+
would land only on the MISS — it throws exactly like a handler write. The
1028+
discriminator is `isInsideLoaderScope()` (DSL scope only, `loaderScopeALS`),
1029+
not `isInsideAnyLoaderScope()` (which also sees the handler-invoked
1030+
`loaderBodyScopeALS`); because the DSL scope ALS survives nested `ctx.use`
1031+
bodies, a handler-invoked loader nested under a DSL loader stays exempt (its
1032+
DSL parent re-invokes it every HIT). ppr loader writes throw regardless — the
1033+
shell prelude flushes before any loader settles.
1034+
1035+
Note this is a WRITE-only narrowing. The request-scoped READ guard
1036+
(`isInsideCacheScope`, `src/server/context.ts`) deliberately stays on the
1037+
BROAD predicate (`isInsideAnyLoaderScope()`): a handler-invoked loader's read
1038+
under `cache()` bakes a shared copy into the cached artifact — the accepted
1039+
consumption-lane tradeoff (#672/#674) — whereas a write has no baked-copy
1040+
semantics on a HIT, so only writes narrow to DSL scope.
10221041
10231042
Mechanics (the invariants the code comments point at):
10241043

‎packages/rangojs-router/docs/internal/feature-map.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ Route-local schema definitions (`search` option), typed route param types (`Rout
212212
- SWR background revalidation re-establishes the request-context ALS (so a cached body reading `getRequestContext()` resolves off the request's I/O context on workerd); profile opt-in `foregroundOnAction` re-executes a stale entry in the foreground during a server action's revalidation render (fresh action response) instead of serving stale + background-revalidating
213213
- Tag-based invalidation: `cacheTag()` (runtime) + `cache({ tags })` (static/dynamic); `updateTag()` (awaitable, read-your-own-writes) and `revalidateTag()` (background, non-blocking — both hard-purge; the only difference is awaitability) fan out to the store-level `invalidateTags()` (the whole tag batch in one call). `cacheTag()` is render-callable: outside a `"use cache"` scope but during a request render it records onto the request's document artifact (`_requestTags`) instead of throwing, so a plain server component tags the PPR shell / document it renders into — PPR's DERIVATIVE invalidation, no first-class ppr tag API (`cacheTag`/`cache-tag.ts`). Built-in stores index tags; the CF store keeps markers in its own KV (single-store, no companion tag store), and the tag-marker reads inherit the L1/L2 latency budgets and fail open. Explicit `cache({ store })` stores are registered for invalidation via a handler-owned, LRU-bounded registry. Document-cache and PPR shell entries are tagged with the request's tag union so they are tag-invalidatable too.
214214
- PPR shell caching (the `ppr` path option; `PartialPrerenderProps` exported from the root) — an opt-in second render axis, integral to the router (no middleware). It caches the rendered HTML shell (React `prerender`'s prelude bytes plus the `postponed` resume state, one coupled `ShellCacheEntry`) and, on a hit, commits the composed response after the WHOLE middleware chain: prelude bytes flush first, then fizz resumes only the holes; the browser sees one ordinary streamed document. Holes are render-defined — `loading()` subtrees (structural; loaders masked at capture), pending promises in handed-over data under the consumer's Suspense (physics), everything else shell (top-level pushed handle promises are awaited pre-SSR and baked; the capture gate holds for that await, bounded by `ppr.captureTimeout` — default 15s; expiry with pushes pending refuses the capture, so a partial head snapshot is never stored). The background capture is mixed-chain (cached segments replay, uncached handlers execute — the cookies()/headers() capture guard is load-bearing) and never re-runs middleware (the derived context inherits post-middleware state). Backed by the optional `getShell`/`putShell` store family (memory/CF/Vercel), reactVersion+buildVersion-gated (isValidShellHit; a redeploy invalidates like a React upgrade, hasIntactShellPayload rejects corrupt payloads pre-commit, a failed HIT tail schedules a healing recapture) and tag-invalidatable. Shell/payload PARITY on a HIT is guaranteed by the CAPTURE DATA SNAPSHOT (`cache/shell-snapshot.ts`, internal): a pre-render write barrier settles the foreground's deferred cache writes so the capture replays the foreground's cache generation (never clobbers it); the capture render records its cache-store read-hits + writes (`RecordingShellStore`, excluding the shell family; `captureAndStoreShell` fires the capture's isolated `onResponse` so the ring-3 segment write runs and is recorded), stores them on `ShellCacheEntry.snapshot` (carried through the CF/Vercel envelopes), and `serveShellHit`'s tail render replays them AS FRESH (`SeededShellStore`) so a shell-baked cached value that DRIFTED (shorter-ttl `cache()`, tag-invalidated item) still matches the frozen prelude — parity beats freshness inside the shell; freshness comes from holes, the shell ttl/swr, and `ppr.tags`. Actions, progressive enhancement, per-request nonce, and `streamMode: "allReady"` (the SEO/bot story) always take axis 1. On a HIT the tail's hydration payload is FRAGMENT-SPLICED (#700): replayed segments carry their STORED per-segment Flight strings verbatim (`__rangoFragment` envelopes, `src/segment-fragments.ts`) instead of being deserialized and re-serialized per request; the SSR resume pass and browser hydration expand them through their own Flight deserializers, so the browser still can't tell. Operability (issue #651): `PartialPrerenderProps.maxSnapshotBytes` (default 8 MiB) skips an over-cap snapshot (shell still stored; once-per-key report; documented drift on later HITs); the `debugShellCapture` router option (`ShellCaptureDebug`/`ShellCaptureDebugEvent`, exported) emits one structured event per capture attempt/skip — outcome, barrier/write-settle waits, prelude/snapshot bytes, backoff state — and in dev the terminal event mirrors into the NEXT ppr GET's Server-Timing (`ppr-capture;desc="…"`, plus a `ppr:shell-read` metric); a KV-less `CFCacheStore` warns once per isolate that its shell family is inert. See [PPR shell caching design](../design/ppr-shell-resume.md).
215-
- Cached-scope header doctrine (#713): ppr is a document-scoped `cache()` — in any cached scenario only MIDDLEWARE writes response headers. One unified guard (`assertCachedHeaderWriteAllowed`, `server/context.ts`) refuses handler header/cookie/status/theme writes inside a `cache()` boundary AND on any render of a `ppr` route (latched at the segment funnels: positional for `cache()`, whole-funnel for ppr — leaf-entry check, same `isPprEntry` + input as the serve path's `resolvePprConfig`; the intercept funnels carry a defense-in-depth latch off the target route), plus loader writes on ppr routes (headers flush with the shell before loaders settle). Enforced at ONE choke point: a guarded Headers proxy shadowed onto the request context's stub `Response`, so `ctx.header`/`setCookie`/`deleteCookie`/`setTheme`, the handler `ctx.headers` proxy, and raw `ctx.res.headers` mutations all hit the guard at the mutation itself (`setStatus`/`onResponse` stay enumerated; internal serve writers are exempt via the raw Headers). Deterministic first-render throw, dev and prod, one message family naming route + layer + the fix ("set response headers in route middleware"). Deliberate asymmetry: loader writes inside plain `cache()` stay allowed (they re-run and merge per request — pinned by cache-scope-guard e2e + vite-rsc-demo shop cart). Middleware headers/cookies merge into every response including shell HITs (`createResponseWithMergedHeaders`/`applyStubHeaders`, `rsc/helpers.ts`). See the header doctrine section in [PPR shell caching design](../design/ppr-shell-resume.md).
215+
- Cached-scope header doctrine (#713): ppr is a document-scoped `cache()` — in any cached scenario only MIDDLEWARE writes response headers. One unified guard (`assertCachedHeaderWriteAllowed`, `server/context.ts`) refuses handler header/cookie/status/theme writes inside a `cache()` boundary AND on any render of a `ppr` route (latched at the segment funnels: positional for `cache()`, whole-funnel for ppr — leaf-entry check, same `isPprEntry` + input as the serve path's `resolvePprConfig`; the intercept funnels carry a defense-in-depth latch off the target route), plus loader writes on ppr routes (headers flush with the shell before loaders settle). Enforced at ONE choke point: a guarded Headers proxy shadowed onto the request context's stub `Response`, so `ctx.header`/`setCookie`/`deleteCookie`/`setTheme`, the handler `ctx.headers` proxy, and raw `ctx.res.headers` mutations all hit the guard at the mutation itself (`setStatus`/`onResponse` stay enumerated; internal serve writers are exempt via the raw Headers). Deterministic first-render throw, dev and prod, one message family naming route + layer + the fix ("set response headers in route middleware"). Deliberate asymmetry: DSL (registered) loader writes inside plain `cache()` stay allowed (they re-run and merge per request — pinned by the `/loader-cookie-allowed` cache-scope-guard e2e + vite-rsc-demo shop cart); a handler-invoked loader body (`ctx.use` from a handler, never registered with `loader()`) throws under `cache()` because it is skipped with its handler on a HIT and its write would land only on the MISS (#725; discriminator `isInsideLoaderScope()` vs `isInsideAnyLoaderScope()`; pinned by the `/handler-loader-cookie-blocked` e2e). Middleware headers/cookies merge into every response including shell HITs (`createResponseWithMergedHeaders`/`applyStubHeaders`, `rsc/helpers.ts`). See the header doctrine section in [PPR shell caching design](../design/ppr-shell-resume.md).
216216
- Build-time PPR shells (producer B, #699): a `Prerender` route that also declares `ppr` gets its complete `ShellCacheEntry` produced at `vite build` and served from the FIRST request after deploy (`x-rango-shell: HIT`, zero runtime capture) — one entry format, two producers, one consumer. The build's shell prerender phase (buildApp post; the prelude embeds the BUILT client bootstrap URL) reuses the discovery temp server and runs producer A's capture core over the just-collected prerender payloads; entries stage as `__ps-*.js` assets + a lazy `__shell-manifest.js` (pathname-only keys) read through on a shell-store MISS. `ppr.ttl` is staleness-only (recapture = the SWR upgrade path); the buildVersion gate retires entries per deploy; `updateTag` evicts by tag-marker comparison (`isTagsInvalidatedSince`, new optional store method on all three stores) against the entry's build-time `createdAt` — no tombstones. Dev parity: the read-through fetches the `/__rsc_shell` dev endpoint (on-demand capture, memoized per HMR generation) for trie `pr`-flagged routes. See prerender-api-design.md (Build-time PPR shells).
217217

218218
### Error and Control Flow

‎packages/rangojs-router/e2e/cache-scope-guard.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,27 @@ test.describe("cache-scope-guard", () => {
161161
);
162162
});
163163

164+
test("handler-invoked loader writing a cookie inside cache() should throw (#725)", async ({
165+
page,
166+
}) => {
167+
const response = await page.goto(
168+
f.url("/cache-scope-guard/handler-loader-cookie-blocked"),
169+
);
170+
await waitForHydration(page);
171+
172+
await expect(page.getByTestId("csg-error-page")).toBeVisible();
173+
await expect(page.getByTestId("csg-error-message")).toContainText(
174+
"cache() boundary",
175+
);
176+
await expect(page.getByTestId("csg-error-message")).toContainText(
177+
"from a loader",
178+
);
179+
// Divergence pin: the MISS-only Set-Cookie never reaches the wire.
180+
expect(response?.headers()["set-cookie"] ?? "").not.toContain(
181+
"csg-hil-cookie",
182+
);
183+
});
184+
164185
test("ctx.headers.set() inside cache() should throw (SSR)", async ({
165186
request,
166187
}) => {
@@ -341,6 +362,22 @@ test.describe("cache-scope-guard (production)", () => {
341362
);
342363
});
343364

365+
test("handler-invoked loader writing a cookie inside cache() should render error boundary (#725)", async ({
366+
page,
367+
}) => {
368+
// Production redacts the error message, so assert the boundary rendered and
369+
// pin the divergence: the MISS-only Set-Cookie never reaches the wire.
370+
const response = await page.goto(
371+
f.url("/cache-scope-guard/handler-loader-cookie-blocked"),
372+
);
373+
await waitForHydration(page);
374+
375+
await expect(page.getByTestId("csg-error-page")).toBeVisible();
376+
expect(response?.headers()["set-cookie"] ?? "").not.toContain(
377+
"csg-hil-cookie",
378+
);
379+
});
380+
344381
test("getRequestContext().get(nonCacheable) inside cache() should render error boundary", async ({
345382
page,
346383
}) => {

‎packages/rangojs-router/e2e/test-app/src/router.named-routes.gen.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ export const NamedRoutes = {
3232
"cacheIsolation.queryVariant": "/cache-isolation/query-variant",
3333
"cacheScopeGuard.asyncLoaderReadAllowed": "/cache-scope-guard/async-loader-read-allowed",
3434
"cacheScopeGuard.cookiesReadBlocked": "/cache-scope-guard/cookies-read-blocked",
35+
"cacheScopeGuard.handlerLoaderCookieBlocked": "/cache-scope-guard/handler-loader-cookie-blocked",
3536
"cacheScopeGuard.headerBlocked": "/cache-scope-guard/header-blocked",
3637
"cacheScopeGuard.headersReadBlocked": "/cache-scope-guard/headers-read-blocked",
3738
"cacheScopeGuard.index": "/cache-scope-guard",

‎packages/rangojs-router/e2e/test-app/src/urls/cache-scope-guard-loader.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,16 @@ export const CookieReaderLoader = createLoader(async () => {
3838
const session = cookies().get("csg-session")?.value;
3939
return { session: session ?? "no-cookie" };
4040
});
41+
42+
// Writes a cookie, but is consumed ONLY via ctx.use from a handler — never
43+
// registered with loader() in the route config. Under cache() this must THROW
44+
// (#725): a handler-invoked loader runs on the MISS but is skipped with its
45+
// handler on a HIT, so the Set-Cookie would land only on the MISS and vanish on
46+
// hits. Contrast CookieWriterLoader (DSL-registered, re-runs every hit,
47+
// ALLOWED).
48+
export const HandlerInvokedCookieWriterLoader = createLoader(async () => {
49+
"use server";
50+
await new Promise((resolve) => setTimeout(resolve, 10));
51+
cookies().set("csg-hil-cookie", "written-by-handler-loader", { path: "/" });
52+
return { wrote: true };
53+
});

‎packages/rangojs-router/e2e/test-app/src/urls/cache-scope-guard.tsx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
AsyncNonCacheableReaderLoader,
1414
CookieWriterLoader,
1515
CookieReaderLoader,
16+
HandlerInvokedCookieWriterLoader,
1617
} from "./cache-scope-guard-loader.js";
1718
import { CacheScopeGuardCookieReader } from "../components/CacheScopeGuardCookieReader.js";
1819

@@ -355,6 +356,28 @@ export const cacheScopeGuardPatterns = urls(
355356
),
356357
]),
357358

359+
// Handler-invoked loader (NOT registered via loader()) calling
360+
// cookies().set() inside cache() — BLOCKED (#725). Unlike
361+
// /loader-cookie-allowed above, the loader is consumed only via ctx.use
362+
// and is never re-run on a HIT (the handler is skipped), so its
363+
// Set-Cookie would land only on the MISS and vanish on hits. The guard
364+
// throws deterministically on the first render instead.
365+
cache({ ttl: 600 }, () => [
366+
errorBoundary((props) => (
367+
<div data-testid="csg-error-page">
368+
<span data-testid="csg-error-message">{props.error.message}</span>
369+
</div>
370+
)),
371+
path(
372+
"/handler-loader-cookie-blocked",
373+
async (ctx) => {
374+
await ctx.use(HandlerInvokedCookieWriterLoader);
375+
return <div>Should not render</div>;
376+
},
377+
{ name: "handlerLoaderCookieBlocked" },
378+
),
379+
]),
380+
358381
// cookies() read inside cache() — BLOCKED (read-purity guard)
359382
cache({ ttl: 600 }, () => [
360383
errorBoundary((props) => (

‎packages/rangojs-router/src/rsc/__tests__/cached-header-guard.test.ts‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@
1111
* escape, all via the guarded-stub-headers choke point; setStatus
1212
* enumerated),
1313
* - PPR/cache() message-family EQUIVALENCE (same Error class, same family),
14-
* - the pinned cache()-loader write exemption (vite-rsc-demo shop cart),
14+
* - the pinned cache()-loader write exemption — DSL (registered) loaders ONLY
15+
* (vite-rsc-demo shop cart); a handler-invoked loader body throws under
16+
* cache() because it is skipped with its handler on a hit (#725),
17+
* - a handler-invoked loader nested under a DSL loader stays exempt (the DSL
18+
* parent re-runs it every hit),
1519
* - middleware merge order on the shell-HIT serve path
1620
* (createResponseWithMergedHeaders: serve-owned headers win, middleware
1721
* headers merge, Set-Cookie appends).
@@ -150,26 +154,61 @@ describe("assertCachedHeaderWriteAllowed (the seam)", () => {
150154
expect(cacheErr.message).toMatch(FAMILY_RE);
151155
});
152156

153-
it("cache() + loader: ALLOWED (pinned exemption — loaders re-run and merge per request)", () => {
157+
it("cache() + DSL loader: ALLOWED (pinned exemption — DSL loaders re-run and merge per request)", () => {
154158
RangoContext.run(makeStore() as never, () => {
155159
latchCachedHeaderScope("cache", "shop");
156160
runInsideLoaderScope(() => {
157161
expect(() =>
158162
assertCachedHeaderWriteAllowed("ctx.setCookie()"),
159163
).not.toThrow();
160164
});
165+
});
166+
});
167+
168+
// #725 gap: a handler-invoked loader body (ctx.use from a handler, never
169+
// registered with loader()) runs only on the MISS — on a HIT the handler and
170+
// this loader are skipped, so its write would silently vanish. It must throw,
171+
// NOT ride the DSL exemption. Regression pin (red before the guard narrowed to
172+
// isInsideLoaderScope()).
173+
it("cache() + handler-invoked loader body: THROWS (handler skipped on hit, write would vanish)", () => {
174+
RangoContext.run(makeStore() as never, () => {
175+
latchCachedHeaderScope("cache", "shop");
161176
runInsideLoaderBodyScope(
162177
() => {
163-
expect(() =>
178+
const err = captureError(() =>
164179
assertCachedHeaderWriteAllowed("ctx.setCookie()"),
165-
).not.toThrow();
180+
);
181+
expect(err.message).toContain("from a loader");
182+
expect(err.message).toContain("cache() boundary");
183+
expect(err.message).toContain("the handler is skipped");
184+
expect(err.message).toMatch(FAMILY_RE);
166185
},
167186
"CartLoader",
168187
true,
169188
);
170189
});
171190
});
172191

192+
// The DSL scope ALS survives into nested ctx.use bodies, so a handler-invoked
193+
// loader nested under a DSL loader stays exempt: the DSL parent re-runs on
194+
// every hit and re-invokes it, so no MISS/HIT divergence exists.
195+
it("cache() + handler-invoked loader body nested in a DSL loader: ALLOWED (DSL parent re-runs it every hit)", () => {
196+
RangoContext.run(makeStore() as never, () => {
197+
latchCachedHeaderScope("cache", "shop");
198+
runInsideLoaderScope(() => {
199+
runInsideLoaderBodyScope(
200+
() => {
201+
expect(() =>
202+
assertCachedHeaderWriteAllowed("ctx.setCookie()"),
203+
).not.toThrow();
204+
},
205+
"NestedLoader",
206+
true,
207+
);
208+
});
209+
});
210+
});
211+
173212
it("first latch wins: a nested cache() does not downgrade a ppr scope", () => {
174213
RangoContext.run(makeStore() as never, () => {
175214
latchCachedHeaderScope("ppr", "product");

0 commit comments

Comments
 (0)