Skip to content

Commit a9551a2

Browse files
committed
fix(ppr): mask live-lane loaders for handler-side ctx.use during shell capture (#672)
The live-lane mask existed only in the segment funnel: resolveLoaderData returned a masked promise for the SEGMENT but never primed the per-request loaderPromises map that handler-side ctx.use consults, so a slot handler awaiting ctx.use(SlotLoader) executed the loader body inline during capture. A cookies()-reading loader then tripped the identity guard and the capture was refused forever (x-rango-shell: MISS permanently). Contrary to the issue's framing, this affected EVERY route, not just non-index ones — the reported working "/" was a stale-shell artifact; reproduced at full router.match fidelity on both routes. Fix, two halves: - primeShellCaptureLoaderMasks (loader-mask.ts), called from createMatchContextForFull when capture is active: walks entries incl. parallel slots and orphan layouts, collects exclusively-live-lane loader ids (dual-lane ids keep the per-entry funnel), and primes loaderPromises with masked promises so any ctx.use hands out the mask. - Settled release: a masked handler never settles, which would hang handleStore.settled (quiesce + handles row) into a maxWaitMs stall and no-shell. ctx.use fires a per-segment release deferred at masked hand-out; trackHandler (capture only) tracks Promise.race([handler, release]) while returning the original promise so the boundary still postpones. Also: refuseOnGuardTrip no longer hardcodes the "bake-lane loader" attribution — the guard records the tripping loader id (loader-body ALS now carries loaderId) and the warning names the real origin; warnNullCaptureOnce gains the awaited-masked-loader cause. Tests: new shell-capture-live-lane-ctx-use.test.ts (full createRouter→match capture; red pre-fix on BOTH routes — loader body executed, guard tripped), e2e slot-ctx.use fixture with two ppr routes in shell-cache.test.ts (red pre-fix in dev, green post-fix; runs in dev + production describes). Full router suite 4937 passed; e2e shell-cache 22/22 in both projects; consumer dogfood suites green; gen files regenerated. Design docs updated (ppr-shell-resume.md prime+release section, loader-container-bake.md note).
1 parent 10003ac commit a9551a2

16 files changed

Lines changed: 773 additions & 22 deletions

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,26 @@ 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 of the LIVE lane is masked by up-front priming**
36+
(issue #672, post-ship): the funnel mask alone never reached the ctx.use
37+
memo map, so `await ctx.use(SlotLoader)` in a slot handler executed the
38+
live-lane loader during capture (identity-guard refusal, eternal MISS — and
39+
slot handlers run BEFORE their entry's resolveLoaders, so funnel-time
40+
registration could not fix it). `primeShellCaptureLoaderMasks`
41+
(loader-mask.ts) pre-registers masked promises for exclusively-live-lane ids
42+
at match-context creation, and capture-time `trackHandler` (router.ts) races
43+
the consuming handler against a per-segment release so `handleStore.settled`
44+
cannot hang on the never-settling hole. NOT primed: dual-lane ids (same
45+
loader registered live AND bake — the bake execution path flows through
46+
ctx.use too) and loaders with their OWN cache() config. Loader-level
47+
cache() declares the value shared, so masking buys no identity safety — and
48+
it broke live (cloudflare-basic /ppr-blog): the masked cached sidebar
49+
loader's pending slot handler hung the capture's ring-3 cacheRoute
50+
serialization, the snapshot drained empty, and HITs hydration-mismatched
51+
(React #418). The capture-time cacheRoute also SKIPS writing a segment set
52+
containing a masked-consuming handler (cache-scope.ts,
53+
`_shellCaptureMaskedHandlerSegments`) rather than hanging. See
54+
ppr-shell-resume.md ("Handler-side consumption").
3555
- **Settled nested promises pin behind a SETTLED marker, not as raw values**
3656
(`$rangoLoaderSettled`, added post-ship). The first cut inlined a settled
3757
nested promise's value directly, so the HIT overlay handed consumers a plain

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

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,64 @@ 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 mask is primed up front (scar tissue)
781+
782+
The mask has TWO consumption funnels and only one of them flows through the
783+
segment system. The funnel-level mask (`resolveLoaderData` returning a
784+
never-resolving promise) never registered anything in the per-match
785+
`loaderPromises` memo map, so a HANDLER doing `await ctx.use(SlotLoader)` — the
786+
/parallel skill's "Composable Slots" shape — missed the memo and EXECUTED the
787+
live-lane loader body during capture. A cookie-reading slot loader then
788+
tripped the identity guard and the capture refused forever (issue #672). Note
789+
the ordering trap that rules out fixing it at the funnel: `resolveParallelEntry`
790+
runs slot handlers BEFORE the parallel entry's own `resolveLoaders`, so a mask
791+
registered at funnel time still loses the race for slots.
792+
793+
Two mechanisms close it, both capture-only:
794+
795+
1. **Prime**: `primeShellCaptureLoaderMasks` (`loader-mask.ts`, called from
796+
`createMatchContextForFull` right after `setupLoaderAccess`) walks the
797+
matched chain — entries, parallel slot entries, orphan layouts — and
798+
pre-registers a masked promise in `loaderPromises` for every EXCLUSIVELY
799+
live-lane loader id, before anything resolves. NOT primed: a loader id
800+
with a bake-lane registration anywhere (its execution also flows through
801+
ctx.use and a primed mask would swallow the container that must bake), and
802+
any loader carrying its OWN cache() config. Loader-level cache() declares
803+
the value SHARED (cache-keyed, served to every visitor), so masking it buys
804+
no identity safety — and it broke parity live: on cloudflare-basic's
805+
/ppr-blog the masked ring-1-cached sidebar loader left its
806+
ctx.use-consuming slot handler pending forever, the capture's ring-3
807+
cacheRoute write hung Flight-serializing that never-settling component,
808+
the snapshot drained EMPTY (settleWrites timeout), and every HIT hydrated
809+
against a different ring-3 generation than the prelude baked (React #418).
810+
2. **Release**: a handler that consumed a masked loader can never settle — it
811+
IS the postponed hole — but `handleStore.settled` gates both the capture's
812+
quiesce and the payload's handles row, so an unreleased tracked promise
813+
would stall the capture to `maxWaitMs` and end in a trivial-prelude
814+
no-shell. During capture `trackHandler` (router.ts) tracks
815+
`Promise.race([handlerPromise, releaseFor(segmentId)])` instead;
816+
`setupLoaderAccess`'s ctx.use fires the release the moment it hands out a
817+
primed masked promise. Signal and arm compose in either order (a handler
818+
may consume the loader only after an earlier real await). The RETURNED
819+
component promise stays the original, so the slot still suspends and
820+
postpones at its `loading()` boundary.
821+
822+
Residuals:
823+
824+
- A handler on an entry WITHOUT renderable `loading()` that awaits a masked
825+
live-lane loader is AWAITED by segment resolution (not streamed), so the
826+
capture's match pins until `maxWaitMs` and degrades to no-shell + backoff —
827+
the same boundary-less-hole class as ever; `warnNullCaptureOnce` names it.
828+
- A cache() ROUTE whose segments include a masked-consuming handler: the
829+
capture's ring-3 cacheRoute write SKIPS (`cache-scope.ts` consults
830+
`_shellCaptureMaskedHandlerSegments`) instead of hanging on the
831+
never-settling component — a partial ring-3 entry would also misrender for
832+
later axis-1 consumers. With no capture-time write there is no snapshot pin
833+
for that route's ring-3 segment, so a HIT can drift against the prelude
834+
(the pre-snapshot degradation, bounded by the drift doctrine). Narrow by
835+
construction: only UNCACHED live-lane loaders consumed in handlers under a
836+
cache() route reach this.
837+
780838
Handles are shell material. `SsrRoot` consumes the handles generator to
781839
completion before rendering anything (`consumeAsyncGenerator` sits above every
782840
Suspense boundary), so handle data cannot be a hole. Three classes:

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,53 @@ 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 (issue #672): the slot
693+
// HANDLER consumes its live-lane loader server-side via `await ctx.use(...)`,
694+
// and the loader reads cookies(). The mask is registration-level, so the
695+
// handler's await must receive the masked promise on EVERY sibling route
696+
// under the layout: both routes flip to HIT, the slot fallback freezes in the
697+
// prelude, and the per-request cookie identity resumes fresh per request.
698+
// Regression: the mask lived only in the segment funnel, the handler-side
699+
// ctx.use executed the loader at capture, cookies() tripped the identity
700+
// guard, and every route under the layout stuck on MISS forever.
701+
for (const [label, route, staticText] of [
702+
["first route", "/shell-cache/slot-use", "Srv slot home static content"],
703+
[
704+
"sibling route",
705+
"/shell-cache/slot-use/other",
706+
"Srv slot other static content",
707+
],
708+
] as const) {
709+
test(`slot handler ctx.use of a cookie-reading live-lane loader (${label}): HIT, fallback frozen, identity fresh per request`, async ({
710+
request,
711+
}) => {
712+
const url = f.url(`${route}?probe=srv-slot`);
713+
await warmToHit(request, url);
714+
715+
const { html } = await measureFirstChunk(url);
716+
const { prelude, resumed } = splitPrelude(html);
717+
718+
expect(prelude).toContain("Srv slot chrome static text");
719+
expect(prelude).toContain(staticText);
720+
expect(prelude).toContain("srv badge pending...");
721+
// The masked loader's value must never bake into the shared prelude.
722+
expect(prelude).not.toMatch(/srv-badge-\d/);
723+
expect(resumed).toMatch(/srv-badge-\d+-anon/);
724+
725+
// The hole is genuinely per-request: a second HIT re-runs the loader
726+
// (seq advances) and resolves the VISITOR's cookie identity.
727+
const second = await request.get(url, {
728+
headers: { ...HTML_HEADERS, Cookie: "srv_visitor=user-a" },
729+
});
730+
expect(second.status()).toBe(200);
731+
expect(second.headers()["x-rango-shell"]).toBe("HIT");
732+
const secondHtml = await second.text();
733+
expect(secondHtml).toMatch(/srv-badge-\d+-user-a/);
734+
const seqOf = (h: string) => Number(h.match(/srv-badge-(\d+)-/)?.[1]);
735+
expect(seqOf(secondHtml)).toBeGreaterThan(seqOf(html));
736+
});
737+
}
691738
}
692739

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

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,8 @@ export const NamedRoutes = {
330330
shellCacheNonceToken: "/shell-cache/nonce-token",
331331
shellCacheSettled: "/shell-cache/settled",
332332
shellCacheSlotHole: "/shell-cache/slot-hole",
333+
shellCacheSlotUse: "/shell-cache/slot-use",
334+
shellCacheSlotUseOther: "/shell-cache/slot-use/other",
333335
shellCacheStream: "/shell-cache/stream",
334336
shellSecure: "/shell-secure",
335337
shellSecureDsl: "/shell-secure-dsl",

‎packages/rangojs-router/e2e/test-app/src/urls/shell-cache.defs.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,3 +200,22 @@ export const ShellIdentityLoader = createLoader(async (): Promise<string> => {
200200
const { cookies } = await import("@rangojs/router");
201201
return cookies().get("session")?.value ?? "anon-visitor";
202202
});
203+
204+
// Issue #672 fixture: a live-lane slot loader consumed SERVER-SIDE via
205+
// `await ctx.use(...)` in the slot HANDLER (the /parallel skill's "Composable
206+
// Slots" shape) — not handed to a client component like ShellBadgeLoader. It
207+
// reads cookies(), the exact identity read the live lane exists for: an
208+
// unmasked capture-time execution trips the identity guard and refuses the
209+
// capture forever. seq advances per execution to prove the hole stays fresh
210+
// per request across shell HITs. ~150ms delay mirrors ShellBadgeLoader.
211+
const SHELL_SRV_BADGE_DELAY_MS = 150;
212+
213+
let shellSrvBadgeSeq = 0;
214+
215+
export const ShellSrvBadgeLoader = createLoader(async (): Promise<string> => {
216+
const { cookies } = await import("@rangojs/router");
217+
const visitor = cookies().get("srv_visitor")?.value ?? "anon";
218+
await new Promise((resolve) => setTimeout(resolve, SHELL_SRV_BADGE_DELAY_MS));
219+
shellSrvBadgeSeq += 1;
220+
return `srv-badge-${shellSrvBadgeSeq}-${visitor}`;
221+
});

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
ShellStreamLoader,
77
ShellChromeLoader,
88
ShellBadgeLoader,
9+
ShellSrvBadgeLoader,
910
ShellIdentityLoader,
1011
ShellSettledLoader,
1112
ShellHandles,
@@ -190,6 +191,40 @@ function ShellSlotHomePage() {
190191
return <p data-testid="shell-slot-home">Slot home static content</p>;
191192
}
192193

194+
// Issue #672: the same slot-owned live lane as ShellSlotChromeLayout, but the
195+
// slot HANDLER consumes the loader SERVER-SIDE via `await ctx.use(...)` (the
196+
// /parallel skill's "Composable Slots" shape) instead of handing it to a
197+
// client component. The mask is registration-level: the handler's await must
198+
// receive the masked promise on EVERY sibling route under the layout, the
199+
// slot postpones at its loading(), and the cookies() read inside the loader
200+
// never runs at capture. Before the fix the handler-side ctx.use funnel
201+
// missed the mask, the loader executed, the identity guard tripped, and every
202+
// route under this layout stuck on x-rango-shell: MISS forever.
203+
function ShellSrvSlotLayout() {
204+
return (
205+
<main data-testid="shell-srv-slot-page">
206+
<p data-testid="shell-srv-slot-chrome">Srv slot chrome static text</p>
207+
<ParallelOutlet name="@srvBadge" />
208+
<Outlet />
209+
</main>
210+
);
211+
}
212+
213+
async function ShellSrvBadgeSlot(ctx: HandlerContext) {
214+
const value = await ctx.use(ShellSrvBadgeLoader);
215+
return <span data-testid="shell-srv-badge">{value}</span>;
216+
}
217+
218+
function ShellSrvSlotHomePage() {
219+
return <p data-testid="shell-srv-slot-home">Srv slot home static content</p>;
220+
}
221+
222+
function ShellSrvSlotOtherPage() {
223+
return (
224+
<p data-testid="shell-srv-slot-other">Srv slot other static content</p>
225+
);
226+
}
227+
193228
function ShellBareHomePage() {
194229
return <p data-testid="shell-bare-home">Bare home static content</p>;
195230
}
@@ -353,5 +388,31 @@ export const shellCachePatterns = urls(
353388
ppr: true,
354389
}),
355390
]),
391+
// Server-side slot consumption (issue #672): see ShellSrvSlotLayout above.
392+
// TWO sibling ppr routes under ONE slot-owning layout pin that the mask
393+
// does not depend on which route is captured.
394+
layout(ShellSrvSlotLayout, () => [
395+
parallel({
396+
"@srvBadge": {
397+
handler: ShellSrvBadgeSlot,
398+
use: () => [
399+
loader(ShellSrvBadgeLoader),
400+
loading(
401+
<span data-testid="shell-srv-badge-fallback">
402+
srv badge pending...
403+
</span>,
404+
),
405+
],
406+
},
407+
}),
408+
path("/shell-cache/slot-use", ShellSrvSlotHomePage, {
409+
name: "shellCacheSlotUse",
410+
ppr: true,
411+
}),
412+
path("/shell-cache/slot-use/other", ShellSrvSlotOtherPage, {
413+
name: "shellCacheSlotUseOther",
414+
ppr: true,
415+
}),
416+
]),
356417
],
357418
);

‎packages/rangojs-router/src/cache/cache-scope.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,28 @@ export class CacheScope {
410410
const nonLoaderSegments = segments.filter((s) => s.type !== "loader");
411411
if (nonLoaderSegments.length === 0) return;
412412

413+
// PPR shell capture: a segment whose handler received a MASKED live-lane
414+
// loader promise (loader-mask.ts) carries a never-settling component.
415+
// Flight-serializing it below would hang this write forever — emptying the
416+
// capture snapshot (settleWrites timeout in captureAndStoreShell) and
417+
// poisoning later attempts' write barriers with a forever-pending task.
418+
// Skip the whole write: a ring-3 entry with a hole-slot would also
419+
// misrender for later axis-1 consumers. Residual: with no capture-time
420+
// write there is no snapshot pin for this route's ring-3 segment, so a HIT
421+
// can drift against the prelude (the pre-snapshot degradation, bounded by
422+
// the drift doctrine) — but only for the cache()-route + masked-slot
423+
// combination, which the primer already narrows to UNCACHED live-lane
424+
// loaders consumed in handlers.
425+
if (requestCtx._shellCaptureRun) {
426+
const releases = requestCtx._shellCaptureHandlerReleases;
427+
if (
428+
releases &&
429+
nonLoaderSegments.some((s) => releases.get(s.id)?.fired)
430+
) {
431+
return;
432+
}
433+
}
434+
413435
const ttl = this.ttl;
414436
const swr = this.swr;
415437

‎packages/rangojs-router/src/router.ts‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,10 @@ import {
6060
setupLoaderAccessSilent,
6161
wrapLoaderWithErrorHandling,
6262
} from "./router/loader-resolution.js";
63+
import {
64+
isShellCaptureActive,
65+
armShellCaptureHandlerRelease,
66+
} from "./router/segment-resolution/loader-mask.js";
6367
import { loadManifest } from "./router/manifest.js";
6468
import { createMetricsStore } from "./router/metrics.js";
6569
import {
@@ -438,11 +442,6 @@ export function createRouter<TEnv = any>(
438442
const findNearestNotFoundBoundary = (entry: EntryData | null) =>
439443
findNotFoundBoundary(entry, defaultNotFoundBoundary);
440444

441-
// Helper to get handleStore from request context
442-
const getHandleStore = (): HandleStore | undefined => {
443-
return _getRequestContext()?._handleStore;
444-
};
445-
446445
// Track a pending handler promise (non-blocking).
447446
// Attaches a side-effect .catch() to report streaming handler errors to onError
448447
// without altering the rejection chain (React's streaming error boundary still handles it).
@@ -453,13 +452,40 @@ export function createRouter<TEnv = any>(
453452
segmentType?: string;
454453
},
455454
): Promise<T> => {
456-
const store = getHandleStore();
457-
const tracked = store ? store.track(promise) : promise;
455+
// One ALS read serves both the store lookup and the capture branch.
456+
const trackReqCtx = _getRequestContext();
457+
const store = trackReqCtx?._handleStore;
458+
let tracked = promise;
459+
if (store) {
460+
// PPR shell capture: a streamed handler that consumes a masked
461+
// live-lane loader via ctx.use never settles (it IS the postponed
462+
// hole), and an unreleased tracked promise would hang
463+
// handleStore.settled — which gates the capture's quiesce and the
464+
// handles row (maxWaitMs stall, trivial prelude, no-shell). Track a
465+
// race against the segment's release deferred instead; setupLoaderAccess
466+
// fires the release at masked hand-out time, in either order relative
467+
// to this call. The RETURNED component promise stays the original so
468+
// the boundary still suspends/postpones on it.
469+
if (
470+
trackReqCtx &&
471+
errorContext?.segmentId &&
472+
isShellCaptureActive(trackReqCtx)
473+
) {
474+
store.track(
475+
Promise.race([
476+
promise,
477+
armShellCaptureHandlerRelease(trackReqCtx, errorContext.segmentId),
478+
]),
479+
);
480+
} else {
481+
tracked = store.track(promise);
482+
}
483+
}
458484

459485
// Report streaming handler errors to onError as a side-effect.
460486
// The rejection still propagates to the RSC stream for client error boundaries.
461487
// Captures request context eagerly (closure) so the catch handler has full context.
462-
const reqCtx = _getRequestContext();
488+
const reqCtx = trackReqCtx;
463489
if (reqCtx && onError) {
464490
tracked.catch((error) => {
465491
callOnError(error, "handler", {

0 commit comments

Comments
 (0)