Skip to content

Commit 4b907f4

Browse files
authored
fix(ppr): dev-stability — producer-B first-request-HIT race (#719) + settled-fast hidden-artifact scoping (#718) (#727)
* fix(ppr): dev shell endpoint signals boot-race NOT-READY; read-through re-polls to keep first-request HIT (#719) Root cause: the dev `/__rsc_shell` endpoint boots its capture realm lazily on the first hit — temp server (Cloudflare preset), registry import, and a Vite dependency re-optimization the first shell-capture import can trigger. All are transient. The read-through fired once and mapped any non-2xx to a hard first-request MISS, so a Prerender+ppr route's FIRST request lost the race and served axis-1 (x-rango-shell: MISS) while a later poll HIT — the build-time first-request-HIT contract held only after a warm-up. Fast machines lose the race deterministically; slow CI arrives after the boot infra settled, so it read "consistent locally, 0-flake on CI". warmToHit in the tests masked it, but the literal first-request-HIT contract was broken. Fix: the endpoint tags the transient not-ready branches with `x-rango-shell-dev: NOT-READY` (HTTP 503) — re-optimization catches, missing runners, and an empty registry. The read-through re-polls ONLY that signal, a bounded await of readiness (10s deadline, 150ms interval). Every genuine outcome — a served entry, a real negative (404: not prerenderable / capture refused), or a network fault — resolves on the first attempt, so a non-baked or already-warm route pays zero extra latency. The endpoint half lives in the Vite plugin, so `pnpm build-router` is required for dist/vite to reflect src. Closes #719. * test(ppr): scope settled-fast assertions under the settled container to skip a hidden fizz artifact (#718) The `*-settled-fast` duplicate is a benign, hidden fizz artifact, not a bug. When the nested-promise Flight payload fills the dehydrated boundary before the trailing `$RC("B:0","S:0")` completeSegment script runs — a streaming window that #706's byte-copy fragment splice widens (the baked payload now finishes well ahead of the resume) — React client-renders the boundary in place and `$RC` leaves fizz's hidden segment container (`<div hidden id="S:0">`) orphaned as a direct child of `<body>`. It carries the `hidden` attribute: invisible, zero layout, out of the a11y tree — but it holds a second `-settled-fast` node, so a bare testid locator strict-mode-collides with it. Fix: scope the `-label` / `-fast` assertions under the visible settled container (`data-testid="shell-settled"` / `ppr-settled`) so the strict-mode locator selects only the in-place copy; the orphan lives outside it. Confirmed once-on-wire; reproduced 6/6 by widening the $RC delay, 1/1 after the scope fix. Closes #718. * fix(ppr): narrow dev readiness NOT-READY to reoptimization only — terminal temp-server/registry failures fail fast, not 10s-retry; + cold/injection dev coverage. Addresses review P2/P3 on #719.
1 parent 7f42803 commit 4b907f4

7 files changed

Lines changed: 410 additions & 35 deletions

File tree

‎packages/rangojs-router/e2e/prerender-ppr.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,3 +226,61 @@ test.describe("prerender-ppr (production)", () => {
226226
});
227227
runPrerenderPprSpec(f);
228228
});
229+
230+
// ---------------------------------------------------------------------
231+
// Dev boot-race readiness (#719 P2/P3). These exercise the dev /__rsc_shell
232+
// endpoint + client re-poll DIRECTLY, on their OWN isolated servers with no
233+
// warm-up slug (the warmToHit beforeAll above masks the boot window). There is
234+
// NO production sibling: production serves the first-request HIT from a build
235+
// manifest with no /__rsc_shell endpoint, no temp server, and no re-poll loop —
236+
// covered by the (production) describe above. A dev-only mechanism has no
237+
// production counterpart to add (hard-rule dev+prod pairing, N/A justified).
238+
// ---------------------------------------------------------------------
239+
240+
test.describe("prerender-ppr dev readiness: injected boot-race (#719)", () => {
241+
// Deterministic regression guard: RANGO_E2E_INJECT_SHELL_NOTREADY makes the
242+
// endpoint emit ONE reopt-class NOT-READY per pathname through the REAL
243+
// classifier before serving, so the read-through's re-poll runs end-to-end
244+
// (a natural cold race settles too fast on quick machines to guard this). The
245+
// FIRST request to a virgin slug must still recover to x-rango-shell: HIT.
246+
const f = useFixture({
247+
root: "./e2e/test-app",
248+
mode: "dev",
249+
isolatedServer: true,
250+
cliOptions: { env: { RANGO_E2E_INJECT_SHELL_NOTREADY: "1" } },
251+
});
252+
253+
test("injected reopt NOT-READY: the FIRST request re-polls to HIT", async ({
254+
request,
255+
}) => {
256+
const res = await request.get(f.url("/pp/alpha"), {
257+
headers: HTML_HEADERS,
258+
});
259+
expect(res.status()).toBe(200);
260+
expect(res.headers()["x-rango-shell"]).toBe("HIT");
261+
});
262+
});
263+
264+
test.describe("prerender-ppr dev readiness: cold first request (#719)", () => {
265+
// Natural cold path (weak guard per #719: a fast machine can settle before the
266+
// first servable request). A virgin Prerender+ppr URL as the literal FIRST
267+
// request on a fresh server — HIT on request one, or a MISS that heals to HIT
268+
// inside the readiness window. Proves the endpoint -> capture -> client path
269+
// works cold end-to-end.
270+
const f = useFixture({
271+
root: "./e2e/test-app",
272+
mode: "dev",
273+
isolatedServer: true,
274+
});
275+
276+
test("cold virgin route: first request HITs (or heals within the readiness window)", async ({
277+
request,
278+
}) => {
279+
const url = f.url("/pp/beta");
280+
const res = await request.get(url, { headers: HTML_HEADERS });
281+
expect(res.status()).toBe(200);
282+
if (res.headers()["x-rango-shell"] !== "HIT") {
283+
await warmToHit(request, url);
284+
}
285+
});
286+
});

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -681,10 +681,22 @@ function runShellCacheSpec(f: Fixture): void {
681681
using __ = guardHydrationErrors(page);
682682
await page.goto(url);
683683
await waitForHydration(page);
684-
await expect(testId(page, "shell-settled-label")).toHaveText(
684+
// Scope to the ShellSettledValue container (data-testid="shell-settled").
685+
// When the nested promise's Flight payload lands client-side before fizz's
686+
// `$RC("B:0","S:0")` completeSegment script executes (a streaming race the
687+
// #706 fragment splice widens — the baked payload is now a byte copy that
688+
// finishes well ahead of the resume), React client-renders the dehydrated
689+
// boundary in place and leaves fizz's HIDDEN segment container
690+
// (`<div hidden id="S:0">`, a direct child of <body>) orphaned in the DOM.
691+
// That orphan carries the `hidden` attribute — invisible, zero layout, out
692+
// of the a11y tree — but it holds a second `shell-settled-fast` node, so a
693+
// bare testid locator strict-mode-collides with it. The container scope
694+
// keeps only the visible in-place copy (the orphan lives outside it).
695+
const settled = testId(page, "shell-settled");
696+
await expect(settled.getByTestId("shell-settled-label")).toHaveText(
685697
/Settled outer \d+/,
686698
);
687-
await expect(testId(page, "shell-settled-fast")).toHaveText(
699+
await expect(settled.getByTestId("shell-settled-fast")).toHaveText(
688700
/Settled fast \d+/,
689701
);
690702
});

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export function ShellSettledValue({
1919
}) {
2020
const { data } = useLoader(loader);
2121
return (
22-
<div>
22+
<div data-testid="shell-settled">
2323
<span data-testid="shell-settled-label">{data.label}</span>{" "}
2424
<Suspense
2525
fallback={

‎packages/rangojs-router/src/rsc/__tests__/shell-build-manifest.test.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,5 +220,92 @@ describe("lookupBuildShell (build-shell read-through gates)", () => {
220220
}),
221221
).toBeNull();
222222
});
223+
224+
// Boot-race readiness (issue #719): a Prerender+ppr route's FIRST request
225+
// can beat the endpoint standing up its capture realm (temp server /
226+
// registry import / Vite dep re-optimization). The endpoint marks those
227+
// TRANSIENT states 503 + x-rango-shell-dev: NOT-READY; the read-through
228+
// must re-poll ONLY that signal so the first request still HITs, rather
229+
// than mapping the boot window to a hard MISS that heals on a later poll.
230+
it("re-polls a NOT-READY boot-race signal, then serves once ready (first-request HIT holds)", async () => {
231+
const fetchMock = vi
232+
.fn()
233+
.mockResolvedValueOnce(
234+
new Response("booting", {
235+
status: 503,
236+
headers: { "x-rango-shell-dev": "NOT-READY" },
237+
}),
238+
)
239+
.mockResolvedValueOnce(
240+
new Response(JSON.stringify(DEV_RECORD), { status: 200 }),
241+
);
242+
vi.stubGlobal("fetch", fetchMock);
243+
const p = lookupBuildShell(url("/pp/a"), BUILD_VERSION, store, {
244+
isPrerenderRoute: true,
245+
routeName: "pp",
246+
ttl: 300,
247+
});
248+
// Fire the ~150ms readiness re-poll delay (fake timers).
249+
await vi.advanceTimersByTimeAsync(200);
250+
const hit = await p;
251+
expect(hit).not.toBeNull();
252+
expect(fetchMock).toHaveBeenCalledTimes(2);
253+
});
254+
255+
it("does NOT re-poll a genuine 404 negative (a non-baked route never stalls the foreground)", async () => {
256+
const fetchMock = vi.fn(
257+
async () => new Response("nope", { status: 404 }),
258+
);
259+
vi.stubGlobal("fetch", fetchMock);
260+
expect(
261+
await lookupBuildShell(url("/pp/a"), BUILD_VERSION, store, {
262+
isPrerenderRoute: true,
263+
routeName: "pp",
264+
ttl: 300,
265+
}),
266+
).toBeNull();
267+
expect(fetchMock).toHaveBeenCalledTimes(1);
268+
});
269+
270+
// Issue #719 P2: only 503 + NOT-READY (a transient re-optimization) is
271+
// re-pollable. A terminal boot failure — a broken temp server or a faulted
272+
// registry import — fails fast with a PLAIN 503 (no NOT-READY header). The
273+
// read-through must MISS on the first attempt, never re-poll a permanently
274+
// broken realm for the full 10s readiness deadline.
275+
it("does NOT re-poll a plain 503 without the NOT-READY header (terminal boot failure MISSes fast)", async () => {
276+
const fetchMock = vi.fn(
277+
async () =>
278+
new Response("Shell capture runners not available", { status: 503 }),
279+
);
280+
vi.stubGlobal("fetch", fetchMock);
281+
expect(
282+
await lookupBuildShell(url("/pp/a"), BUILD_VERSION, store, {
283+
isPrerenderRoute: true,
284+
routeName: "pp",
285+
ttl: 300,
286+
}),
287+
).toBeNull();
288+
expect(fetchMock).toHaveBeenCalledTimes(1);
289+
});
290+
291+
it("concedes a MISS when NOT-READY never clears (readiness wait is bounded)", async () => {
292+
const fetchMock = vi.fn(
293+
async () =>
294+
new Response("booting", {
295+
status: 503,
296+
headers: { "x-rango-shell-dev": "NOT-READY" },
297+
}),
298+
);
299+
vi.stubGlobal("fetch", fetchMock);
300+
const p = lookupBuildShell(url("/pp/a"), BUILD_VERSION, store, {
301+
isPrerenderRoute: true,
302+
routeName: "pp",
303+
ttl: 300,
304+
});
305+
// Advance past the readiness deadline: the bounded loop must exit, not spin.
306+
await vi.advanceTimersByTimeAsync(11_000);
307+
expect(await p).toBeNull();
308+
expect(fetchMock.mock.calls.length).toBeGreaterThan(1);
309+
});
223310
});
224311
});

‎packages/rangojs-router/src/rsc/shell-build-manifest.ts‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,32 @@ export interface DevShellLookup {
146146
/** Retry delay (~400ms) plus quiesce/fizz/store headroom past the budgets. */
147147
const DEV_SHELL_RETRY_MARGIN_MS = 5_000;
148148

149+
/**
150+
* Dev boot-race readiness (issue #719). The `/__rsc_shell` endpoint stands up
151+
* the capture realm lazily on its first hit — the temp server (Cloudflare
152+
* preset), the registry import, and, on either preset, a Vite dependency
153+
* re-optimization that the first import of the shell-capture graph can trigger.
154+
* All three are TRANSIENT: retrying the same request seconds later succeeds.
155+
*
156+
* Before this, the read-through fired ONCE and mapped any non-2xx to a hard
157+
* MISS, so a Prerender+ppr route's FIRST request lost the race and served
158+
* axis-1 (x-rango-shell: MISS) while a later poll HIT — the build-time
159+
* first-request-HIT contract held only after a warm-up. A fast machine loses
160+
* the race deterministically (the document request beats the boot infra);
161+
* slow CI arrives after it settled, hence "0-flake on CI".
162+
*
163+
* Fix: the endpoint tags the transient not-ready branches with
164+
* `x-rango-shell-dev: NOT-READY` (HTTP 503), and the read-through re-polls
165+
* ONLY that signal — a bounded await of readiness, not a blind retry. A
166+
* genuine negative (route not prerenderable, capture refused: 404) stays an
167+
* immediate MISS, so a non-baked route never stalls the foreground. The window
168+
* is capped by DEV_SHELL_READINESS_DEADLINE_MS; the boot infra normally
169+
* settles well inside the first poll.
170+
*/
171+
const DEV_SHELL_NOT_READY = "NOT-READY";
172+
const DEV_SHELL_READINESS_DEADLINE_MS = 10_000;
173+
const DEV_SHELL_READINESS_POLL_MS = 150;
174+
149175
/**
150176
* Timed out like the dev prerender store fetch (see #697): inside a workerd
151177
* waitUntil an unsettled fetch pends forever instead of rejecting; on timeout
@@ -192,14 +218,30 @@ async function fetchDevShellEntry(
192218
if (dev.captureTimeout !== undefined) {
193219
params.set("captureTimeout", String(dev.captureTimeout));
194220
}
195-
try {
196-
const res = await fetch(`${devUrl}/__rsc_shell?${params}`, {
197-
signal: AbortSignal.timeout(devShellFetchTimeoutMs(dev.captureTimeout)),
198-
});
199-
if (!res.ok) return undefined;
200-
return (await res.json()) as BuildShellEntry;
201-
} catch {
202-
return undefined;
221+
const shellUrl = `${devUrl}/__rsc_shell?${params}`;
222+
// Await the endpoint's boot readiness (issue #719): re-poll ONLY the
223+
// NOT-READY signal, capped by DEV_SHELL_READINESS_DEADLINE_MS. Every other
224+
// outcome — a served entry, a genuine negative (404), or a network fault —
225+
// resolves on the first attempt, so a non-baked route never stalls here.
226+
const readinessDeadline = Date.now() + DEV_SHELL_READINESS_DEADLINE_MS;
227+
for (;;) {
228+
try {
229+
const res = await fetch(shellUrl, {
230+
signal: AbortSignal.timeout(devShellFetchTimeoutMs(dev.captureTimeout)),
231+
});
232+
if (
233+
res.status === 503 &&
234+
res.headers.get("x-rango-shell-dev") === DEV_SHELL_NOT_READY &&
235+
Date.now() < readinessDeadline
236+
) {
237+
await new Promise((r) => setTimeout(r, DEV_SHELL_READINESS_POLL_MS));
238+
continue;
239+
}
240+
if (!res.ok) return undefined;
241+
return (await res.json()) as BuildShellEntry;
242+
} catch {
243+
return undefined;
244+
}
203245
}
204246
}
205247

0 commit comments

Comments
 (0)