@rangojs/router 0.0.0-experimental.140 → 0.0.0-experimental.141

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,19 @@
1
1
  /**
2
2
  * PPR shell capture orchestration (Axis 2, see docs/design/ppr-shell-resume.md).
3
3
  *
4
- * Capture does NOT flow through the HTTP middleware pipeline. The shell-cache
5
- * middleware sets a `_shellCapture` DESCRIPTOR before its single foreground
6
- * next(); the render layer (rsc-rendering.ts) reads it after building the served
7
- * response and calls scheduleShellCapture. The capture then runs as a background
8
- * task that re-derives the shell via `ctx.router.match()` under its OWN derived
9
- * request context — fresh handle store, `_shellCaptureRun: true` so loaders mask
10
- * (loader-mask.ts) and every loader-consuming subtree postpones. It drives the
11
- * static prerender to a quiescent shell, aborts to freeze the prelude + postponed
12
- * state, and stores the pair via putShell. Because it uses match() rather than a
13
- * second next(), the middleware chain (auth, logging, the single-use next() latch)
14
- * never re-runs — and the capture inherits the foreground's post-middleware
15
- * context state (variables, cache store) it delegates to.
4
+ * Capture does NOT flow through the HTTP middleware pipeline. The integrated PPR
5
+ * serve path (rsc-rendering.ts + shell-serve.ts) builds a ShellCaptureDescriptor
6
+ * from the route's `ppr` path option after the served response is built and calls
7
+ * scheduleShellCapture. The capture then runs as a background task that re-derives
8
+ * the page via `ctx.router.match()` under its OWN derived request context — fresh
9
+ * handle store, `_shellCaptureRun: true` so loaders mask (loader-mask.ts) and every
10
+ * loading() subtree postpones. The render is MIXED-CHAIN: cache()'d segments replay
11
+ * from ring 3, uncached segments execute their handlers fresh. It drives the static
12
+ * prerender to a quiescent shell, aborts to freeze the prelude + postponed state,
13
+ * and stores the pair via putShell. Because it uses match() rather than the HTTP
14
+ * pipeline, the middleware chain (auth, logging) never re-runs — it already ran for
15
+ * the triggering request, and the derived context inherits its post-middleware
16
+ * state (variables, cache store). Guarding is serve-time.
16
17
  */
17
18
 
18
19
  import React from "react";
@@ -23,13 +24,23 @@ import { observePhase, PHASES } from "../router/instrument.js";
23
24
  import {
24
25
  runWithRequestContext,
25
26
  setRequestContextParams,
27
+ UNTRACKED_BACKGROUND_TASK,
26
28
  type RequestContext,
27
29
  } from "../server/request-context.js";
28
30
  import { createHandleStore, type HandleStore } from "../server/handle-store.js";
29
- import type { ShellCacheEntry } from "../cache/types.js";
31
+ import type {
32
+ ShellCacheEntry,
33
+ SegmentCacheStore,
34
+ ShellSnapshotRecord,
35
+ } from "../cache/types.js";
36
+ import {
37
+ RecordingShellStore,
38
+ getRecordingStore,
39
+ } from "../cache/shell-snapshot.js";
30
40
  import type { HandlerContext } from "./handler-context.js";
31
41
  import type { RscPayload, SSRModule } from "./types.js";
32
42
  import { buildFullPayload } from "./full-payload.js";
43
+ import { resolveDeferredHandleValues } from "../handles/deferred-resolution.js";
33
44
 
34
45
  /**
35
46
  * Task-quantized quiesce: the number of consecutive macrotask hops with zero new
@@ -50,13 +61,101 @@ import { buildFullPayload } from "./full-payload.js";
50
61
  * window (the masked loaders, and any genuinely pending I/O) becomes a hole. The
51
62
  * only residual is raw per-request I/O rendered directly in shell (not via a
52
63
  * loader) that resolves inside the window — a documented shell anti-pattern; put
53
- * per-request data in loaders or behind live(). See docs/design/ppr-shell-resume.md.
64
+ * per-request data in loaders. See docs/design/ppr-shell-resume.md.
54
65
  */
55
66
  const FLIGHT_QUIET_HOPS = 2;
56
67
 
57
68
  /** Default upper bound on the capture prerender wait before forcing the abort. */
58
69
  const SHELL_CAPTURE_MAX_WAIT_MS = 5000;
59
70
 
71
+ /**
72
+ * Upper bound on waiting for the capture's DEFERRED cache writes to settle before
73
+ * draining the snapshot. Cache writes run under waitUntil (fire-and-forget on
74
+ * Node, executionContext on workerd), so a MISS-at-capture value's setItem/set —
75
+ * hence its snapshot record — can land after the shell has quiesced. We collect
76
+ * those write promises and await them here so the written value is pinned. Kept
77
+ * short: a pathological slow write must never stall the background capture; a key
78
+ * that does not settle in time is simply left unpinned (it drifts, the
79
+ * pre-snapshot behavior) rather than hanging. Reads that HIT are recorded
80
+ * synchronously during the render and do not depend on this.
81
+ */
82
+ const SHELL_SNAPSHOT_WRITE_SETTLE_MS = 1000;
83
+
84
+ /**
85
+ * Upper bound on the pre-render WRITE BARRIER: before the capture's match/render,
86
+ * settle the background tasks the FOREGROUND request already scheduled — its
87
+ * deferred ring-3 cacheRoute and ring-1 setItem writes all go through
88
+ * reqCtx.waitUntil, and every one of them is scheduled BEFORE scheduleShellCapture
89
+ * runs (the response, and its onResponse callbacks, are committed first). Draining
90
+ * them turns the capture's cache reads from a RACE into an ORDERING EDGE: the
91
+ * capture deterministically observes the foreground's cache generation, replays it
92
+ * (handler skipped, module-level side effects untouched), and records THAT
93
+ * generation into the snapshot — so prelude, snapshot, and ring-3 all agree on the
94
+ * foreground's generation and the capture can never clobber a foreground-produced
95
+ * entry with a re-render of its own. Scar tissue: without this, the capture's
96
+ * ring-3 lookup could land between the foreground write chain's serialization and
97
+ * its store.set, MISS, re-execute the route handler (bumping module-level
98
+ * counters), and — via the synthetic onResponse fire below — overwrite the
99
+ * foreground's entry (the mini shell-manifest regression). Bounded: a slow
100
+ * consumer waitUntil task must never stall the background capture; on timeout the
101
+ * capture proceeds with the pre-barrier (racy) behavior.
102
+ */
103
+ const SHELL_CAPTURE_WRITE_BARRIER_MS = 1500;
104
+
105
+ /**
106
+ * Settle the tracked background tasks on `reqCtx._pendingBackgroundTasks`,
107
+ * ITERATIVELY: a settled task can have scheduled a nested one (cache-store's
108
+ * cacheRoute outer task schedules the actual store.set in a second waitUntil), so
109
+ * each awaited batch may append more. Loop until no new tasks appear or the
110
+ * deadline passes. The capture's own task never enters the list
111
+ * (UNTRACKED_BACKGROUND_TASK), so the loop terminates.
112
+ */
113
+ async function settleTrackedBackgroundTasks(
114
+ reqCtx: RequestContext<any>,
115
+ timeoutMs: number,
116
+ ): Promise<void> {
117
+ const tasks = reqCtx._pendingBackgroundTasks;
118
+ if (!tasks) return;
119
+ const deadline = Date.now() + timeoutMs;
120
+ let seen = 0;
121
+ while (tasks.length > seen) {
122
+ const remaining = deadline - Date.now();
123
+ if (remaining <= 0) return;
124
+ const batch = tasks.slice(seen);
125
+ seen = tasks.length;
126
+ let timer: ReturnType<typeof setTimeout> | undefined;
127
+ const guard = new Promise<void>((resolve) => {
128
+ timer = setTimeout(resolve, remaining);
129
+ (timer as { unref?: () => void }).unref?.();
130
+ });
131
+ await Promise.race([Promise.allSettled(batch).then(() => {}), guard]);
132
+ if (timer) clearTimeout(timer);
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Delay before the in-place retry of a capture that produced no usable shell.
138
+ *
139
+ * The dominant reason a first capture comes back with a trivial prelude is a
140
+ * COLD render: in dev the module transform graph (route modules, the SSR/Flight
141
+ * transforms) is being built lazily and outlasts the task-quantized quiesce, so
142
+ * the shell has not finished rendering when we freeze it; on a cold worker the
143
+ * first invocation pays the same one-time cost. The first attempt WARMS that
144
+ * graph, so a second attempt a short beat later usually completes the shell in
145
+ * the SAME background task — no extra HTTP request needed. Short enough to feel
146
+ * instant, long enough for the module graph to settle. See
147
+ * docs/design/ppr-shell-resume.md ("Capture retry-in-place").
148
+ */
149
+ const SHELL_CAPTURE_RETRY_DELAY_MS = 400;
150
+
151
+ /** Sleep `ms`, unref'd so a Node dev process is never kept alive by the timer. */
152
+ function delay(ms: number): Promise<void> {
153
+ return new Promise((resolve) => {
154
+ const t = setTimeout(resolve, ms);
155
+ (t as { unref?: () => void }).unref?.();
156
+ });
157
+ }
158
+
60
159
  /**
61
160
  * Module-level in-flight key set: the stampede guard for background captures, and
62
161
  * its single owner. One capture runs per key per isolate; concurrent MISS/stale
@@ -68,23 +167,94 @@ const SHELL_CAPTURE_MAX_WAIT_MS = 5000;
68
167
  */
69
168
  const inFlightCaptures = new Set<string>();
70
169
 
170
+ /**
171
+ * Refused-capture backoff bounds. The window is EXPONENTIAL in the consecutive
172
+ * failure count: `min(BASE * 2^(failures-1), MAX)` — 1s, 2s, 4s, … capped at 60s.
173
+ *
174
+ * Why exponential and not a flat 60s: a flat long window conflates two very
175
+ * different failures. A STRUCTURALLY ineligible route (no loading(), a cookie
176
+ * reader) fails forever and wants the long 60s cap. But a cold-but-ELIGIBLE route
177
+ * can also fail the in-place retry under a truly cold graph (dev module transform,
178
+ * or a cold worker under parallel load) — and it must recover FAST, on the next
179
+ * request or two, not be frozen for 60s (that would re-break the very cold-start DX
180
+ * the retry fixes; it bit the cloudflare dev e2e). Escalating from 1s means the
181
+ * eligible route re-probes almost immediately (warm now → HIT and clear), while the
182
+ * doomed route ramps to the 60s cap within a handful of failures. Either way an
183
+ * app-wide mount never re-renders a doomed route on EVERY request.
184
+ */
185
+ const REFUSED_CAPTURE_BASE_MS = 1_000;
186
+ const REFUSED_CAPTURE_MAX_MS = 60_000;
187
+
188
+ /**
189
+ * Refused-capture backoff: key -> { consecutive failure count, epoch ms until which
190
+ * the key is not re-probed }. A key enters backoff only after runShellCapture's
191
+ * in-place retry ALSO failed (or a genuine error). A successful capture clears the
192
+ * entry outright (failure count resets). Module-level (same lifetime as
193
+ * inFlightCaptures) so the whole lifecycle lives in one layer.
194
+ */
195
+ const refusedCaptures = new Map<string, { failures: number; until: number }>();
196
+
197
+ /** True iff `key` is still inside its (exponential) backoff window. */
198
+ function isCaptureBackedOff(key: string): boolean {
199
+ const entry = refusedCaptures.get(key);
200
+ if (entry === undefined) return false;
201
+ // Window elapsed: allow a re-probe. Keep the entry (its failure count drives the
202
+ // NEXT window's escalation if the re-probe also fails); a success clears it.
203
+ return Date.now() < entry.until;
204
+ }
205
+
206
+ /** Record a refused/failed capture, escalating the backoff window exponentially. */
207
+ function markCaptureBackoff(key: string): void {
208
+ const failures = (refusedCaptures.get(key)?.failures ?? 0) + 1;
209
+ const window = Math.min(
210
+ REFUSED_CAPTURE_BASE_MS * 2 ** (failures - 1),
211
+ REFUSED_CAPTURE_MAX_MS,
212
+ );
213
+ refusedCaptures.set(key, { failures, until: Date.now() + window });
214
+ }
215
+
216
+ /** Clear any backoff for a key that just captured successfully. */
217
+ function clearCaptureBackoff(key: string): void {
218
+ refusedCaptures.delete(key);
219
+ }
220
+
71
221
  /**
72
222
  * Keys already warned about a refused (null) capture, so the eternal-MISS shape
73
223
  * logs once per key per isolate instead of on every request.
74
224
  */
75
225
  const warnedNullCaptures = new Set<string>();
76
226
 
227
+ /**
228
+ * Warn once per key that a capture produced no usable shell EVEN AFTER the
229
+ * in-place retry (runShellCapture attempt 2). Naming both causes with the
230
+ * distinguishing signal — does the route ever flip to HIT — is the whole point:
231
+ * the pre-retry version blamed "a loader route without loading()" unconditionally
232
+ * and misled users whose route DID have loading() and was merely cold. Because the
233
+ * retry already absorbs the cold-start case, by the time this fires cold-start has
234
+ * usually healed, so a firing warning leans toward the structural cause — but we
235
+ * still name both so a cold-start straggler is not misdiagnosed.
236
+ *
237
+ * The pointer is shipped-path-safe (a05c8251 convention): the /ppr skill ships in
238
+ * the npm tarball, but docs/design/ is repo-only, so link it by absolute GitHub URL
239
+ * rather than a relative path that dead-ends for consumers.
240
+ */
77
241
  function warnNullCaptureOnce(key: string): void {
78
242
  if (warnedNullCaptures.has(key)) return;
79
243
  warnedNullCaptures.add(key);
80
244
  console.warn(
81
- `[rango] Shell capture for "${key}" produced no usable shell (empty or ` +
82
- "not-ready prelude); nothing was stored, so this request stays on MISS. A later " +
83
- "request re-captures - if the route NEVER flips to HIT, the most common cause is " +
84
- "a loader route without a route-level loading() boundary: its loader data is " +
245
+ `[rango] Shell capture for "${key}" produced no usable shell after an in-place ` +
246
+ "retry; nothing was stored, so this request stays on MISS. Two things cause this, " +
247
+ "told apart by whether the route ever flips to HIT:\n" +
248
+ " 1. Cold-start warmup (dev module transform, or a cold worker): the capture raced " +
249
+ "an unfinished shell render. This SELF-HEALS — the route flips to HIT once a later " +
250
+ "request warms the modules. Usually nothing to do.\n" +
251
+ " 2. A loader route WITHOUT a route-level loading() boundary: its loader data is " +
85
252
  "awaited at tree-build, so under capture's masked loaders no shell exists above " +
86
- "<body>. Add loading() to the loader route (and keep shell material in a layout) " +
87
- "to make it PPR-capturable. See docs/design/ppr-shell-resume.md.",
253
+ "<body>, and the route NEVER flips to HIT. Add loading() to the loader route (and " +
254
+ "keep shell material in a layout) to make it PPR-capturable.\n" +
255
+ 'See the /ppr skill (node_modules/@rangojs/router/skills/ppr/SKILL.md), "The hole ' +
256
+ 'contract", or the design doc: ' +
257
+ "https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/design/ppr-shell-resume.md",
88
258
  );
89
259
  }
90
260
 
@@ -124,10 +294,23 @@ export interface FlightCaptureGate {
124
294
  * hop timers are unref'd so they never keep a Node process alive, and the source
125
295
  * closing (no holes) fires quiesce immediately for the DATA variant — the
126
296
  * TransformStream then closes the readable, so fizz completes with postponed null.
297
+ *
298
+ * `holdUntil` keeps the gate from FREEZING before shell material with real latency
299
+ * has emitted. The hole doctrine bakes TOP-LEVEL pushed handle promises into the
300
+ * shell (resolvedHandleStream awaits them before the handles row emits), but a
301
+ * pushed promise that takes longer than the quiet window would otherwise be frozen
302
+ * out — the handles row would never reach fizz and the prelude would come back
303
+ * trivial. While `holdUntil` is pending, byte-quiet detection keeps running but the
304
+ * gate neither fires nor freezes; once it resolves, the quiet counter restarts so a
305
+ * burst of rows unblocked by it (the resolved handles row) is still captured. It
306
+ * never delays a HOLE from postponing: holes are pending promises that emit no
307
+ * bytes, so holding the gate open longer only ever admits shell rows. Bounded by
308
+ * captureShellHTML's maxWaitMs like every other quiesce input.
127
309
  */
128
310
  export function gateFlightForCapture(
129
311
  source: ReadableStream<Uint8Array>,
130
312
  quietHops: number = FLIGHT_QUIET_HOPS,
313
+ holdUntil?: Promise<unknown>,
131
314
  ): FlightCaptureGate {
132
315
  let resolveQuiet!: () => void;
133
316
  const quiesce = new Promise<void>((resolve) => {
@@ -139,9 +322,32 @@ export function gateFlightForCapture(
139
322
  let settled = false;
140
323
  let disposed = false;
141
324
  let frozen = false;
325
+ let held = holdUntil !== undefined;
326
+ let heldFirePending = false;
327
+
328
+ if (holdUntil !== undefined) {
329
+ const release = (): void => {
330
+ held = false;
331
+ if (heldFirePending && !settled && !disposed) {
332
+ // Quiet elapsed while held: restart the quiet count instead of firing
333
+ // immediately, so rows unblocked by the hold (the baked handles row)
334
+ // still flow before the freeze.
335
+ heldFirePending = false;
336
+ armed = false;
337
+ arm();
338
+ }
339
+ };
340
+ // Resolve OR reject releases the hold (a rejected handle value is dropped by
341
+ // resolveDeferredHandleValues; the capture must not hang on it).
342
+ holdUntil.then(release, release);
343
+ }
142
344
 
143
345
  const fire = (): void => {
144
346
  if (settled) return;
347
+ if (held) {
348
+ heldFirePending = true;
349
+ return;
350
+ }
145
351
  settled = true;
146
352
  frozen = true;
147
353
  resolveQuiet();
@@ -205,6 +411,27 @@ export function gateFlightForCapture(
205
411
  };
206
412
  }
207
413
 
414
+ /**
415
+ * The background shell-capture descriptor: everything the capture task needs to
416
+ * store the shell. Built by the integrated PPR serve path (rsc-rendering.ts) from
417
+ * the route's `ppr` path option (`PartialPrerenderProps`) and the app-level cache
418
+ * store, and passed to scheduleShellCapture directly — it is NOT threaded through
419
+ * the request context. `tags` carries the route's OPERATIONAL `ppr.tags`; the
420
+ * capture UNIONS them with the shell's own auto-collected (non-loader) request
421
+ * tags from its derived render (the collected set stays authoritative). `store`
422
+ * is the same store the serve path resolved for its getShell read
423
+ * (requestCtx._cacheStore), so the capture writes where the serve reads.
424
+ */
425
+ export interface ShellCaptureDescriptor {
426
+ key: string;
427
+ ttl?: number;
428
+ swr?: number;
429
+ tags?: string[];
430
+ store?: SegmentCacheStore<any>;
431
+ /** Gates the concise per-attempt capture breadcrumbs (INTERNAL_RANGO_DEBUG). */
432
+ debug?: boolean;
433
+ }
434
+
208
435
  /**
209
436
  * Schedule the background shell capture for a served document. Stampede-guarded:
210
437
  * one capture per key per isolate. Runs via runBackground (waitUntil on workerd,
@@ -223,14 +450,17 @@ export function scheduleShellCapture(
223
450
  url: URL,
224
451
  reqCtx: RequestContext<any>,
225
452
  ssrModule: SSRModule,
226
- descriptor: NonNullable<RequestContext["_shellCapture"]>,
453
+ descriptor: ShellCaptureDescriptor,
227
454
  ): void {
228
455
  const key = descriptor.key;
229
456
  if (inFlightCaptures.has(key)) return;
457
+ // Refused/failed within the window → skip the doomed re-render (one probe per
458
+ // key per window per isolate). Expired entries self-evict inside the check.
459
+ if (isCaptureBackedOff(key)) return;
230
460
  inFlightCaptures.add(key);
231
- runBackground(reqCtx, async () => {
461
+ const captureTask = async () => {
232
462
  try {
233
- await runShellCapture(
463
+ const outcome = await runShellCapture(
234
464
  ctx,
235
465
  request,
236
466
  env,
@@ -239,19 +469,121 @@ export function scheduleShellCapture(
239
469
  ssrModule,
240
470
  descriptor,
241
471
  );
472
+ // Update the negative cache off the terminal outcome. A stored shell clears
473
+ // any prior backoff; a `no-shell` (after the in-place retry) backs the key
474
+ // off so the next requests don't re-probe it. A `redirect` has no shell but
475
+ // is not a doomed render — leave the backoff untouched.
476
+ if (outcome === "stored") clearCaptureBackoff(key);
477
+ else if (outcome === "no-shell") markCaptureBackoff(key);
242
478
  } catch (error) {
243
479
  // Detached background task — pass reqCtx so onError still fires when the ALS
244
- // context is gone. Best-effort: a failure just means the next request
245
- // recaptures.
480
+ // context is gone. A genuine failure recurs, so back it off too (re-probe
481
+ // once per window, not every request) and report it once.
482
+ markCaptureBackoff(key);
246
483
  reportCacheError(error, "cache-write", "[ShellCache] capture", reqCtx);
247
484
  } finally {
248
485
  inFlightCaptures.delete(key);
249
486
  }
250
- });
487
+ };
488
+ // The capture's own task must NOT enter reqCtx._pendingBackgroundTasks: the
489
+ // capture drains that list before rendering (the write-barrier ordering edge),
490
+ // and awaiting its own still-running promise would burn the whole barrier
491
+ // deadline on every capture.
492
+ (captureTask as { [UNTRACKED_BACKGROUND_TASK]?: boolean })[
493
+ UNTRACKED_BACKGROUND_TASK
494
+ ] = true;
495
+ runBackground(reqCtx, captureTask);
496
+ }
497
+
498
+ /**
499
+ * The outcome of one capture attempt.
500
+ * - `stored`: a usable shell was captured (and a putShell was attempted; a store
501
+ * I/O failure is reported separately and does NOT make the attempt retryable —
502
+ * the capture itself worked).
503
+ * - `redirect`: the matched route redirects, so there is no shell to capture.
504
+ * - `no-shell`: the prelude came back trivial (no <body>) OR captureShellHTML
505
+ * rejected with our own abort. This is the only RETRYABLE outcome.
506
+ */
507
+ type CaptureAttemptOutcome = "stored" | "redirect" | "no-shell";
508
+
509
+ /**
510
+ * Run the shell capture with a single in-place retry, then store the result.
511
+ *
512
+ * Each attempt re-derives EVERYTHING (fresh context, fresh router.match, fresh
513
+ * Flight render) via {@link attemptCapture} — a capture consumes its handle store,
514
+ * its request-tag set, and its one-shot Flight stream, so none of them are
515
+ * reusable across attempts. A first attempt that comes back `no-shell` is almost
516
+ * always a cold render (dev module transform / cold worker) that had not finished
517
+ * when we froze the shell; the attempt itself warmed the module graph, so a second
518
+ * attempt a short beat later usually completes the shell in the SAME background
519
+ * task. That kills the old multi-request warmup where the caller had to re-issue
520
+ * several HTTP requests before a capture stuck. We retry ONLY on `no-shell` (and a
521
+ * defensively-caught abort); a genuine render error is NOT retried — it propagates
522
+ * to scheduleShellCapture's reportCacheError. See docs/design/ppr-shell-resume.md.
523
+ *
524
+ * `retryDelayMs` is a parameter (defaulting to the module const) so unit tests can
525
+ * drive the retry without a real 400ms wall-clock wait.
526
+ */
527
+ async function runShellCapture(
528
+ ctx: HandlerContext<any>,
529
+ request: Request,
530
+ env: any,
531
+ url: URL,
532
+ reqCtx: RequestContext<any>,
533
+ ssrModule: SSRModule,
534
+ descriptor: ShellCaptureDescriptor,
535
+ retryDelayMs: number = SHELL_CAPTURE_RETRY_DELAY_MS,
536
+ ): Promise<CaptureAttemptOutcome> {
537
+ const log = descriptor.debug
538
+ ? (message: string) => console.log(message)
539
+ : () => {};
540
+
541
+ const first = await attemptCapture(
542
+ ctx,
543
+ request,
544
+ env,
545
+ url,
546
+ reqCtx,
547
+ ssrModule,
548
+ descriptor,
549
+ );
550
+ // "stored" (success) or "redirect" (no shell exists): nothing to retry.
551
+ if (first !== "no-shell") return first;
552
+
553
+ // Attempt 1 produced no usable shell. Retry ONCE in place — the first attempt
554
+ // warmed the dev transform graph / cold worker, so attempt 2 typically completes
555
+ // the shell without another HTTP request. The concise line is gated on the
556
+ // middleware's debug flag (threaded via the descriptor) so it replaces the old
557
+ // full DOMException dump with one readable breadcrumb.
558
+ log(
559
+ `[ShellCache] capture attempt 1/2 for ${descriptor.key} aborted before shell completed (cold modules?) — retrying`,
560
+ );
561
+ await delay(retryDelayMs);
562
+ const second = await attemptCapture(
563
+ ctx,
564
+ request,
565
+ env,
566
+ url,
567
+ reqCtx,
568
+ ssrModule,
569
+ descriptor,
570
+ );
571
+ if (second !== "no-shell") return second;
572
+
573
+ // Both attempts came back with no usable shell. Cold-start would have healed by
574
+ // now, so the eternal-MISS structural shape (a loader route without loading()) is
575
+ // the likely cause — warn once per key. Ordering matters: because the retry
576
+ // absorbs cold-start, cold-start routes almost never reach this warning. The
577
+ // caller (scheduleShellCapture) reads this `no-shell` return to back the key off.
578
+ log(
579
+ `[ShellCache] capture attempt 2/2 for ${descriptor.key} aborted — giving up until next request`,
580
+ );
581
+ warnNullCaptureOnce(descriptor.key);
582
+ return "no-shell";
251
583
  }
252
584
 
253
585
  /**
254
- * Run the shell capture in a DERIVED request context, then store the result.
586
+ * One capture attempt in a DERIVED request context.
255
587
  *
256
588
  * The derived context is `Object.create(reqCtx)` so it inherits the foreground's
257
589
  * post-middleware state (variables, cache store, env/request/url, waitUntil) while
@@ -267,19 +599,39 @@ export function scheduleShellCapture(
267
599
  * set a shell entry should be invalidatable by (loader tags belong to holes).
268
600
  * - _transitionWhen: a fresh [] so the capture's transition gating is its own.
269
601
  * - _shellCaptureRun: true — the switch loaders/cookies/headers guards read.
270
- * - _shellCapture: the descriptor (informational; putShell target/ttl/swr).
271
602
  * - _metricsStore: undefined so the capture never appends to the foreground's
272
603
  * (already-finalized) metrics.
604
+ *
605
+ * The capture is MIXED-CHAIN: its match() behaves like a normal render with
606
+ * respect to the segment cache — cache()'d segments replay from ring 3, UNCACHED
607
+ * segments execute their handlers fresh (which is why the cookies()/headers()
608
+ * capture guard is load-bearing). Middleware is NOT re-run: it already ran for the
609
+ * triggering request, and the derived context inherits its post-middleware state
610
+ * (guarding is serve-time; the shell is never served without the full chain).
611
+ *
612
+ * A FRESH context (and match/render) per attempt is what makes the retry sound:
613
+ * the second attempt is a clean capture, not a resumption of the first.
273
614
  */
274
- async function runShellCapture(
615
+ async function attemptCapture(
275
616
  ctx: HandlerContext<any>,
276
617
  request: Request,
277
618
  env: any,
278
619
  url: URL,
279
620
  reqCtx: RequestContext<any>,
280
621
  ssrModule: SSRModule,
281
- descriptor: NonNullable<RequestContext["_shellCapture"]>,
282
- ): Promise<void> {
622
+ descriptor: ShellCaptureDescriptor,
623
+ ): Promise<CaptureAttemptOutcome> {
624
+ // WRITE BARRIER (ordering edge, not a narrower race): settle the foreground's
625
+ // already-scheduled background tasks — its deferred ring-3/ring-1 cache writes —
626
+ // BEFORE this attempt's match/render, so the capture's cache reads observe the
627
+ // foreground's generation deterministically. Contract: a capture must never
628
+ // clobber a ring-3 entry the foreground produced; with the barrier, the
629
+ // capture's ring-3 lookup HITs the foreground's entry and REPLAYS it (handler
630
+ // skipped, cache-store middleware's write path gated off by state.cacheHit), so
631
+ // prelude, snapshot, and ring-3 agree on the foreground's generation. Runs per
632
+ // attempt (the retry re-checks; already-settled promises are free).
633
+ await settleTrackedBackgroundTasks(reqCtx, SHELL_CAPTURE_WRITE_BARRIER_MS);
634
+
283
635
  const freshHandleStore = createHandleStore();
284
636
  freshHandleStore.onError = reqCtx._handleStore.onError;
285
637
 
@@ -288,13 +640,43 @@ async function runShellCapture(
288
640
  derivedCtx._requestTags = new Set<string>();
289
641
  derivedCtx._transitionWhen = [];
290
642
  derivedCtx._shellCaptureRun = true;
291
- derivedCtx._shellCapture = descriptor;
292
643
  derivedCtx._metricsStore = undefined;
644
+ // Own onResponse list so the capture's match-middleware callbacks (the ring-3
645
+ // segment cache write registers here) are ISOLATED from the foreground's shared
646
+ // array AND can be fired by captureAndStoreShell. The segment write is gated
647
+ // behind onResponse, which the capture never triggers (it builds no Response) —
648
+ // without firing it, a ring-3 cache() MISS at capture renders fresh into the
649
+ // prelude but is never written, so it is never recorded and drifts on a HIT.
650
+ derivedCtx._onResponseCallbacks = [];
293
651
 
294
- await runWithRequestContext(derivedCtx, async () => {
652
+ // Capture data snapshot: read every cache-store hit/write through a recording
653
+ // wrapper on the DERIVED context's store (own property, so the shared
654
+ // reqCtx._cacheStore is untouched — the snapshot is per-capture). Its records
655
+ // ride inside the ShellCacheEntry so a HIT can reproduce the shell's cached
656
+ // content byte-identically. See cache/shell-snapshot.ts and the design doc.
657
+ //
658
+ // Cache writes are deferred (waitUntil): a MISS-at-capture value's setItem/set
659
+ // — hence its record — would otherwise land after the shell quiesces. Override
660
+ // the derived context's waitUntil to COLLECT those write promises (still
661
+ // forwarding to the parent so the write persists and the worker stays alive),
662
+ // then captureAndStoreShell awaits them before draining. Reads that HIT are
663
+ // recorded synchronously during the render and need none of this.
664
+ if (reqCtx._cacheStore) {
665
+ const recordingStore = new RecordingShellStore(reqCtx._cacheStore);
666
+ derivedCtx._cacheStore = recordingStore;
667
+ derivedCtx.waitUntil = (fn: () => Promise<void>): void => {
668
+ const p = Promise.resolve().then(fn);
669
+ recordingStore.trackWrite(p);
670
+ reqCtx.waitUntil(() => p);
671
+ };
672
+ }
673
+
674
+ return runWithRequestContext(derivedCtx, async () => {
295
675
  const match = await ctx.router.match(request, { env });
296
- // A route that redirects has no shell to capture — bail (no store write).
297
- if (match.redirect) return;
676
+ // A route that redirects has no shell to capture — bail (no store write, no
677
+ // retry: a redirect is deterministic).
678
+ if (match.redirect) return "redirect";
679
+
298
680
  setRequestContextParams(match.params, match.routeName);
299
681
 
300
682
  const payload = buildFullPayload(
@@ -311,14 +693,15 @@ async function runShellCapture(
311
693
  });
312
694
 
313
695
  // Shell tags = the non-loader request tags the capture render recorded on its
314
- // own fresh _requestTags. Loaders are masked, so loader cache tags (which
315
- // belong to the holes, not the shell) are correctly excluded.
316
- const tags =
317
- derivedCtx._requestTags.size > 0
318
- ? [...derivedCtx._requestTags]
319
- : undefined;
320
-
321
- await captureAndStoreShell(
696
+ // own fresh _requestTags (loaders are masked, so loader cache tags — which
697
+ // belong to the holes, not the shell — are correctly excluded), UNIONED with
698
+ // the middleware's operational `tags` option (descriptor.tags). The collected
699
+ // set is authoritative; the option only adds tags the render cannot know.
700
+ const collected = [...derivedCtx._requestTags];
701
+ const union = new Set<string>([...(descriptor.tags ?? []), ...collected]);
702
+ const tags = union.size > 0 ? [...union] : undefined;
703
+
704
+ return captureAndStoreShell(
322
705
  ssrModule,
323
706
  rscStream,
324
707
  freshHandleStore,
@@ -333,18 +716,24 @@ async function runShellCapture(
333
716
 
334
717
  /**
335
718
  * Seal handles, derive the quiesce signal, prerender + abort via the SSR module's
336
- * captureShellHTML, and store the result. Never throws out of the store write: a
337
- * failed putShell is routed through reportCacheError so the background task stays
338
- * best-effort. `ssrModule.captureShellHTML` MUST be present (eligibility is
339
- * checked before scheduling).
719
+ * captureShellHTML, and store the result. Returns the attempt outcome (the caller
720
+ * owns retry/warn decisions — this function no longer warns). Never throws out of
721
+ * the store write: a failed putShell is routed through reportCacheError so the
722
+ * background task stays best-effort, and the attempt still counts as `stored` (the
723
+ * capture worked; only the store I/O failed). `ssrModule.captureShellHTML` MUST be
724
+ * present (eligibility is checked before scheduling).
725
+ *
726
+ * A `no-shell` result (trivial prelude, or a defensively-caught abort) is the only
727
+ * retryable outcome; a genuine (non-abort) captureShellHTML error propagates so it
728
+ * reaches reportCacheError and is NOT retried.
340
729
  */
341
730
  async function captureAndStoreShell(
342
731
  ssrModule: SSRModule,
343
732
  rscStream: ReadableStream<Uint8Array>,
344
733
  handleStore: HandleStore,
345
734
  reqCtx: RequestContext<any>,
346
- capture: NonNullable<RequestContext["_shellCapture"]>,
347
- ): Promise<void> {
735
+ capture: ShellCaptureDescriptor,
736
+ ): Promise<Exclude<CaptureAttemptOutcome, "redirect">> {
348
737
  const captureShellHTML = ssrModule.captureShellHTML!;
349
738
 
350
739
  // Seal the handle store so the payload's handles generator (resolvedHandleStream
@@ -364,7 +753,19 @@ async function captureAndStoreShell(
364
753
  // excludes loaders. See docs/design/ppr-shell-resume.md ("Loaders and handles").
365
754
  handleStore.seal();
366
755
 
367
- const gate = gateFlightForCapture(rscStream);
756
+ // Handles contract, shell half ("nesting = liveness"): TOP-LEVEL pushed handle
757
+ // promises are BAKED into the shell — resolvedHandleStream awaits them before
758
+ // the payload's handles row emits. A pushed promise with real latency would lose
759
+ // the byte-quiet race (the pending handles row emits no bytes, the gate freezes,
760
+ // the row is dropped, SsrRoot suspends at the root), so the gate is HELD open
761
+ // until the same await completes: handlesBaked mirrors resolvedHandleStream's
762
+ // resolution (getData waits the tracked-handler barrier; resolveDeferredHandleValues
763
+ // awaits the top-level thenables). NESTED promises inside pushed containers are
764
+ // shallow-skipped by isThenable and never hold the gate — they stay holes.
765
+ // Bounded by maxWaitMs like every quiesce input (a defer hanging on a masked
766
+ // loader still ends in the sanity-gate refusal).
767
+ const handlesBaked = handleStore.getData().then(resolveDeferredHandleValues);
768
+ const gate = gateFlightForCapture(rscStream, undefined, handlesBaked);
368
769
  // Quiesce = handles settled AND the Flight shell rows went task-quiet. Either
369
770
  // half stalling is bounded by captureShellHTML's maxWaitMs.
370
771
  const quiesce = Promise.all([handleStore.settled, gate.quiesce]).then(
@@ -373,23 +774,35 @@ async function captureAndStoreShell(
373
774
 
374
775
  try {
375
776
  // captureShellHTML CONSUMES the (gated) stream — it is not also SSR'd.
376
- const result = await observePhase(PHASES.ssr, () =>
377
- captureShellHTML(gate.stream, {
378
- quiesce,
379
- maxWaitMs: SHELL_CAPTURE_MAX_WAIT_MS,
380
- }),
381
- );
777
+ let result: Awaited<ReturnType<typeof captureShellHTML>>;
778
+ try {
779
+ result = await observePhase(PHASES.ssr, () =>
780
+ captureShellHTML(gate.stream, {
781
+ quiesce,
782
+ maxWaitMs: SHELL_CAPTURE_MAX_WAIT_MS,
783
+ }),
784
+ );
785
+ } catch (error) {
786
+ // captureShellHTML normally converts its OWN deliberate abort to a null
787
+ // return (index.tsx). This catch is defensive: if an AbortError still escapes
788
+ // (a runtime where the abort surfaces as a stream rejection outside its
789
+ // guard), treat it as the same retryable "no usable shell" degradation rather
790
+ // than a failure — do NOT report it as an error. A genuine (non-abort) render
791
+ // error is a real failure: rethrow so it reaches reportCacheError (no retry).
792
+ if ((error as { name?: string } | null)?.name === "AbortError") {
793
+ return "no-shell";
794
+ }
795
+ throw error;
796
+ }
382
797
 
383
- // null = sanity gate refused (trivial/empty prelude, no <body>). Store
384
- // nothing; the route stays on axis 1 and every future request re-captures to
385
- // the same refusal, so surface it once per key: the dominant cause is a
386
- // route shape with no capturable shell — a loader route WITHOUT a route-level
387
- // loading() boundary awaits its loader data at tree-build (renderSegments'
388
- // loading-less branch), so the masked loader pins the whole tree above
389
- // <body>. Silent refusal made that shape an undiagnosable eternal MISS.
798
+ // null = sanity gate refused (trivial/empty prelude, no <body>). Store nothing
799
+ // and report `no-shell` so the caller (runShellCapture) can retry once and, if
800
+ // that also fails, warn once per key. On a cold render this is the shell not
801
+ // yet finished; on a loader route WITHOUT a route-level loading() boundary it is
802
+ // the structural eternal-MISS shape (the masked loader pins the tree above
803
+ // <body> at tree-build). The caller's warning names both.
390
804
  if (result === null) {
391
- warnNullCaptureOnce(capture.key);
392
- return;
805
+ return "no-shell";
393
806
  }
394
807
 
395
808
  // Store per the flag's key/ttl/swr/tags, into the flag's store: the middleware
@@ -398,6 +811,42 @@ async function captureAndStoreShell(
398
811
  // them. The _cacheStore fallback covers a flag armed without a store (tests).
399
812
  // reactVersion is read from the same React.version import the middleware
400
813
  // validates reads against, so capture and serve always agree.
814
+ // Fire the capture's isolated onResponse callbacks with a synthetic 200 so
815
+ // the ring-3 segment cache write (cacheScope.cacheRoute, registered via
816
+ // onResponse by the cache-store match-middleware and gated on a 200) runs
817
+ // DURING capture, routed through the recording store. The foreground path
818
+ // never fires for the capture — it builds no Response — so without this a
819
+ // cache() SEGMENT that MISSED at capture would be rendered fresh into the
820
+ // prelude yet never written, hence never recorded, and would drift on a HIT
821
+ // (an item-family "use cache" write already runs inline during the render, so
822
+ // it needs none of this; only segment writes are onResponse-gated). The
823
+ // derived context's own _onResponseCallbacks holds only capture match-
824
+ // middleware callbacks (HTTP middleware never runs for a capture), so firing
825
+ // them is safe. Best-effort: a throwing callback must not fail the capture.
826
+ const responseCallbacks = reqCtx._onResponseCallbacks;
827
+ if (responseCallbacks && responseCallbacks.length > 0) {
828
+ const synthetic = new Response(null, { status: 200 });
829
+ for (const cb of responseCallbacks) {
830
+ try {
831
+ cb(synthetic);
832
+ } catch {
833
+ // A capture-time cache write that throws is degradation, not failure.
834
+ }
835
+ }
836
+ }
837
+
838
+ // Drain the capture data snapshot from the recording store on the derived
839
+ // context. Await the deferred cache writes first so a MISS-at-capture value
840
+ // (setItem/set scheduled under waitUntil, including the segment write just
841
+ // fired) is pinned, not just read-hits. When no recording store is installed
842
+ // (unit tests that call this directly), there is simply no snapshot.
843
+ const recording = getRecordingStore(reqCtx._cacheStore);
844
+ let snapshot: ShellSnapshotRecord[] | undefined;
845
+ if (recording) {
846
+ await recording.settleWrites(SHELL_SNAPSHOT_WRITE_SETTLE_MS);
847
+ snapshot = recording.drainSnapshot();
848
+ }
849
+
401
850
  const store = capture.store ?? reqCtx._cacheStore;
402
851
  if (store?.putShell) {
403
852
  try {
@@ -408,6 +857,12 @@ async function captureAndStoreShell(
408
857
  prelude: bufferToBase64(result.prelude.slice().buffer as ArrayBuffer),
409
858
  postponed: result.postponed,
410
859
  reactVersion: React.version,
860
+ // The theme this capture's payload was built with (buildFullPayload
861
+ // reads reqCtx.theme off the derived context). The serve tail replays
862
+ // it so the resume tree matches the frozen prelude — see
863
+ // ShellCacheEntry.initialTheme.
864
+ initialTheme: reqCtx.theme,
865
+ snapshot,
411
866
  createdAt: Date.now(),
412
867
  };
413
868
  await store.putShell(
@@ -427,6 +882,9 @@ async function captureAndStoreShell(
427
882
  );
428
883
  }
429
884
  }
885
+ // A shell was captured (the store I/O may have failed, but that is reported,
886
+ // not retried) — so this attempt is `stored` and the caller does not retry.
887
+ return "stored";
430
888
  } finally {
431
889
  // Stop the hop loop for the pathological never-quiets path (quiesce never
432
890
  // fired, capture returned via maxWaitMs). On the normal path the loop already