Skip to content

Commit 1315b06

Browse files
committed
fix(ppr): consumption-lane rule — handler ctx.use(loader) bakes during shell capture, identity reads permitted (#672)
A slot handler awaiting ctx.use(SlotLoader) during PPR shell capture executed the loader and tripped the cookies() identity guard, refusing the capture forever (x-rango-shell: MISS permanently) with a warning blaming a bake-lane loader that did not exist. This affected EVERY route (the issue's working "/" was a stale-shell artifact). Resolution: align PPR capture with the cache()/"use cache" precedent instead of adding masking machinery. The CONSUMPTION-LANE RULE, now doctrine: for any shared-artifact capture, server-side handler consumption via ctx.use(loader) yields a BAKED copy with cookies()/headers() reads permitted — the same documented footgun cache() already carries ("Cache purity & tainted objects"); client-side useLoader is the live lane. DSL segment lanes are untouched: a live-lane (loading()) registration still masks its segment — so for the parallel-slot shape the slot stays a LIVE hole (the segment mask pins the boundary; the handler's baked copy is discarded with the postponed subtree), and the baked copy materializes only where the value renders as unshielded shell material. Mechanism: the loader-body ALS scope (which already carries loaderId for guard attribution) gains handlerInvoked, set when the invoking ctx.use ran outside DSL loader scope; the shell-capture identity guard in cookie-store exempts handler-invoked loader bodies. Nothing else: no priming, no release machinery, no new request-context fields. refuseOnGuardTrip now names the actual tripping loader; the misleading bake-lane attribution is gone. Locked in as doctrine: semantic-matrix row [PPR3] (dev+prod) + docs/internal/execution-model.md; e2e pins for BOTH artifact types (shell-cache slot-use cases both modes; new cache() handler-consumed baked- copy cases both modes); design docs (ppr-shell-resume.md, incl. the masking history as scar tissue; loader-container-bake.md); skills (/rango invariant, /ppr, /parallel, /caching, /use-cache, /loader). Tests: guard exemption proven red (2 failed with the exemption disabled); full router suite 4937 passed; shell-cache e2e 22/22 both projects; semantic matrix 21 dev / 24 production; cloudflare-basic ppr-shell 19/19 both projects (confirms the slot settles and ring-3 writes serialize — no hang); typecheck 15/15; lint; skills/doc-links/docs-api guards green; gen files regenerated.
1 parent 10003ac commit 1315b06

25 files changed

Lines changed: 817 additions & 31 deletions

‎packages/rangojs-router/docs/design/loader-container-bake.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,21 @@ Implementation notes (deltas from the sketch below, all deliberate):
3232
recorded pre-wrap (the wrapper is deterministic), serialized with
3333
`serializeResult` (null-preserving), and seeded via `_shellLoaderSeed` on
3434
the HIT tail's derived context.
35+
- **Handler-side consumption follows the CONSUMPTION-LANE RULE** (issue
36+
#672 / #674, post-ship): `await ctx.use(loader)` in a HANDLER executes
37+
during capture with identity reads permitted (the shell guard exempts
38+
handler-invoked loader bodies — the cache() purity precedent), and the
39+
value bakes as a capture-time copy wherever it renders as unshielded shell
40+
material. The lane machinery in THIS doc is untouched: it applies to DSL
41+
`loader()` SEGMENTS only (renderable loading() = masked live lane; no
42+
loading() = bake lane WITH the guard active), and a registered live-lane
43+
segment's mask still keeps its boundary a live hole even when a handler
44+
also consumes the same loader. An earlier fix MASKED handler consumption
45+
instead; it hung the capture's ring-3 cacheRoute serialization on the
46+
never-settling slot component (cloudflare-basic /ppr-blog, React #418 on
47+
every HIT) and was replaced by the rule. Pinned by semantic-matrix row
48+
PPR3. See ppr-shell-resume.md ("Handler-side consumption") and
49+
docs/internal/execution-model.md ("The consumption-lane rule").
3550
- **Settled nested promises pin behind a SETTLED marker, not as raw values**
3651
(`$rangoLoaderSettled`, added post-ship). The first cut inlined a settled
3752
nested promise's value directly, so the HIT overlay handed consumers a plain

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,57 @@ Serve runs them fresh through the unchanged execution path; `resume` streams
777777
their output into the frozen shell's holes. Fetchable loaders and refresh
778778
groups are `_rsc_loader` requests and never touch the PPR serve path.
779779
780+
### Handler-side consumption: the consumption-lane rule
781+
782+
For every shared-artifact capture — `cache()`, `"use cache"`, and the PPR
783+
shell — HOW a loader is consumed decides its lane:
784+
785+
- **Server-side handler consumption** (`await ctx.use(loader)`) is the BAKED
786+
lane. During capture the loader EXECUTES, and its identity reads
787+
(`cookies()`/`headers()`) are PERMITTED: the shell guard exempts
788+
handler-invoked loader bodies (`assertNotInsideShellCapture` consults
789+
`isInsideHandlerInvokedLoaderBody()`, the `handlerInvoked` flag riding the
790+
loader-body ALS — set by `useLoader` when the invoking ctx.use ran outside
791+
the DSL loader scope, the same discriminator the deadlock guard uses). The
792+
value freezes as a capture-time copy wherever it renders as unshielded
793+
shell material — a documented footgun, identical to cache()'s existing
794+
purity allowance for handler-consumed loader values.
795+
- **Client-side consumption** (`useLoader` in a `"use client"` component) is
796+
the LIVE lane: fresh per request, per visitor.
797+
- **DSL `loader()` segments** keep their lane machinery unchanged: renderable
798+
`loading()` = live (masked at the `resolveLoaderData` funnel), otherwise
799+
bake (executes at capture WITH the identity guard active). Corollary worth
800+
stating: when a handler consumes a loader that is ALSO registered live-lane
801+
on the same subtree (the parallel-slot shape: `loader()+loading()` plus
802+
`await ctx.use(...)` in the slot handler), the segment's masked
803+
`loaderDataPromise` still pins the slot's LoaderBoundary (segment-system),
804+
so the slot stays a LIVE hole — the handler's baked copy is discarded with
805+
the postponed subtree; the executed body's only capture-time observable is
806+
its side effects.
807+
808+
Pinned by semantic-matrix row `[PPR3]`, `e2e/shell-cache.test.ts` (slot-use
809+
cases: the unshielded chip BAKES frozen across HITs and visitors; the
810+
registered live-lane slot stays a fresh hole), and the cache()-tier twin in
811+
`e2e/cache.test.ts` ("handler ctx.use value is a baked copy"). Stated once in
812+
`docs/internal/execution-model.md` ("The consumption-lane rule").
813+
814+
History (scar tissue): issue #672 was first fixed by MASKING handler
815+
consumption (priming the ctx.use memo map with never-settling promises plus a
816+
handle-store release race). That contradicted the cache() precedent and broke
817+
cache()-composed fixtures: masking cloudflare-basic's ring-1-cached /ppr-blog
818+
sidebar left its slot handler pending forever, the capture's ring-3
819+
cacheRoute write hung Flight-serializing the never-settling component, the
820+
snapshot drained empty (settleWrites timeout), and every HIT
821+
hydration-mismatched against the prelude (React #418). The rule replaced the
822+
machinery outright: handler-consumed loaders settle normally, so captures
823+
quiesce, ring-3 writes serialize, and snapshots record — no masking special
824+
cases, no release deferreds.
825+
826+
The identity footgun is the accepted trade: an identity read in a
827+
handler-consumed loader bakes the CAPTURE request's value into the shared
828+
shell. Keep identity in client-consumed loaders (live holes) when it must
829+
stay per-visitor.
830+
780831
Handles are shell material. `SsrRoot` consumes the handles generator to
781832
completion before rendering anything (`consumeAsyncGenerator` sits above every
782833
Suspense boundary), so handle data cannot be a hole. Three classes:

‎packages/rangojs-router/docs/internal/execution-model.md‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,9 @@ global middleware
115115
HTTP request (pinned by the middleware-run counter in `[PPR1]`). Within the
116116
capture, `cache()`d segments replay from the segment cache and UNCACHED
117117
segments execute their handlers fresh (the `cookies()`/`headers()` capture
118-
guard is load-bearing); loaders are masked — they are the structural holes.
118+
guard is load-bearing for handler/render code and bake-lane segment loaders;
119+
handler-INVOKED loader bodies are exempt — the consumption-lane rule below);
120+
live-lane segment loaders are masked — they are the structural holes.
119121
Holes are render-defined: `loading()` subtrees (structural), pending promises
120122
in handed-over data under the consumer's Suspense (physics), everything else
121123
is shell — including TOP-LEVEL pushed handle promises, which are awaited
@@ -125,6 +127,25 @@ global middleware
125127
HIT — runs the full chain (middleware + handlers + fresh loaders); only the
126128
shell HTML is cached, so a HIT still runs the loader holes fresh. Pinned by
127129
the `[PPR2]` semantic matrix row.
130+
- **The consumption-lane rule.** For every shared-artifact capture — `cache()`,
131+
`"use cache"`, and the PPR shell — HOW a loader is consumed decides its lane:
132+
- Server-side handler consumption (`await ctx.use(loader)`) is the BAKED
133+
lane: the loader executes during capture and identity reads
134+
(`cookies()`/`headers()`) are PERMITTED there (the shell guard exempts
135+
handler-invoked loader bodies, exactly like the cache-purity guards). The
136+
value freezes as a capture-time copy wherever it renders as unshielded
137+
shell/cache material — a documented footgun, consistent across all three
138+
artifact tiers.
139+
- Client-side consumption (`useLoader` in a `"use client"` component) is the
140+
LIVE lane: fresh per request, per visitor.
141+
- DSL `loader()` segments follow their lane machinery: renderable
142+
`loading()` = live (masked at capture — and the mask also keeps a
143+
same-loader handler consumption's subtree a live hole when it sits under
144+
that boundary), otherwise bake (executes at capture WITH the identity
145+
guard active).
146+
Pinned by the `[PPR3]` semantic matrix row and
147+
`e2e/shell-cache.test.ts` (slot-use cases); cache()-tier precedent pinned
148+
by the blog-cache suites (frozen sidebar on ring-3 hits).
128149

129150
## Handler Loading Contract
130151

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

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,43 @@ test.describe("cache-loader-behavior", () => {
346346
loadedAt: firstLoadedAt,
347347
});
348348
});
349+
350+
// Consumption-lane rule, cache() tier (docs/internal/execution-model.md;
351+
// the PPR twin is semantic matrix row PPR3): a route-level cache() scope
352+
// whose HANDLER consumes an UNCACHED loader via `await ctx.use(...)` serves
353+
// the BAKED copy on every hit — count and loadedAt frozen at the values the
354+
// cached render captured. Client-side useLoader is the live lane.
355+
test("route-level cache(): handler ctx.use value is a baked copy, frozen across hits", async ({
356+
page,
357+
}) => {
358+
using _ = expectNoPageError(page);
359+
360+
await page.goto(f.url("/cache-test/handler-consumed"));
361+
await waitForHydration(page);
362+
363+
const firstCount = await page.getByTestId("loader-count").textContent();
364+
const firstLoadedAt = await page.getByTestId("loaded-at").textContent();
365+
366+
await page.goto(f.url("/"));
367+
await waitForHydration(page);
368+
369+
await expect
370+
.poll(
371+
async () => {
372+
await page.goto(f.url("/cache-test/handler-consumed"));
373+
await waitForHydration(page);
374+
const count = await page.getByTestId("loader-count").textContent();
375+
const loadedAt = await page.getByTestId("loaded-at").textContent();
376+
return { count, loadedAt };
377+
},
378+
{
379+
timeout: 8000,
380+
message:
381+
"Expected the handler-consumed value to be served from cache",
382+
},
383+
)
384+
.toEqual({ count: firstCount, loadedAt: firstLoadedAt });
385+
});
349386
});
350387

351388
// ============================================================================
@@ -417,6 +454,41 @@ test.describe("cache-loader-behavior (production)", () => {
417454
loadedAt: firstLoadedAt,
418455
});
419456
});
457+
458+
// Consumption-lane rule, cache() tier — production counterpart of the dev
459+
// case above (docs/internal/execution-model.md; PPR twin: semantic matrix
460+
// row PPR3).
461+
test("route-level cache(): handler ctx.use value is a baked copy, frozen across hits", async ({
462+
page,
463+
}) => {
464+
using _ = expectNoPageError(page);
465+
466+
await page.goto(f.url("/cache-test/handler-consumed"));
467+
await waitForHydration(page);
468+
469+
const firstCount = await page.getByTestId("loader-count").textContent();
470+
const firstLoadedAt = await page.getByTestId("loaded-at").textContent();
471+
472+
await page.goto(f.url("/"));
473+
await waitForHydration(page);
474+
475+
await expect
476+
.poll(
477+
async () => {
478+
await page.goto(f.url("/cache-test/handler-consumed"));
479+
await waitForHydration(page);
480+
const count = await page.getByTestId("loader-count").textContent();
481+
const loadedAt = await page.getByTestId("loaded-at").textContent();
482+
return { count, loadedAt };
483+
},
484+
{
485+
timeout: 8000,
486+
message:
487+
"Expected the handler-consumed value to be served from cache",
488+
},
489+
)
490+
.toEqual({ count: firstCount, loadedAt: firstLoadedAt });
491+
});
420492
});
421493

422494
// Intentionally dev-only: these tests verify cache key differentiation

‎packages/rangojs-router/e2e/semantic-matrix.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,55 @@ const matrixRows: SemanticMatrixRow[] = [
625625
expect(body).toContain("Live price:");
626626
},
627627
},
628+
// The CONSUMPTION-LANE RULE (issue #672 / #674): server-side handler
629+
// consumption via `await ctx.use(loader)` is the BAKED lane in every shared
630+
// artifact — cache(), "use cache", and the PPR shell. During capture the
631+
// loader EXECUTES with identity reads (cookies()/headers()) permitted
632+
// (mirroring the cache() purity allowance), so the capture is never refused;
633+
// the value freezes as a capture-time copy wherever it renders as
634+
// unshielded shell material. DSL segment lanes are unchanged — a loader
635+
// ALSO registered live-lane (loader()+loading()) still masks at capture and
636+
// keeps its boundary a live hole. Client-side useLoader is the live lane.
637+
{
638+
id: "PPR3",
639+
contract:
640+
"consumption-lane rule: handler ctx.use of a cookie-reading loader executes at capture (no refusal); unshielded value bakes frozen; a registered live-lane slot stays a live hole",
641+
transport: "request",
642+
execution: "shell-capture",
643+
scope: "layout-parallel",
644+
assert: async ({ request, baseUrl }) => {
645+
const html = { headers: { Accept: "text/html" } };
646+
const url = baseUrl("/shell-cache/slot-use?probe=matrix-lane");
647+
648+
// No refusal: the route reaches HIT despite the handlers' cookies()
649+
// reads (pre-rule these tripped the identity guard -> MISS forever).
650+
await expect(async () => {
651+
const r = await request.get(url, html);
652+
expect(r.headers()["x-rango-shell"]).toBe("HIT");
653+
}).toPass({ timeout: 10000 });
654+
655+
const first = await (await request.get(url, html)).text();
656+
const prelude = first.slice(0, first.indexOf("</html>"));
657+
// BAKED: layout-handler-consumed unregistered loader (capture ran
658+
// cookie-less -> "anon") froze into the shared prelude.
659+
const chip = prelude.match(/srv-chip-(\d+)-anon/);
660+
expect(chip).not.toBeNull();
661+
// Segment lane unchanged: the same-consumption slot whose loader is
662+
// registered live-lane still postpones (fallback frozen, hole live).
663+
expect(prelude).toContain("srv badge pending...");
664+
expect(prelude).not.toMatch(/srv-badge-\d/);
665+
666+
// Frozen across HITs AND visitors — the rule's documented footgun.
667+
const second = await (
668+
await request.get(url, {
669+
headers: { ...html.headers, Cookie: "srv_visitor=user-a" },
670+
})
671+
).text();
672+
const secondPrelude = second.slice(0, second.indexOf("</html>"));
673+
expect(secondPrelude).toContain(`srv-chip-${chip![1]}-anon`);
674+
expect(secondPrelude).not.toMatch(/srv-chip-\d+-user-a/);
675+
},
676+
},
628677
];
629678

630679
function registerSemanticMatrixSuite(build: BuildAxis): void {

‎packages/rangojs-router/e2e/shell-cache.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,75 @@ function runShellCacheSpec(f: Fixture): void {
688688
const secondSeq = Number(second.html.match(/badge-(\d+)/)?.[1]);
689689
expect(secondSeq).toBeGreaterThan(firstSeq);
690690
});
691+
692+
// /shell-cache/slot-use + /shell-cache/slot-use/other: the CONSUMPTION-LANE
693+
// RULE (issue #672 / #674; semantic-matrix row "ppr-capture-handler-ctx-use").
694+
// Handlers consume cookie-reading loaders server-side via `await
695+
// ctx.use(...)`; during capture the loaders EXECUTE and the identity reads
696+
// are EXEMPT from the shell guard (mirroring cache() purity semantics) — no
697+
// refusal, both routes flip MISS->HIT. WHERE the value lands splits by what
698+
// shields it, and this test pins both halves on both routes:
699+
// - the CHIP (layout handler, UNREGISTERED loader, plain shell material):
700+
// the capture-time value — seq AND cookie identity — BAKES into the
701+
// shared prelude, identical across HITs and across visitors. The frozen
702+
// identity is the rule's documented footgun; client-side useLoader
703+
// (/shell-cache/slot-hole above) is the live lane.
704+
// - the @srvBadge SLOT (same loader also registered live-lane on the
705+
// parallel: loader()+loading()): the SEGMENT lane is unchanged by the
706+
// rule — its masked loaderData pins the slot boundary, so the slot stays
707+
// a LIVE hole: fallback frozen in the prelude, value fresh (and
708+
// visitor-correct) per serve.
709+
for (const [label, route, staticText] of [
710+
["first route", "/shell-cache/slot-use", "Srv slot home static content"],
711+
[
712+
"sibling route",
713+
"/shell-cache/slot-use/other",
714+
"Srv slot other static content",
715+
],
716+
] as const) {
717+
test(`handler ctx.use of cookie-reading loaders (${label}): HIT; unshielded value BAKED and frozen, live-lane slot stays a fresh hole`, async ({
718+
request,
719+
}) => {
720+
const url = f.url(`${route}?probe=srv-slot`);
721+
await warmToHit(request, url);
722+
723+
const { html } = await measureFirstChunk(url);
724+
const { prelude, resumed } = splitPrelude(html);
725+
726+
expect(prelude).toContain("Srv slot chrome static text");
727+
expect(prelude).toContain(staticText);
728+
729+
// BAKED half: the chip (capture ran cookie-less -> "anon") is IN the
730+
// shared prelude.
731+
const bakedChip = prelude.match(/srv-chip-(\d+)-anon/);
732+
expect(bakedChip).not.toBeNull();
733+
734+
// LIVE half: the slot's registered live-lane segment keeps the badge a
735+
// hole — fallback frozen, value only in the resumed tail.
736+
expect(prelude).toContain("srv badge pending...");
737+
expect(prelude).not.toMatch(/srv-badge-\d/);
738+
expect(resumed).toMatch(/srv-badge-\d+-anon/);
739+
740+
// Frozen across HITs AND visitors: a later HIT carrying a visitor
741+
// cookie still serves the SAME baked chip seq + identity in the
742+
// prelude — the shared-copy footgun the rule accepts and documents —
743+
// while the live badge hole resolves the REAL visitor, fresh seq.
744+
const second = await request.get(url, {
745+
headers: { ...HTML_HEADERS, Cookie: "srv_visitor=user-a" },
746+
});
747+
expect(second.status()).toBe(200);
748+
expect(second.headers()["x-rango-shell"]).toBe("HIT");
749+
const secondHtml = await second.text();
750+
const secondPrelude = splitPrelude(secondHtml).prelude;
751+
const secondChip = secondPrelude.match(/srv-chip-(\d+)-anon/);
752+
expect(secondChip).not.toBeNull();
753+
expect(secondChip![1]).toBe(bakedChip![1]);
754+
expect(secondPrelude).not.toMatch(/srv-chip-\d+-user-a/);
755+
expect(secondHtml).toMatch(/srv-badge-\d+-user-a/);
756+
const badgeSeq = (h: string) => Number(h.match(/srv-badge-(\d+)-/)?.[1]);
757+
expect(badgeSeq(secondHtml)).toBeGreaterThan(badgeSeq(html));
758+
});
759+
}
691760
}
692761

693762
test.describe("shell-cache (dev)", () => {

‎packages/rangojs-router/e2e/test-app/src/loaders.tsx‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,27 @@ export const CachedTestLoader = createLoader(async () => {
460460
};
461461
});
462462

463+
// Counter for the handler-consumed cache() route loader
464+
let handlerConsumedLoaderCount = 0;
465+
466+
/**
467+
* Consumption-lane rule, cache() tier: an UNCACHED loader consumed by a
468+
* HANDLER (`await ctx.use(...)`) inside a route-level cache() scope. The
469+
* handler-consumed value is a BAKED copy — it freezes into the cached route
470+
* segments and is served as-is on every cache hit (client-side useLoader is
471+
* the live lane). count/loadedAt advance per execution so the e2e can pin
472+
* "frozen across hits" (see e2e/cache.test.ts and the PPR twin, semantic
473+
* matrix row PPR3).
474+
*/
475+
export const HandlerConsumedTestLoader = createLoader(async () => {
476+
handlerConsumedLoaderCount++;
477+
return {
478+
count: handlerConsumedLoaderCount,
479+
message: "Handler-consumed loader data",
480+
loadedAt: new Date().toISOString(),
481+
};
482+
});
483+
463484
// Counter for intercept cache test loader
464485
let interceptCacheLoaderCount = 0;
465486

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ export const NamedRoutes = {
5656
"cacheTag.cacheTagItem": "/cache-tag-test/item/:id",
5757
"cacheTag.cacheTagRevalidate": "/cache-tag-test/revalidate/:tag",
5858
"cacheTest.cachedLoader": "/cache-test/cached-loader",
59+
"cacheTest.handlerConsumed": "/cache-test/handler-consumed",
5960
"cacheTest.interceptDetail": "/cache-test/intercept/:itemId",
6061
"cacheTest.interceptIndex": "/cache-test/intercept",
6162
"cacheTest.nonCachedLoader": "/cache-test/non-cached-loader",
@@ -330,6 +331,8 @@ export const NamedRoutes = {
330331
shellCacheNonceToken: "/shell-cache/nonce-token",
331332
shellCacheSettled: "/shell-cache/settled",
332333
shellCacheSlotHole: "/shell-cache/slot-hole",
334+
shellCacheSlotUse: "/shell-cache/slot-use",
335+
shellCacheSlotUseOther: "/shell-cache/slot-use/other",
333336
shellCacheStream: "/shell-cache/stream",
334337
shellSecure: "/shell-secure",
335338
shellSecureDsl: "/shell-secure-dsl",

0 commit comments

Comments
 (0)