From 7ab4113fd722e472b670c4032222e4d8eb810e95 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 12 Apr 2026 13:38:50 +0200 Subject: [PATCH 1/9] plan --- docs/router/route-match-loading-rfc.md | 1067 ++++++++++++++++++++++++ 1 file changed, 1067 insertions(+) create mode 100644 docs/router/route-match-loading-rfc.md diff --git a/docs/router/route-match-loading-rfc.md b/docs/router/route-match-loading-rfc.md new file mode 100644 index 0000000000..99ace604f2 --- /dev/null +++ b/docs/router/route-match-loading-rfc.md @@ -0,0 +1,1067 @@ +--- +id: route-match-loading-rfc +title: Route Match Loading RFC +--- + +# Route Match Loading And Rendering RFC + +Status: phase 1 complete, phase 2 ready to start + +Owner: multi-session effort, React-first + +Decision defaults: + +- Source of truth: the new spec wins over current code/tests when they disagree +- Phase 1 artifact: this checked-in RFC/doc is the coordination hub +- Phase 3 rollout: rework router-core plus React first, then align Solid and Vue + +## Purpose + +This document is the working coordination hub for redesigning how TanStack Router loads and renders route matches. + +The current implementation works, but the behavior is spread across several files, pools, framework adapters, timers, and promise lifetimes. We have repeatedly hit bugs and races around match context visibility, pending UI continuity, redirects, not-found handling, hydration, background reloads, and cache promotion/eviction. + +This effort is split into three phases: + +1. Specify how route-match loading and rendering should work. +2. Model the required semantics in FizzBee. +3. Re-implement from first principles against the model. + +This RFC captures the plan and also starts phase 1. + +## Problem Statement + +Representative failure modes already seen in the current system: + +- a route match renders before the effective route context is complete, so data from `beforeLoad` is initially `undefined` +- a promise consumed by a framework adapter disappears while the match is still mounted +- a match is evicted or replaced before navigation/rendering semantics are actually finished with it +- a redirect/not-found/error from an older or background load leaks into a newer render generation +- hydration-only flags and render-driven timers leak framework details into router-core state + +The core challenge is that the router must coordinate all of the following at once: + +- initial client load +- SSR hydration +- client-only hydration gaps (`ssr: false`, `ssr: 'data-only'`) +- navigation +- preload +- invalidation and stale reloads +- redirect and not-found interruption +- lazy route chunk loading +- framework-specific suspense/error-boundary behavior + +## Primary Code Map + +Current behavior is spread across these files. + +Core loading and state: + +- `packages/router-core/src/router.ts:1389-1668` + Match creation, reuse, initial context assembly. +- `packages/router-core/src/router.ts:1758-1787` + Match cancellation. +- `packages/router-core/src/router.ts:2327-2860` + `beforeLoad`, `load`, pending-to-active commit, invalidation, preloading, cache cleanup. +- `packages/router-core/src/load-matches.ts:23-1278` + The main loading pipeline: serial `beforeLoad`, parallel loaders, pending timers, redirect/notFound/error handling, head execution, lazy chunk loading. +- `packages/router-core/src/Matches.ts:118-175` + Match shape and `_nonReactive` promise/timer state. +- `packages/router-core/src/stores.ts:72-340` + Active, pending, and cached match pools and their store reconciliation rules. +- `packages/router-core/src/ssr/ssr-client.ts:19-309` + Client hydration, forced pending, display-pending, rehydrated context/head reconstruction. + +React rendering: + +- `packages/react-router/src/Matches.tsx:46-113` + Root-level suspense/catch setup. +- `packages/react-router/src/Match.tsx:25-568` + Per-match suspense, catch, not-found routing, client-only rendering, `MatchInner`, and `Outlet` behavior. +- `packages/react-router/src/CatchBoundary.tsx:7-116` + Error-boundary reset semantics. +- `packages/react-router/src/Transitioner.tsx:13-139` + Transition integration and `onLoad`/`onResolved`/`onRendered` timing. + +Other adapters: + +- `packages/solid-router/src/Match.tsx:21-507` +- `packages/vue-router/src/Match.tsx:26-564` + +Tests worth using as anchors while specifying behavior: + +- `packages/router-core/tests/load.test.ts:574-650` + `beforeLoad` reruns on stay, loaders may not. +- `packages/router-core/tests/load.test.ts:1170-1381` + beforeLoad/notFound hierarchy, ancestor loader/head behavior, serial error behavior. +- `packages/router-core/tests/hydrate.test.ts:222-350` + hydration of `globalNotFound`. +- `packages/react-router/tests/routeContext.test.tsx:447-574` + expected context visible in `beforeLoad`. +- `packages/react-router/tests/loaders.test.tsx:468-648` + route context and loader data coherence through navigation and invalidation. +- `packages/react-router/tests/router.test.tsx:2337-2537` + beforeLoad notFound with and without pending components. +- `packages/react-router/tests/redirect.test.tsx:116-125` + redirect while pending UI is already showing. + +## Current Lifecycle Map + +This section describes the current implementation, not the target design. + +### 1. Match creation + +- `router.beforeLoad()` cancels pending work and computes the next pending matches. +- `matchRoutesInternal()` creates or reuses a `match.id` from `route.id + interpolatedPath + loaderDepsHash`. +- New matches start in `status: 'pending'` if they have `beforeLoad`, `loader`, lazy route options, or preloadable components. +- Reused matches carry forward substantial state, including cached data and `_nonReactive` state. + +References: + +- `packages/router-core/src/router.ts:1502-1600` +- `packages/router-core/src/router.ts:2327-2371` + +### 2. Loading + +- `loadMatches()` runs `beforeLoad` serially from root to leaf. +- `loadRouteMatch()` then runs loaders in parallel for the surviving prefix. +- `beforeLoad` may set `__beforeLoadContext`, redirect, notFound, or error. +- Loaders may reuse fresh data, reload in the foreground, or stale-reload in the background. +- Heads run after loading/error/notFound resolution. + +References: + +- `packages/router-core/src/load-matches.ts:355-558` +- `packages/router-core/src/load-matches.ts:641-959` +- `packages/router-core/src/load-matches.ts:961-1185` + +### 3. Commit + +- `router.load()` promotes `pendingMatches` to active matches in `onReady`. +- Exiting active matches may be moved into the cache if they are not `error`, `notFound`, or `redirected`. +- Lifecycle hooks use `routeId` identity, while storage pools use `match.id` identity. + +References: + +- `packages/router-core/src/router.ts:2402-2505` + +### 4. Hydration + +- hydration copies server data into client matches +- hydration may set `_forcePending` and `_displayPending` +- hydration may skip a normal `router.load()` if everything is already SSR-backed + +References: + +- `packages/router-core/src/ssr/ssr-client.ts:107-163` +- `packages/router-core/src/ssr/ssr-client.ts:249-308` + +### 5. React rendering + +- `MatchInner` throws promises for `_displayPending`, `_forcePending`, `status: 'pending'`, and `status: 'redirected'` +- `status: 'error'` throws on the client but renders directly on the server +- non-root not-found uses `status: 'notFound'` +- root not-found is represented as `status: 'success'` plus `globalNotFound: true` + +References: + +- `packages/react-router/src/Match.tsx:141-207` +- `packages/react-router/src/Match.tsx:404-489` +- `packages/react-router/src/Match.tsx:542-567` + +## Initial Findings + +These are phase-1 observations, not final conclusions. + +### 1. Match identity and lifecycle identity are mixed + +Storage and reuse are keyed by `match.id`, but enter/stay/leave semantics are keyed by `routeId`. + +References: + +- `packages/router-core/src/router.ts:1502-1514` +- `packages/router-core/src/router.ts:2419-2467` + +This is likely necessary, but the current implementation makes the distinction implicit instead of explicit. + +### 2. Pool lookup order is surprising + +`getMatch()` reads `cached -> pending -> active`. + +Reference: + +- `packages/router-core/src/router.ts:2653-2658` + +That ordering makes sense only if the same `match.id` can never exist in multiple pools at once. That appears to be intended, but it is not enforced as an invariant. + +### 3. Rendering semantics depend on promises with implicit ownership + +The adapters depend on promises in `_nonReactive`, but ownership and lifetime are spread across many branches. + +References: + +- `packages/router-core/src/load-matches.ts:396-401` +- `packages/router-core/src/load-matches.ts:451` +- `packages/router-core/src/load-matches.ts:925` +- `packages/router-core/src/load-matches.ts:938-945` +- `packages/react-router/src/Match.tsx:264-277` + +This makes it easy to end up with a mounted match still trying to suspend on a promise that has been resolved, removed, or replaced unexpectedly. + +### 4. React hydration concerns leak into core match state + +`_forcePending` and `_displayPending` are currently router-core state even though they are primarily adapter/rendering concerns. + +References: + +- `packages/router-core/src/ssr/ssr-client.ts:107-129` +- `packages/router-core/src/ssr/ssr-client.ts:272-306` + +### 5. Reuse/reset semantics are not explicit enough + +The HMR path already has to manually clear stale `loaderData` and `__beforeLoadContext` before invalidation. + +Reference: + +- `packages/router-plugin/src/core/route-hmr-statement.ts:99-138` + +That is a strong sign that “what survives match reuse” is currently emergent instead of specified. + +## Phase Plan + +### Phase 1. Specify intended behavior + +Deliverables: + +- glossary and explicit terminology +- normative invariants +- scenario matrix across all entry points +- clear split between router-core guarantees and adapter guarantees +- documented divergences from the current implementation + +### Phase 2. Model behavior in FizzBee + +Deliverables: + +- a compact state model for match lifecycle, cache membership, generation, and render gating +- assertions for exclusivity, precedence, continuity, and generation safety +- guided traces for key scenarios: redirects, notFound, preload promotion, hydration, background reloads + +### Phase 3. Re-implement from first principles + +Deliverables: + +- explicit lifecycle/generation model in router-core +- React-first adapter integration +- follow-up alignment of Solid and Vue + +## Phase 1: Initial Spec Draft + +This section is the start of phase 1. It should be treated as normative unless superseded by later RFC edits. + +### Terminology + +- Match identity: the concrete `match.id` instance, including route id, concrete pathname, and loader-deps hash. +- Route presence identity: the logical presence of a route in the tree, keyed by `routeId`. +- Active match: a match currently committed to the rendered tree. +- Pending match: a match being prepared for possible promotion to active. +- Cached match: an inactive match retained for reuse. +- Load generation: a single causally ordered attempt to make a match render-ready. +- Effective context: router context plus accumulated parent `context()` values plus accumulated `beforeLoad` returns up to the current match. +- Render gate: the state that determines whether the adapter may render the route component, render pending UI, render not-found UI, render error UI, or suspend. + +### Normative Goals + +1. A render-visible match must never expose incomplete effective context for its own generation. +2. The router must model match loading as explicit generations, so stale completions cannot overwrite newer state. +3. A match must never exist in more than one pool at a time. +4. A render-visible pending or redirected match must retain a valid suspension/render-gate contract for the entire period it is visible. +5. `beforeLoad` execution is serial from root to leaf. +6. Loader execution begins only after the serial `beforeLoad` prefix is established, and loaders may run in parallel after that. +7. The failure that wins for a navigation/preload is the highest-priority failure closest to the root under the defined precedence rules. +8. Cache promotion and reuse must be explicit. Reused data and rerun work must be determined by spec, not by incidental object reuse. +9. Eviction and garbage collection must not invalidate currently rendered or still-needed render gates. +10. Router-core should model routing facts; framework adapters should model framework-specific rendering mechanics. + +### Normative Invariants + +These invariants should later become FizzBee assertions. + +1. Tentative exclusive pool membership + A given `match.id` should ideally be in exactly one of `active`, `pending`, or `cached`, or in none of them. + This is a preferred simplifying invariant for the redesign, but it may be relaxed if it blocks a materially better solution. +2. Generation monotonicity + A completion from generation `N` must not mutate the visible state for generation `N + 1`. +3. Context completeness before render + If a match may render its route component, then its effective context for that generation is complete. +4. Pending continuity + If a match is intentionally rendered as pending, the adapter must always have a valid render gate for it until the match leaves pending display. +5. Redirect continuity + If a match is observed as redirected during a transition, the adapter must still be able to abandon the stale render safely. +6. Root not-found shell preservation + Root not-found must preserve the root shell/layout contract. +7. Ancestor visibility + If a child fails in a way that still requires ancestor UI/head/data to render, the required ancestor work must be preserved. +8. Explicit reuse rules + Reusing a cached or active match must not implicitly reuse stale `beforeLoad` context or loader data unless the spec says it does. + +### Router-Core Versus Adapter Contract + +Router-core should guarantee: + +- pool membership +- generation identity and completion rules +- the final state of each match for a generation +- when context is complete enough for each phase +- whether a match is renderable, pending-renderable, error-renderable, or not-found-renderable + +Adapters should guarantee: + +- how a render gate maps to the framework primitive +- continuity between router-led pending and userland suspense where the framework requires it +- framework-specific shell/error/not-found presentation details +- framework-specific on-mount timing hooks such as React view transitions + +### Phase 1 Decisions That Close The Original Gaps + +The following phase-1 decisions are now treated as settled enough to begin phase 2. + +#### D1. Preload reuse rules + +When a preload later becomes active for the same `match.id`: + +- `beforeLoad` reruns on navigation +- a fresh successful loader result may be reused +- an in-flight preload loader may be adopted by navigation +- a resolved preload redirect/notFound/error is not reusable as success data + +See rules `P4`, `P9`, and `P10`. + +#### D2. Generation-scoped versus match-instance-scoped state + +The phase-2 model should treat the following as match-instance-scoped: + +- `match.id` +- `routeId` +- `pathname` +- `params` +- `search` +- `loaderDeps` +- static route metadata needed for boundary resolution and SSR inheritance + +The phase-2 model should treat the following as generation-scoped: + +- load status +- fetch phase +- effective context +- loader result data +- terminal error/redirect/notFound outcome +- render gate +- abort signal / generation cancellation state +- freshness result for the current generation + +The implementation may store some of these together, but the semantics should remain separated. + +#### D3. Route `context()` semantics + +For spec purposes, route `context()` is recomputed for every load generation after the parent effective context is known and before the current match's `beforeLoad` consumes it. + +An implementation may memoize or structurally share equivalent results, but the observable semantics must match recomputation-per-generation. + +This decision is intentionally spec-first because stale route-context reuse is a likely source of correctness bugs. + +#### D4. Failure precedence + +Failure precedence is defined by the table in the `Failure Precedence Table` section below. + +#### D5. Render-gate ownership split + +Router-core owns semantic render-gate facts such as: + +- not renderable yet +- render pending +- render ready +- render notFound +- render error +- abandon stale generation + +Adapters own the framework mechanism used to realize those facts, such as: + +- thrown promises +- suspense/resource wiring +- `ClientOnly` +- framework-specific boundary placement + +#### D6. Acceptable adapter divergence + +Adapters may diverge in rendering mechanics, but not in observable route-loading semantics. + +Allowed divergence: + +- React throws promises +- Solid uses resources plus suspense +- Vue renders pending directly and avoids unsupported nested suspense assumptions + +Required shared semantics: + +- routing/lifecycle semantics +- cache/reuse/eviction semantics +- failure precedence +- hydration boundary semantics +- boundary ownership and root-shell preservation + +#### D7. Residual non-blocking note + +The tentative exclusive-pool-membership invariant remains preferred, but phase 2 may relax it if doing so leads to a cleaner and safer model. + +### Draft Rule Set: Preload, Cache, Reuse, And Eviction + +This is the third concrete semantic slice of phase 1. + +#### Rule P1. Match identity is route id plus concrete path plus loader-deps identity + +Search params only affect match identity through `loaderDeps`. + +References: + +- `packages/router-core/src/router.ts:1482-1510` + +#### Rule P2. Preload creates cache entries immediately + +`preloadRoute()` creates cache entries at preload start, not only after success. + +References: + +- `packages/router-core/src/router.ts:2799-2824` +- `packages/router-core/tests/load.test.ts:189-200` +- `packages/router-core/tests/load.test.ts:434-445` + +#### Rule P3. Navigation promotes through pending first + +Navigation does not promote cached entries directly to active. Matching first produces a pending tree, then readiness promotes pending to active. + +References: + +- `packages/router-core/src/router.ts:2355-2371` +- `packages/router-core/src/router.ts:2410-2488` + +#### Rule P4. `beforeLoad` and `loader` reuse are intentionally asymmetric + +The target spec keeps the current user-visible asymmetry unless phase-1 work finds a stronger reason to change it: + +- `beforeLoad` reruns on navigation even if a preload already exists for the same match +- loader results may be reused if they are still reusable under freshness and invalidation rules + +References: + +- `packages/router-core/tests/load.test.ts:176-339` +- `packages/router-core/tests/load.test.ts:408-571` +- `packages/router-core/tests/load.test.ts:574-650` + +#### Rule P5. Freshness is mode-specific + +- preload freshness uses `preloadStaleTime` +- navigation freshness uses `staleTime` + +References: + +- `packages/router-core/src/load-matches.ts:796-803` + +#### Rule P6. Staleness alone does not always force reload + +A stale successful match should reload only when at least one of the following is true: + +- explicit same-location reload +- match cause is `enter` +- the route reappears with a different `match.id` +- the match is invalidated +- `shouldReload` says to reload + +References: + +- `packages/router-core/src/load-matches.ts:816-827` +- `packages/router-core/src/router.ts:2402-2406` +- `packages/router-core/tests/load.test.ts:809-865` +- `packages/router-core/tests/load.test.ts:929-1044` + +#### Rule P7. Background stale reload preserves the current renderable match + +If stale reload mode is background, navigation may commit with stale data immediately while the reload continues in the background. + +References: + +- `packages/router-core/src/load-matches.ts:829-850` +- `packages/router-core/src/load-matches.ts:936-955` +- `packages/router-core/tests/load.test.ts:773-807` +- `packages/router-core/tests/load.test.ts:1067-1117` + +#### Rule P8. Blocking stale reload delays activation + +If stale reload mode is blocking, navigation waits for the stale reload before activation. + +References: + +- `packages/router-core/tests/load.test.ts:735-771` +- `packages/router-core/tests/load.test.ts:1078-1100` + +#### Rule P9. In-flight preload loaders are reused by navigation + +If navigation begins while the same preload loader is still in flight, navigation should reuse that in-flight loader rather than start a second one. + +References: + +- `packages/router-core/src/load-matches.ts:892-920` +- `packages/router-core/tests/load.test.ts:434-571` + +#### Rule P10. Resolved preload failures are not reusable success data + +A completed preload whose terminal result is redirect, notFound, or error is not reusable as success data for later navigation. + +References: + +- `packages/router-core/tests/load.test.ts:447-556` + +#### Rule P11. Cache eviction is lazy, not timer-driven + +GC eligibility is time-based, but actual removal happens on later GC passes, not on a live timer. + +References: + +- `packages/router-core/src/router.ts:2476-2488` +- `packages/router-core/src/router.ts:2764-2788` + +#### Rule P12. Error-like terminal states do not remain reusable cache entries + +- exiting active matches in `error`, `notFound`, or `redirected` do not enter reusable cache on commit +- cached matches that become `redirected` are removed from cache + +References: + +- `packages/router-core/src/router.ts:2479-2488` +- `packages/router-core/src/router.ts:2636-2648` + +#### Rule P13. Invalidation applies uniformly across active, pending, and cached matches + +Invalidation marks selected matches stale everywhere, and `error`/`notFound` matches reset to `pending` so they rerun. + +References: + +- `packages/router-core/src/router.ts:2661-2701` + +### Draft Rule Set: Context Visibility + +This is the first concrete semantic slice of phase 1. + +#### Rule C1. Parent route context is available to child `beforeLoad` + +If a parent route modifies context via `context()` or `beforeLoad`, a child `beforeLoad` must observe the updated value. + +Evidence and anchors: + +- `packages/react-router/tests/routeContext.test.tsx:532-574` +- `packages/react-router/tests/routeContext.test.tsx:952-984` +- `packages/router-core/src/load-matches.ts:453-458` + +#### Rule C2. A match's own `beforeLoad` output is not render-visible until that `beforeLoad` resolves + +Current code explicitly avoids updating `match.context` during async `beforeLoad` execution to avoid rendering incomplete context. + +Reference: + +- `packages/router-core/src/load-matches.ts:426-429` + +The target spec should keep the safety property but express it positively: + +- a match may not render its route component until its effective context for that generation is complete +- the match's loader must observe the same effective context that the route component will later observe for that generation + +#### Rule C3. Redirects start a fresh context generation + +If an older destination redirects to a new destination, the new destination's `beforeLoad` must observe the correct effective context for the new destination, independent of the abandoned one. + +Evidence and anchors: + +- `packages/react-router/tests/routeContext.test.tsx:987-1057` +- `packages/router-core/src/load-matches.ts:159-166` + +#### Rule C4. Context coherence must hold across invalidation and sibling navigation + +If `beforeLoad` reruns and loader data reruns or reuses according to policy, the route component and the loader for that generation must remain coherent. + +Evidence and anchors: + +- `packages/router-core/tests/load.test.ts:574-650` +- `packages/react-router/tests/loaders.test.tsx:468-648` + +### Draft Rule Set: Render-Gate Continuity + +This is the second concrete semantic slice of phase 1. + +#### Rule R1. Pending display needs a stable render gate + +If a match is intentionally displayed as pending, the adapter must have a stable render gate for the entire visible pending interval. + +Current React implementation suspends on one of: + +- `displayPendingPromise` +- `minPendingPromise` +- `loadPromise` + +References: + +- `packages/react-router/src/Match.tsx:404-435` +- `packages/router-core/src/ssr/ssr-client.ts:107-129` +- `packages/router-core/src/ssr/ssr-client.ts:272-306` + +The target spec should not depend on these exact promise names, but it must preserve the continuity guarantee they currently try to provide. + +#### Rule R2. Redirected matches still need an abandonment gate + +If React observes a match as `redirected` during an in-flight transition, the stale render must still be able to suspend and get abandoned safely. + +References: + +- `packages/react-router/src/Match.tsx:448-461` +- `packages/react-router/tests/redirect.test.tsx:116-160` + +#### Rule R3. Hydration-only pending behavior is still part of the render contract + +Hydration may need to preserve pending UI even when the normal client-side render path would create timers too late. + +References: + +- `packages/router-core/src/ssr/ssr-client.ts:107-129` +- `packages/router-core/src/ssr/ssr-client.ts:272-306` + +The target design should describe this in terms of render gates, not ad hoc React-specific flags in the core model. + +#### Rule R4. Render gates must outlive visible pool transitions + +Cache promotion, pending-to-active promotion, redirect finalization, and stale background completion must not destroy the active render gate while the adapter can still read it. + +Relevant implementation anchors: + +- `packages/router-core/src/load-matches.ts:115-167` +- `packages/router-core/src/load-matches.ts:925-945` +- `packages/router-core/src/router.ts:2476-2488` + +### Draft Rule Set: Failure Precedence + +This is still provisional, but it is specific enough to guide phase-2 modeling. + +#### Rule F1. Serial `beforeLoad` failures cut off deeper serial work + +If `beforeLoad` fails at match index `i`, deeper `beforeLoad` work does not run for that generation. + +Reference: + +- `packages/router-core/src/load-matches.ts:985-1005` + +#### Rule F2. beforeLoad notFound may still require ancestor loader/head completion + +If a child `beforeLoad` throws `notFound`, ancestor loaders and heads may still be required so the eventual boundary has the required parent data and document head state. + +Evidence and anchors: + +- `packages/router-core/tests/load.test.ts:1170-1307` +- `packages/router-core/tests/load.test.ts:1334-1381` +- `packages/router-core/src/load-matches.ts:1007-1119` + +#### Rule F3. Redirect wins immediately for the current generation + +A redirect aborts the current generation and starts resolution of the redirect target. + +Reference: + +- `packages/router-core/src/load-matches.ts:115-167` + +#### Rule F4. The winning notFound is the boundary-rendered notFound, not merely the throwing route + +The not-found result that matters for rendering is the resolved boundary route, which may differ from the throwing route. + +Reference: + +- `packages/router-core/src/load-matches.ts:80-113` +- `packages/router-core/src/load-matches.ts:1066-1119` + +#### Rule F5. Mixed failure precedence still needs a formal table + +The exact precedence order for mixed redirect/notFound/error outcomes across multiple matches is defined below for phase-2 modeling. + +### Failure Precedence Table + +For a single load generation, the winning outcome is resolved in this order. + +| Rank | Outcome source | Outcome type | Notes | +| ---- | --------------------- | ------------- | ------------------------------------------------------------------------------------------- | +| 1 | serial phase | redirect | params/search validation and `beforeLoad` redirect abort the generation immediately | +| 2 | parallel loader phase | redirect | wins over all non-serial-redirect results | +| 3 | parallel loader phase | regular error | wins over any notFound and over deferred serial regular errors | +| 4 | parallel loader phase | notFound | wins over serial beforeLoad notFound and serial regular errors | +| 5 | serial phase | notFound | provisional during serial phase, final only if no higher-ranked loader result supersedes it | +| 6 | serial phase | regular error | final only if no higher-ranked loader result supersedes it | + +Tie-breakers: + +- within launched loaders, the winner is chosen by lowest match index, not fastest completion time +- explicit `notFound({ routeId })` targets the exact matched boundary if present; otherwise notFound resolution falls back toward root +- root notFound renders via `globalNotFound`, not `status: 'notFound'` + +References: + +- `packages/router-core/src/load-matches.ts:985-1005` +- `packages/router-core/src/load-matches.ts:1007-1055` +- `packages/router-core/src/load-matches.ts:1066-1119` +- `packages/router-core/src/load-matches.ts:1176-1181` +- `packages/router-core/tests/load.test.ts:1170-1432` + +### Failure Precedence Narrative + +TanStack Router resolves failures in two stages: a serial preflight stage and a parallel loader stage. + +- A redirect thrown during the serial stage terminates the generation immediately. +- A serial-stage `notFound` or regular error is provisional: it stops deeper serial work, but eligible ancestor loaders may still run. +- Once loaders settle, loader outcomes are resolved in route-match order with precedence `redirect > error > notFound`. +- If no loader outcome supersedes the provisional serial result, the router finalizes the serial `notFound` or regular error. +- notFound rendering is based on the resolved boundary route, not merely the throwing route. +- root notFound preserves the root shell by using `globalNotFound`. + +### Draft Rule Set: Hydration And No-SSR Rendering + +This is the fourth concrete semantic slice of phase 1. + +#### Rule H1. Data participation and render participation are separate concepts + +The spec distinguishes: + +- did the server provide usable data for this match? +- did the server provide authoritative DOM for this match? + +Current `ssr` modes map as follows: + +- `ssr: true` => server data, server DOM +- `ssr: 'data-only'` => server data, client-owned first meaningful DOM +- `ssr: false` => client-owned data, client-owned first meaningful DOM + +References: + +- `packages/router-core/src/router.ts:154-155` +- `packages/router-core/src/load-matches.ts:263-290` + +#### Rule H2. The first client-rendered match is the hydration boundary + +The first active match whose authoritative DOM is client-owned becomes the hydration boundary that may need forced pending or client-only gating. + +References: + +- `packages/router-core/src/ssr/ssr-client.ts:140-163` + +#### Rule H3. Full SSR hydration does not run an unnecessary client load + +If all matches are fully SSR-backed and hydration is not in SPA mode, client hydration should not run a redundant `router.load()`. + +References: + +- `packages/router-core/src/ssr/ssr-client.ts:249-263` + +#### Rule H4. SPA-mode hydration preserves pending without blocking the root unnecessarily + +If hydration is effectively falling back to SPA-mode, the first non-root client-rendered match may display pending while the router finishes loading, without forcing the whole root tree through an unnecessary initial suspense cycle. + +References: + +- `packages/router-core/src/ssr/ssr-client.ts:265-308` +- `packages/react-router/src/Matches.tsx:55-66` + +#### Rule H5. Adapters may implement pending differently, but observable semantics must match + +Allowed adapter divergence: + +- React may suspend by throwing promises +- Solid may use resources plus suspense +- Vue may render pending directly and must avoid nested suspense assumptions that corrupt DOM + +Required shared semantics: + +- no duplicate initial load during SSR hydration +- hydration-safe fallback for client-rendered matches +- pending remains visible where configured +- SSR inheritance semantics stay intact + +References: + +- `packages/react-router/src/Match.tsx:404-462` +- `packages/solid-router/src/Match.tsx:300-413` +- `packages/vue-router/src/Match.tsx:436-472` +- `packages/vue-router/src/Match.tsx:555-561` + +#### Rule H6. Optional hydration facts must preserve client-derived truth + +Hydration should only overwrite optional facts like `globalNotFound` when the server payload explicitly provided them. + +References: + +- `packages/router-core/src/ssr/ssr-client.ts:30-37` +- `packages/router-core/tests/hydrate.test.ts:222-350` + +### Scenario Rules + +The matrix above is summarized here as explicit rules by entry point. + +#### Initial page load + +- the router computes the full pending tree for the destination +- all `beforeLoad` run serially from root to leaf until cut off by failure +- loaders run for the surviving prefix according to the failure rules above +- activation happens only through pending-to-active promotion + +#### Fully SSR-backed hydration + +- dehydrated matches become the active tree +- route context and head/script data are reconstructed client-side +- no additional client load runs if hydration is fully SSR-backed and not in SPA mode + +#### Hydration with client-rendered boundary + +- the first client-rendered match becomes the hydration boundary +- the adapter may show a hydration-safe fallback for that boundary and below +- forced/display-pending behavior is allowed here to preserve continuity + +#### Client navigation + +- navigation always computes a fresh pending tree +- `beforeLoad` reruns on navigation even when loader results are still reusable +- activation and exiting-cache behavior follow the cache rules above + +#### Preload + +- preload may create cache entries before success +- preload never commits active UI directly +- in-flight preload loader work may be adopted by a later navigation for the same match + +#### Redirect during navigation or preload + +- redirect terminates the current generation according to the precedence table +- redirect starts target resolution as a fresh generation +- stale redirected renders must still retain a valid abandonment gate until discarded + +#### beforeLoad notFound + +- deeper serial work stops immediately +- ancestor loaders and heads may still need to run so the boundary can render correctly +- boundary selection is based on the resolved notFound boundary, not just the throwing route + +#### Background stale reload + +- the current active match remains renderable while background reload continues +- late completion from background reload must not clobber a newer generation + +#### Invalidation + +- invalidation applies to active, pending, and cached entries uniformly +- invalidation marks matches stale and may reset terminal error/notFound matches to pending + +#### GC and eviction + +- eviction is lazy and only removes GC-eligible cached entries +- eviction must not break any still-visible or still-needed render gate + +### Phase 1 Coverage And Gaps + +Coverage already anchoring the spec: + +- route context visibility in `beforeLoad` and loader: `packages/react-router/tests/routeContext.test.tsx:447-1057`, `packages/react-router/tests/loaders.test.tsx:468-648` +- navigation/preload/cache/reload rules: `packages/router-core/tests/load.test.ts:176-1117` +- notFound hierarchy and head behavior: `packages/router-core/tests/load.test.ts:1170-1882` +- hydration and `globalNotFound`: `packages/router-core/tests/hydrate.test.ts:222-396` +- pending/redirect UI regressions: `packages/react-router/tests/router.test.tsx:2337-2576`, `packages/react-router/tests/redirect.test.tsx:116-160` + +Important remaining gaps to close during implementation: + +- explicit tests for mixed loader error vs serial beforeLoad notFound precedence +- explicit tests for generation safety during background reload plus fast subsequent navigation +- explicit adapter-level tests for hydration boundary semantics across React, Solid, and Vue +- explicit tests for promise/render-gate continuity when pool membership changes + +## Scenario Matrix + +This is the first pass of the phase-1 inventory. It is intentionally broad so later sessions can drill into each cell. + +| Scenario | Match creation/reuse | beforeLoad | loader | cache/promotion | render gate | failure handling | +| --------------------------------------------- | ------------------------------------------------------- | ------------------------------------ | ----------------------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------- | +| Initial page load | all next matches created or reused | serial root to leaf | parallel after serial prefix | may reuse fresh cached data | may show pending depending on route/router defaults | redirect/notFound/error may prevent full tree mount | +| SSR hydration, fully SSR-backed | matches hydrated from server payload | may be skipped on first client pass | may be skipped on first client pass | hydrated matches become active immediately | avoid hydration mismatch; no extra pending UI unless needed | hydration-time errors/notFound still need defined behavior | +| SSR hydration with `ssr: false` / `data-only` | first non-SSR match becomes special | may need rerun on client | may need rerun on client | hydrated prefix may coexist with client-only suffix | pending continuity must survive hydration | redirect/notFound/error cannot corrupt hydrated prefix | +| Client navigation | pending tree derived from next location | serial root to leaf | parallel | active matches may be preserved; exiting matches may cache | pending may appear late or immediately | winning failure must be deterministic | +| Preload | target tree may be loaded into cache only | serial root to leaf | parallel | later navigation may promote or rerun | no active render, but render-gate facts may still matter later | preload redirect/notFound/error must not poison active tree | +| Redirect during navigation | next location may supersede older generation | may come from `beforeLoad` | may come from loader | stale work must not win later | stale render must abandon safely | redirect must preserve target navigation semantics | +| beforeLoad notFound | partial tree may still need ancestors | serial failure truncates deeper work | ancestors may still need loader/head work | no accidental cache poisoning | boundary route must be known | nearest valid boundary and root shell rules must hold | +| Background stale reload | active match remains visible | usually reruns serial prefix first | loader may continue in background | cached/active data remains usable | current render gate stays stable | late error/redirect must not clobber newer generation | +| Invalidation | existing active/cached matches are marked stale/pending | reruns according to spec | reruns according to spec | reuse rules must be explicit | active UI may remain while reload happens | previous error/notFound state must reset correctly | +| GC/eviction | inactive cached matches may drop | n/a | n/a | must not evict still-needed matches | no visible render gate may break | eviction cannot affect active/pending generations | + +## Phase 2 Bootstrap + +Phase 1 is complete enough to start modeling. + +The goal of phase 2 is not to encode React, Solid, or Vue internals directly. The goal is to model router-core semantics plus an abstract render-gate contract that all adapters must satisfy. + +Recommended first model file: `docs/router/route-match-loading.fizz` + +### Recommended first model scope + +Start with a deliberately small model. + +- at most 3 matched indices: root, parent, leaf +- at most 1 active generation and 1 next generation at a time +- support these entry points first: initial load, navigation, preload, redirect, beforeLoad notFound, background stale reload, hydration with one client-rendered boundary +- ignore code-splitting details at first except as a boolean “chunk needed before render-ready” fact +- model userland suspense only as an adapter-side opaque condition, not as part of router-core state + +### Recommended model vocabulary + +Use these terms in the first FizzBee model. + +- match instance +- load generation +- active tree +- pending tree +- cached entries +- effective context +- freshness +- boundary owner +- hydration boundary +- render gate +- terminal outcome + +### Recommended abstract state + +The first model should represent at least the following facts. + +- `matches_by_id` + Match instance facts: `routeId`, `pathnameShape`, `loaderDepsKey`, boundary capabilities, SSR mode. +- `pool_by_match_id` + `active`, `pending`, `cached`, or `none`. +- `generation_by_match_id` + Current generation number or token for that match instance. +- `status_by_match_id` + `idle`, `beforeLoad`, `loading`, `ready`, `error`, `redirected`, `notFound`. +- `context_state_by_match_id` + `unknown`, `parent_ready`, `ready`. +- `loader_state_by_match_id` + `not_started`, `in_flight`, `success`, `error`, `redirect`, `notFound`. +- `render_gate_by_match_id` + `blocked`, `pending`, `ready`, `error`, `notFound`, `abandon`. +- `freshness_by_match_id` + `fresh`, `stale`, `invalid`. +- `hydration_mode_by_match_id` + `server_dom`, `data_only`, `client_only`. +- generation-level facts: + - current entry point + - serial cursor for `beforeLoad` + - launched loader set + - provisional serial failure, if any + - winning final outcome, if any + +### Recommended first actions + +The first model should include actions equivalent to: + +1. `InitInitialLoad` +2. `InitNavigation` +3. `InitPreload` +4. `InitHydration` +5. `RunBeforeLoadStep` +6. `ResolveBeforeLoadSuccess` +7. `ResolveBeforeLoadRedirect` +8. `ResolveBeforeLoadNotFound` +9. `ResolveBeforeLoadError` +10. `LaunchEligibleLoaders` +11. `ResolveLoaderSuccess` +12. `ResolveLoaderRedirect` +13. `ResolveLoaderNotFound` +14. `ResolveLoaderError` +15. `FinalizeWinningOutcome` +16. `PromotePendingTree` +17. `StartBackgroundReload` +18. `CompleteBackgroundReload` +19. `InvalidateMatch` +20. `EvictCachedMatch` + +Hydration-specific actions can be added immediately after the first model passes the core assertions: + +- `HydrateMatchFromServer` +- `MarkHydrationBoundary` +- `EnterDisplayPending` +- `ExitDisplayPending` + +### Recommended first assertions + +The first FizzBee model should prove these assertions. + +1. Generation safety + A completion from an older generation never changes the winning visible outcome of a newer generation. +2. Context completeness + A match with render gate `ready` always has effective context `ready` for that generation. +3. Redirect abandonment safety + A redirected stale generation never becomes render gate `ready` again. +4. Pending continuity + A match with render gate `pending` never loses its ability to remain pending until it transitions to another valid gate. +5. Failure precedence + For any generation, the final winning outcome matches the precedence table in this RFC. +6. Boundary correctness + A finalized notFound always resolves to the correct rendered boundary owner. +7. Root shell preservation + Root notFound never requires replacing the root shell with a non-root-style notFound state. +8. Reuse correctness + Reused preload/cache data is only observed in cases permitted by rules `P4`, `P9`, and `P10`. + +### Recommended first trace checklist + +The first guided traces should cover at least: + +1. initial load success +2. initial load with parent beforeLoad modifying child context +3. preload success followed by navigation reuse +4. preload in flight followed by navigation adoption +5. beforeLoad notFound with ancestor loader/head preservation +6. redirect while pending is already visible +7. stale background reload followed by a faster next navigation +8. hydration with one `data-only` boundary + +### Recommended first FizzBee config + +The first model should stay intentionally small. + +- `max_concurrent_actions: 2` +- small bounded route tree depth +- small bounded generation count +- no crash injection at first +- BFS exploration first, then guided traces for the interesting races + +### Recommended first implementation boundary after the model exists + +Once the first model passes, phase 3 should begin by implementing explicit generation tracking and semantic render gates in router-core before touching adapter-specific mechanics. + +## Phase 1 Exit Status + +Phase 1 is considered complete for now because this RFC now contains: + +- a shared vocabulary +- explicit normative goals and invariants +- explicit rules for context visibility +- explicit rules for render-gate continuity +- explicit rules for preload/cache/reuse/background reload/eviction +- an explicit failure-precedence table +- hydration and no-SSR semantics plus adapter constraints +- scenario rules by entry point +- a phase-2 modeling bootstrap with state, actions, assertions, and trace coverage + +Any remaining uncertainty is narrow enough to be resolved inside phase 2 while modeling, rather than blocking phase 2 from starting. + +## Notes For Later Agents + +- Treat this document as the source of truth for coordination until a successor RFC replaces it. +- Prefer editing this RFC incrementally instead of scattering planning notes across new files. +- When current code and this RFC disagree, preserve the disagreement in the RFC and treat it as an explicit design decision to resolve, not as a reason to silently follow the current implementation. +- The most important unresolved seam is the implicit state machine spread across `router.ts`, `load-matches.ts`, hydration, and the framework adapters. From c100a865bcdf3e9aafd30f416976813fca609364 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 12 Apr 2026 13:39:01 +0200 Subject: [PATCH 2/9] fizzbee skills --- .agents/skills/fizz-check/SKILL.md | 224 ++++++++++++++++++++ .agents/skills/fizz-debug/SKILL.md | 228 ++++++++++++++++++++ .agents/skills/fizz-mbt/SKILL.md | 314 ++++++++++++++++++++++++++++ .agents/skills/fizz-spec/SKILL.md | 325 +++++++++++++++++++++++++++++ 4 files changed, 1091 insertions(+) create mode 100644 .agents/skills/fizz-check/SKILL.md create mode 100644 .agents/skills/fizz-debug/SKILL.md create mode 100644 .agents/skills/fizz-mbt/SKILL.md create mode 100644 .agents/skills/fizz-spec/SKILL.md diff --git a/.agents/skills/fizz-check/SKILL.md b/.agents/skills/fizz-check/SKILL.md new file mode 100644 index 0000000000..8715b8dc20 --- /dev/null +++ b/.agents/skills/fizz-check/SKILL.md @@ -0,0 +1,224 @@ +--- +name: fizz-check +description: > + Run the FizzBee model checker or simulator on a .fizz spec. Use when the + user wants to verify a spec, run the model checker, simulate behavior, + check a guided trace, or interpret model checker output. +--- + +# FizzBee Model Checker + +## Installation + +```bash +brew tap fizzbee-io/fizzbee && brew install fizzbee +``` + +## Running + +```bash +fizz spec.fizz # full model checking (exhaustive) +fizz -x --max_runs 1 --seed 42 spec.fizz # simulation (single random path) +``` + +Note: `fizz` is the installed binary. If building from source, use `./fizz` (wrapper script in the repo root). + +--- + +## All Flags + +| Flag | Default | Description | +| -------------------------- | ---------------- | --------------------------------------------------------- | +| `-x` / `--simulation` | off | Simulation mode: single random path, fast | +| `--seed N` | 0 | Random seed for reproducible simulation | +| `--max_runs N` | 0 (unlimited) | Number of simulation runs | +| `--exploration_strategy` | `bfs` | State exploration: `bfs`, `dfs`, or `random` | +| `--trace "line1\nline2"` | — | Guided trace: follow specific action sequence | +| `--trace-file FILE` | — | Load guided trace from file | +| `--trace-extend N` | 0 | After trace, explore N more steps (shows enabled actions) | +| `--preinit-hook "STMT"` | — | Override constants before Init runs | +| `--preinit-hook-file FILE` | — | Load preinit hook from `.cfg` file | +| `--output-dir DIR` | auto-timestamped | Where to write output | +| `--no-copy-ast` | off | Don't copy AST to output dir | + +--- + +## Understanding Output + +``` +Model checking specs/counter.json +StateSpaceOptions: options:{max_actions:100 max_concurrent_actions:2} +Nodes: 12, queued: 0, elapsed: 2.1ms +Valid Nodes: 12 Unique states: 8 +IsLive: true +PASSED: Model checker completed successfully +``` + +- **Nodes**: total graph nodes explored +- **Valid Nodes**: nodes that passed all safety assertions +- **Unique states**: distinct system states (after symmetry reduction) +- **IsLive**: liveness assertions passed +- **PASSED / FAILED**: overall result + +Output files go to `/out/run_/`: + +- `graph.dot` — state graph (auto-generated for < 250 nodes) +- `communication.dot` — role interaction diagram +- Node/link JSON files for the explorer + +Convert to SVG for visual inspection: + +```bash +dot -Tsvg out/*/graph.dot -o graph.svg && open graph.svg +``` + +--- + +## Simulation Mode + +Good for: sanity-checking, exploring behavior, testing at realistic scale. + +```bash +fizz -x --max_runs 1 --seed 42 spec.fizz +``` + +Extract the transition sequence from the output: + +```bash +grep -o 'label="[^"]*"' out/*/graph.dot | sed 's/.*label="//;s/"//' +``` + +Try several seeds to find interesting behaviors: + +```bash +for seed in 1 2 3 7 13 42; do + fizz -x --max_runs 1 --seed $seed spec.fizz +done +``` + +--- + +## Guided Traces + +Force a specific action sequence to test a scenario: + +```bash +fizz --trace "Server.Write +Any:key=1 +Client.Read" spec.fizz +``` + +**Trace format rules:** + +- One transition per line +- `#` comments and blank lines are ignored +- Init is automatic — don't include it +- The `[fn.call]` suffix from simulation output can be omitted +- `Any:varname=value` lines specify nondeterministic choices + +**Explore what comes next with `--trace-extend`:** + +```bash +fizz --trace "Server.Write +Any:key=1" --trace-extend 2 spec.fizz +# Shows all enabled actions 2 steps beyond the trace +``` + +**Use a file for longer traces:** + +```bash +# mytrace.txt +# Step 1: acquire lock +Node#0.RequestLock +# Step 2: do work +Node#0.DoWork +# Step 3: release +Node#0.ReleaseLock + +fizz --trace-file mytrace.txt spec.fizz +``` + +**Incomplete trace warning:** If you see `WARNING: Trace execution incomplete`, a `require` guard blocked execution. This is often a bug in the spec. + +--- + +## Configuration Overrides + +### Spec options (deadlock_detection, max_concurrent_actions, etc.) + +Checker options go in YAML frontmatter inside the `.fizz` file or in a separate `fizz.yaml`. Prefer frontmatter to keep config and spec together, unless sharing config across multiple specs: + +``` +--- +deadlock_detection: false +options: + max_concurrent_actions: 1 + crash_on_yield: true +--- +# rest of the spec... +``` + +### Constant overrides (preinit-hook) + +Override constants without editing the spec — useful for testing different configurations: + +```bash +# Inline override +fizz --preinit-hook "MAX_ITEMS = 3 +NUM_CLIENTS = 2" spec.fizz + +# From file (.cfg extension — NOT .star, which auto-imports as a module) +fizz --preinit-hook-file small.cfg spec.fizz +``` + +All builtins available in the hook: `symmetry`, `record`, `enum`, `bag`, `math`, etc. + +**Strategy: use small configs for model checking, large configs for simulation.** + +```bash +# Model check with minimal config (isolate each concern) +fizz --preinit-hook "NUM_CLIENTS=2 +NUM_SERVERS=1" spec.fizz + +# Simulate with realistic config (no state explosion) +fizz -x --max_runs 1 --seed 42 --preinit-hook "NUM_CLIENTS=100 +NUM_SERVERS=10" spec.fizz +``` + +--- + +## Common Workflows + +### Verify a new spec + +```bash +# 1. Quick simulation sanity check +fizz -x --max_runs 1 --seed 42 spec.fizz + +# 2. Check key scenarios with guided traces +fizz --trace "..." spec.fizz + +# 3. Full model check with small config +fizz --preinit-hook "N=2" spec.fizz + +# 4. If FAILED: reduce config and visualize +fizz --preinit-hook "N=1" spec.fizz +dot -Tsvg out/*/graph.dot -o graph.svg && open graph.svg +``` + +### Baseline comparison + +Reference examples include `baseline.txt` files with expected state counts. +Compare your output's `Nodes`, `Valid Nodes`, `Unique states` against the baseline. + +--- + +## Verification Checklist + +1. Simulate: `fizz -x --max_runs 1 --seed N spec.fizz` — try 3-5 seeds +2. Guided traces for key scenarios (happy path, race conditions, edge cases) +3. Config variants: small configs for model checking, large for simulation +4. Full model check: verify PASSED + state counts make sense +5. If < 250 nodes: visualize with `dot -Tsvg` + +**Full guide**: `~/.claude/skills/fizzbee-docs/VERIFICATION_GUIDE.md` diff --git a/.agents/skills/fizz-debug/SKILL.md b/.agents/skills/fizz-debug/SKILL.md new file mode 100644 index 0000000000..57f6f6ac9e --- /dev/null +++ b/.agents/skills/fizz-debug/SKILL.md @@ -0,0 +1,228 @@ +--- +name: fizz-debug +description: > + Debug a FizzBee spec that fails, produces unexpected results, is too slow, + or has an incorrect state space. Use when the model checker reports FAILED, + a trace is incomplete, state counts are wrong, or the spec is timing out. +--- + +# FizzBee Debugging Guide + +**Full references**: `~/.claude/skills/fizzbee-docs/VERIFICATION_GUIDE.md`, `~/.claude/skills/fizzbee-docs/GOTCHAS.md`, `~/.claude/skills/fizzbee-docs/PERFORMANCE_GUIDE.md` + +--- + +## When Model Checker Reports FAILED + +A FAILED result means a safety assertion was violated. The output includes a counterexample trace. + +**Step 1: Read the failing trace** + +The output shows the sequence of actions that led to the violation. Look at: + +- Which assertion failed (`AlwaysFoo`, `BalanceNonNegative`, etc.) +- What state variables were when it failed +- What action just ran before the failure + +**Step 2: Reproduce with a guided trace** + +Copy the failing action sequence and replay it: + +```bash +fizz --trace "Node#0.RequestLock +Node#1.RequestLock +Node#0.DoWork" spec.fizz +``` + +Add `--trace-extend 1` to see what enabled actions exist at each step: + +```bash +fizz --trace "Node#0.RequestLock" --trace-extend 1 spec.fizz +``` + +**Step 3: Reduce config to minimum** + +Shrink the state space so you can visualize it: + +```bash +fizz --preinit-hook "N=1" spec.fizz +dot -Tsvg out/*/graph.dot -o graph.svg && open graph.svg +# Graph auto-generated when < 250 nodes +``` + +In the SVG, look for: + +- The state where the assertion fails (highlighted) +- What changed in the step before failure + +--- + +## When Trace Is Incomplete + +``` +WARNING: Trace execution incomplete. Expected 8 links, executed 6 links. +``` + +A transition in your trace was blocked. Most common causes: + +1. A `require` guard failed — a condition you expected to be true wasn't +2. A symmetry limit was exceeded (e.g., `limit=2` but trace creates 3 distinct values) +3. The action name in the trace doesn't match (case-sensitive, exact match) + +Debug by running the trace up to the failing step and using `--trace-extend 1` to see what's actually enabled: + +```bash +fizz --trace "Step1 +Step2" --trace-extend 1 spec.fizz +``` + +--- + +## When Behavior Seems Wrong (But PASSED) + +The model may be over-constraining (silent pruning) or assertions may be tautological. + +**Check with simulation:** + +```bash +for seed in 1 2 3 7 13 42; do + fizz -x --max_runs 1 --seed $seed spec.fizz + # Extract transitions + grep -o 'label="[^"]*"' out/*/graph.dot | sed 's/.*label="//;s/"//' +done +``` + +**Ask:** Are all expected actions appearing? If an action never fires: + +- Check `require` guards — is the condition too tight? +- Check enabling conditions — does the action body execute a simple statement? +- Remember: `any empty_list` disables the action + +**Write a guided trace for the missing scenario:** + +```bash +fizz --trace "ActionThatShouldHappen" spec.fizz +# If incomplete: the action's require guard is blocking it +``` + +--- + +## When State Count Is Unexpectedly Large + +**Check symmetry configuration:** + +- Are symmetric role instances stored in `bag()` or `list()`? Lists break symmetry — use `bag()`. +- Are symmetry limits too loose? Limit = max _coexisting_ values, not total ever created. +- Are old symmetric values being cleaned up? + +```python +# Wrong: list breaks symmetry +workers = [] +workers.append(Worker()) # BAD + +# Right: bag preserves symmetry +workers = bag() +workers.add(Worker()) # GOOD +``` + +**Apply performance techniques:** + +Replace for-loops with list comprehensions (35-45% fewer nodes): + +```python +# Slow: multiple statements, multiple yield points +result = [] +for item in items: + if item.active: + result.append(item) + +# Fast: single expression, single yield point +result = [item for item in items if item.active] +``` + +Replace loop+require with `require all([...])`: + +```python +# Slow +for a in appointments: + require not (a.slot == slot and a.day == day) + +# Fast +require all([not (a.slot == slot and a.day == day) for a in appointments]) +``` + +Use smaller configs for model checking: + +```bash +fizz --preinit-hook "N=2" spec.fizz # instead of N=5 +``` + +--- + +## When Model Checker Times Out or Uses Too Much Memory + +**Reduce config first:** + +```bash +fizz --preinit-hook "N=1 +SLOTS=1 +WINDOW=1" spec.fizz +``` + +**Check for state space explosion causes:** + +1. Non-atomic loops — convert to comprehensions or `atomic for` +2. Loose symmetry limits — tighten them +3. Too many concurrent actions — add `max_concurrent_actions: 1` for single-user models +4. Missing cleanup of old symmetric values + +**Use DFS instead of BFS to find bugs faster:** + +```bash +fizz --exploration_strategy dfs spec.fizz +``` + +DFS finds counterexamples faster; BFS finds the shortest ones. + +**Profile the spec:** + +- Run with `--max_runs 1` simulation first to get a baseline time +- Comment out assertions one by one to find which one is slow +- Use `fizz --internal_profile spec.fizz` for internal profiling + +--- + +## Common Gotchas Checklist + +| Symptom | Likely Cause | Fix | +| -------------------------------------- | --------------------------------------- | ------------------------------------- | +| `fizz functions can only be called...` | `self.x = role.fn()` | Use `tmp = role.fn(); self.x = tmp` | +| Action never fires | `any empty_list` or `require` too tight | Check guards | +| Symmetry not working | Symmetric roles in a `list` | Use `bag()` | +| Role Init fails to see global | Global created after role | Reorder: create globals first | +| Transition assertion fails on startup | Missing stutter-step check | Add `if before.x != after.x:` | +| `for k, v in dict.items()` error | Tuple unpacking not supported | `for k in d: v = d[k]` | +| Model passes but wrong | `require` used instead of assertion | Use `always assertion` for invariants | + +**Full gotchas list**: `~/.claude/skills/fizzbee-docs/GOTCHAS.md` + +--- + +## Debugging Workflow Summary + +```bash +# 1. Reproduce failure with minimal config +fizz --preinit-hook "N=1" spec.fizz + +# 2. Visualize (works when < 250 nodes) +dot -Tsvg out/*/graph.dot -o graph.svg && open graph.svg + +# 3. Guided trace to isolate the path +fizz --trace "Step1\nStep2\nStep3" spec.fizz + +# 4. Explore beyond the trace +fizz --trace "Step1\nStep2" --trace-extend 2 spec.fizz + +# 5. Simulate to explore behavior +fizz -x --max_runs 1 --seed 42 spec.fizz +``` diff --git a/.agents/skills/fizz-mbt/SKILL.md b/.agents/skills/fizz-mbt/SKILL.md new file mode 100644 index 0000000000..5187f604fd --- /dev/null +++ b/.agents/skills/fizz-mbt/SKILL.md @@ -0,0 +1,314 @@ +--- +name: fizz-mbt +description: > + Create model-based tests (MBT) connecting a FizzBee spec to a real system + under test (SUT). Use when the user has a .fizz spec and wants to generate + and run tests against a TypeScript/Playwright UI, Go service, Rust library, + or Java application. Also use when working with fizzbee-mbt adapter code + in any of these languages. +--- + +# FizzBee Model-Based Testing (MBT) + +FizzBee MBT generates exhaustive test sequences from a verified Fizz spec and runs them against the real system under test (SUT). + +**Examples**: https://github.com/fizzbee-io/fizzbee-mbt-examples + +## Installation + +```bash +# fizzbee (model checker) +brew tap fizzbee-io/fizzbee && brew install fizzbee + +# fizzbee-mbt (test runner + server) +brew tap fizzbee-io/fizzbee-mbt && brew install fizzbee-mbt +``` + +--- + +## Language Support Overview + +| Feature | TypeScript | Go | Rust | Java | +| --------------------------- | --------------- | --- | ---- | ---- | +| Sequential testing | ✓ | ✓ | ✓ | ✓ | +| Concurrent testing | ✓ (cooperative) | ✓ | ✓ | ✓ | +| StateGetter | ✓ | ✓ | ✓ | ✓ | +| SnapshotStateGetter | ✓ | ✓ | ✓ | ✓ | +| Sentinel values (IGNORE) | ✓ | ✓ | ✓ | ✓ | +| AfterActionHook | ✓ | — | — | — | +| OverridesProvider (fuzzing) | ✓ | — | — | — | +| Playwright utilities | ✓ | — | — | — | + +TypeScript and Go have the broadest feature support. TypeScript is the primary language for UI/E2E testing. + +--- + +## Workflow + +1. Write and verify the `.fizz` spec: `fizz spec.fizz` → PASSED +2. Scaffold: `fizz mbt-scaffold --lang --gen-adapter --out-dir spec.fizz` +3. Implement the adapter methods +4. Start the MBT server: `fizzbee-mbt-server --states_file out/run_/` +5. Run tests + +--- + +## Scaffold Commands + +```bash +# TypeScript +fizz mbt-scaffold --lang typescript --gen-adapter --out-dir src/fizztests/ spec.fizz + +# Go +fizz mbt-scaffold --lang go --go-package myapp --gen-adapter --out-dir fizztests/ spec.fizz + +# Rust +fizz mbt-scaffold --lang rust --gen-adapter --out-dir src/fizztests/ spec.fizz + +# Java +fizz mbt-scaffold --lang java --java-package org.example.myapp --gen-adapter --out-dir fizztests/ spec.fizz +``` + +Three files are generated per spec: + +| File | Description | Edit? | +| ---------------------------- | --------------------------------- | ------- | +| `*_interfaces.ts/go/rs/java` | Role + model interfaces from spec | No | +| `*_adapters.ts/go/rs/java` | Stub methods to implement | **Yes** | +| `*_test.ts/go/rs/java` | Test runner wiring | No | + +--- + +## TypeScript / Playwright + +### Setting Up + +```bash +npm install @fizzbee/mbt +``` + +### Model Structure + +```typescript +import { + Model, + Role, + StateGetter, + AfterActionHook, + OverridesProvider, + OverridesBuilder, + FuzzOptions, + Arg, + IGNORE, + ignored, +} from '@fizzbee/mbt' +import { waitForDOMSettled } from '@fizzbee/mbt/playwright' + +export class MyModelAdapter + implements MyModel, AfterActionHook, OverridesProvider +{ + private page?: Page + + async init(): Promise { + // Called before each test run — set up browser page, reset app state + this.page = await browser.newPage() + await this.page.goto('http://localhost:3000') + } + + async cleanup(): Promise { + // Called after each test run — close the page + await this.page?.close() + } + + async cleanupAll(): Promise { + // Called once at the very end — close the browser + await browser.close() + } + + // Called after every action — wait for UI to settle + async afterAction(): Promise { + await waitForDOMSettled(this.page!, { debounceTimeout: 1 }) + } + + async getRoles(): Promise> { + return new Map([['MyRole#0', this.myRole]]) + } +} +``` + +### Playwright Best Practices + +**Use `waitForDOMSettled`, never `waitForTimeout` or `slowMo`:** + +```typescript +// ✓ Precise: waits for DOM mutations to stop +await waitForDOMSettled(page, { debounceTimeout: 1 }) + +// ✗ Fragile: arbitrary delay, flaky on slow machines +await page.waitForTimeout(500) +``` + +**Use role-based and test-ID locators, not CSS selectors:** + +```typescript +// ✓ Semantic locators — survive UI refactors +const input = page.getByRole('textbox', { name: 'What needs to be done?' }) +const item = page.getByTestId('todo-item').nth(index) +const btn = item.getByRole('button', { name: 'Delete' }) + +// ✗ Brittle — breaks on class/structure changes +const item = page.locator('.todo-item').nth(index) +``` + +**Do not use `expect` assertions in adapter actions.** FizzBee drives the assertions from the spec's `always assertion` blocks and state comparison — `expect` in the adapter fights against that model. Just execute the action: + +```typescript +async actionUserAddsItem(args: Arg[]): Promise { + const title = args[0].toString(); + await page.getByRole('textbox', { name: 'What needs to be done?' }).fill(title); + await page.getByRole('textbox', { name: 'What needs to be done?' }).press('Enter'); + // No expect() here — FizzBee handles validation +} +``` + +**Use `getState()` to expose DOM/storage state for assertion:** + +```typescript +async getState(): Promise> { + const items = await page.evaluate(() => { + const stored = localStorage.getItem('todos'); + return stored ? JSON.parse(stored) : []; + }); + + const todos = new Map(); + for (const item of items) { + todos.set(ignored(), { // ignored() = unique placeholder key + id: IGNORE, // IGNORE = field not compared + title: item.title, + completed: item.completed, + }); + } + return { todos }; +} +``` + +**No parallel tests for UI:** + +```typescript +export function getTestOptions(): Record { + return { + 'max-seq-runs': 1000, + 'max-parallel-runs': 0, // Playwright is not thread-safe + 'max-fuzz-seq-runs': 4, + 'max-actions': 10, + } +} +``` + +### Sentinel Values + +Use when state contains non-deterministic or intentionally ignored fields: + +```typescript +import { IGNORE, ignored } from '@fizzbee/mbt' + +// IGNORE: field exists but value is not compared (e.g. DB-generated IDs) +return { id: IGNORE, title: 'Buy milk', done: false } + +// ignored(): unique placeholder for map keys that aren't compared +// Use a fresh ignored() per entry so the map has the right size +const todos = new Map() +todos.set(ignored(), { title: 'Buy milk', completed: false }) +todos.set(ignored(), { title: 'Walk dog', completed: true }) +return { todos } +``` + +### Fuzzing with OverridesProvider + +Override Fizz constants with generated test data: + +```typescript +import fc from 'fast-check'; +import { OverridesBuilder, FuzzOptions, Tuple } from '@fizzbee/mbt'; + +provideOverrides(builder: OverridesBuilder, options: FuzzOptions): void { + // Generate diverse inputs using fast-check, reproducible via seed + const samples = fc.sample( + fc.string({ unit: 'grapheme', minLength: 1, maxLength: 30 }), + { seed: options.seed, numRuns: 3 } + ); + builder.setTuple('TODO_STRINGS', new Tuple(...samples)); +} +``` + +The Fizz spec defines `TODO_STRINGS` as a constant; the override replaces it per fuzz run with generated values. + +--- + +## Go + +```go +type MyRoleAdapter struct { sut *MySUT } + +func (a *MyRoleAdapter) ActionDoThing(args []mbt.Arg) (any, error) { + return nil, a.sut.DoThing(context.Background()) +} + +// Optional: expose state for assertions +func (a *MyRoleAdapter) GetState() (map[string]any, error) { + v, err := a.sut.GetValue() + return map[string]any{"value": v}, err +} + +type MyModelAdapter struct { role *MyRoleAdapter } + +func (m *MyModelAdapter) Init() error { + m.role = &MyRoleAdapter{sut: NewMySUT()} + return nil +} +func (m *MyModelAdapter) Cleanup() error { return m.role.sut.Close() } +func (m *MyModelAdapter) GetState() (map[string]any, error) { + return nil, mbt.ErrNotImplemented +} +func (m *MyModelAdapter) GetRoles() (map[mbt.RoleId]mbt.Role, error) { + return map[mbt.RoleId]mbt.Role{ + {RoleName: "MyRole", Index: 0}: m.role, + }, nil +} +``` + +Run tests: + +```bash +# Terminal 1 +fizzbee-mbt-server --states_file specs/out/run_/ + +# Terminal 2 +go test ./fizztests +go get github.com/fizzbee-io/fizzbee/mbt/lib/go +``` + +--- + +## Starlark → Host Language Type Mapping + +| Starlark | TypeScript | Go | Rust | +| -------------------- | -------------------- | ---------------- | ----------------------- | +| `int` | `number` (int) | `int64` | `i64` | +| `float` | `number` | `float64` | `f64` | +| `bool` | `boolean` | `bool` | `bool` | +| `string` | `string` | `string` | `String` | +| `list`/`tuple`/`set` | `any[]` | `[]any` | `Vec` | +| `dict` | `Map` | `map[any]any` | `HashMap` | +| `None` | `null` | `nil` | `None` | +| record/struct | `Record` | `map[string]any` | `HashMap` | + +--- + +## Implementation Tips + +- Implement `Init()` + `getRoles()` first, run tests, then implement actions one by one +- Return `NotImplementedError` / `mbt.ErrNotImplemented` for unimplemented actions — the runner skips them rather than failing +- Keep `cleanup()` lightweight — it runs between every test trace +- Keep `cleanupAll()` for expensive teardown (close browser, connection pool) — runs once at end +- For concurrent testing: if the SUT isn't thread-safe, set `max-parallel-runs: 0` diff --git a/.agents/skills/fizz-spec/SKILL.md b/.agents/skills/fizz-spec/SKILL.md new file mode 100644 index 0000000000..0dbc2ef62f --- /dev/null +++ b/.agents/skills/fizz-spec/SKILL.md @@ -0,0 +1,325 @@ +--- +name: fizz-spec +description: > + Write, edit, or review FizzBee (.fizz) specifications for model checking + distributed systems. Use when the user asks to model a system, write a + formal spec, define invariants or liveness properties, or when working + with a .fizz file. +--- + +# FizzBee Spec Writing + +FizzBee is a Python-like formal spec language built on Starlark. Specs model distributed systems; the model checker exhaustively verifies safety and liveness properties. + +**Full reference**: `~/.claude/skills/fizzbee-docs/LANGUAGE_REFERENCE.md` +**Examples index**: `~/.claude/skills/fizzbee-docs/README.md` + +## Installation + +```bash +brew tap fizzbee-io/fizzbee && brew install fizzbee +# Then run: fizz spec.fizz +``` + +--- + +## File Structure + +```yaml +--- +# Optional YAML frontmatter +options: + max_actions: 100 + max_concurrent_actions: 2 # 1 for single-user apps + crash_on_yield: true # enable fault injection + +action_options: + 'RoleName.ActionName': + max_actions: 10 + +deadlock_detection: true # false for interactive apps +liveness: strict +--- +``` + +Then the Fizz spec: + +1. Top-level constants +2. Functions (pure helpers) +3. Roles (actors/processes) +4. Top-level actions (Init + others) +5. Assertions + +--- + +## Core Syntax + +### Constants and Global State + +```python +MAX = 10 # constant +State = enum('IDLE', 'RUNNING') # enum + +action Init: + counter = 0 # becomes global state variable + items = [] + server = Server() # create role instance +``` + +### Actions + +```python +# Modifier order: [flow] [fairness] action Name +atomic action Increment: # atomic = no interleaving + counter = counter + 1 + +fair action Progress: # fair = weak fairness + require not done + done = True + +atomic fair action Produce: # both modifiers + require len(queue) < MAX + queue.append(item) +``` + +**Key rules:** + +- No parameters on actions +- `Init` runs once; all variables defined in it become global state +- `require condition` disables the action (doesn't execute it) +- An action is "enabled" only after it executes a simple statement (`=`, method call, `pass`) + +### Roles + +```python +@state(ephemeral=['cache']) # cache resets on crash +role Server: + action Init: + self.data = {} # role state (persists) + self.cache = {} # ephemeral (resets on crash) + + atomic func Read(key): # function: can have params + return + return self.data.get(key, None) + + action Write: + key = oneof self.pending_keys + self.data[key] = self.pending[key] +``` + +**Key rules:** + +- `self.*` = role state; local vars are not part of state +- `self.__id__` = auto-generated unique ID (read-only) +- Functions can only be called from atomic context or inside roles +- `result = role.fn()` works; `self.x = role.fn()` crashes — use a local var first + +### Flow Modifiers + +```python +atomic action AllAtOnce: # one indivisible step + x = 1; y = 2 + +action SerialSteps: # yields between statements (default) + x = 1 # yield point here + y = 2 # yield point here + +action Concurrent: + parallel: # explores all interleavings + x = x + 1 + y = y + 1 + +action Choose: + oneof: # nondeterministically pick one branch + status = "success" + status = "failure" +``` + +### Nondeterminism + +```python +x = oneof [1, 2, 3] # pick one element (nondeterministic) +x = oneof range(10) # pick one integer 0..9 +x = oneof items # pick one element from collection +# Note: oneof on empty collection disables the action + +oneof x in items: # for-each style: pick one x, execute body + process(x) + +# `any` is a deprecated alias for `oneof` (emits DeprecationWarning) +x = any items # old form — still works but deprecated +``` + +### Assertions + +```python +always assertion SafetyProp: # must hold in ALL states + return counter >= 0 + +exists assertion Reachable: # holds in AT LEAST ONE state + return counter == MAX + +transition assertion Monotonic(before, after): # on every transition + if after.counter != before.counter: + return after.counter > before.counter + return True # must allow stutter steps (no-change transitions) + +eventually always assertion Stabilizes: # eventually stable (needs fairness) + return done == True + +always eventually assertion Progresses: # always makes progress (needs strong fairness) + return processed > 0 +``` + +### Symmetry Reduction + +Dramatically reduces state space for interchangeable values/actors: + +```python +# Unique IDs (nominal = only identity matters) +IDS = symmetry.nominal(name="id", limit=3) # max 3 live at once +id = IDS.fresh() + +# Interchangeable pool (e.g., task content) +TEXTS = symmetry.nominal(name="task", limit=3) +v = oneof TEXTS.choices() # grows naturally: 1 option first, then more + +# Symmetric roles (N! reduction for N instances) +symmetric role Worker: + action Init: + self.status = "idle" + +workers = bag() +workers.add(Worker()) # use bag(), not list, for symmetric roles +``` + +**Symmetry limits**: set to max _coexisting_ values, not total ever created. + +--- + +## Data Types + +| Type | Use | Example | +| --------------------- | ----------------------------------------- | ------------------------------- | +| list | ordered, mutable | `items = []`, `items.append(x)` | +| set | unordered, unique, hashable | `s = set()`, `s.add(x)` | +| dict | key-value, hashable keys | `d = {}`, `d[k] = v` | +| bag | multiset | `b = bag()`, `b.add(x)` | +| record | mutable named struct | `r = record(x=1, y=2)` | +| struct | immutable named struct | `s = struct(x=1)` | +| enum | named constants | `E = enum('A','B')`, `E.A` | +| genericset/genericmap | non-hashable elements (local scope only!) | `gs = genericset()` | + +--- + +## Fault Injection + +```yaml +--- +options: + crash_on_yield: true # roles can crash at yield points +--- +``` + +```python +@state(ephemeral=['cache']) # cache lost on crash, data persists +role Node: + action Init: + self.data = 0 # durable + self.cache = 0 # ephemeral +``` + +Cross-role function calls can also be lost (message loss simulation) — model checker explores both delivery and loss. + +--- + +## Gotchas + +1. **Cross-role return**: `self.x = role.fn()` crashes → use `tmp = role.fn(); self.x = tmp` +2. **No tuple unpacking in for**: `for k, v in d.items()` fails → `for k in d: v = d[k]` +3. **Role Init ordering**: create globals before creating roles that depend on them +4. **`require` ≠ assertion**: `require x >= 0` disables action; use `always assertion` for invariants +5. **Lists break symmetry**: use `bag()` not `[]` to hold symmetric role instances +6. **`oneof`/`any` on empty**: disables the action (no `require len > 0` needed) +7. **`any` keyword vs Python `any()` function**: `x = any([cond for ...])` is a parse error — `any` is the deprecated nondeterministic choice keyword. Prefer `oneof` (no collision: `oneof` can't be an identifier). For boolean checks use `all([...])` or `len([x for x in xs if cond]) > 0`. +8. **Function calls**: can only call fizz functions from atomic context or inside roles; extract to variable before using in expressions +9. **`None` works**: use `== None`, not `is None` (no `is` operator) + +--- + +## Common Patterns + +### Server + Client roles + +```python +role Server: + action Init: + self.store = {} + + atomic func Write(key, value): + self.store[key] = value + + atomic func Read(key): + return self.store.get(key, None) + +role Client: + action Init: + self.result = None + + action DoRead: + v = server.Read("key") # local var first! + self.result = v + +action Init: + server = Server() + client = Client() +``` + +### Message queue + +```python +action Init: + queue = [] + +atomic fair action Send: + require len(queue) < MAX + queue.append(record(id=next_id, body="msg")) + +atomic fair action Receive: + require len(queue) > 0 + msg = queue.pop(0) + processed = processed + [msg.id] +``` + +### Dynamic roles (hire/fire) + +```python +symmetric role Employee: + action Init: + self.active = True + +action Init: + employees = bag() + +action Hire: + employees.add(Employee()) + +action Fire: + target = oneof [e for e in employees if e.active] + employees = bag([e for e in employees if e.__id__ != target.__id__]) +``` + +--- + +## Reference Examples (by topic) + +Installed example specs (after `fizz install-skills`): + +- `~/.claude/skills/fizzbee-docs/examples/01-counter.fizz` — basics: init, atomic action, assertion +- `~/.claude/skills/fizzbee-docs/examples/09-assertions.fizz` — always/exists/transition assertions +- `~/.claude/skills/fizzbee-docs/examples/11-roles.fizz` — two-role communication +- `~/.claude/skills/fizzbee-docs/examples/13-two-phase-commit.fizz` — distributed protocol +- `~/.claude/skills/fizzbee-docs/examples/14-fault-injection.fizz` — crash-on-yield, ephemeral state +- `~/.claude/skills/fizzbee-docs/examples/16-symmetry.fizz` — nominal symmetry, symmetric roles + +Full examples index: `~/.claude/skills/fizzbee-docs/README.md` +All 100+ examples on GitHub: https://github.com/fizzbee-io/fizzbee/tree/main/examples/references From 922dd898e5ad7e1a8de23678117e2f1633471582 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 12 Apr 2026 14:45:02 +0200 Subject: [PATCH 3/9] plan update --- docs/router/route-match-loading-rfc.md | 379 ++++++++++++++++++------- 1 file changed, 272 insertions(+), 107 deletions(-) diff --git a/docs/router/route-match-loading-rfc.md b/docs/router/route-match-loading-rfc.md index 99ace604f2..8792be1444 100644 --- a/docs/router/route-match-loading-rfc.md +++ b/docs/router/route-match-loading-rfc.md @@ -5,7 +5,7 @@ title: Route Match Loading RFC # Route Match Loading And Rendering RFC -Status: phase 1 complete, phase 2 ready to start +Status: phase 1 core contract complete, phase 2 ready to start Owner: multi-session effort, React-first @@ -261,59 +261,65 @@ This section is the start of phase 1. It should be treated as normative unless s ### Terminology -- Match identity: the concrete `match.id` instance, including route id, concrete pathname, and loader-deps hash. -- Route presence identity: the logical presence of a route in the tree, keyed by `routeId`. -- Active match: a match currently committed to the rendered tree. -- Pending match: a match being prepared for possible promotion to active. -- Cached match: an inactive match retained for reuse. +- Match instance: an implementation-level record representing one matched route occurrence. +- Route presence identity: the logical continuity of a route in the visible tree. +- Load resource identity: the key used to determine whether previously acquired route-loading artifacts may be reused for a route. + Today the implementation approximates this with `route.id + interpolatedPath + loaderDepsHash`, but phase 2 should model the semantic concept, not the current string construction. +- Committed tree: the currently visible route tree. +- Candidate tree: the next route tree being evaluated for possible commit. +- Reusable artifacts: any previously acquired route-loading artifacts that a later generation may be allowed to reuse. - Load generation: a single causally ordered attempt to make a match render-ready. - Effective context: router context plus accumulated parent `context()` values plus accumulated `beforeLoad` returns up to the current match. -- Render gate: the state that determines whether the adapter may render the route component, render pending UI, render not-found UI, render error UI, or suspend. +- Render gate: a semantic visibility state emitted by router-core, such as blocked, pending, ready, error, or notFound. +- Generation obsolescence: the fact that an older generation may no longer affect the visible tree. ### Normative Goals 1. A render-visible match must never expose incomplete effective context for its own generation. 2. The router must model match loading as explicit generations, so stale completions cannot overwrite newer state. -3. A match must never exist in more than one pool at a time. -4. A render-visible pending or redirected match must retain a valid suspension/render-gate contract for the entire period it is visible. -5. `beforeLoad` execution is serial from root to leaf. -6. Loader execution begins only after the serial `beforeLoad` prefix is established, and loaders may run in parallel after that. -7. The failure that wins for a navigation/preload is the highest-priority failure closest to the root under the defined precedence rules. -8. Cache promotion and reuse must be explicit. Reused data and rerun work must be determined by spec, not by incidental object reuse. -9. Eviction and garbage collection must not invalidate currently rendered or still-needed render gates. -10. Router-core should model routing facts; framework adapters should model framework-specific rendering mechanics. +3. The committed tree must update atomically and coherently, never as an observably inconsistent mix of generations. +4. If an implementation uses multiple pools or stores, their aliasing semantics must be explicit and must not affect correctness. +5. A render-visible pending or redirected match must retain a valid render contract for the entire period it is visible. +6. `beforeLoad` execution is serial from root to leaf. +7. Loader execution begins only after the serial `beforeLoad` prefix is established, and loaders may run in parallel after that. +8. The winning failure for a generation must be determined by semantic precedence and boundary ownership, not by completion timing accidents. +9. Cache promotion and reuse must be explicit. Reused data and rerun work must be determined by spec, not by incidental object reuse. +10. Eviction and garbage collection must not invalidate currently rendered or still-needed render gates. +11. Router-core should model routing facts; framework adapters should model framework-specific rendering mechanics. ### Normative Invariants These invariants should later become FizzBee assertions. -1. Tentative exclusive pool membership - A given `match.id` should ideally be in exactly one of `active`, `pending`, or `cached`, or in none of them. - This is a preferred simplifying invariant for the redesign, but it may be relaxed if it blocks a materially better solution. -2. Generation monotonicity +1. Generation monotonicity A completion from generation `N` must not mutate the visible state for generation `N + 1`. -3. Context completeness before render +2. Context completeness before render If a match may render its route component, then its effective context for that generation is complete. +3. Commit atomicity/coherence + The committed tree must never expose a mix of route-loading facts that could not have come from one coherent generation. 4. Pending continuity If a match is intentionally rendered as pending, the adapter must always have a valid render gate for it until the match leaves pending display. 5. Redirect continuity - If a match is observed as redirected during a transition, the adapter must still be able to abandon the stale render safely. + If a match is observed as redirected during a transition, the stale generation must not later become render-ready again. 6. Root not-found shell preservation Root not-found must preserve the root shell/layout contract. 7. Ancestor visibility If a child fails in a way that still requires ancestor UI/head/data to render, the required ancestor work must be preserved. 8. Explicit reuse rules Reusing a cached or active match must not implicitly reuse stale `beforeLoad` context or loader data unless the spec says it does. +9. Implementation alias safety + If the implementation stores equivalent route information in multiple pools or stores, that duplication must not create ambiguous lookups or divergent visible semantics. ### Router-Core Versus Adapter Contract Router-core should guarantee: -- pool membership +- committed-tree and candidate-tree semantics +- load resource reuse decisions - generation identity and completion rules -- the final state of each match for a generation +- the final semantic outcome of each route for a generation - when context is complete enough for each phase -- whether a match is renderable, pending-renderable, error-renderable, or not-found-renderable +- semantic render-gate facts and generation obsolescence Adapters should guarantee: @@ -328,7 +334,14 @@ The following phase-1 decisions are now treated as settled enough to begin phase #### D1. Preload reuse rules -When a preload later becomes active for the same `match.id`: +This remains a compatibility policy, not a sacred first-principles law. + +The current working principle is: + +- `beforeLoad` is conservative preflight/context/authorization work +- `loader` is reusable data acquisition work + +Unless phase 2 disproves that split, when a preload later becomes active for the same load resource identity: - `beforeLoad` reruns on navigation - a fresh successful loader result may be reused @@ -339,15 +352,23 @@ See rules `P4`, `P9`, and `P10`. #### D2. Generation-scoped versus match-instance-scoped state -The phase-2 model should treat the following as match-instance-scoped: +The phase-2 model should separate three concepts that are blurred together in the current implementation: + +- route presence identity +- load resource identity +- implementation-level match instance + +The phase-2 model should treat the following as stable route/presence facts: -- `match.id` - `routeId` -- `pathname` -- `params` -- `search` -- `loaderDeps` -- static route metadata needed for boundary resolution and SSR inheritance +- route boundary capabilities +- SSR inheritance facts + +The phase-2 model should treat the following as reusable-resource identity inputs: + +- the route identity +- the relevant path/input key used for reusable artifacts +- loader-relevant dependency inputs The phase-2 model should treat the following as generation-scoped: @@ -357,7 +378,7 @@ The phase-2 model should treat the following as generation-scoped: - loader result data - terminal error/redirect/notFound outcome - render gate -- abort signal / generation cancellation state +- generation obsolescence / cancellation state - freshness result for the current generation The implementation may store some of these together, but the semantics should remain separated. @@ -368,11 +389,14 @@ For spec purposes, route `context()` is recomputed for every load generation aft An implementation may memoize or structurally share equivalent results, but the observable semantics must match recomputation-per-generation. -This decision is intentionally spec-first because stale route-context reuse is a likely source of correctness bugs. +This decision is intentionally spec-first because stale route-context reuse is a likely source of correctness bugs and the current implementation already has to compensate for this during hydration. #### D4. Failure precedence -Failure precedence is defined by the table in the `Failure Precedence Table` section below. +Failure precedence has two layers: + +- semantic principles, which are normative for the rewrite +- a current-compatibility baseline, which phase 2 can test against and then challenge if a cleaner semantic formulation proves equivalent or better #### D5. Render-gate ownership split @@ -383,13 +407,14 @@ Router-core owns semantic render-gate facts such as: - render ready - render notFound - render error -- abandon stale generation + +Router-core also owns generation-obsolescence facts such as “this stale generation may no longer affect the committed tree.” Adapters own the framework mechanism used to realize those facts, such as: - thrown promises - suspense/resource wiring -- `ClientOnly` +- client-only DOM gating - framework-specific boundary placement #### D6. Acceptable adapter divergence @@ -412,23 +437,31 @@ Required shared semantics: #### D7. Residual non-blocking note -The tentative exclusive-pool-membership invariant remains preferred, but phase 2 may relax it if doing so leads to a cleaner and safer model. +The tentative exclusive-pool-membership invariant is no longer treated as normative core semantics. + +If phase 2 finds that strict exclusivity improves the model, it can be reintroduced as an implementation simplifier. If not, the model must instead define explicit alias-safety semantics. ### Draft Rule Set: Preload, Cache, Reuse, And Eviction This is the third concrete semantic slice of phase 1. -#### Rule P1. Match identity is route id plus concrete path plus loader-deps identity +#### Rule P1. Current implementation approximates load resource identity with route id plus concrete path plus loader-deps identity -Search params only affect match identity through `loaderDeps`. +For current-implementation compatibility, reusable loader artifacts are keyed by route id plus concrete path plus loader-deps identity. + +For the rewrite, this should be treated as the current approximation of load resource identity, not as an untouchable semantic law. + +Search params only affect resource reuse through the derived loader-relevant inputs. References: - `packages/router-core/src/router.ts:1482-1510` -#### Rule P2. Preload creates cache entries immediately +#### Rule P2. Preload creates reusable artifacts before success -`preloadRoute()` creates cache entries at preload start, not only after success. +Semantically, preload may create reusable route-loading artifacts before success. + +Current implementation note: `preloadRoute()` materializes those artifacts as cached entries at preload start, not only after success. References: @@ -436,9 +469,11 @@ References: - `packages/router-core/tests/load.test.ts:189-200` - `packages/router-core/tests/load.test.ts:434-445` -#### Rule P3. Navigation promotes through pending first +#### Rule P3. Navigation evaluates a candidate tree before visible commit -Navigation does not promote cached entries directly to active. Matching first produces a pending tree, then readiness promotes pending to active. +Semantically, navigation evaluates a candidate tree before updating the committed tree. + +Current implementation note: matching first produces a pending tree, then readiness promotes pending to active. References: @@ -473,7 +508,7 @@ A stale successful match should reload only when at least one of the following i - explicit same-location reload - match cause is `enter` -- the route reappears with a different `match.id` +- the route reappears with a different load resource identity - the match is invalidated - `shouldReload` says to reload @@ -521,9 +556,11 @@ References: - `packages/router-core/tests/load.test.ts:447-556` -#### Rule P11. Cache eviction is lazy, not timer-driven +#### Rule P11. Eviction timing is an implementation choice subject to safety constraints -GC eligibility is time-based, but actual removal happens on later GC passes, not on a live timer. +Semantically, eviction must not break visible or still-needed route-loading state. + +Current implementation note: GC eligibility is time-based, but actual removal happens on later GC passes, not on a live timer. References: @@ -615,9 +652,11 @@ References: The target spec should not depend on these exact promise names, but it must preserve the continuity guarantee they currently try to provide. -#### Rule R2. Redirected matches still need an abandonment gate +#### Rule R2. Redirected stale generations must remain safely discardable -If React observes a match as `redirected` during an in-flight transition, the stale render must still be able to suspend and get abandoned safely. +If a stale generation has already become visible enough for an adapter to be working with it, a redirect must not leave that adapter with an invalid intermediate state. + +Different adapters may realize safe discard differently, but phase 2 should model the semantic guarantee rather than React's thrown-promise mechanism. References: @@ -635,9 +674,9 @@ References: The target design should describe this in terms of render gates, not ad hoc React-specific flags in the core model. -#### Rule R4. Render gates must outlive visible pool transitions +#### Rule R4. Render gates must outlive visible implementation transitions -Cache promotion, pending-to-active promotion, redirect finalization, and stale background completion must not destroy the active render gate while the adapter can still read it. +Implementation transitions such as cache promotion, candidate-to-committed promotion, redirect finalization, and stale background completion must not destroy the active render gate while the adapter can still read it. Relevant implementation anchors: @@ -645,6 +684,22 @@ Relevant implementation anchors: - `packages/router-core/src/load-matches.ts:925-945` - `packages/router-core/src/router.ts:2476-2488` +#### Rule R5. Pending timing is an observable contract, not an adapter mechanism + +The router's pending semantics include two observable timing commitments: + +- pending is not shown until the configured optimistic threshold elapses (`pendingMs`) +- once pending becomes visible, it remains visible for at least the configured minimum duration (`pendingMinMs`) + +Adapters may realize this with different primitives, but phase 2 should model the timing semantics explicitly rather than infer them from promise shapes. + +References: + +- `docs/router/guide/data-loading.md:509-523` +- `packages/react-router/src/Match.tsx:412-435` +- `packages/solid-router/src/Match.tsx:322-367` +- `packages/vue-router/src/Match.tsx:436-471` + ### Draft Rule Set: Failure Precedence This is still provisional, but it is specific enough to guide phase-2 modeling. @@ -669,7 +724,9 @@ Evidence and anchors: #### Rule F3. Redirect wins immediately for the current generation -A redirect aborts the current generation and starts resolution of the redirect target. +A redirect dominates the current generation and starts resolution of the redirect target. + +Phase 2 should model this as a semantic dominance rule, not as a claim about the exact timing of current implementation finalization. Reference: @@ -688,9 +745,30 @@ Reference: The exact precedence order for mixed redirect/notFound/error outcomes across multiple matches is defined below for phase-2 modeling. -### Failure Precedence Table +### Semantic Failure Principles -For a single load generation, the winning outcome is resolved in this order. +These principles are more important than any current table or status encoding. + +1. Redirect dominance + A redirect dominates all non-redirect outcomes for the same generation. +2. Deterministic winner selection + The winning outcome for a generation must be deterministic and must not depend on completion timing races. +3. Boundary ownership + notFound and error outcomes are resolved relative to the boundary that will actually render them, not merely the throwing route. +4. Root-shell preservation + A root-level notFound must preserve the root shell contract. +5. Ancestor work preservation + Child failure may still require ancestor work so the winning boundary can render coherently. + +### Current Compatibility Precedence Baseline + +The table below captures the current compatibility baseline inferred from existing code and tests. + +This baseline is non-normative. Phase 2 should first model the semantic failure principles and only then add this baseline as an optional compatibility target. + +Phase 2 may replace it with a cleaner semantic formulation if the observable behavior remains correct or improves intentionally. + +For the current baseline, a single load generation is resolved in this order. | Rank | Outcome source | Outcome type | Notes | | ---- | --------------------- | ------------- | ------------------------------------------------------------------------------------------- | @@ -717,14 +795,14 @@ References: ### Failure Precedence Narrative -TanStack Router resolves failures in two stages: a serial preflight stage and a parallel loader stage. +TanStack Router currently resolves failures in two stages: a serial preflight stage and a parallel loader stage. - A redirect thrown during the serial stage terminates the generation immediately. - A serial-stage `notFound` or regular error is provisional: it stops deeper serial work, but eligible ancestor loaders may still run. - Once loaders settle, loader outcomes are resolved in route-match order with precedence `redirect > error > notFound`. - If no loader outcome supersedes the provisional serial result, the router finalizes the serial `notFound` or regular error. - notFound rendering is based on the resolved boundary route, not merely the throwing route. -- root notFound preserves the root shell by using `globalNotFound`. +- current implementation preserves root notFound via `globalNotFound`, but the rewrite should treat root-shell preservation as the semantic requirement rather than copy the exact flag. ### Draft Rule Set: Hydration And No-SSR Rendering @@ -748,9 +826,13 @@ References: - `packages/router-core/src/router.ts:154-155` - `packages/router-core/src/load-matches.ts:263-290` -#### Rule H2. The first client-rendered match is the hydration boundary +#### Rule H2. Hydration boundaries are defined by DOM ownership, not implementation index -The first active match whose authoritative DOM is client-owned becomes the hydration boundary that may need forced pending or client-only gating. +Hydration introduces a client-render boundary wherever authoritative DOM transitions from server-owned to client-owned. + +Current working simplification: the first active match with client-owned authoritative DOM is treated as the hydration boundary. + +Phase 2 should model the semantic boundary, not copy today's implementation heuristics mechanically. References: @@ -766,7 +848,9 @@ References: #### Rule H4. SPA-mode hydration preserves pending without blocking the root unnecessarily -If hydration is effectively falling back to SPA-mode, the first non-root client-rendered match may display pending while the router finishes loading, without forcing the whole root tree through an unnecessary initial suspense cycle. +If hydration is effectively falling back to SPA-mode, the client may display pending below the root while the router finishes loading, without forcing the whole root tree through an unnecessary initial suspense cycle. + +Current implementation note: the existing code special-cases the first non-root match during SPA-mode hydration. Phase 2 should preserve only the user-observable behavior, not the index-based heuristic. References: @@ -787,6 +871,7 @@ Required shared semantics: - hydration-safe fallback for client-rendered matches - pending remains visible where configured - SSR inheritance semantics stay intact +- committed-tree coherence is preserved during hydration and post-hydration loading References: @@ -810,32 +895,32 @@ The matrix above is summarized here as explicit rules by entry point. #### Initial page load -- the router computes the full pending tree for the destination +- the router computes the full candidate tree for the destination - all `beforeLoad` run serially from root to leaf until cut off by failure - loaders run for the surviving prefix according to the failure rules above -- activation happens only through pending-to-active promotion +- the committed tree updates only after a coherent candidate result exists #### Fully SSR-backed hydration -- dehydrated matches become the active tree +- dehydrated matches become the committed tree - route context and head/script data are reconstructed client-side - no additional client load runs if hydration is fully SSR-backed and not in SPA mode #### Hydration with client-rendered boundary -- the first client-rendered match becomes the hydration boundary +- a semantic client-render boundary exists wherever authoritative DOM shifts from server-owned to client-owned - the adapter may show a hydration-safe fallback for that boundary and below - forced/display-pending behavior is allowed here to preserve continuity #### Client navigation -- navigation always computes a fresh pending tree +- navigation always computes a fresh candidate tree - `beforeLoad` reruns on navigation even when loader results are still reusable -- activation and exiting-cache behavior follow the cache rules above +- commit and reusable-artifact behavior follow the reuse/eviction rules above #### Preload -- preload may create cache entries before success +- preload may create reusable artifacts before success - preload never commits active UI directly - in-flight preload loader work may be adopted by a later navigation for the same match @@ -843,7 +928,7 @@ The matrix above is summarized here as explicit rules by entry point. - redirect terminates the current generation according to the precedence table - redirect starts target resolution as a fresh generation -- stale redirected renders must still retain a valid abandonment gate until discarded +- stale redirected renders must still remain safely discardable until the adapter releases them #### beforeLoad notFound @@ -853,17 +938,17 @@ The matrix above is summarized here as explicit rules by entry point. #### Background stale reload -- the current active match remains renderable while background reload continues +- the current committed route state remains renderable while background reload continues - late completion from background reload must not clobber a newer generation #### Invalidation -- invalidation applies to active, pending, and cached entries uniformly -- invalidation marks matches stale and may reset terminal error/notFound matches to pending +- invalidation applies uniformly to committed route state, candidate route state, and reusable artifacts selected by policy +- invalidation marks the selected route-loading facts stale and may reset terminal error/notFound outcomes so they can rerun #### GC and eviction -- eviction is lazy and only removes GC-eligible cached entries +- eviction removes only reusable artifacts that are no longer needed by the committed tree or an in-flight candidate tree - eviction must not break any still-visible or still-needed render gate ### Phase 1 Coverage And Gaps @@ -881,7 +966,7 @@ Important remaining gaps to close during implementation: - explicit tests for mixed loader error vs serial beforeLoad notFound precedence - explicit tests for generation safety during background reload plus fast subsequent navigation - explicit adapter-level tests for hydration boundary semantics across React, Solid, and Vue -- explicit tests for promise/render-gate continuity when pool membership changes +- explicit tests for promise/render-gate continuity across implementation transitions such as reuse, commit, and eviction ## Scenario Matrix @@ -891,7 +976,7 @@ This is the first pass of the phase-1 inventory. It is intentionally broad so la | --------------------------------------------- | ------------------------------------------------------- | ------------------------------------ | ----------------------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------- | | Initial page load | all next matches created or reused | serial root to leaf | parallel after serial prefix | may reuse fresh cached data | may show pending depending on route/router defaults | redirect/notFound/error may prevent full tree mount | | SSR hydration, fully SSR-backed | matches hydrated from server payload | may be skipped on first client pass | may be skipped on first client pass | hydrated matches become active immediately | avoid hydration mismatch; no extra pending UI unless needed | hydration-time errors/notFound still need defined behavior | -| SSR hydration with `ssr: false` / `data-only` | first non-SSR match becomes special | may need rerun on client | may need rerun on client | hydrated prefix may coexist with client-only suffix | pending continuity must survive hydration | redirect/notFound/error cannot corrupt hydrated prefix | +| SSR hydration with `ssr: false` / `data-only` | first client-render boundary becomes special | may need rerun on client | may need rerun on client | hydrated prefix may coexist with client-only suffix | pending continuity must survive hydration | redirect/notFound/error cannot corrupt hydrated prefix | | Client navigation | pending tree derived from next location | serial root to leaf | parallel | active matches may be preserved; exiting matches may cache | pending may appear late or immediately | winning failure must be deterministic | | Preload | target tree may be loaded into cache only | serial root to leaf | parallel | later navigation may promote or rerun | no active render, but render-gate facts may still matter later | preload redirect/notFound/error must not poison active tree | | Redirect during navigation | next location may supersede older generation | may come from `beforeLoad` | may come from loader | stale work must not win later | stale render must abandon safely | redirect must preserve target navigation semantics | @@ -900,9 +985,78 @@ This is the first pass of the phase-1 inventory. It is intentionally broad so la | Invalidation | existing active/cached matches are marked stale/pending | reruns according to spec | reruns according to spec | reuse rules must be explicit | active UI may remain while reload happens | previous error/notFound state must reset correctly | | GC/eviction | inactive cached matches may drop | n/a | n/a | must not evict still-needed matches | no visible render gate may break | eviction cannot affect active/pending generations | +## Phase 1 Evaluation Findings + +An adversarial subagent review of this RFC produced the following conclusions, and this document has already been updated to reflect them. + +What survived review as strong first-principles material: + +- effective context must be complete before render +- generations must isolate stale completions from newer visible state +- serial preflight plus parallel data loading remains a sound core model +- boundary ownership and root-shell preservation are the right way to reason about notFound and error rendering +- router-core and adapter responsibilities must remain separate + +What was corrected or reframed after review: + +- `match.id` is no longer treated as the core semantic identity; the RFC now separates route presence identity, load resource identity, and implementation-level match instances +- active/pending/cached pools are no longer treated as normative core semantics; they are implementation choices subject to alias-safety requirements +- the failure-precedence table is now treated as a current compatibility baseline beneath a smaller set of semantic failure principles +- root notFound semantics are defined in terms of root-shell preservation, not `globalNotFound` as a required representation +- hydration is now defined in terms of semantic client-render boundaries, not just the current index-based heuristics +- pending timing is now called out as an observable contract independent of adapter mechanism + +What remains intentionally provisional going into phase 2: + +- whether the current `beforeLoad` versus `loader` reuse asymmetry is a fundamental product rule or a compatibility policy +- whether strict cross-pool exclusivity is worth preserving as an implementation simplifier +- whether the current compatibility precedence baseline should survive unchanged once modeled semantically + +## Phase 2 Progress + +Phase 2 has started. + +Artifacts added: + +- executable model: `docs/router/route-match-loading.fizz` +- tiny exhaustive-check config: `docs/router/route-match-loading-tiny.cfg` +- two-generation exploratory config: `docs/router/route-match-loading-small.cfg` + +Current modeled semantics: + +- committed tree vs candidate generation separation +- route presence identity vs reusable leaf-resource identity +- serial `beforeLoad` progression with parent-context gating +- parallel loader progression after serial preflight +- redirect dominance during finalization +- notFound boundary ownership and root-shell preservation +- reusable artifact success reuse, in-flight adoption, and failure non-reuse +- stale-generation protection for committed-state updates +- commit atomicity as a model assertion + +Not yet modeled in the first executable spec: + +- hydration boundary semantics +- adapter-specific pending display timing beyond the abstract contract +- a richer cross-generation model with exhaustive overlap checking for multiple live generations +- more precise error-boundary ownership beyond the current simplified source-owner rule + +Current verification status: + +- `fizz --preinit-hook-file docs/router/route-match-loading-tiny.cfg docs/router/route-match-loading.fizz` + Passed with `Valid Nodes: 12954` and `Unique states: 1007`. +- `fizz --preinit-hook-file docs/router/route-match-loading-small.cfg docs/router/route-match-loading.fizz` + Remains useful for exploration but currently exceeds the 2-minute local command budget; it is the next target for state-space reduction or scenario-focused guided traces. + +Initial model-driven corrections already made while starting phase 2: + +- root-shell notFound rendering needed explicit context completion in the model to satisfy the context-ready invariant +- fresh-artifact reuse needed a generation-local assertion rather than one tied to the artifact's later global state +- the phase-2 model structure worked better when helper logic was inlined instead of relying on top-level function calls in FizzBee actions + ## Phase 2 Bootstrap -Phase 1 is complete enough to start modeling. +Phase 1's core semantic contract is complete enough to start modeling. The goal of phase 2 is not to encode React, Solid, or Vue internals directly. The goal is to model router-core semantics plus an abstract render-gate contract that all adapters must satisfy. @@ -913,7 +1067,7 @@ Recommended first model file: `docs/router/route-match-loading.fizz` Start with a deliberately small model. - at most 3 matched indices: root, parent, leaf -- at most 1 active generation and 1 next generation at a time +- start with 1 committed-tree generation and 1 candidate-tree generation, then expand quickly to allow at least one stale older generation to overlap a newer candidate generation - support these entry points first: initial load, navigation, preload, redirect, beforeLoad notFound, background stale reload, hydration with one client-rendered boundary - ignore code-splitting details at first except as a boolean “chunk needed before render-ready” fact - model userland suspense only as an adapter-side opaque condition, not as part of router-core state @@ -922,39 +1076,47 @@ Start with a deliberately small model. Use these terms in the first FizzBee model. -- match instance +- committed tree +- candidate tree +- route presence identity +- load resource identity +- reusable artifacts - load generation -- active tree -- pending tree -- cached entries - effective context - freshness - boundary owner - hydration boundary - render gate - terminal outcome +- generation obsolescence ### Recommended abstract state The first model should represent at least the following facts. -- `matches_by_id` - Match instance facts: `routeId`, `pathnameShape`, `loaderDepsKey`, boundary capabilities, SSR mode. -- `pool_by_match_id` - `active`, `pending`, `cached`, or `none`. -- `generation_by_match_id` - Current generation number or token for that match instance. -- `status_by_match_id` - `idle`, `beforeLoad`, `loading`, `ready`, `error`, `redirected`, `notFound`. -- `context_state_by_match_id` +- `committed_tree` + Ordered route presence chain currently visible to the user. +- `candidate_tree` + Ordered route presence chain currently being evaluated for possible commit. +- `route_facts_by_presence_id` + Stable route facts such as `routeId`, boundary capabilities, and SSR inheritance facts. +- `resource_key_by_presence_id` + The load resource identity currently associated with each route presence. +- `reusable_artifacts_by_resource_id` + Reusable route-loading artifacts and their freshness state. +- `generations` + First-class generation records keyed by generation token, each carrying entry point, affected route presences/resources, provisional failure, final outcome, and obsolescence state. +- `preflight_state_by_generation_and_presence` + `not_started`, `in_flight`, `success`, `redirect`, `notFound`, `error`. +- `data_state_by_generation_and_resource` + `not_started`, `in_flight`, `success`, `redirect`, `notFound`, `error`. +- `context_state_by_generation_and_presence` `unknown`, `parent_ready`, `ready`. -- `loader_state_by_match_id` - `not_started`, `in_flight`, `success`, `error`, `redirect`, `notFound`. -- `render_gate_by_match_id` - `blocked`, `pending`, `ready`, `error`, `notFound`, `abandon`. -- `freshness_by_match_id` - `fresh`, `stale`, `invalid`. -- `hydration_mode_by_match_id` +- `render_gate_by_generation_and_presence` + `blocked`, `pending`, `ready`, `error`, `notFound`. +- `obsolescence_by_generation` + Whether a generation is still allowed to affect the committed tree. +- `hydration_mode_by_presence_id` `server_dom`, `data_only`, `client_only`. - generation-level facts: - current entry point @@ -981,19 +1143,20 @@ The first model should include actions equivalent to: 12. `ResolveLoaderRedirect` 13. `ResolveLoaderNotFound` 14. `ResolveLoaderError` -15. `FinalizeWinningOutcome` -16. `PromotePendingTree` +15. `DetermineBoundaryOwner` +16. `FinalizeWinningOutcome` 17. `StartBackgroundReload` 18. `CompleteBackgroundReload` -19. `InvalidateMatch` -20. `EvictCachedMatch` +19. `CommitCandidateTree` +20. `InvalidateResource` +21. `EvictReusableArtifacts` Hydration-specific actions can be added immediately after the first model passes the core assertions: -- `HydrateMatchFromServer` +- `HydrateServerFacts` - `MarkHydrationBoundary` -- `EnterDisplayPending` -- `ExitDisplayPending` +- `EnterPendingFallback` +- `ExitPendingFallback` ### Recommended first assertions @@ -1003,18 +1166,20 @@ The first FizzBee model should prove these assertions. A completion from an older generation never changes the winning visible outcome of a newer generation. 2. Context completeness A match with render gate `ready` always has effective context `ready` for that generation. -3. Redirect abandonment safety - A redirected stale generation never becomes render gate `ready` again. +3. Redirect discard safety + A redirected stale generation never becomes render gate `ready` again and never corrupts the committed tree. 4. Pending continuity A match with render gate `pending` never loses its ability to remain pending until it transitions to another valid gate. 5. Failure precedence - For any generation, the final winning outcome matches the precedence table in this RFC. + For any generation, the final winning outcome satisfies the semantic failure principles in this RFC and, when running a compatibility-focused model, the current compatibility baseline. 6. Boundary correctness A finalized notFound always resolves to the correct rendered boundary owner. 7. Root shell preservation Root notFound never requires replacing the root shell with a non-root-style notFound state. 8. Reuse correctness Reused preload/cache data is only observed in cases permitted by rules `P4`, `P9`, and `P10`. +9. Commit atomicity + Any visible commit corresponds to one coherent candidate-tree resolution. ### Recommended first trace checklist @@ -1045,7 +1210,7 @@ Once the first model passes, phase 3 should begin by implementing explicit gener ## Phase 1 Exit Status -Phase 1 is considered complete for now because this RFC now contains: +Phase 1 is considered complete at the core semantic level because this RFC now contains: - a shared vocabulary - explicit normative goals and invariants @@ -1057,7 +1222,7 @@ Phase 1 is considered complete for now because this RFC now contains: - scenario rules by entry point - a phase-2 modeling bootstrap with state, actions, assertions, and trace coverage -Any remaining uncertainty is narrow enough to be resolved inside phase 2 while modeling, rather than blocking phase 2 from starting. +Several compatibility-oriented details remain intentionally provisional, but they are now narrow enough to be resolved inside phase 2 while modeling, rather than blocking phase 2 from starting. ## Notes For Later Agents From ba49fab95719d2bfe08608752f5c3f2591857c0f Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 12 Apr 2026 15:56:31 +0200 Subject: [PATCH 4/9] phase 2 done --- docs/router/route-match-background.fizz | 110 +++++ docs/router/route-match-failures.fizz | 283 +++++++++++ docs/router/route-match-hydration.fizz | 176 +++++++ docs/router/route-match-loading-phase-3.md | 442 +++++++++++++++++ docs/router/route-match-loading-rfc.md | 95 +++- docs/router/route-match-loading-small.cfg | 2 + docs/router/route-match-loading-tiny.cfg | 2 + docs/router/route-match-loading.fizz | 529 +++++++++++++++++++++ docs/router/route-match-overlap.fizz | 181 +++++++ docs/router/route-match-pending.fizz | 98 ++++ 10 files changed, 1895 insertions(+), 23 deletions(-) create mode 100644 docs/router/route-match-background.fizz create mode 100644 docs/router/route-match-failures.fizz create mode 100644 docs/router/route-match-hydration.fizz create mode 100644 docs/router/route-match-loading-phase-3.md create mode 100644 docs/router/route-match-loading-small.cfg create mode 100644 docs/router/route-match-loading-tiny.cfg create mode 100644 docs/router/route-match-loading.fizz create mode 100644 docs/router/route-match-overlap.fizz create mode 100644 docs/router/route-match-pending.fizz diff --git a/docs/router/route-match-background.fizz b/docs/router/route-match-background.fizz new file mode 100644 index 0000000000..05e10a11ce --- /dev/null +++ b/docs/router/route-match-background.fizz @@ -0,0 +1,110 @@ +--- +deadlock_detection: false +options: + max_actions: 12 + max_concurrent_actions: 1 +--- + +# Phase 2 background-reload-focused model. +# +# This spec isolates one semantic guarantee: +# while stale background reload work is in flight, the currently committed view +# remains stable, and a late background completion cannot clobber a newer +# committed navigation. + +ArtifactState = enum('SUCCESS', 'IN_FLIGHT', 'FAILED') +Freshness = enum('STALE', 'INVALID', 'NONE', 'FRESH') +BackgroundState = enum('NONE', 'IN_FLIGHT', 'SUCCESS', 'FAILURE') +NavigationState = enum('NONE', 'IN_FLIGHT', 'SUCCESS', 'FAILURE') +CommittedView = enum('BASE', 'NEWER') + +action Init: + committed_view = CommittedView.BASE + committed_renderable = True + + artifact_state = ArtifactState.SUCCESS + artifact_freshness = Freshness.STALE + + background_state = BackgroundState.NONE + background_obsolete = False + + navigation_state = NavigationState.NONE + +atomic action MarkArtifactInvalid: + require committed_view == CommittedView.BASE + require artifact_state == ArtifactState.SUCCESS + artifact_freshness = Freshness.INVALID + +atomic action StartBackgroundReload: + require committed_view == CommittedView.BASE + require background_state == BackgroundState.NONE + require artifact_state == ArtifactState.SUCCESS + require artifact_freshness in [Freshness.STALE, Freshness.INVALID] + + background_state = BackgroundState.IN_FLIGHT + artifact_state = ArtifactState.IN_FLIGHT + artifact_freshness = Freshness.NONE + +atomic action StartNewerNavigation: + require navigation_state == NavigationState.NONE + navigation_state = NavigationState.IN_FLIGHT + background_obsolete = background_state == BackgroundState.IN_FLIGHT + +atomic action CompleteNewerNavigationSuccess: + require navigation_state == NavigationState.IN_FLIGHT + navigation_state = NavigationState.SUCCESS + committed_view = CommittedView.NEWER + committed_renderable = True + +atomic action CompleteNewerNavigationFailure: + require navigation_state == NavigationState.IN_FLIGHT + navigation_state = NavigationState.FAILURE + committed_renderable = True + +atomic action CompleteBackgroundSuccess: + require background_state == BackgroundState.IN_FLIGHT + background_state = BackgroundState.SUCCESS + artifact_state = ArtifactState.SUCCESS + artifact_freshness = Freshness.FRESH + +atomic action CompleteBackgroundFailure: + require background_state == BackgroundState.IN_FLIGHT + background_state = BackgroundState.FAILURE + artifact_state = ArtifactState.FAILED + artifact_freshness = Freshness.NONE + +always assertion BaseRemainsRenderableDuringBackgroundReload: + if committed_view != CommittedView.BASE: + return True + if background_state != BackgroundState.IN_FLIGHT: + return True + return committed_renderable + +always assertion BackgroundCompletionDoesNotChangeCommittedViewByItself: + if background_state not in [BackgroundState.SUCCESS, BackgroundState.FAILURE]: + return True + if navigation_state == NavigationState.SUCCESS: + return committed_view == CommittedView.NEWER + return committed_view == CommittedView.BASE + +always assertion ObsoleteBackgroundCannotClobberNewerCommit: + if background_obsolete == False: + return True + if navigation_state != NavigationState.SUCCESS: + return True + return committed_view == CommittedView.NEWER + +always assertion BackgroundFailureDoesNotRenderErrorOnCommittedView: + if background_state != BackgroundState.FAILURE: + return True + return committed_renderable + +always assertion NewerCommitRequiresNavigationSuccess: + if committed_view != CommittedView.NEWER: + return True + return navigation_state == NavigationState.SUCCESS + +always assertion InvalidOrStaleStartsBackgroundOnlyFromCommittedBase: + if background_state == BackgroundState.NONE: + return True + return committed_view in [CommittedView.BASE, CommittedView.NEWER] diff --git a/docs/router/route-match-failures.fizz b/docs/router/route-match-failures.fizz new file mode 100644 index 0000000000..cbd27a2912 --- /dev/null +++ b/docs/router/route-match-failures.fizz @@ -0,0 +1,283 @@ +--- +deadlock_detection: false +options: + max_actions: 16 + max_concurrent_actions: 1 +--- + +# Phase 2 failure-precedence and boundary-ownership model. + +Presence = enum('ROOT', 'PARENT', 'LEAF') +PreflightState = enum('NOT_STARTED', 'SUCCESS', 'REDIRECT', 'NOT_FOUND', 'ERROR') +LoaderState = enum('NOT_STARTED', 'IN_FLIGHT', 'SUCCESS', 'REDIRECT', 'NOT_FOUND', 'ERROR') +Outcome = enum('NONE', 'SUCCESS', 'REDIRECT', 'NOT_FOUND', 'ERROR') + +PRESENCES = [Presence.ROOT, Presence.PARENT, Presence.LEAF] + +action Init: + serial_cursor = Presence.ROOT + loaders_launched = False + root_shell_preserved = False + + provisional_outcome = Outcome.NONE + provisional_source = None + + final_outcome = Outcome.NONE + final_source = None + final_boundary = None + + preflight_state = {} + loader_state = {} + + for p in PRESENCES: + preflight_state[p] = PreflightState.NOT_STARTED + loader_state[p] = LoaderState.NOT_STARTED + +atomic action ResolveBeforeLoadSuccess: + require serial_cursor != None + p = serial_cursor + preflight_state[p] = PreflightState.SUCCESS + + if p == Presence.ROOT: + serial_cursor = Presence.PARENT + elif p == Presence.PARENT: + serial_cursor = Presence.LEAF + else: + serial_cursor = None + +atomic action ResolveBeforeLoadRedirect: + require serial_cursor != None + p = serial_cursor + preflight_state[p] = PreflightState.REDIRECT + provisional_outcome = Outcome.REDIRECT + provisional_source = p + serial_cursor = None + +atomic action ResolveBeforeLoadNotFound: + require serial_cursor != None + p = serial_cursor + preflight_state[p] = PreflightState.NOT_FOUND + provisional_outcome = Outcome.NOT_FOUND + provisional_source = p + serial_cursor = None + +atomic action ResolveBeforeLoadError: + require serial_cursor != None + p = serial_cursor + preflight_state[p] = PreflightState.ERROR + provisional_outcome = Outcome.ERROR + provisional_source = p + serial_cursor = None + +atomic action LaunchLoaders: + require serial_cursor == None + require loaders_launched == False + require provisional_outcome != Outcome.REDIRECT + + load_root = False + load_parent = False + load_leaf = False + + if provisional_outcome == Outcome.NONE: + load_root = True + load_parent = True + load_leaf = True + elif provisional_outcome == Outcome.NOT_FOUND: + load_root = True + if provisional_source != Presence.ROOT: + load_parent = True + elif provisional_outcome == Outcome.ERROR: + if provisional_source == Presence.PARENT or provisional_source == Presence.LEAF: + load_root = True + if provisional_source == Presence.LEAF: + load_parent = True + + if load_root: + loader_state[Presence.ROOT] = LoaderState.IN_FLIGHT + if load_parent: + loader_state[Presence.PARENT] = LoaderState.IN_FLIGHT + if load_leaf: + loader_state[Presence.LEAF] = LoaderState.IN_FLIGHT + + loaders_launched = True + +atomic action ResolveLoaderSuccess: + p = oneof PRESENCES + require loader_state[p] == LoaderState.IN_FLIGHT + loader_state[p] = LoaderState.SUCCESS + +atomic action ResolveLoaderRedirect: + p = oneof PRESENCES + require loader_state[p] == LoaderState.IN_FLIGHT + loader_state[p] = LoaderState.REDIRECT + +atomic action ResolveLoaderNotFound: + p = oneof PRESENCES + require loader_state[p] == LoaderState.IN_FLIGHT + loader_state[p] = LoaderState.NOT_FOUND + +atomic action ResolveLoaderError: + p = oneof PRESENCES + require loader_state[p] == LoaderState.IN_FLIGHT + loader_state[p] = LoaderState.ERROR + +atomic action Finalize: + require final_outcome == Outcome.NONE + require serial_cursor == None + require provisional_outcome == Outcome.REDIRECT or loaders_launched + require len([p for p in PRESENCES if loader_state[p] == LoaderState.IN_FLIGHT]) == 0 + + redirect_source = None + loader_error_source = None + loader_notfound_source = None + serial_notfound_source = None + serial_error_source = None + + for p in PRESENCES: + if redirect_source == None and (preflight_state[p] == PreflightState.REDIRECT or loader_state[p] == LoaderState.REDIRECT): + redirect_source = p + if loader_error_source == None and loader_state[p] == LoaderState.ERROR: + loader_error_source = p + if loader_notfound_source == None and loader_state[p] == LoaderState.NOT_FOUND: + loader_notfound_source = p + if serial_notfound_source == None and preflight_state[p] == PreflightState.NOT_FOUND: + serial_notfound_source = p + if serial_error_source == None and preflight_state[p] == PreflightState.ERROR: + serial_error_source = p + + if redirect_source != None: + final_outcome = Outcome.REDIRECT + final_source = redirect_source + return + + if loader_error_source != None: + final_outcome = Outcome.ERROR + final_source = loader_error_source + if loader_error_source == Presence.LEAF: + final_boundary = Presence.PARENT + else: + final_boundary = loader_error_source + return + + if loader_notfound_source != None: + final_outcome = Outcome.NOT_FOUND + final_source = loader_notfound_source + if loader_notfound_source == Presence.ROOT: + final_boundary = Presence.ROOT + root_shell_preserved = True + else: + final_boundary = Presence.PARENT + return + + if serial_notfound_source != None: + final_outcome = Outcome.NOT_FOUND + final_source = serial_notfound_source + if serial_notfound_source == Presence.ROOT: + final_boundary = Presence.ROOT + root_shell_preserved = True + else: + final_boundary = Presence.PARENT + return + + if serial_error_source != None: + final_outcome = Outcome.ERROR + final_source = serial_error_source + if serial_error_source == Presence.LEAF: + final_boundary = Presence.PARENT + else: + final_boundary = serial_error_source + return + + final_outcome = Outcome.SUCCESS + +always assertion BeforeLoadIsSerial: + if preflight_state[Presence.PARENT] != PreflightState.NOT_STARTED and preflight_state[Presence.ROOT] != PreflightState.SUCCESS: + return False + if preflight_state[Presence.LEAF] != PreflightState.NOT_STARTED and preflight_state[Presence.PARENT] != PreflightState.SUCCESS: + return False + return True + +always assertion LeafBeforeLoadNotFoundPreservesAncestorLoaders: + if preflight_state[Presence.LEAF] != PreflightState.NOT_FOUND: + return True + if loaders_launched == False: + return True + if loader_state[Presence.ROOT] == LoaderState.NOT_STARTED: + return False + if loader_state[Presence.PARENT] == LoaderState.NOT_STARTED: + return False + return loader_state[Presence.LEAF] == LoaderState.NOT_STARTED + +always assertion ParentBeforeLoadErrorSkipsOwnAndChildLoader: + if preflight_state[Presence.PARENT] != PreflightState.ERROR: + return True + if loaders_launched == False: + return True + if loader_state[Presence.ROOT] == LoaderState.NOT_STARTED: + return False + if loader_state[Presence.PARENT] != LoaderState.NOT_STARTED: + return False + return loader_state[Presence.LEAF] == LoaderState.NOT_STARTED + +always assertion RedirectDominatesFinalOutcome: + has_redirect = False + for p in PRESENCES: + if preflight_state[p] == PreflightState.REDIRECT or loader_state[p] == LoaderState.REDIRECT: + has_redirect = True + if has_redirect == False: + return True + if final_outcome == Outcome.NONE: + return True + return final_outcome == Outcome.REDIRECT + +always assertion LoaderErrorBeatsSerialNotFound: + has_loader_error = False + has_serial_notfound = False + has_redirect = False + for p in PRESENCES: + if loader_state[p] == LoaderState.ERROR: + has_loader_error = True + if preflight_state[p] == PreflightState.NOT_FOUND: + has_serial_notfound = True + if preflight_state[p] == PreflightState.REDIRECT or loader_state[p] == LoaderState.REDIRECT: + has_redirect = True + if has_loader_error == False or has_serial_notfound == False or has_redirect: + return True + if final_outcome == Outcome.NONE: + return True + return final_outcome == Outcome.ERROR + +always assertion LoaderNotFoundBeatsSerialError: + has_loader_notfound = False + has_serial_error = False + has_redirect = False + has_loader_error = False + for p in PRESENCES: + if loader_state[p] == LoaderState.NOT_FOUND: + has_loader_notfound = True + if preflight_state[p] == PreflightState.ERROR: + has_serial_error = True + if preflight_state[p] == PreflightState.REDIRECT or loader_state[p] == LoaderState.REDIRECT: + has_redirect = True + if loader_state[p] == LoaderState.ERROR: + has_loader_error = True + if has_loader_notfound == False or has_serial_error == False or has_redirect or has_loader_error: + return True + if final_outcome == Outcome.NONE: + return True + return final_outcome == Outcome.NOT_FOUND + +always assertion LeafErrorUsesParentBoundary: + if final_outcome != Outcome.ERROR or final_source != Presence.LEAF: + return True + return final_boundary == Presence.PARENT + +always assertion LeafNotFoundUsesParentBoundary: + if final_outcome != Outcome.NOT_FOUND or final_source != Presence.LEAF: + return True + return final_boundary == Presence.PARENT + +always assertion RootNotFoundPreservesShell: + if final_outcome != Outcome.NOT_FOUND or final_boundary != Presence.ROOT: + return True + return root_shell_preserved diff --git a/docs/router/route-match-hydration.fizz b/docs/router/route-match-hydration.fizz new file mode 100644 index 0000000000..e710eddb35 --- /dev/null +++ b/docs/router/route-match-hydration.fizz @@ -0,0 +1,176 @@ +--- +deadlock_detection: false +options: + max_actions: 10 + max_concurrent_actions: 1 +--- + +# Phase 2 hydration-focused model. +# +# This spec isolates hydration boundary semantics from the broader overlap/reuse +# model so we can check the cross-adapter contract without paying the full +# multi-generation state-space cost. + +Presence = enum('ROOT', 'PARENT', 'LEAF') +HydrationMode = enum('SERVER_DOM', 'DATA_ONLY', 'CLIENT_ONLY') +RenderGate = enum('BLOCKED', 'PENDING', 'READY', 'ERROR') +DataState = enum('NONE', 'READY', 'LOADING', 'ERROR') + +PRESENCES = [Presence.ROOT, Presence.PARENT, Presence.LEAF] + +action Init: + hydration_started = False + hydration_completed = False + client_load_required = False + client_load_started = False + client_load_completed = False + client_load_failed = False + hydration_boundary = None + + hydration_mode = {} + render_gate = {} + data_state = {} + + hydration_mode[Presence.ROOT] = HydrationMode.SERVER_DOM + hydration_mode[Presence.PARENT] = HydrationMode.SERVER_DOM + hydration_mode[Presence.LEAF] = HydrationMode.SERVER_DOM + + for p in PRESENCES: + render_gate[p] = RenderGate.BLOCKED + data_state[p] = DataState.NONE + +atomic action StartHydration: + require hydration_started == False + leaf_mode = oneof [HydrationMode.SERVER_DOM, HydrationMode.DATA_ONLY, HydrationMode.CLIENT_ONLY] + + hydration_started = True + hydration_mode[Presence.LEAF] = leaf_mode + + render_gate[Presence.ROOT] = RenderGate.READY + render_gate[Presence.PARENT] = RenderGate.READY + data_state[Presence.ROOT] = DataState.READY + data_state[Presence.PARENT] = DataState.READY + + if leaf_mode == HydrationMode.SERVER_DOM: + hydration_boundary = None + client_load_required = False + hydration_completed = True + render_gate[Presence.LEAF] = RenderGate.READY + data_state[Presence.LEAF] = DataState.READY + return + + hydration_boundary = Presence.LEAF + client_load_required = True + render_gate[Presence.LEAF] = RenderGate.PENDING + + if leaf_mode == HydrationMode.DATA_ONLY: + data_state[Presence.LEAF] = DataState.READY + else: + data_state[Presence.LEAF] = DataState.NONE + +atomic action StartClientLoad: + require hydration_started + require client_load_required + require client_load_started == False + + client_load_started = True + + if hydration_mode[Presence.LEAF] == HydrationMode.CLIENT_ONLY: + data_state[Presence.LEAF] = DataState.LOADING + +atomic action CompleteClientLoadSuccess: + require client_load_started + require client_load_completed == False + require client_load_failed == False + + client_load_completed = True + hydration_completed = True + render_gate[Presence.LEAF] = RenderGate.READY + data_state[Presence.LEAF] = DataState.READY + +atomic action CompleteClientLoadError: + require client_load_started + require client_load_completed == False + require client_load_failed == False + + client_load_failed = True + hydration_completed = True + render_gate[Presence.LEAF] = RenderGate.ERROR + data_state[Presence.LEAF] = DataState.ERROR + +always assertion HydrationBoundaryIsFirstClientOwned: + if hydration_started == False: + return True + + if hydration_mode[Presence.LEAF] == HydrationMode.SERVER_DOM: + return hydration_boundary == None + + return hydration_boundary == Presence.LEAF + +always assertion FullSSRHydrationSkipsClientLoad: + if hydration_mode[Presence.LEAF] != HydrationMode.SERVER_DOM: + return True + + if client_load_required: + return False + if client_load_started: + return False + return True + +always assertion HydratedPrefixRemainsRenderable: + if hydration_started == False: + return True + + if render_gate[Presence.ROOT] != RenderGate.READY: + return False + if render_gate[Presence.PARENT] != RenderGate.READY: + return False + if data_state[Presence.ROOT] != DataState.READY: + return False + if data_state[Presence.PARENT] != DataState.READY: + return False + return True + +always assertion DataOnlyUsesServerDataButClientDOM: + if hydration_mode[Presence.LEAF] != HydrationMode.DATA_ONLY: + return True + + if client_load_completed == False and client_load_failed == False: + if data_state[Presence.LEAF] != DataState.READY: + return False + if render_gate[Presence.LEAF] != RenderGate.PENDING: + return False + + return True + +always assertion ClientOnlyBelowBoundaryNotReadyEarly: + if hydration_mode[Presence.LEAF] != HydrationMode.CLIENT_ONLY: + return True + + if client_load_completed == False and render_gate[Presence.LEAF] == RenderGate.READY: + return False + + if client_load_completed == False and data_state[Presence.LEAF] == DataState.READY: + return False + + return True + +always assertion HydrationFailureDoesNotCorruptHydratedPrefix: + if render_gate[Presence.LEAF] != RenderGate.ERROR: + return True + + if render_gate[Presence.ROOT] != RenderGate.READY: + return False + if render_gate[Presence.PARENT] != RenderGate.READY: + return False + return True + +always assertion PendingOnlyAtHydrationBoundary: + for p in [Presence.ROOT, Presence.PARENT]: + if render_gate[p] == RenderGate.PENDING: + return False + + if render_gate[Presence.LEAF] == RenderGate.PENDING and hydration_boundary != Presence.LEAF: + return False + + return True diff --git a/docs/router/route-match-loading-phase-3.md b/docs/router/route-match-loading-phase-3.md new file mode 100644 index 0000000000..7d319ed2f3 --- /dev/null +++ b/docs/router/route-match-loading-phase-3.md @@ -0,0 +1,442 @@ +--- +id: route-match-loading-phase-3 +title: Route Match Loading Phase 3 Guide +--- + +# Route Match Loading Phase 3 Guide + +Status: phase 3 implementation handoff + +This document is the standalone handoff for the phase 3 first-principles rewrite of route-match loading and rendering. + +An agent should be able to start implementation from this document alone. + +## Mission + +Replace the current implicit, pool-and-promise-driven route-match loading pipeline with an explicit generation-based lifecycle that: + +- preserves the intended observable behavior +- eliminates known race conditions and lifecycle bugs +- maps directly to the phase-2 FizzBee models +- keeps adapter-specific mechanics out of router-core + +## Source Of Truth + +If current code, existing tests, and old implementation habits disagree, use this priority order: + +1. This document +2. `docs/router/route-match-loading-rfc.md` +3. The phase-2 `.fizz` models and traces +4. Current implementation details + +This rewrite is spec-first, not legacy-first. + +## Phase 3 Goal + +Build a new internal route-match lifecycle that makes these semantic concepts explicit: + +- route presence identity +- load resource identity +- load generations +- committed tree vs candidate tree +- semantic render gates +- explicit reuse policy +- explicit failure precedence +- explicit hydration boundary semantics + +The rewrite should preserve observable semantics, not internal representation. + +## What We Learned + +### 1. Generations must be first-class + +This is the single most important lesson from phase 2. + +Old work must be explicitly obsolete-able. Newer generations must not be clobbered by stale completions from: + +- old navigations +- preloads +- background stale reloads +- hydration follow-up work + +Do not infer obsolescence from pool transitions, promise replacement, or store mutation order. + +### 2. Identity must be split into separate concepts + +Do not use one implementation key to mean all of the following at once: + +- route presence in the visible tree +- reusable loader artifact identity +- storage record identity + +Treat these as distinct semantic concepts: + +- Route presence identity + The logical continuity of a route in the committed or candidate tree. +- Load resource identity + The identity used to decide whether route-loading artifacts may be reused. +- Storage identity + The implementation-level record/store used to hold runtime state. + +### 3. Router-core should emit semantic render facts, not framework mechanics + +Router-core should decide things like: + +- blocked +- pending +- ready +- error +- notFound +- obsolete/discardable generation + +Adapters should decide how to realize those facts: + +- React promise throwing and boundary placement +- Solid suspense/resource wiring +- Vue DOM-safe rendering behavior + +### 4. Reuse must be policy, not accidental object survival + +The rewrite should encode reuse rules explicitly. + +Current intended policy: + +- `beforeLoad` is conservative preflight/context/authorization work +- `loader` is reusable data acquisition work +- fresh successful loader artifacts may be reused +- in-flight preload loader work may be adopted by navigation +- terminal failure artifacts are not reusable as success data +- later artifact failure must not retroactively poison a navigation that already reused fresh data + +### 5. Slice models worked better than one monolithic model + +Phase 2 succeeded by isolating the hard seams instead of forcing them into one giant exhaustive graph. + +Phase 3 should keep that same structure in code, even if the implementation lives in fewer files. + +That means the rewrite should keep explicit sub-lifecycles for: + +- preflight / `beforeLoad` +- loader / reusable artifact acquisition +- final outcome resolution +- committed-tree update +- hydration boundary handling +- pending timing +- background stale reload handling + +### 6. Context readiness is modeled; full context-value coherence is still the biggest open implementation risk + +Phase 2 proved the importance of context completeness before render, but it models readiness more strongly than concrete merged values. + +Phase 3 should be especially careful about: + +- parent-to-child context visibility +- `beforeLoad` updates becoming render-visible at the right time +- redirecting into a new generation with fresh context +- invalidation and rerun behavior for context-producing routes + +If implementation work exposes uncertainty about actual context-value coherence, pause and extend phase 2 rather than guessing. + +## What Must Be Preserved + +### Committed Tree Coherence + +The user-visible tree must update atomically. + +Do not expose a partially committed mixture of: + +- old and new generations +- old and new route contexts +- old and new terminal outcomes + +### Serial `beforeLoad`, Parallel `loader` + +- `beforeLoad` runs serially from root to leaf +- loader work begins only after the serial preflight prefix is established +- loader work may run in parallel after that + +### Failure Precedence + +The semantic rules are: + +1. Redirect dominates all non-redirect outcomes for the same generation. +2. Winner selection must be deterministic and must not depend on completion timing. +3. notFound and error rendering are resolved against the boundary that actually renders them. +4. Root notFound must preserve the root shell. +5. Child failure may still require ancestor work so the final boundary can render coherently. + +Compatibility baseline already captured in phase 2: + +- loader error beats serial notFound when no redirect is present +- loader notFound beats serial error when no redirect or loader error is present +- leaf notFound resolves to parent boundary +- leaf error resolves to parent boundary + +### Pending Timing Contract + +Pending UI is an observable timing contract, not just a React promise shape. + +Must preserve: + +- pending is not shown before `pendingMs` +- if the load finishes before pending shows, pending never flashes +- once pending becomes visible, it remains visible for at least `pendingMinMs` + +### Hydration Boundary Semantics + +The rewrite must preserve the semantic distinction between: + +- `SERVER_DOM` +- `DATA_ONLY` +- `CLIENT_ONLY` + +Meaning: + +- fully SSR-backed hydration should not trigger an unnecessary extra client load +- a `data-only` boundary may start with usable data while still being client-owned for first meaningful DOM +- a `client-only` boundary must not become render-ready early +- hydrated server-owned prefix must remain coherent even if the client-owned suffix fails + +### Background Stale Reload Semantics + +While stale background work is running: + +- the currently committed view must remain renderable +- a newer committed navigation must not be clobbered by late background completion +- background failure must not force visible error UI for the already committed view by itself + +### Reuse / Adoption Semantics + +Must preserve: + +- fresh artifact reuse on navigation +- in-flight preload adoption by navigation +- obsolete older generations never becoming the committed winner +- failure artifacts not being reused as success data + +## What Must Not Be Copied From The Old Implementation + +These are implementation accidents or legacy shapes, not rewrite goals. + +- active/pending/cached pools as semantic truth +- `_nonReactive.*Promise` names as part of the design +- `match.id` string construction as the semantic definition of reuse identity +- `globalNotFound` as a required representation +- hydration heuristics expressed as index-based hacks rather than boundary semantics +- adapter behavior being driven directly by router-core promise lifetime accidents + +These may still exist internally if useful, but only as implementation details under clearer semantic state. + +## Recommended Internal Architecture + +### Core Runtime Concepts + +Implement explicit runtime records for these concepts. + +1. Route presence record + Represents a route's presence in a committed or candidate tree. + +2. Load resource record + Represents reusable route-loading artifacts and their freshness. + +3. Generation record + Represents one causally ordered attempt to make a candidate tree render-ready. + +4. Render gate record + Represents semantic visibility state for a route presence in a generation. + +### Suggested Generation Record + +The implementation does not need these exact names, but it should expose these concepts clearly. + +- generation id +- entry type + Initial load, navigation, preload, hydration follow-up, background reload +- obsolete / live status +- candidate tree +- per-route preflight status +- per-resource loader status +- final resolved outcome +- winning boundary owner, if any +- commit eligibility + +### Suggested Resource Record + +- resource identity +- acquisition status +- freshness +- reusable success payload +- non-reusable terminal failure marker +- which generations are currently observing or adopting it + +### Suggested Render-Gate API + +Router-core should produce a small semantic gate surface, for example: + +- `blocked` +- `pending` +- `ready` +- `error` +- `notFound` +- `obsolete` + +The exact names can differ, but phase 3 should keep the surface small and semantic. + +### Suggested Lifecycle Split + +Keep the implementation factored around these responsibilities: + +1. Candidate-tree construction +2. Preflight runner +3. Resource acquisition / reuse / adoption +4. Final outcome resolver +5. Commit coordinator +6. Hydration coordinator +7. Adapter gate mapping + +This is preferable to keeping all logic in one mega-pipeline, even if the old code centered around `loadMatches()`. + +## Recommended Rewrite Strategy + +### 1. Keep the public API stable while replacing internals + +Prefer replacing internal orchestration behind existing public router behavior. + +Do not start by redesigning public route APIs. + +### 2. Build the new core semantics before rewriting adapter mechanics + +Recommended order: + +1. introduce generation/resource/presence concepts in router-core +2. reimplement finalization and commit logic around them +3. reimplement preflight and loader orchestration +4. expose semantic render gates to adapters +5. port React adapter to semantic gates +6. align Solid and Vue afterward + +### 3. Port React first + +React remains the main focus. + +The React adapter should consume semantic gates and preserve: + +- pending continuity +- redirect discard safety +- root-shell notFound behavior +- hydration boundary behavior + +React-specific promise handling should become an adapter implementation of semantic states, not the core lifecycle itself. + +### 4. Keep slice-based testability + +Every focused `.fizz` model should correspond to focused implementation tests. + +Suggested mapping: + +- `route-match-hydration.fizz` -> hydration adapter/core tests +- `route-match-overlap.fizz` -> preload/navigation reuse tests +- `route-match-background.fizz` -> stale reload / newer navigation tests +- `route-match-pending.fizz` -> pending timing tests +- `route-match-failures.fizz` -> failure precedence and boundary tests + +## Minimum Acceptance Criteria For Phase 3 + +Before considering the rewrite correct, the implementation should satisfy all of the following: + +1. The new internal state machine is generation-based, not promise-lifetime-based. +2. Render-visible route components never observe incomplete effective context. +3. Redirects, notFound, and errors follow the modeled precedence and boundary rules. +4. Fresh reuse and in-flight adoption match the overlap model. +5. Background stale reloads cannot clobber newer committed state. +6. Pending timing matches the pending model. +7. Hydration semantics match the hydration model. +8. React adapter behavior matches semantic render gates instead of inventing its own lifecycle. +9. Existing tests are updated or replaced where they encode accidental legacy behavior. +10. New focused tests exist for each model slice. + +## Remaining Doubts + +These are the few remaining uncertainties that are real enough to justify more phase-2 work if phase 3 runs into them. + +### Doubt 1. Concrete context-value coherence + +We modeled context readiness, but not full merged context values. + +If phase 3 needs to answer questions like: + +- exactly when a child should observe a parent's `beforeLoad` return +- whether route `context()` should rerun in a corner case +- how invalidation changes context value reuse + +then extend phase 2 before finalizing the implementation. + +### Doubt 2. Invalidation and eviction semantics are weaker than the other slices + +The suite covers stale background reload and explicit resource freshness, but it does not yet have a dedicated invalidation/eviction model slice. + +If phase 3 work reaches GC, cache eviction, or invalidation corner cases that affect visible lifecycle guarantees, pause and model that slice first. + +### Doubt 3. One shared exhaustive model does not exist + +The phase-2 suite is intentionally slice-based. + +If a phase-3 design depends on subtle interactions across: + +- hydration +- pending timing +- background reload +- failure precedence +- reuse/adoption + +then consider adding a targeted combined model for that exact interaction, rather than assuming the cross-product is already proven. + +### Doubt 4. Adapter-specific continuity is still semantic, not mechanical + +The suite proves adapter obligations semantically, not the exact promise choreography inside React/Solid/Vue. + +If an adapter rewrite runs into a framework-specific lifecycle puzzle, model or test that mechanism directly instead of forcing router-core to own it. + +## Exact Phase 2 Assets + +Primary RFC and status: + +- `docs/router/route-match-loading-rfc.md` + +Core and focused models: + +- `docs/router/route-match-loading.fizz` +- `docs/router/route-match-hydration.fizz` +- `docs/router/route-match-overlap.fizz` +- `docs/router/route-match-background.fizz` +- `docs/router/route-match-pending.fizz` +- `docs/router/route-match-failures.fizz` + +Useful trace files: + +- `docs/router/route-match-overlap-fresh.trace` +- `docs/router/route-match-overlap-adopt.trace` +- `docs/router/route-match-background-late-success.trace` +- `docs/router/route-match-background-failure.trace` +- `docs/router/route-match-pending-fast.trace` +- `docs/router/route-match-pending-slow.trace` +- `docs/router/route-match-failures-root-notfound.trace` +- `docs/router/route-match-failures-leaf-notfound.trace` +- `docs/router/route-match-failures-notfound-redirect.trace` +- `docs/router/route-match-failures-error-vs-loader-notfound.trace` +- `docs/router/route-match-failures-leaf-loader-error.trace` + +Current code hotspots to replace or absorb: + +- `packages/router-core/src/load-matches.ts` +- `packages/router-core/src/router.ts` +- `packages/router-core/src/ssr/ssr-client.ts` +- `packages/react-router/src/Match.tsx` + +## Final Instruction To A Phase 3 Agent + +Do not start by reshuffling the current code. + +Start by implementing explicit semantic state in router-core that matches the model suite. Then make React consume that state. Only after the semantic core is stable should you align the other adapters and remove obsolete legacy machinery. + +If implementation work exposes uncertainty about semantics rather than code mechanics, stop and iterate on phase 2 before shipping the rewrite. diff --git a/docs/router/route-match-loading-rfc.md b/docs/router/route-match-loading-rfc.md index 8792be1444..4cb77983e3 100644 --- a/docs/router/route-match-loading-rfc.md +++ b/docs/router/route-match-loading-rfc.md @@ -5,7 +5,7 @@ title: Route Match Loading RFC # Route Match Loading And Rendering RFC -Status: phase 1 core contract complete, phase 2 ready to start +Status: phase 1 complete, phase 2 complete, phase 3 ready to start Owner: multi-session effort, React-first @@ -1012,49 +1012,98 @@ What remains intentionally provisional going into phase 2: - whether strict cross-pool exclusivity is worth preserving as an implementation simplifier - whether the current compatibility precedence baseline should survive unchanged once modeled semantically -## Phase 2 Progress +## Phase 2 Status -Phase 2 has started. +Phase 2 is complete. + +The resulting artifact is a suite of focused executable FizzBee models, not one monolithic exhaustive model. The broad umbrella spec remains useful for exploration, but phase-2 correctness is now carried by the focused slice models below. Artifacts added: -- executable model: `docs/router/route-match-loading.fizz` -- tiny exhaustive-check config: `docs/router/route-match-loading-tiny.cfg` -- two-generation exploratory config: `docs/router/route-match-loading-small.cfg` +- core model: `docs/router/route-match-loading.fizz` +- core tiny exhaustive-check config: `docs/router/route-match-loading-tiny.cfg` +- core two-generation exploratory config: `docs/router/route-match-loading-small.cfg` +- hydration-focused model: `docs/router/route-match-hydration.fizz` +- overlap/reuse-focused model: `docs/router/route-match-overlap.fizz` +- background-reload-focused model: `docs/router/route-match-background.fizz` +- pending-timing-focused model: `docs/router/route-match-pending.fizz` +- failure-precedence-focused model: `docs/router/route-match-failures.fizz` +- overlap scenario traces: `docs/router/route-match-overlap-fresh.trace`, `docs/router/route-match-overlap-adopt.trace` +- background scenario traces: `docs/router/route-match-background-late-success.trace`, `docs/router/route-match-background-failure.trace` +- pending scenario traces: `docs/router/route-match-pending-fast.trace`, `docs/router/route-match-pending-slow.trace` +- failure scenario traces: `docs/router/route-match-failures-root-notfound.trace`, `docs/router/route-match-failures-leaf-notfound.trace`, `docs/router/route-match-failures-notfound-redirect.trace`, `docs/router/route-match-failures-error-vs-loader-notfound.trace`, `docs/router/route-match-failures-leaf-loader-error.trace` -Current modeled semantics: +Phase-1 semantic coverage now maps to the suite like this: -- committed tree vs candidate generation separation -- route presence identity vs reusable leaf-resource identity -- serial `beforeLoad` progression with parent-context gating -- parallel loader progression after serial preflight -- redirect dominance during finalization -- notFound boundary ownership and root-shell preservation -- reusable artifact success reuse, in-flight adoption, and failure non-reuse -- stale-generation protection for committed-state updates -- commit atomicity as a model assertion +- committed tree vs candidate generation separation, effective context readiness, notFound root-shell preservation, and core finalization structure: `docs/router/route-match-loading.fizz` +- hydration boundary semantics for fully SSR-backed, `data-only`, and `client-only` leaf boundaries: `docs/router/route-match-hydration.fizz` +- fresh artifact reuse, preload adoption, obsolete-generation non-commit, and generation-local reuse safety: `docs/router/route-match-overlap.fizz` +- background stale reload and late-completion non-clobbering: `docs/router/route-match-background.fizz` +- pending timing contract (`pendingMs` / `pendingMinMs`) at the semantic level: `docs/router/route-match-pending.fizz` +- failure precedence, ancestor preservation, redirect dominance, and error/notFound boundary ownership: `docs/router/route-match-failures.fizz` -Not yet modeled in the first executable spec: +Items intentionally left out of the phase-2 suite because they are implementation refinements rather than blockers for phase 3: -- hydration boundary semantics -- adapter-specific pending display timing beyond the abstract contract -- a richer cross-generation model with exhaustive overlap checking for multiple live generations -- more precise error-boundary ownership beyond the current simplified source-owner rule +- one shared exhaustive model covering every slice at once +- adapter-specific rendering mechanics such as React promise throwing or Vue DOM workarounds +- code-splitting, chunk loading, and head/script asset semantics beyond their effect on readiness and boundary availability Current verification status: - `fizz --preinit-hook-file docs/router/route-match-loading-tiny.cfg docs/router/route-match-loading.fizz` Passed with `Valid Nodes: 12954` and `Unique states: 1007`. - `fizz --preinit-hook-file docs/router/route-match-loading-small.cfg docs/router/route-match-loading.fizz` - Remains useful for exploration but currently exceeds the 2-minute local command budget; it is the next target for state-space reduction or scenario-focused guided traces. + Remains useful for exploration but currently exceeds the 2-minute local command budget; it is now treated as an exploratory umbrella model rather than the only overlap-checking path. +- `fizz docs/router/route-match-hydration.fizz` + Passed with `Valid Nodes: 11` and `Unique states: 10`. +- `fizz docs/router/route-match-overlap.fizz` + Passed with `Valid Nodes: 162` and `Unique states: 162`. +- `fizz docs/router/route-match-background.fizz` + Passed with `Valid Nodes: 36` and `Unique states: 36`. +- `fizz docs/router/route-match-pending.fizz` + Passed with `Valid Nodes: 7` and `Unique states: 7`. +- `fizz docs/router/route-match-failures.fizz` + Passed with `Valid Nodes: 1740` and `Unique states: 348`. +- `fizz --trace-file docs/router/route-match-overlap-fresh.trace docs/router/route-match-overlap.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-overlap-adopt.trace docs/router/route-match-overlap.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-background-late-success.trace docs/router/route-match-background.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-background-failure.trace docs/router/route-match-background.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-pending-fast.trace docs/router/route-match-pending.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-pending-slow.trace docs/router/route-match-pending.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-failures-root-notfound.trace docs/router/route-match-failures.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-failures-leaf-notfound.trace docs/router/route-match-failures.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-failures-notfound-redirect.trace docs/router/route-match-failures.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-failures-error-vs-loader-notfound.trace docs/router/route-match-failures.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-failures-leaf-loader-error.trace docs/router/route-match-failures.fizz` + Passed. Initial model-driven corrections already made while starting phase 2: - root-shell notFound rendering needed explicit context completion in the model to satisfy the context-ready invariant - fresh-artifact reuse needed a generation-local assertion rather than one tied to the artifact's later global state - the phase-2 model structure worked better when helper logic was inlined instead of relying on top-level function calls in FizzBee actions +- overlap/reuse reachability works better as explicit guided traces than as `exists assertion`s in the current FizzBee toolchain +- a later artifact failure must not retroactively poison a navigation that already reused fresh data; the overlap model now encodes that explicitly +- failure precedence assertions had to be conditioned on higher-ranked outcomes being absent, which helped sharpen the semantic precedence rules -## Phase 2 Bootstrap +Phase 2 exit criteria met: + +- every remaining phase-1 semantic gap was given a focused executable model or trace-backed scenario +- all focused slice models pass exhaustive bounded checks +- all critical scenario traces pass +- remaining non-modeled details are now implementation refinements, not blockers for phase 3 + +## Phase 2 Bootstrap (Historical) Phase 1's core semantic contract is complete enough to start modeling. diff --git a/docs/router/route-match-loading-small.cfg b/docs/router/route-match-loading-small.cfg new file mode 100644 index 0000000000..f07c95d563 --- /dev/null +++ b/docs/router/route-match-loading-small.cfg @@ -0,0 +1,2 @@ +GEN_IDS = [1, 2] +RESOURCES = [Resource.LEAF_A] diff --git a/docs/router/route-match-loading-tiny.cfg b/docs/router/route-match-loading-tiny.cfg new file mode 100644 index 0000000000..55a8b6883d --- /dev/null +++ b/docs/router/route-match-loading-tiny.cfg @@ -0,0 +1,2 @@ +GEN_IDS = [1] +RESOURCES = [Resource.LEAF_A] diff --git a/docs/router/route-match-loading.fizz b/docs/router/route-match-loading.fizz new file mode 100644 index 0000000000..f20e468468 --- /dev/null +++ b/docs/router/route-match-loading.fizz @@ -0,0 +1,529 @@ +--- +deadlock_detection: false +options: + max_actions: 20 + max_concurrent_actions: 1 +--- + +# Phase 2 initial model for route-match loading semantics. +# +# This first executable spec focuses on: +# - committed tree vs candidate generations +# - route presence identity vs reusable loader artifacts +# - serial beforeLoad then parallel loaders +# - redirect dominance and notFound boundary ownership +# - preload/background artifact reuse +# - stale-generation isolation for committed state +# +# It intentionally does not yet model all hydration details or adapter-specific +# rendering mechanics. Those will layer on top of the semantic render-gate model. + +Presence = enum('ROOT', 'PARENT', 'LEAF') +Entry = enum('NONE', 'INITIAL', 'NAVIGATION', 'PRELOAD', 'BACKGROUND') +PreflightState = enum('NOT_STARTED', 'SUCCESS', 'REDIRECT', 'NOT_FOUND', 'ERROR') +DataState = enum('NOT_STARTED', 'IN_FLIGHT', 'SUCCESS', 'REDIRECT', 'NOT_FOUND', 'ERROR') +ContextState = enum('UNKNOWN', 'PARENT_READY', 'READY') +RenderGate = enum('BLOCKED', 'PENDING', 'READY', 'NOT_FOUND', 'ERROR') +Outcome = enum('NONE', 'SUCCESS', 'REDIRECT', 'NOT_FOUND', 'ERROR') +ArtifactState = enum('NONE', 'IN_FLIGHT', 'SUCCESS', 'REDIRECT', 'NOT_FOUND', 'ERROR') +Freshness = enum('NONE', 'FRESH', 'STALE', 'INVALID') +Obsolescence = enum('LIVE', 'OBSOLETE') +Resource = enum('LEAF_A', 'LEAF_B') + +GEN_IDS = [1, 2, 3] +PRESENCES = [Presence.ROOT, Presence.PARENT, Presence.LEAF] +RESOURCES = [Resource.LEAF_A, Resource.LEAF_B] + +atomic func initialize_generation(g, entry, leaf_resource): + generation_entry[g] = entry + generation_obsolete[g] = Obsolescence.LIVE + generation_candidate_tree[g] = [Presence.ROOT, Presence.PARENT, Presence.LEAF] + generation_leaf_resource[g] = leaf_resource + generation_serial_cursor[g] = Presence.ROOT + generation_provisional_outcome[g] = Outcome.NONE + generation_final_outcome[g] = Outcome.NONE + generation_boundary_owner[g] = None + generation_error_source[g] = None + generation_root_shell_preserved[g] = False + generation_loaders_launched[g] = False + generation_used_fresh_artifact[g] = False + generation_adopted_inflight[g] = False + + for p in PRESENCES: + preflight_state[(g, p)] = PreflightState.NOT_STARTED + data_state[(g, p)] = DataState.NOT_STARTED + context_state[(g, p)] = ContextState.UNKNOWN + render_gate[(g, p)] = RenderGate.BLOCKED + + context_state[(g, Presence.ROOT)] = ContextState.PARENT_READY + +action Init: + next_generation = 1 + committed_tree = [] + committed_generation = 0 + + generation_entry = {} + generation_obsolete = {} + generation_candidate_tree = {} + generation_leaf_resource = {} + generation_serial_cursor = {} + generation_provisional_outcome = {} + generation_final_outcome = {} + generation_boundary_owner = {} + generation_error_source = {} + generation_root_shell_preserved = {} + generation_loaders_launched = {} + generation_used_fresh_artifact = {} + generation_adopted_inflight = {} + + preflight_state = {} + data_state = {} + context_state = {} + render_gate = {} + + artifact_state = {} + artifact_freshness = {} + + for resource in RESOURCES: + artifact_state[resource] = ArtifactState.NONE + artifact_freshness[resource] = Freshness.NONE + + for g in GEN_IDS: + generation_entry[g] = Entry.NONE + generation_obsolete[g] = Obsolescence.OBSOLETE + generation_candidate_tree[g] = [] + generation_leaf_resource[g] = None + generation_serial_cursor[g] = None + generation_provisional_outcome[g] = Outcome.NONE + generation_final_outcome[g] = Outcome.NONE + generation_boundary_owner[g] = None + generation_error_source[g] = None + generation_root_shell_preserved[g] = False + generation_loaders_launched[g] = False + generation_used_fresh_artifact[g] = False + generation_adopted_inflight[g] = False + + for p in PRESENCES: + preflight_state[(g, p)] = PreflightState.NOT_STARTED + data_state[(g, p)] = DataState.NOT_STARTED + context_state[(g, p)] = ContextState.UNKNOWN + render_gate[(g, p)] = RenderGate.BLOCKED + +atomic action StartInitialLoad: + require next_generation == 1 + initialize_generation(next_generation, Entry.INITIAL, Resource.LEAF_A) + next_generation = next_generation + 1 + +atomic action StartPreload: + require committed_generation != 0 + require next_generation <= 3 + require len([g for g in GEN_IDS if generation_entry[g] == Entry.PRELOAD and generation_obsolete[g] == Obsolescence.LIVE]) == 0 + leaf_resource = oneof RESOURCES + initialize_generation(next_generation, Entry.PRELOAD, leaf_resource) + next_generation = next_generation + 1 + +atomic action StartNavigation: + require committed_generation != 0 + require next_generation <= 3 + leaf_resource = oneof RESOURCES + + for g in GEN_IDS: + if generation_entry[g] != Entry.NONE and generation_obsolete[g] == Obsolescence.LIVE and g != committed_generation: + generation_obsolete[g] = Obsolescence.OBSOLETE + + initialize_generation(next_generation, Entry.NAVIGATION, leaf_resource) + next_generation = next_generation + 1 + +atomic action MarkCommittedArtifactStale: + require committed_generation != 0 + resource = generation_leaf_resource[committed_generation] + require artifact_state[resource] == ArtifactState.SUCCESS + artifact_freshness[resource] = Freshness.STALE + +atomic action InvalidateCommittedResource: + require committed_generation != 0 + resource = generation_leaf_resource[committed_generation] + require artifact_state[resource] == ArtifactState.SUCCESS + artifact_freshness[resource] = Freshness.INVALID + +atomic action StartBackgroundReload: + require committed_generation != 0 + require next_generation <= 3 + resource = generation_leaf_resource[committed_generation] + require artifact_freshness[resource] in [Freshness.STALE, Freshness.INVALID] + initialize_generation(next_generation, Entry.BACKGROUND, resource) + next_generation = next_generation + 1 + +atomic action ResolveBeforeLoadSuccess: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE and generation_serial_cursor[gen] != None + p = generation_serial_cursor[gen] + + preflight_state[(gen, p)] = PreflightState.SUCCESS + context_state[(gen, p)] = ContextState.READY + + nxt = None + if p == Presence.ROOT: + nxt = Presence.PARENT + elif p == Presence.PARENT: + nxt = Presence.LEAF + + if nxt != None: + context_state[(gen, nxt)] = ContextState.PARENT_READY + + generation_serial_cursor[gen] = nxt + +atomic action ResolveBeforeLoadRedirect: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE and generation_serial_cursor[gen] != None + p = generation_serial_cursor[gen] + preflight_state[(gen, p)] = PreflightState.REDIRECT + generation_provisional_outcome[gen] = Outcome.REDIRECT + generation_final_outcome[gen] = Outcome.REDIRECT + generation_serial_cursor[gen] = None + +atomic action ResolveBeforeLoadNotFound: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE and generation_serial_cursor[gen] != None + p = generation_serial_cursor[gen] + preflight_state[(gen, p)] = PreflightState.NOT_FOUND + generation_provisional_outcome[gen] = Outcome.NOT_FOUND + if p == Presence.ROOT: + generation_boundary_owner[gen] = Presence.ROOT + else: + generation_boundary_owner[gen] = Presence.PARENT + generation_serial_cursor[gen] = None + +atomic action ResolveBeforeLoadError: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE and generation_serial_cursor[gen] != None + p = generation_serial_cursor[gen] + preflight_state[(gen, p)] = PreflightState.ERROR + generation_provisional_outcome[gen] = Outcome.ERROR + generation_error_source[gen] = p + generation_serial_cursor[gen] = None + +atomic action LaunchEligibleLoaders: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE + require generation_serial_cursor[gen] == None + require generation_loaders_launched[gen] == False + require generation_final_outcome[gen] != Outcome.REDIRECT + + limit = 2 + if generation_provisional_outcome[gen] == Outcome.NOT_FOUND: + if generation_boundary_owner[gen] == Presence.ROOT: + limit = 0 + else: + limit = 1 + elif generation_provisional_outcome[gen] == Outcome.ERROR: + if generation_error_source[gen] == Presence.ROOT: + limit = -1 + elif generation_error_source[gen] == Presence.PARENT: + limit = 0 + else: + limit = 1 + + for p in PRESENCES: + p_depth = 0 + if p == Presence.PARENT: + p_depth = 1 + elif p == Presence.LEAF: + p_depth = 2 + + if p_depth <= limit: + if p == Presence.LEAF: + resource = generation_leaf_resource[gen] + if generation_entry[gen] == Entry.NAVIGATION and artifact_state[resource] == ArtifactState.SUCCESS and artifact_freshness[resource] == Freshness.FRESH: + data_state[(gen, p)] = DataState.SUCCESS + generation_used_fresh_artifact[gen] = True + else: + data_state[(gen, p)] = DataState.IN_FLIGHT + if artifact_state[resource] == ArtifactState.IN_FLIGHT: + generation_adopted_inflight[gen] = True + else: + artifact_state[resource] = ArtifactState.IN_FLIGHT + artifact_freshness[resource] = Freshness.NONE + else: + data_state[(gen, p)] = DataState.IN_FLIGHT + + generation_loaders_launched[gen] = True + +atomic action ResolveLoaderSuccess: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE + require len([p for p in PRESENCES if data_state[(gen, p)] == DataState.IN_FLIGHT]) > 0 + p = oneof PRESENCES + require data_state[(gen, p)] == DataState.IN_FLIGHT + + if p == Presence.LEAF: + resource = generation_leaf_resource[gen] + if artifact_state[resource] == ArtifactState.IN_FLIGHT: + artifact_state[resource] = ArtifactState.SUCCESS + artifact_freshness[resource] = Freshness.FRESH + for g in GEN_IDS: + if generation_leaf_resource[g] == resource and data_state[(g, Presence.LEAF)] == DataState.IN_FLIGHT: + data_state[(g, Presence.LEAF)] = DataState.SUCCESS + else: + data_state[(gen, p)] = DataState.SUCCESS + return + + data_state[(gen, p)] = DataState.SUCCESS + +atomic action ResolveLoaderRedirect: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE + require len([p for p in PRESENCES if data_state[(gen, p)] == DataState.IN_FLIGHT]) > 0 + p = oneof PRESENCES + require data_state[(gen, p)] == DataState.IN_FLIGHT + + if p == Presence.LEAF: + resource = generation_leaf_resource[gen] + if artifact_state[resource] == ArtifactState.IN_FLIGHT: + artifact_state[resource] = ArtifactState.REDIRECT + artifact_freshness[resource] = Freshness.NONE + for g in GEN_IDS: + if generation_leaf_resource[g] == resource and data_state[(g, Presence.LEAF)] == DataState.IN_FLIGHT: + data_state[(g, Presence.LEAF)] = DataState.REDIRECT + else: + data_state[(gen, p)] = DataState.REDIRECT + return + + data_state[(gen, p)] = DataState.REDIRECT + +atomic action ResolveLoaderNotFound: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE + require len([p for p in PRESENCES if data_state[(gen, p)] == DataState.IN_FLIGHT]) > 0 + p = oneof PRESENCES + require data_state[(gen, p)] == DataState.IN_FLIGHT + + if p == Presence.LEAF: + resource = generation_leaf_resource[gen] + if artifact_state[resource] == ArtifactState.IN_FLIGHT: + artifact_state[resource] = ArtifactState.NOT_FOUND + artifact_freshness[resource] = Freshness.NONE + for g in GEN_IDS: + if generation_leaf_resource[g] == resource and data_state[(g, Presence.LEAF)] == DataState.IN_FLIGHT: + data_state[(g, Presence.LEAF)] = DataState.NOT_FOUND + else: + data_state[(gen, p)] = DataState.NOT_FOUND + return + + data_state[(gen, p)] = DataState.NOT_FOUND + +atomic action ResolveLoaderError: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE + require len([p for p in PRESENCES if data_state[(gen, p)] == DataState.IN_FLIGHT]) > 0 + p = oneof PRESENCES + require data_state[(gen, p)] == DataState.IN_FLIGHT + + if p == Presence.LEAF: + resource = generation_leaf_resource[gen] + if artifact_state[resource] == ArtifactState.IN_FLIGHT: + artifact_state[resource] = ArtifactState.ERROR + artifact_freshness[resource] = Freshness.NONE + for g in GEN_IDS: + if generation_leaf_resource[g] == resource and data_state[(g, Presence.LEAF)] == DataState.IN_FLIGHT: + data_state[(g, Presence.LEAF)] = DataState.ERROR + else: + data_state[(gen, p)] = DataState.ERROR + return + + data_state[(gen, p)] = DataState.ERROR + +atomic action FinalizeGeneration: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE + require generation_final_outcome[gen] == Outcome.NONE + require generation_serial_cursor[gen] == None + require generation_provisional_outcome[gen] == Outcome.REDIRECT or (generation_loaders_launched[gen] and len([p for p in PRESENCES if data_state[(gen, p)] == DataState.IN_FLIGHT]) == 0) + + redirect_source = None + error_source = None + not_found_source = None + for p in PRESENCES: + if redirect_source == None and (preflight_state[(gen, p)] == PreflightState.REDIRECT or data_state[(gen, p)] == DataState.REDIRECT): + redirect_source = p + if error_source == None and (preflight_state[(gen, p)] == PreflightState.ERROR or data_state[(gen, p)] == DataState.ERROR): + error_source = p + if not_found_source == None and (preflight_state[(gen, p)] == PreflightState.NOT_FOUND or data_state[(gen, p)] == DataState.NOT_FOUND): + not_found_source = p + + if generation_provisional_outcome[gen] == Outcome.REDIRECT or redirect_source != None: + generation_final_outcome[gen] = Outcome.REDIRECT + return + + if error_source != None or generation_provisional_outcome[gen] == Outcome.ERROR: + generation_final_outcome[gen] = Outcome.ERROR + if error_source == None: + error_source = generation_error_source[gen] + generation_boundary_owner[gen] = error_source + if error_source == Presence.ROOT: + context_state[(gen, Presence.ROOT)] = ContextState.READY + render_gate[(gen, Presence.ROOT)] = RenderGate.ERROR + render_gate[(gen, Presence.PARENT)] = RenderGate.BLOCKED + render_gate[(gen, Presence.LEAF)] = RenderGate.BLOCKED + elif error_source == Presence.PARENT: + context_state[(gen, Presence.ROOT)] = ContextState.READY + context_state[(gen, Presence.PARENT)] = ContextState.READY + render_gate[(gen, Presence.ROOT)] = RenderGate.READY + render_gate[(gen, Presence.PARENT)] = RenderGate.ERROR + render_gate[(gen, Presence.LEAF)] = RenderGate.BLOCKED + else: + context_state[(gen, Presence.ROOT)] = ContextState.READY + context_state[(gen, Presence.PARENT)] = ContextState.READY + context_state[(gen, Presence.LEAF)] = ContextState.READY + render_gate[(gen, Presence.ROOT)] = RenderGate.READY + render_gate[(gen, Presence.PARENT)] = RenderGate.READY + render_gate[(gen, Presence.LEAF)] = RenderGate.ERROR + return + + if not_found_source != None or generation_provisional_outcome[gen] == Outcome.NOT_FOUND: + generation_final_outcome[gen] = Outcome.NOT_FOUND + if not_found_source == None: + if generation_boundary_owner[gen] == Presence.ROOT: + generation_boundary_owner[gen] = Presence.ROOT + else: + generation_boundary_owner[gen] = Presence.PARENT + else: + if not_found_source == Presence.ROOT: + generation_boundary_owner[gen] = Presence.ROOT + else: + generation_boundary_owner[gen] = Presence.PARENT + + owner = generation_boundary_owner[gen] + if owner == Presence.ROOT: + generation_root_shell_preserved[gen] = True + context_state[(gen, Presence.ROOT)] = ContextState.READY + render_gate[(gen, Presence.ROOT)] = RenderGate.READY + render_gate[(gen, Presence.PARENT)] = RenderGate.BLOCKED + render_gate[(gen, Presence.LEAF)] = RenderGate.BLOCKED + return + + context_state[(gen, Presence.ROOT)] = ContextState.READY + context_state[(gen, Presence.PARENT)] = ContextState.READY + render_gate[(gen, Presence.ROOT)] = RenderGate.READY + render_gate[(gen, Presence.PARENT)] = RenderGate.NOT_FOUND + render_gate[(gen, Presence.LEAF)] = RenderGate.BLOCKED + return + + generation_final_outcome[gen] = Outcome.SUCCESS + for p in PRESENCES: + render_gate[(gen, p)] = RenderGate.READY + +atomic action CommitCandidateTree: + gen = oneof GEN_IDS + require generation_entry[gen] != Entry.NONE and generation_obsolete[gen] == Obsolescence.LIVE + require generation_entry[gen] != Entry.PRELOAD + require generation_final_outcome[gen] in [Outcome.SUCCESS, Outcome.NOT_FOUND, Outcome.ERROR] + + previous_committed = committed_generation + committed_tree = generation_candidate_tree[gen] + committed_generation = gen + + if previous_committed != 0 and previous_committed != gen: + generation_obsolete[previous_committed] = Obsolescence.OBSOLETE + + for g in GEN_IDS: + if g != gen and generation_entry[g] != Entry.NONE and generation_entry[g] != Entry.PRELOAD and generation_obsolete[g] == Obsolescence.LIVE: + generation_obsolete[g] = Obsolescence.OBSOLETE + +always assertion ReadyImpliesContextReady: + for g in GEN_IDS: + for p in PRESENCES: + if render_gate[(g, p)] == RenderGate.READY and context_state[(g, p)] != ContextState.READY: + return False + return True + +always assertion BeforeLoadIsSerial: + for g in GEN_IDS: + if preflight_state[(g, Presence.PARENT)] != PreflightState.NOT_STARTED and preflight_state[(g, Presence.ROOT)] != PreflightState.SUCCESS: + return False + if preflight_state[(g, Presence.LEAF)] != PreflightState.NOT_STARTED and preflight_state[(g, Presence.PARENT)] != PreflightState.SUCCESS: + return False + return True + +always assertion CommittedGenerationIsLive: + if committed_generation == 0: + return True + return generation_obsolete[committed_generation] == Obsolescence.LIVE + +always assertion CommitMatchesCandidate: + if committed_generation == 0: + return True + return committed_tree == generation_candidate_tree[committed_generation] + +always assertion NotFoundBoundaryOwnerCorrect: + for g in GEN_IDS: + if generation_final_outcome[g] == Outcome.NOT_FOUND: + owner = generation_boundary_owner[g] + if owner == None: + return False + + source = None + for p in PRESENCES: + if source == None and (preflight_state[(g, p)] == PreflightState.NOT_FOUND or data_state[(g, p)] == DataState.NOT_FOUND): + source = p + + expected_owner = owner + if source != None: + if source == Presence.ROOT: + expected_owner = Presence.ROOT + else: + expected_owner = Presence.PARENT + + if owner != expected_owner: + return False + return True + +always assertion AncestorPreservedOnLeafBeforeLoadNotFound: + for g in GEN_IDS: + if preflight_state[(g, Presence.LEAF)] == PreflightState.NOT_FOUND and generation_loaders_launched[g]: + if data_state[(g, Presence.ROOT)] == DataState.NOT_STARTED: + return False + if data_state[(g, Presence.PARENT)] == DataState.NOT_STARTED: + return False + if data_state[(g, Presence.LEAF)] != DataState.NOT_STARTED: + return False + return True + +always assertion FreshArtifactReuseProducesLeafSuccess: + for g in GEN_IDS: + if generation_used_fresh_artifact[g]: + if generation_entry[g] != Entry.NAVIGATION: + return False + if generation_leaf_resource[g] == None: + return False + if data_state[(g, Presence.LEAF)] != DataState.SUCCESS: + return False + return True + +always assertion NoFailureArtifactReuseAsSuccess: + for resource in RESOURCES: + if artifact_state[resource] in [ArtifactState.REDIRECT, ArtifactState.NOT_FOUND, ArtifactState.ERROR]: + for g in GEN_IDS: + if generation_leaf_resource[g] == resource and generation_used_fresh_artifact[g]: + return False + return True + +always assertion RootNotFoundPreservesShell: + for g in GEN_IDS: + if generation_final_outcome[g] == Outcome.NOT_FOUND and generation_boundary_owner[g] == Presence.ROOT: + if generation_root_shell_preserved[g] == False: + return False + if render_gate[(g, Presence.ROOT)] != RenderGate.READY: + return False + return True + +always assertion ObsoleteGenerationNeverCommitted: + for g in GEN_IDS: + if generation_obsolete[g] == Obsolescence.OBSOLETE and committed_generation == g: + return False + return True + +always assertion CommitUsesResolvedGeneration: + if committed_generation == 0: + return True + return generation_final_outcome[committed_generation] in [Outcome.SUCCESS, Outcome.NOT_FOUND, Outcome.ERROR] diff --git a/docs/router/route-match-overlap.fizz b/docs/router/route-match-overlap.fizz new file mode 100644 index 0000000000..1328162651 --- /dev/null +++ b/docs/router/route-match-overlap.fizz @@ -0,0 +1,181 @@ +--- +deadlock_detection: false +options: + max_actions: 14 + max_concurrent_actions: 1 +--- + +# Phase 2 overlap-focused model. +# +# This spec isolates one high-value overlapping-generation slice: +# - a committed base route already exists +# - a preload may start an in-flight artifact load +# - a newer navigation may adopt that in-flight artifact or reuse a fresh one +# - obsolete generations must not commit visible state + +Generation = enum('OLDER', 'NEWER') +Entry = enum('NONE', 'PRELOAD', 'NAVIGATION') +PreflightState = enum('NOT_STARTED', 'SUCCESS') +DataState = enum('NOT_STARTED', 'IN_FLIGHT', 'SUCCESS', 'FAILURE') +ArtifactState = enum('SUCCESS', 'IN_FLIGHT', 'NON_REUSABLE_FAILURE') +Freshness = enum('FRESH', 'STALE', 'INVALID', 'NONE') +LoadSource = enum('NONE', 'FRESH_REUSE', 'ADOPT_INFLIGHT', 'START_NEW') +Outcome = enum('NONE', 'SUCCESS', 'FAILURE') +CommitSource = enum('BASE', 'NEWER') + +GENERATIONS = [Generation.OLDER, Generation.NEWER] + +action Init: + artifact_state = ArtifactState.SUCCESS + artifact_freshness = Freshness.FRESH + committed_source = CommitSource.BASE + + generation_entry = {} + generation_obsolete = {} + preflight_state = {} + data_state = {} + load_source = {} + outcome = {} + + for g in GENERATIONS: + generation_entry[g] = Entry.NONE + generation_obsolete[g] = False + preflight_state[g] = PreflightState.NOT_STARTED + data_state[g] = DataState.NOT_STARTED + load_source[g] = LoadSource.NONE + outcome[g] = Outcome.NONE + +atomic action MarkArtifactStale: + require artifact_state == ArtifactState.SUCCESS + require artifact_freshness == Freshness.FRESH + artifact_freshness = Freshness.STALE + +atomic action InvalidateArtifact: + require artifact_state == ArtifactState.SUCCESS + artifact_freshness = Freshness.INVALID + +atomic action StartOlderPreload: + require generation_entry[Generation.OLDER] == Entry.NONE + require generation_entry[Generation.NEWER] == Entry.NONE + generation_entry[Generation.OLDER] = Entry.PRELOAD + +atomic action ResolveOlderBeforeLoadSuccess: + require generation_entry[Generation.OLDER] == Entry.PRELOAD + require preflight_state[Generation.OLDER] == PreflightState.NOT_STARTED + preflight_state[Generation.OLDER] = PreflightState.SUCCESS + +atomic action LaunchOlderLoad: + require generation_entry[Generation.OLDER] == Entry.PRELOAD + require preflight_state[Generation.OLDER] == PreflightState.SUCCESS + require data_state[Generation.OLDER] == DataState.NOT_STARTED + require artifact_freshness in [Freshness.STALE, Freshness.INVALID] + + artifact_state = ArtifactState.IN_FLIGHT + artifact_freshness = Freshness.NONE + data_state[Generation.OLDER] = DataState.IN_FLIGHT + load_source[Generation.OLDER] = LoadSource.START_NEW + +atomic action StartNewerNavigation: + require generation_entry[Generation.NEWER] == Entry.NONE + generation_entry[Generation.NEWER] = Entry.NAVIGATION + + if generation_entry[Generation.OLDER] != Entry.NONE: + generation_obsolete[Generation.OLDER] = True + +atomic action ResolveNewerBeforeLoadSuccess: + require generation_entry[Generation.NEWER] == Entry.NAVIGATION + require preflight_state[Generation.NEWER] == PreflightState.NOT_STARTED + preflight_state[Generation.NEWER] = PreflightState.SUCCESS + +atomic action LaunchNewerLoad: + require generation_entry[Generation.NEWER] == Entry.NAVIGATION + require preflight_state[Generation.NEWER] == PreflightState.SUCCESS + require data_state[Generation.NEWER] == DataState.NOT_STARTED + + if artifact_state == ArtifactState.SUCCESS and artifact_freshness == Freshness.FRESH: + data_state[Generation.NEWER] = DataState.SUCCESS + load_source[Generation.NEWER] = LoadSource.FRESH_REUSE + return + + if artifact_state == ArtifactState.IN_FLIGHT: + data_state[Generation.NEWER] = DataState.IN_FLIGHT + load_source[Generation.NEWER] = LoadSource.ADOPT_INFLIGHT + return + + artifact_state = ArtifactState.IN_FLIGHT + artifact_freshness = Freshness.NONE + data_state[Generation.NEWER] = DataState.IN_FLIGHT + load_source[Generation.NEWER] = LoadSource.START_NEW + +atomic action CompleteArtifactSuccess: + require artifact_state == ArtifactState.IN_FLIGHT + artifact_state = ArtifactState.SUCCESS + artifact_freshness = Freshness.FRESH + + for g in GENERATIONS: + if data_state[g] == DataState.IN_FLIGHT: + data_state[g] = DataState.SUCCESS + +atomic action CompleteArtifactFailure: + require artifact_state == ArtifactState.IN_FLIGHT + artifact_state = ArtifactState.NON_REUSABLE_FAILURE + artifact_freshness = Freshness.NONE + + for g in GENERATIONS: + if data_state[g] == DataState.IN_FLIGHT: + data_state[g] = DataState.FAILURE + +atomic action FinalizeNewerSuccess: + require generation_entry[Generation.NEWER] == Entry.NAVIGATION + require data_state[Generation.NEWER] == DataState.SUCCESS + require outcome[Generation.NEWER] == Outcome.NONE + outcome[Generation.NEWER] = Outcome.SUCCESS + +atomic action FinalizeNewerFailure: + require generation_entry[Generation.NEWER] == Entry.NAVIGATION + require data_state[Generation.NEWER] == DataState.FAILURE + require outcome[Generation.NEWER] == Outcome.NONE + outcome[Generation.NEWER] = Outcome.FAILURE + +atomic action CommitNewer: + require outcome[Generation.NEWER] == Outcome.SUCCESS + committed_source = CommitSource.NEWER + +always assertion OnlyNewerCommits: + return committed_source in [CommitSource.BASE, CommitSource.NEWER] + +always assertion NavigationLoadRequiresBeforeLoadSuccess: + if data_state[Generation.NEWER] != DataState.NOT_STARTED: + return preflight_state[Generation.NEWER] == PreflightState.SUCCESS + return True + +always assertion FreshReuseProducesImmediateSuccess: + if load_source[Generation.NEWER] != LoadSource.FRESH_REUSE: + return True + return data_state[Generation.NEWER] == DataState.SUCCESS + +always assertion AdoptedInflightNeverCommitsBeforeArtifactResolves: + if load_source[Generation.NEWER] != LoadSource.ADOPT_INFLIGHT: + return True + if outcome[Generation.NEWER] == Outcome.SUCCESS and artifact_state != ArtifactState.SUCCESS: + return False + return True + +always assertion FailureAfterFreshReuseDoesNotPoisonCommittedSuccess: + if artifact_state != ArtifactState.NON_REUSABLE_FAILURE: + return True + if load_source[Generation.NEWER] != LoadSource.FRESH_REUSE: + return True + return data_state[Generation.NEWER] == DataState.SUCCESS + +always assertion AdoptedInflightFailurePreventsCommit: + if load_source[Generation.NEWER] != LoadSource.ADOPT_INFLIGHT: + return True + if data_state[Generation.NEWER] != DataState.FAILURE: + return True + return committed_source != CommitSource.NEWER + +always assertion CommitRequiresNewerSuccess: + if committed_source != CommitSource.NEWER: + return True + return outcome[Generation.NEWER] == Outcome.SUCCESS and data_state[Generation.NEWER] == DataState.SUCCESS diff --git a/docs/router/route-match-pending.fizz b/docs/router/route-match-pending.fizz new file mode 100644 index 0000000000..ddb0817f27 --- /dev/null +++ b/docs/router/route-match-pending.fizz @@ -0,0 +1,98 @@ +--- +deadlock_detection: false +options: + max_actions: 10 + max_concurrent_actions: 1 +--- + +# Phase 2 pending-timing-focused model. +# +# This spec models the observable timing contract of pending UI: +# - pending is not shown before the optimistic delay threshold +# - if loading finishes before pending shows, pending never flashes +# - once pending becomes visible, it remains visible until the minimum pending +# duration elapses, even if the underlying load completes earlier + +RenderGate = enum('IDLE', 'LOADING', 'PENDING', 'READY') + +action Init: + load_started = False + load_completed = False + pending_threshold_elapsed = False + pending_visible = False + pending_min_elapsed = False + render_gate = RenderGate.IDLE + +atomic action StartLoad: + require load_started == False + load_started = True + render_gate = RenderGate.LOADING + +atomic action ElapsePendingThreshold: + require load_started + require load_completed == False + require pending_visible == False + + pending_threshold_elapsed = True + pending_visible = True + render_gate = RenderGate.PENDING + +atomic action CompleteLoad: + require load_started + require load_completed == False + + load_completed = True + + if pending_visible == False: + render_gate = RenderGate.READY + return + + if pending_min_elapsed: + render_gate = RenderGate.READY + else: + render_gate = RenderGate.PENDING + +atomic action ElapsePendingMin: + require pending_visible + require pending_min_elapsed == False + + pending_min_elapsed = True + + if load_completed: + render_gate = RenderGate.READY + else: + render_gate = RenderGate.PENDING + +always assertion PendingNotVisibleBeforeThreshold: + if pending_visible == False: + return render_gate != RenderGate.PENDING + return True + +always assertion FastLoadNeverShowsPending: + if load_completed == False: + return True + if pending_visible: + return True + return render_gate == RenderGate.READY + +always assertion PendingVisibleUntilMinimumExpires: + if pending_visible == False: + return True + if pending_min_elapsed: + return True + return render_gate == RenderGate.PENDING + +always assertion ReadyRequiresCompletedLoad: + if render_gate != RenderGate.READY: + return True + return load_completed + +always assertion MinimumOnlyStartsAfterPendingVisible: + if pending_min_elapsed == False: + return True + return pending_visible + +always assertion NoReturnToLoadingAfterPending: + if pending_visible == False: + return True + return render_gate != RenderGate.LOADING From de0f15fc34f61fb9544c3249a269dcd87f45ff8a Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 12 Apr 2026 16:23:59 +0200 Subject: [PATCH 5/9] commit fizzbee traces --- docs/router/route-match-background-failure.trace | 2 ++ docs/router/route-match-background-late-success.trace | 4 ++++ ...oute-match-failures-error-vs-loader-notfound.trace | 9 +++++++++ .../route-match-failures-leaf-loader-error.trace | 11 +++++++++++ docs/router/route-match-failures-leaf-notfound.trace | 9 +++++++++ .../route-match-failures-notfound-redirect.trace | 9 +++++++++ docs/router/route-match-failures-root-notfound.trace | 5 +++++ docs/router/route-match-overlap-adopt.trace | 10 ++++++++++ docs/router/route-match-overlap-fresh.trace | 5 +++++ docs/router/route-match-pending-fast.trace | 2 ++ docs/router/route-match-pending-slow.trace | 4 ++++ 11 files changed, 70 insertions(+) create mode 100644 docs/router/route-match-background-failure.trace create mode 100644 docs/router/route-match-background-late-success.trace create mode 100644 docs/router/route-match-failures-error-vs-loader-notfound.trace create mode 100644 docs/router/route-match-failures-leaf-loader-error.trace create mode 100644 docs/router/route-match-failures-leaf-notfound.trace create mode 100644 docs/router/route-match-failures-notfound-redirect.trace create mode 100644 docs/router/route-match-failures-root-notfound.trace create mode 100644 docs/router/route-match-overlap-adopt.trace create mode 100644 docs/router/route-match-overlap-fresh.trace create mode 100644 docs/router/route-match-pending-fast.trace create mode 100644 docs/router/route-match-pending-slow.trace diff --git a/docs/router/route-match-background-failure.trace b/docs/router/route-match-background-failure.trace new file mode 100644 index 0000000000..63a0fb0ca0 --- /dev/null +++ b/docs/router/route-match-background-failure.trace @@ -0,0 +1,2 @@ +StartBackgroundReload +CompleteBackgroundFailure diff --git a/docs/router/route-match-background-late-success.trace b/docs/router/route-match-background-late-success.trace new file mode 100644 index 0000000000..16db76e965 --- /dev/null +++ b/docs/router/route-match-background-late-success.trace @@ -0,0 +1,4 @@ +StartBackgroundReload +StartNewerNavigation +CompleteNewerNavigationSuccess +CompleteBackgroundSuccess diff --git a/docs/router/route-match-failures-error-vs-loader-notfound.trace b/docs/router/route-match-failures-error-vs-loader-notfound.trace new file mode 100644 index 0000000000..9e64eb3d34 --- /dev/null +++ b/docs/router/route-match-failures-error-vs-loader-notfound.trace @@ -0,0 +1,9 @@ +ResolveBeforeLoadSuccess +ResolveBeforeLoadSuccess +ResolveBeforeLoadError +LaunchLoaders +ResolveLoaderNotFound +Any:p="ROOT" +ResolveLoaderSuccess +Any:p="PARENT" +Finalize diff --git a/docs/router/route-match-failures-leaf-loader-error.trace b/docs/router/route-match-failures-leaf-loader-error.trace new file mode 100644 index 0000000000..8161143567 --- /dev/null +++ b/docs/router/route-match-failures-leaf-loader-error.trace @@ -0,0 +1,11 @@ +ResolveBeforeLoadSuccess +ResolveBeforeLoadSuccess +ResolveBeforeLoadSuccess +LaunchLoaders +ResolveLoaderSuccess +Any:p="ROOT" +ResolveLoaderSuccess +Any:p="PARENT" +ResolveLoaderError +Any:p="LEAF" +Finalize diff --git a/docs/router/route-match-failures-leaf-notfound.trace b/docs/router/route-match-failures-leaf-notfound.trace new file mode 100644 index 0000000000..3bd0082f92 --- /dev/null +++ b/docs/router/route-match-failures-leaf-notfound.trace @@ -0,0 +1,9 @@ +ResolveBeforeLoadSuccess +ResolveBeforeLoadSuccess +ResolveBeforeLoadNotFound +LaunchLoaders +ResolveLoaderSuccess +Any:p="ROOT" +ResolveLoaderSuccess +Any:p="PARENT" +Finalize diff --git a/docs/router/route-match-failures-notfound-redirect.trace b/docs/router/route-match-failures-notfound-redirect.trace new file mode 100644 index 0000000000..e788351a3d --- /dev/null +++ b/docs/router/route-match-failures-notfound-redirect.trace @@ -0,0 +1,9 @@ +ResolveBeforeLoadSuccess +ResolveBeforeLoadSuccess +ResolveBeforeLoadNotFound +LaunchLoaders +ResolveLoaderRedirect +Any:p="ROOT" +ResolveLoaderSuccess +Any:p="PARENT" +Finalize diff --git a/docs/router/route-match-failures-root-notfound.trace b/docs/router/route-match-failures-root-notfound.trace new file mode 100644 index 0000000000..a1e4ba4b56 --- /dev/null +++ b/docs/router/route-match-failures-root-notfound.trace @@ -0,0 +1,5 @@ +ResolveBeforeLoadNotFound +LaunchLoaders +ResolveLoaderSuccess +Any:p="ROOT" +Finalize diff --git a/docs/router/route-match-overlap-adopt.trace b/docs/router/route-match-overlap-adopt.trace new file mode 100644 index 0000000000..f17e02c021 --- /dev/null +++ b/docs/router/route-match-overlap-adopt.trace @@ -0,0 +1,10 @@ +MarkArtifactStale +StartOlderPreload +ResolveOlderBeforeLoadSuccess +LaunchOlderLoad +StartNewerNavigation +ResolveNewerBeforeLoadSuccess +LaunchNewerLoad +CompleteArtifactSuccess +FinalizeNewerSuccess +CommitNewer diff --git a/docs/router/route-match-overlap-fresh.trace b/docs/router/route-match-overlap-fresh.trace new file mode 100644 index 0000000000..afc6eec74d --- /dev/null +++ b/docs/router/route-match-overlap-fresh.trace @@ -0,0 +1,5 @@ +StartNewerNavigation +ResolveNewerBeforeLoadSuccess +LaunchNewerLoad +FinalizeNewerSuccess +CommitNewer diff --git a/docs/router/route-match-pending-fast.trace b/docs/router/route-match-pending-fast.trace new file mode 100644 index 0000000000..8cc3219376 --- /dev/null +++ b/docs/router/route-match-pending-fast.trace @@ -0,0 +1,2 @@ +StartLoad +CompleteLoad diff --git a/docs/router/route-match-pending-slow.trace b/docs/router/route-match-pending-slow.trace new file mode 100644 index 0000000000..b2c03c935f --- /dev/null +++ b/docs/router/route-match-pending-slow.trace @@ -0,0 +1,4 @@ +StartLoad +ElapsePendingThreshold +CompleteLoad +ElapsePendingMin From 0a81e7c6bbf8c927bfb4e6811ad73181b1f57ba5 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 12 Apr 2026 17:18:35 +0200 Subject: [PATCH 6/9] plan cleanup --- docs/router/route-match-loading-phase-3.md | 103 ++++++++++-- docs/router/route-match-loading-rfc.md | 36 ++++- docs/router/route-match-loading.fizz | 42 +++-- docs/router/route-match-overlap.fizz | 9 +- .../route-match-terminal-cache-error.trace | 6 + .../route-match-terminal-cache-notfound.trace | 6 + .../route-match-terminal-cache-redirect.trace | 5 + ...te-match-terminal-cache-stale-reload.trace | 7 + docs/router/route-match-terminal-cache.fizz | 151 ++++++++++++++++++ 9 files changed, 328 insertions(+), 37 deletions(-) create mode 100644 docs/router/route-match-terminal-cache-error.trace create mode 100644 docs/router/route-match-terminal-cache-notfound.trace create mode 100644 docs/router/route-match-terminal-cache-redirect.trace create mode 100644 docs/router/route-match-terminal-cache-stale-reload.trace create mode 100644 docs/router/route-match-terminal-cache.fizz diff --git a/docs/router/route-match-loading-phase-3.md b/docs/router/route-match-loading-phase-3.md index 7d319ed2f3..7a398d67b0 100644 --- a/docs/router/route-match-loading-phase-3.md +++ b/docs/router/route-match-loading-phase-3.md @@ -20,6 +20,18 @@ Replace the current implicit, pool-and-promise-driven route-match loading pipeli - maps directly to the phase-2 FizzBee models - keeps adapter-specific mechanics out of router-core +This is a first-principles rewrite. + +It is not a refactor that incrementally preserves the structure of the current implementation. + +The current code should be treated as an observable legacy implementation to learn from, not as the scaffold for the new design. + +In particular: + +- `packages/router-core/src/load-matches.ts` should probably be replaced in its entirety, not patched into compliance +- `packages/react-router/src/Match.tsx` should be re-expressed around semantic render gates, not preserved as a throw-heavy decision tree +- old helper structure, promise naming, and control-flow shape should not be carried forward just because they already exist + ## Source Of Truth If current code, existing tests, and old implementation habits disagree, use this priority order: @@ -46,6 +58,30 @@ Build a new internal route-match lifecycle that makes these semantic concepts ex The rewrite should preserve observable semantics, not internal representation. +The target outcome is a clean and readable implementation that looks like the models and the semantics we now understand, not a compatibility layer spread across the old architecture. + +## Rewrite Posture + +Use the existing code to answer questions like: + +- what observable behavior exists today? +- which tests and edge cases need to be preserved intentionally? +- where are the current bugs and accidental behaviors coming from? + +Do not use the existing code as the structural blueprint for the rewrite. + +Phase 3 should prefer: + +- new explicit lifecycle/state modules over reusing `load-matches.ts` helper clusters +- direct semantic state over implicit promise choreography +- small readable adapter mappings over large nested runtime branching + +Phase 3 should avoid: + +- duct-taping generation semantics on top of the current `load-matches.ts` shape +- preserving legacy pool/promise coupling as the organizing principle +- keeping React rendering control flow in its current many-throw form if semantic gates make a simpler structure possible + ## What We Learned ### 1. Generations must be first-class @@ -95,6 +131,10 @@ Adapters should decide how to realize those facts: - Solid suspense/resource wiring - Vue DOM-safe rendering behavior +The React consequence should be explicit: once router-core owns render gating semantically, `packages/react-router/src/Match.tsx` should not need dozens of distinct `throw`-driven control-flow paths. + +Some throws will still be appropriate because React Suspense and error boundaries require them, but the rewrite should aim for a small number of clearly justified throws that directly correspond to semantic gate transitions. + ### 4. Reuse must be policy, not accidental object survival The rewrite should encode reuse rules explicitly. @@ -104,10 +144,18 @@ Current intended policy: - `beforeLoad` is conservative preflight/context/authorization work - `loader` is reusable data acquisition work - fresh successful loader artifacts may be reused +- fresh cached terminal outcomes may be reused as the same terminal outcome when policy allows - in-flight preload loader work may be adopted by navigation -- terminal failure artifacts are not reusable as success data +- terminal outcomes are cacheable under the same cache/eviction rules as successful matches +- terminal outcomes are not reusable as success data - later artifact failure must not retroactively poison a navigation that already reused fresh data +This distinction is important: + +- cacheable terminal outcome != reusable success payload +- a cached `redirect`, `notFound`, or regular `error` may be reused as that same terminal outcome +- it must never be reinterpreted as a successful data result + ### 5. Slice models worked better than one monolithic model Phase 2 succeeded by isolating the hard seams instead of forcing them into one giant exhaustive graph. @@ -210,9 +258,11 @@ While stale background work is running: Must preserve: - fresh artifact reuse on navigation +- fresh terminal-outcome reuse on navigation - in-flight preload adoption by navigation - obsolete older generations never becoming the committed winner -- failure artifacts not being reused as success data +- terminal outcomes remaining cacheable under the same rules as non-terminal matches +- terminal outcomes not being reused as success data ## What Must Not Be Copied From The Old Implementation @@ -224,9 +274,13 @@ These are implementation accidents or legacy shapes, not rewrite goals. - `globalNotFound` as a required representation - hydration heuristics expressed as index-based hacks rather than boundary semantics - adapter behavior being driven directly by router-core promise lifetime accidents +- the overall control-flow structure of `packages/router-core/src/load-matches.ts` +- the current throw-heavy branching structure in `packages/react-router/src/Match.tsx` These may still exist internally if useful, but only as implementation details under clearer semantic state. +The default assumption should be replacement, not preservation. + ## Recommended Internal Architecture ### Core Runtime Concepts @@ -266,7 +320,7 @@ The implementation does not need these exact names, but it should expose these c - acquisition status - freshness - reusable success payload -- non-reusable terminal failure marker +- reusable terminal outcome payload, if the current cached artifact is terminal - which generations are currently observing or adopting it ### Suggested Render-Gate API @@ -296,6 +350,8 @@ Keep the implementation factored around these responsibilities: This is preferable to keeping all logic in one mega-pipeline, even if the old code centered around `loadMatches()`. +If a proposed implementation still looks like a cleaned-up version of `load-matches.ts` rather than an explicit lifecycle built around generations, resources, outcomes, and render gates, it is probably too close to the old design. + ## Recommended Rewrite Strategy ### 1. Keep the public API stable while replacing internals @@ -304,16 +360,19 @@ Prefer replacing internal orchestration behind existing public router behavior. Do not start by redesigning public route APIs. +But do replace internal loading/rendering orchestration aggressively if needed. The right bias is to write new internals that satisfy the models, then delete obsolete legacy machinery, not to incrementally massage the old machinery into shape. + ### 2. Build the new core semantics before rewriting adapter mechanics Recommended order: 1. introduce generation/resource/presence concepts in router-core -2. reimplement finalization and commit logic around them -3. reimplement preflight and loader orchestration -4. expose semantic render gates to adapters -5. port React adapter to semantic gates -6. align Solid and Vue afterward +2. build a new lifecycle/orchestration path around them instead of extending `load-matches.ts` +3. reimplement finalization and commit logic around the new lifecycle +4. reimplement preflight and loader orchestration +5. expose semantic render gates to adapters +6. port React adapter to semantic gates with a much simpler throw surface +7. align Solid and Vue afterward ### 3. Port React first @@ -328,6 +387,10 @@ The React adapter should consume semantic gates and preserve: React-specific promise handling should become an adapter implementation of semantic states, not the core lifecycle itself. +The adapter target is readability and directness. + +With 20-20 hindsight, the rewritten `packages/react-router/src/Match.tsx` should be dramatically simpler than the current version. It should map semantic gate states to a small number of React mechanisms instead of embedding a large distributed control-flow machine in render. + ### 4. Keep slice-based testability Every focused `.fizz` model should correspond to focused implementation tests. @@ -348,12 +411,13 @@ Before considering the rewrite correct, the implementation should satisfy all of 2. Render-visible route components never observe incomplete effective context. 3. Redirects, notFound, and errors follow the modeled precedence and boundary rules. 4. Fresh reuse and in-flight adoption match the overlap model. -5. Background stale reloads cannot clobber newer committed state. -6. Pending timing matches the pending model. -7. Hydration semantics match the hydration model. -8. React adapter behavior matches semantic render gates instead of inventing its own lifecycle. -9. Existing tests are updated or replaced where they encode accidental legacy behavior. -10. New focused tests exist for each model slice. +5. Cached terminal outcomes follow the same cache/reuse/eviction rules as non-terminal matches, while preserving their terminal kind. +6. Background stale reloads cannot clobber newer committed state. +7. Pending timing matches the pending model. +8. Hydration semantics match the hydration model. +9. React adapter behavior matches semantic render gates instead of inventing its own lifecycle. +10. Existing tests are updated or replaced where they encode accidental legacy behavior. +11. New focused tests exist for each model slice. ## Remaining Doubts @@ -411,6 +475,7 @@ Core and focused models: - `docs/router/route-match-background.fizz` - `docs/router/route-match-pending.fizz` - `docs/router/route-match-failures.fizz` +- `docs/router/route-match-terminal-cache.fizz` Useful trace files: @@ -420,6 +485,10 @@ Useful trace files: - `docs/router/route-match-background-failure.trace` - `docs/router/route-match-pending-fast.trace` - `docs/router/route-match-pending-slow.trace` +- `docs/router/route-match-terminal-cache-redirect.trace` +- `docs/router/route-match-terminal-cache-notfound.trace` +- `docs/router/route-match-terminal-cache-error.trace` +- `docs/router/route-match-terminal-cache-stale-reload.trace` - `docs/router/route-match-failures-root-notfound.trace` - `docs/router/route-match-failures-leaf-notfound.trace` - `docs/router/route-match-failures-notfound-redirect.trace` @@ -433,10 +502,16 @@ Current code hotspots to replace or absorb: - `packages/router-core/src/ssr/ssr-client.ts` - `packages/react-router/src/Match.tsx` +These files should be treated as legacy reference material, not as the skeleton of the new implementation. + +`packages/router-core/src/load-matches.ts` in particular should be assumed replaceable in full unless a very small isolated fragment is clearly worth carrying over. + ## Final Instruction To A Phase 3 Agent Do not start by reshuffling the current code. Start by implementing explicit semantic state in router-core that matches the model suite. Then make React consume that state. Only after the semantic core is stable should you align the other adapters and remove obsolete legacy machinery. +If you find yourself preserving the broad structure of `load-matches.ts` or reproducing the current many-branch `Match.tsx` control flow, stop and reset toward a cleaner first-principles design. + If implementation work exposes uncertainty about semantics rather than code mechanics, stop and iterate on phase 2 before shipping the rewrite. diff --git a/docs/router/route-match-loading-rfc.md b/docs/router/route-match-loading-rfc.md index 4cb77983e3..9ef4ba7f14 100644 --- a/docs/router/route-match-loading-rfc.md +++ b/docs/router/route-match-loading-rfc.md @@ -346,6 +346,7 @@ Unless phase 2 disproves that split, when a preload later becomes active for the - `beforeLoad` reruns on navigation - a fresh successful loader result may be reused - an in-flight preload loader may be adopted by navigation +- a resolved preload redirect/notFound/error is cacheable and may be reused as the same terminal outcome when reuse policy allows - a resolved preload redirect/notFound/error is not reusable as success data See rules `P4`, `P9`, and `P10`. @@ -504,7 +505,7 @@ References: #### Rule P6. Staleness alone does not always force reload -A stale successful match should reload only when at least one of the following is true: +A stale cached match or cached terminal outcome should reload only when at least one of the following is true: - explicit same-location reload - match cause is `enter` @@ -548,9 +549,13 @@ References: - `packages/router-core/src/load-matches.ts:892-920` - `packages/router-core/tests/load.test.ts:434-571` -#### Rule P10. Resolved preload failures are not reusable success data +#### Rule P10. Resolved preload terminal outcomes are cacheable and reusable as terminal outcomes -A completed preload whose terminal result is redirect, notFound, or error is not reusable as success data for later navigation. +A completed preload whose terminal result is redirect, notFound, or error: + +- is cacheable under the same cache/eviction rules as a successful match +- may be reused later as the same terminal outcome when freshness and invalidation policy allow +- is not reusable as success data for later navigation References: @@ -567,10 +572,11 @@ References: - `packages/router-core/src/router.ts:2476-2488` - `packages/router-core/src/router.ts:2764-2788` -#### Rule P12. Error-like terminal states do not remain reusable cache entries +#### Rule P12. Terminal outcome matches remain cacheable -- exiting active matches in `error`, `notFound`, or `redirected` do not enter reusable cache on commit -- cached matches that become `redirected` are removed from cache +- exiting active matches in `error`, `notFound`, or `redirected` remain eligible for cache under the same rules as other matches +- cached terminal outcomes remain eligible for reuse or rerun under the same freshness and invalidation policy as other cached matches +- terminal outcome reuse preserves the terminal outcome kind; it does not reinterpret a cached terminal outcome as success data References: @@ -579,7 +585,7 @@ References: #### Rule P13. Invalidation applies uniformly across active, pending, and cached matches -Invalidation marks selected matches stale everywhere, and `error`/`notFound` matches reset to `pending` so they rerun. +Invalidation marks selected matches stale everywhere. Terminal outcomes follow the same invalidation and rerun policy as non-terminal matches. References: @@ -1028,9 +1034,11 @@ Artifacts added: - background-reload-focused model: `docs/router/route-match-background.fizz` - pending-timing-focused model: `docs/router/route-match-pending.fizz` - failure-precedence-focused model: `docs/router/route-match-failures.fizz` +- terminal-cache-focused model: `docs/router/route-match-terminal-cache.fizz` - overlap scenario traces: `docs/router/route-match-overlap-fresh.trace`, `docs/router/route-match-overlap-adopt.trace` - background scenario traces: `docs/router/route-match-background-late-success.trace`, `docs/router/route-match-background-failure.trace` - pending scenario traces: `docs/router/route-match-pending-fast.trace`, `docs/router/route-match-pending-slow.trace` +- terminal-cache scenario traces: `docs/router/route-match-terminal-cache-redirect.trace`, `docs/router/route-match-terminal-cache-notfound.trace`, `docs/router/route-match-terminal-cache-error.trace`, `docs/router/route-match-terminal-cache-stale-reload.trace` - failure scenario traces: `docs/router/route-match-failures-root-notfound.trace`, `docs/router/route-match-failures-leaf-notfound.trace`, `docs/router/route-match-failures-notfound-redirect.trace`, `docs/router/route-match-failures-error-vs-loader-notfound.trace`, `docs/router/route-match-failures-leaf-loader-error.trace` Phase-1 semantic coverage now maps to the suite like this: @@ -1041,6 +1049,7 @@ Phase-1 semantic coverage now maps to the suite like this: - background stale reload and late-completion non-clobbering: `docs/router/route-match-background.fizz` - pending timing contract (`pendingMs` / `pendingMinMs`) at the semantic level: `docs/router/route-match-pending.fizz` - failure precedence, ancestor preservation, redirect dominance, and error/notFound boundary ownership: `docs/router/route-match-failures.fizz` +- cacheability and reuse of terminal redirect/notFound/error outcomes: `docs/router/route-match-terminal-cache.fizz` Items intentionally left out of the phase-2 suite because they are implementation refinements rather than blockers for phase 3: @@ -1051,7 +1060,7 @@ Items intentionally left out of the phase-2 suite because they are implementatio Current verification status: - `fizz --preinit-hook-file docs/router/route-match-loading-tiny.cfg docs/router/route-match-loading.fizz` - Passed with `Valid Nodes: 12954` and `Unique states: 1007`. + Passed with `Valid Nodes: 18858` and `Unique states: 1475`. - `fizz --preinit-hook-file docs/router/route-match-loading-small.cfg docs/router/route-match-loading.fizz` Remains useful for exploration but currently exceeds the 2-minute local command budget; it is now treated as an exploratory umbrella model rather than the only overlap-checking path. - `fizz docs/router/route-match-hydration.fizz` @@ -1064,6 +1073,8 @@ Current verification status: Passed with `Valid Nodes: 7` and `Unique states: 7`. - `fizz docs/router/route-match-failures.fizz` Passed with `Valid Nodes: 1740` and `Unique states: 348`. +- `fizz docs/router/route-match-terminal-cache.fizz` + Passed with `Valid Nodes: 80` and `Unique states: 80`. - `fizz --trace-file docs/router/route-match-overlap-fresh.trace docs/router/route-match-overlap.fizz` Passed. - `fizz --trace-file docs/router/route-match-overlap-adopt.trace docs/router/route-match-overlap.fizz` @@ -1076,6 +1087,14 @@ Current verification status: Passed. - `fizz --trace-file docs/router/route-match-pending-slow.trace docs/router/route-match-pending.fizz` Passed. +- `fizz --trace-file docs/router/route-match-terminal-cache-redirect.trace docs/router/route-match-terminal-cache.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-terminal-cache-notfound.trace docs/router/route-match-terminal-cache.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-terminal-cache-error.trace docs/router/route-match-terminal-cache.fizz` + Passed. +- `fizz --trace-file docs/router/route-match-terminal-cache-stale-reload.trace docs/router/route-match-terminal-cache.fizz` + Passed. - `fizz --trace-file docs/router/route-match-failures-root-notfound.trace docs/router/route-match-failures.fizz` Passed. - `fizz --trace-file docs/router/route-match-failures-leaf-notfound.trace docs/router/route-match-failures.fizz` @@ -1095,6 +1114,7 @@ Initial model-driven corrections already made while starting phase 2: - overlap/reuse reachability works better as explicit guided traces than as `exists assertion`s in the current FizzBee toolchain - a later artifact failure must not retroactively poison a navigation that already reused fresh data; the overlap model now encodes that explicitly - failure precedence assertions had to be conditioned on higher-ranked outcomes being absent, which helped sharpen the semantic precedence rules +- cacheability and success-reuse are distinct concerns: cached terminal outcomes are reusable as the same terminal outcome, while still not being reusable as success data Phase 2 exit criteria met: diff --git a/docs/router/route-match-loading.fizz b/docs/router/route-match-loading.fizz index f20e468468..6d82d7ed1e 100644 --- a/docs/router/route-match-loading.fizz +++ b/docs/router/route-match-loading.fizz @@ -47,6 +47,7 @@ atomic func initialize_generation(g, entry, leaf_resource): generation_root_shell_preserved[g] = False generation_loaders_launched[g] = False generation_used_fresh_artifact[g] = False + generation_reused_artifact_state[g] = None generation_adopted_inflight[g] = False for p in PRESENCES: @@ -74,6 +75,7 @@ action Init: generation_root_shell_preserved = {} generation_loaders_launched = {} generation_used_fresh_artifact = {} + generation_reused_artifact_state = {} generation_adopted_inflight = {} preflight_state = {} @@ -101,6 +103,7 @@ action Init: generation_root_shell_preserved[g] = False generation_loaders_launched[g] = False generation_used_fresh_artifact[g] = False + generation_reused_artifact_state[g] = None generation_adopted_inflight[g] = False for p in PRESENCES: @@ -137,13 +140,13 @@ atomic action StartNavigation: atomic action MarkCommittedArtifactStale: require committed_generation != 0 resource = generation_leaf_resource[committed_generation] - require artifact_state[resource] == ArtifactState.SUCCESS + require artifact_state[resource] in [ArtifactState.SUCCESS, ArtifactState.REDIRECT, ArtifactState.NOT_FOUND, ArtifactState.ERROR] artifact_freshness[resource] = Freshness.STALE atomic action InvalidateCommittedResource: require committed_generation != 0 resource = generation_leaf_resource[committed_generation] - require artifact_state[resource] == ArtifactState.SUCCESS + require artifact_state[resource] in [ArtifactState.SUCCESS, ArtifactState.REDIRECT, ArtifactState.NOT_FOUND, ArtifactState.ERROR] artifact_freshness[resource] = Freshness.INVALID atomic action StartBackgroundReload: @@ -234,9 +237,17 @@ atomic action LaunchEligibleLoaders: if p_depth <= limit: if p == Presence.LEAF: resource = generation_leaf_resource[gen] - if generation_entry[gen] == Entry.NAVIGATION and artifact_state[resource] == ArtifactState.SUCCESS and artifact_freshness[resource] == Freshness.FRESH: - data_state[(gen, p)] = DataState.SUCCESS + if generation_entry[gen] == Entry.NAVIGATION and artifact_state[resource] in [ArtifactState.SUCCESS, ArtifactState.REDIRECT, ArtifactState.NOT_FOUND, ArtifactState.ERROR] and artifact_freshness[resource] == Freshness.FRESH: + if artifact_state[resource] == ArtifactState.SUCCESS: + data_state[(gen, p)] = DataState.SUCCESS + elif artifact_state[resource] == ArtifactState.REDIRECT: + data_state[(gen, p)] = DataState.REDIRECT + elif artifact_state[resource] == ArtifactState.NOT_FOUND: + data_state[(gen, p)] = DataState.NOT_FOUND + else: + data_state[(gen, p)] = DataState.ERROR generation_used_fresh_artifact[gen] = True + generation_reused_artifact_state[gen] = artifact_state[resource] else: data_state[(gen, p)] = DataState.IN_FLIGHT if artifact_state[resource] == ArtifactState.IN_FLIGHT: @@ -489,22 +500,31 @@ always assertion AncestorPreservedOnLeafBeforeLoadNotFound: return False return True -always assertion FreshArtifactReuseProducesLeafSuccess: +always assertion FreshArtifactReusePreservesLeafOutcome: for g in GEN_IDS: if generation_used_fresh_artifact[g]: if generation_entry[g] != Entry.NAVIGATION: return False if generation_leaf_resource[g] == None: return False - if data_state[(g, Presence.LEAF)] != DataState.SUCCESS: + reused = generation_reused_artifact_state[g] + if reused == None: + return False + if reused == ArtifactState.SUCCESS and data_state[(g, Presence.LEAF)] != DataState.SUCCESS: + return False + if reused == ArtifactState.REDIRECT and data_state[(g, Presence.LEAF)] != DataState.REDIRECT: + return False + if reused == ArtifactState.NOT_FOUND and data_state[(g, Presence.LEAF)] != DataState.NOT_FOUND: + return False + if reused == ArtifactState.ERROR and data_state[(g, Presence.LEAF)] != DataState.ERROR: return False return True -always assertion NoFailureArtifactReuseAsSuccess: - for resource in RESOURCES: - if artifact_state[resource] in [ArtifactState.REDIRECT, ArtifactState.NOT_FOUND, ArtifactState.ERROR]: - for g in GEN_IDS: - if generation_leaf_resource[g] == resource and generation_used_fresh_artifact[g]: +always assertion TerminalOutcomeReuseDoesNotBecomeSuccess: + for g in GEN_IDS: + if generation_used_fresh_artifact[g]: + if generation_reused_artifact_state[g] in [ArtifactState.REDIRECT, ArtifactState.NOT_FOUND, ArtifactState.ERROR]: + if data_state[(g, Presence.LEAF)] == DataState.SUCCESS: return False return True diff --git a/docs/router/route-match-overlap.fizz b/docs/router/route-match-overlap.fizz index 1328162651..7f3d01730a 100644 --- a/docs/router/route-match-overlap.fizz +++ b/docs/router/route-match-overlap.fizz @@ -10,14 +10,14 @@ options: # This spec isolates one high-value overlapping-generation slice: # - a committed base route already exists # - a preload may start an in-flight artifact load -# - a newer navigation may adopt that in-flight artifact or reuse a fresh one +# - a newer navigation may adopt that in-flight artifact or reuse a fresh success artifact # - obsolete generations must not commit visible state Generation = enum('OLDER', 'NEWER') Entry = enum('NONE', 'PRELOAD', 'NAVIGATION') PreflightState = enum('NOT_STARTED', 'SUCCESS') DataState = enum('NOT_STARTED', 'IN_FLIGHT', 'SUCCESS', 'FAILURE') -ArtifactState = enum('SUCCESS', 'IN_FLIGHT', 'NON_REUSABLE_FAILURE') +ArtifactState = enum('SUCCESS', 'IN_FLIGHT', 'TERMINAL_FAILURE') Freshness = enum('FRESH', 'STALE', 'INVALID', 'NONE') LoadSource = enum('NONE', 'FRESH_REUSE', 'ADOPT_INFLIGHT', 'START_NEW') Outcome = enum('NONE', 'SUCCESS', 'FAILURE') @@ -77,6 +77,7 @@ atomic action LaunchOlderLoad: atomic action StartNewerNavigation: require generation_entry[Generation.NEWER] == Entry.NONE + require artifact_state in [ArtifactState.SUCCESS, ArtifactState.IN_FLIGHT] generation_entry[Generation.NEWER] = Entry.NAVIGATION if generation_entry[Generation.OLDER] != Entry.NONE: @@ -118,7 +119,7 @@ atomic action CompleteArtifactSuccess: atomic action CompleteArtifactFailure: require artifact_state == ArtifactState.IN_FLIGHT - artifact_state = ArtifactState.NON_REUSABLE_FAILURE + artifact_state = ArtifactState.TERMINAL_FAILURE artifact_freshness = Freshness.NONE for g in GENERATIONS: @@ -162,7 +163,7 @@ always assertion AdoptedInflightNeverCommitsBeforeArtifactResolves: return True always assertion FailureAfterFreshReuseDoesNotPoisonCommittedSuccess: - if artifact_state != ArtifactState.NON_REUSABLE_FAILURE: + if artifact_state != ArtifactState.TERMINAL_FAILURE: return True if load_source[Generation.NEWER] != LoadSource.FRESH_REUSE: return True diff --git a/docs/router/route-match-terminal-cache-error.trace b/docs/router/route-match-terminal-cache-error.trace new file mode 100644 index 0000000000..2627f4e4d0 --- /dev/null +++ b/docs/router/route-match-terminal-cache-error.trace @@ -0,0 +1,6 @@ +SetArtifactError +SetFresh +StartNavigation +ResolveBeforeLoadSuccess +ReuseFreshTerminal +CommitVisibleTerminal diff --git a/docs/router/route-match-terminal-cache-notfound.trace b/docs/router/route-match-terminal-cache-notfound.trace new file mode 100644 index 0000000000..4f80e9228d --- /dev/null +++ b/docs/router/route-match-terminal-cache-notfound.trace @@ -0,0 +1,6 @@ +SetArtifactNotFound +SetFresh +StartNavigation +ResolveBeforeLoadSuccess +ReuseFreshTerminal +CommitVisibleTerminal diff --git a/docs/router/route-match-terminal-cache-redirect.trace b/docs/router/route-match-terminal-cache-redirect.trace new file mode 100644 index 0000000000..34583201dc --- /dev/null +++ b/docs/router/route-match-terminal-cache-redirect.trace @@ -0,0 +1,5 @@ +SetArtifactRedirect +SetFresh +StartNavigation +ResolveBeforeLoadSuccess +ReuseFreshTerminal diff --git a/docs/router/route-match-terminal-cache-stale-reload.trace b/docs/router/route-match-terminal-cache-stale-reload.trace new file mode 100644 index 0000000000..7bb28b62a7 --- /dev/null +++ b/docs/router/route-match-terminal-cache-stale-reload.trace @@ -0,0 +1,7 @@ +SetArtifactError +SetStale +StartNavigation +ResolveBeforeLoadSuccess +StartReload +ResolveReloadSuccess +CommitVisibleTerminal diff --git a/docs/router/route-match-terminal-cache.fizz b/docs/router/route-match-terminal-cache.fizz new file mode 100644 index 0000000000..8364127cc0 --- /dev/null +++ b/docs/router/route-match-terminal-cache.fizz @@ -0,0 +1,151 @@ +--- +deadlock_detection: false +options: + max_actions: 10 + max_concurrent_actions: 1 +--- + +# Phase 2 terminal-cache-focused model. +# +# This spec captures the correction that cached terminal outcomes are cacheable +# under the same rules as non-terminal matches. A fresh cached redirect, +# notFound, or error may be reused as that same terminal outcome. Stale or +# invalid cached terminal outcomes go through the normal reload path. + +ArtifactState = enum('REDIRECT', 'NOT_FOUND', 'ERROR') +Freshness = enum('FRESH', 'STALE', 'INVALID') +LoadSource = enum('NONE', 'REUSE_TERMINAL', 'START_RELOAD') +Outcome = enum('NONE', 'SUCCESS', 'REDIRECT', 'NOT_FOUND', 'ERROR') +CommittedOutcome = enum('BASE', 'NEWER_SUCCESS', 'NEWER_NOT_FOUND', 'NEWER_ERROR') + +action Init: + artifact_state = ArtifactState.ERROR + artifact_freshness = Freshness.FRESH + + navigation_started = False + beforeload_success = False + load_started = False + load_source = LoadSource.NONE + final_outcome = Outcome.NONE + committed_outcome = CommittedOutcome.BASE + +atomic action SetArtifactRedirect: + require navigation_started == False + artifact_state = ArtifactState.REDIRECT + +atomic action SetArtifactNotFound: + require navigation_started == False + artifact_state = ArtifactState.NOT_FOUND + +atomic action SetArtifactError: + require navigation_started == False + artifact_state = ArtifactState.ERROR + +atomic action SetFresh: + require navigation_started == False + artifact_freshness = Freshness.FRESH + +atomic action SetStale: + require navigation_started == False + artifact_freshness = Freshness.STALE + +atomic action SetInvalid: + require navigation_started == False + artifact_freshness = Freshness.INVALID + +atomic action StartNavigation: + require navigation_started == False + navigation_started = True + +atomic action ResolveBeforeLoadSuccess: + require navigation_started + require beforeload_success == False + beforeload_success = True + +atomic action ReuseFreshTerminal: + require beforeload_success + require load_source == LoadSource.NONE + require artifact_freshness == Freshness.FRESH + + load_source = LoadSource.REUSE_TERMINAL + if artifact_state == ArtifactState.REDIRECT: + final_outcome = Outcome.REDIRECT + elif artifact_state == ArtifactState.NOT_FOUND: + final_outcome = Outcome.NOT_FOUND + else: + final_outcome = Outcome.ERROR + +atomic action StartReload: + require beforeload_success + require load_source == LoadSource.NONE + require artifact_freshness in [Freshness.STALE, Freshness.INVALID] + + load_source = LoadSource.START_RELOAD + load_started = True + +atomic action ResolveReloadSuccess: + require load_started + require final_outcome == Outcome.NONE + final_outcome = Outcome.SUCCESS + +atomic action ResolveReloadRedirect: + require load_started + require final_outcome == Outcome.NONE + final_outcome = Outcome.REDIRECT + +atomic action ResolveReloadNotFound: + require load_started + require final_outcome == Outcome.NONE + final_outcome = Outcome.NOT_FOUND + +atomic action ResolveReloadError: + require load_started + require final_outcome == Outcome.NONE + final_outcome = Outcome.ERROR + +atomic action CommitVisibleTerminal: + require final_outcome in [Outcome.SUCCESS, Outcome.NOT_FOUND, Outcome.ERROR] + if final_outcome == Outcome.SUCCESS: + committed_outcome = CommittedOutcome.NEWER_SUCCESS + elif final_outcome == Outcome.NOT_FOUND: + committed_outcome = CommittedOutcome.NEWER_NOT_FOUND + else: + committed_outcome = CommittedOutcome.NEWER_ERROR + +always assertion TerminalReuseRequiresFreshArtifact: + if load_source != LoadSource.REUSE_TERMINAL: + return True + return artifact_freshness == Freshness.FRESH + +always assertion TerminalReusePreservesTerminalKind: + if load_source != LoadSource.REUSE_TERMINAL: + return True + if artifact_state == ArtifactState.REDIRECT: + return final_outcome == Outcome.REDIRECT + if artifact_state == ArtifactState.NOT_FOUND: + return final_outcome == Outcome.NOT_FOUND + return final_outcome == Outcome.ERROR + +always assertion FreshTerminalReuseDoesNotStartReload: + if load_source != LoadSource.REUSE_TERMINAL: + return True + return load_started == False + +always assertion StaleOrInvalidTerminalStartsReload: + if load_source != LoadSource.START_RELOAD: + return True + return artifact_freshness in [Freshness.STALE, Freshness.INVALID] + +always assertion RedirectReuseDoesNotCommitVisibleTree: + if final_outcome != Outcome.REDIRECT: + return True + return committed_outcome == CommittedOutcome.BASE + +always assertion ErrorOrNotFoundReuseMayCommitAsSameTerminalKind: + if load_source != LoadSource.REUSE_TERMINAL: + return True + if final_outcome == Outcome.NOT_FOUND: + return committed_outcome in [CommittedOutcome.BASE, CommittedOutcome.NEWER_NOT_FOUND] + if final_outcome == Outcome.ERROR: + return committed_outcome in [CommittedOutcome.BASE, CommittedOutcome.NEWER_ERROR] + return True From a1b017e51b9ac21f7225a1d0ec3596da76e58e88 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Apr 2026 01:05:59 +0200 Subject: [PATCH 7/9] updated plan after 1st attempt --- docs/router/route-match-loading-phase-3.md | 386 +++++++++++++++++++++ 1 file changed, 386 insertions(+) diff --git a/docs/router/route-match-loading-phase-3.md b/docs/router/route-match-loading-phase-3.md index 7a398d67b0..c4a193683e 100644 --- a/docs/router/route-match-loading-phase-3.md +++ b/docs/router/route-match-loading-phase-3.md @@ -185,6 +185,392 @@ Phase 3 should be especially careful about: If implementation work exposes uncertainty about actual context-value coherence, pause and extend phase 2 rather than guessing. +## Phase 3 Retrospective + +This section is a direct implementation retrospective from doing phase 3 work for real. + +Keep it in mind while implementing. It is the shortest path away from rebuilding the old architecture in a different shape. + +### The problem is really about committed-tree semantics + +The hard problem is not "run loaders correctly". + +The hard problem is: + +- build candidate trees coherently +- keep preflight, loader reuse, and failure resolution separate +- commit the visible tree atomically +- ensure render-visible state never observes a half-old/half-new mixture + +If the implementation is centered on match mutation, promise choreography, or cache pool transitions, it is already drifting back toward the old design. + +### `RouteMatch` should be treated as a visible-tree projection, not the runtime + +This is the single most important practical lesson from phase-3 implementation work. + +`RouteMatch` is a reasonable adapter-facing representation of the committed tree. + +It is a bad place to store: + +- generation state +- resource cache state +- pending timers +- suspense bookkeeping +- hydration ownership bookkeeping +- shell-level notFound semantics + +When `RouteMatch` becomes the runtime, code volume grows, state duplication grows, and reuse/obsolescence bugs become much harder to reason about. + +### Preserve the two param semantics explicitly + +Implementation work exposed a crucial distinction that should stay explicit: + +- `params` + The cumulative parsed param bag for the active branch. +- `_strictParams` + The route-local parsed params for the current route only. + +This distinction matters for: + +- `useParams({ strict: false })` +- remount stability +- child-route navigation where only descendant params change + +If these are accidentally collapsed into one representation, regressions appear quickly. + +### `beforeLoad` and `loader` are different phases, but error handling must still feel uniform + +`beforeLoad` is serial preflight work and `loader` is reusable resource work. + +But observable route error behavior should still remain coherent. + +In particular, implementation work showed that these expectations must be preserved explicitly: + +- a route `beforeLoad` error still renders through that route's `errorComponent` +- search/param validation failures still participate in route `onError` +- `beforeLoad` errors should not silently degrade into generic root-boundary behavior + +Do not let the internal phase distinction leak into user-visible boundary behavior by accident. + +### Root-shell notFound is a render semantic, not a match field + +The old `globalNotFound` style of representation is a smell. + +Root-shell notFound really means: + +- the root shell remains mounted +- the next outlet renders notFound content + +That should be modeled as runtime or committed-tree semantic state, not as a boolean permanently attached to a match record. + +### Start with an acceptance matrix, not code + +Phase 3 goes much better when implementation starts from an explicit matrix of acceptance criteria and focused tests. + +Do this before writing substantial code: + +1. map each phase-3 acceptance criterion to at least one focused test file +2. identify which current tests are observable-intent tests and which only encode deleted internals +3. run the full `router-core` and `react-router` unit suites early, not only targeted slices + +Without this, it is too easy to "pass the focused rewrite tests" while regressing real observable behavior elsewhere. + +### Distinguish intent tests from internal-shape tests + +Implementation work exposed two very different classes of failures. + +Tests that still matter because they assert real behavior: + +- route error rendering +- invalid search / `onError` behavior +- same-route remount stability +- parsed param visibility +- pending timing + +Tests that should be rewritten or deleted when they only assert deleted architecture: + +- match-pool presence +- cached/pending id arrays +- pool-specific store behavior +- exact compatibility helpers that phase 3 intentionally removed + +If a failing test is about observable behavior, fix the implementation. + +If a failing test is about deleted architecture, rewrite the test. + +### Exact update counts are fragile; upper bounds are better + +Store-update count tests can still be useful, but exact-count assertions are brittle across a rewrite like phase 3. + +If update counts go down, that is usually a good outcome, not a regression. + +### Practical anti-patterns to avoid immediately + +If you see yourself doing any of the following, stop and reset: + +- recreating `pending`/`cached` match pools under new names +- adding lifecycle promises/timers back onto `RouteMatch` +- introducing helper methods whose only job is to preserve deleted architecture for tests or devtools +- adding wrappers like `cloneMatch` that do not reduce semantic complexity +- splitting one large file into several files without reducing state duplication or branching +- keeping both runtime truth and match truth for the same concept unless there is a very strong reason + +### Good implementation direction + +The best direction observed in phase-3 work was: + +- runtime records own lifecycle truth +- committed visible tree is projected from runtime state +- adapters consume semantic gates and committed-tree state only +- tests are organized by model slice, not by helper cluster + +The more the code looks like that, the better phase 3 goes. + +### React should consume render plans, not infer lifecycle from raw state + +One of the clearest implementation lessons from phase 3 is that `packages/react-router/src/Match.tsx` stays complicated if router-core only exposes low-level ingredients and expects React to reconstruct the lifecycle from them. + +If React still has to infer behavior from combinations of: + +- `match.status` +- `match.error` +- `match.ssr` +- shell-level notFound state +- suspense promise lookup +- route option branching + +then the adapter still contains too much lifecycle intelligence. + +That is a smell in the state model, not just in the adapter. + +The desired direction is: + +- router-core decides the semantic render situation +- adapters only map that semantic render situation to framework primitives + +For React specifically, the best target is something conceptually closer to a render plan such as: + +- ready +- pending with suspense promise +- error with boundary owner +- notFound with boundary owner and shell-preservation fact +- obsolete / discardable + +React will still need some complexity for: + +- Suspense +- error boundaries +- client-only / data-only / server-owned hydration behavior +- remount key calculation + +But it should not have to reverse-engineer lifecycle semantics from raw router state. + +If `Match.tsx` still feels like a mini state machine, phase 3 has not pushed enough semantic ownership into router-core. + +### Route-match code should read like a procedure, not a helper forest + +Another major implementation lesson is that simply splitting a large file into many `route-match-*` files does not automatically count as simplification. + +Formal models look simple because they express a small number of state transitions and omit many implementation details. + +A good phase-3 implementation should still aim to read like a step-by-step procedure: + +1. build candidate tree +2. run serial preflight +3. decide resource mode for each route +4. await required work +5. resolve terminal winner and boundary owner +6. commit visible tree +7. let adapters realize semantic gates + +If the implementation instead becomes a large collection of helper functions and exports with state spread across many files, that is usually a sign of one of these problems: + +- duplicated semantic state +- too many side channels for the same concept +- core steps not being modeled explicitly enough +- file splitting used as an organizational tactic without actually reducing branching or duplication + +The route-match problem is genuinely subtle, but it should still read as a small lifecycle with a few explicit phases. + +Prefer: + +- a small number of procedural phase functions +- one explicit resource mode decision per route/resource +- one explicit final outcome / boundary-owner decision +- one explicit commit step + +Avoid: + +- many exported helpers that only move code around without deleting state +- repeated "patch match and return" logic across multiple files +- multiple representations of the same fact unless the distinction is semantically necessary + +If a route-match subsystem grows across many files and still does not feel like a readable lifecycle, treat that as a design warning, not as an acceptable cost of the problem. + +### Keep one source of truth per concept + +A repeated implementation failure mode was keeping the same semantic fact in multiple places at once. + +Examples of facts that should have one clear owner: + +- route context for the current generation +- shell-level notFound ownership +- whether a reusable resource is currently cached or in flight +- which generation currently owns visible state + +If phase 3 introduces both: + +- a runtime-level truth, and +- a match/store/helper-level mirror of the same truth + +then the burden of keeping them synchronized usually outweighs the convenience. + +Prefer one owning representation and derive everything else as late as possible. + +### If React still feels like a mini runtime, core modeling is not finished + +The React adapter is an excellent smell detector. + +If `packages/react-router/src/Match.tsx` still has to do substantial work to: + +- discover the correct thing to suspend on +- decide whether to throw an error or render one +- decide whether shell notFound applies +- infer boundary ownership from raw match state + +then router-core is still exporting raw ingredients instead of semantic render facts. + +Do not accept a complicated adapter as inevitable too early. + +The right question is not "how do we simplify `Match.tsx` by reorganizing it?" + +The right question is "what semantic render plan is router-core still failing to provide?" + +### Full-package tests catch important intent that slice tests will miss + +Focused slice tests are necessary but not sufficient. + +During implementation, several important regressions only showed up when running the full package unit suites. + +In particular, these tests caught real observable regressions and should be treated as phase-3 guardrails, not noise: + +- `packages/react-router/tests/errorComponent.test.tsx` + Caught incorrect `beforeLoad` error rendering behavior. +- `packages/react-router/tests/link.test.tsx` + Caught invalid search / `onError` regression. +- `packages/react-router/tests/router.test.tsx` + Caught same-route remount stability regressions. +- `packages/react-router/tests/useParams.test.tsx` + Caught accidental collapse of cumulative params vs route-local strict params. +- `packages/react-router/tests/store-updates-during-navigation.test.tsx` + Helped distinguish good reductions in update count from brittle exact-count assertions. + +Phase 3 should run full `router-core` and `react-router` unit suites early and repeatedly, not only after the rewrite feels complete. + +### Preserve observable behavior even when internal phase distinctions change + +Implementation work repeatedly showed that internal distinctions can be semantically correct but still produce wrong user-visible behavior if boundary rules are not carried through. + +Examples that must stay explicit: + +- `beforeLoad` and `loader` are different phases internally, but route-level error rendering should still feel coherent +- route-local parsed params and cumulative params are different internally, but hooks must still expose the right public shape +- root-shell notFound is not a match field, but the adapter must still preserve the same shell behavior + +Do not let internal refactoring leak through as a changed public behavior unless the change is intentional and specified. + +### Start from a short procedural sketch before writing code + +Before implementing phase 3, write a small pseudocode outline for the lifecycle. + +For example: + +1. build candidate tree +2. derive route-local context inputs +3. run serial preflight +4. decide resource mode per route +5. run/adopt/reuse required resource work +6. resolve winner and boundary owner +7. commit visible tree and semantic gates + +If the code stops matching a sketch like this, it is usually a sign that too much logic has leaked into helpers or side channels. + +### Prefer deleting state over renaming state + +A common trap is replacing old state with new state that means the same thing under a different name. + +Good phase-3 progress is measured by deleting categories of state entirely, for example: + +- deleting pools rather than renaming pools +- deleting match-level lifecycle promises rather than renaming them +- deleting shell-level match flags rather than moving them to another match field + +If the number of semantic concepts is not going down, the rewrite is probably not simplifying enough. + +### Concrete startup checklist for the next implementation attempt + +Before doing substantial code changes: + +1. Write the acceptance matrix from `## Minimum Acceptance Criteria For Phase 3` into concrete test files. +2. Run full `router-core` and `react-router` unit suites once to establish baseline failures. +3. List which current failures are intent regressions vs deleted-internal tests. +4. Write a short procedural lifecycle sketch. +5. Decide the single owning representation for: + - route context + - shell-level notFound + - cached resource state + - visible committed tree + +If any of those are undecided, phase 3 is not ready to be implemented cleanly. + +## Must-Save Decisions + +If implementation is restarted from scratch, preserve these conclusions. + +- `RouteMatch` should remain a visible-tree projection, not the runtime. +- Do not restore match pools. +- Do not restore promise/timer state on matches. +- Root-shell notFound should not be modeled as a match field. +- `params` and `_strictParams` must remain distinct concepts. +- `beforeLoad` errors still need route-level `errorComponent` behavior. +- search/param validation failures still need route `onError` behavior. +- terminal cache entries must remain terminal and never become success data. +- invalidation-triggered reloads should remain blocking, not background reuse. + +## Focused Test Matrix + +These are the focused test categories that most directly cover the phase-3 acceptance criteria. + +1. Overlap / adoption + Fresh success reuse, in-flight preload adoption, obsolete preload discard. +2. Terminal cache + Cached `redirect`, `notFound`, and `error` reuse as the same terminal kind. +3. Background reload + Late background completion never clobbers newer committed state. +4. Pending timing + `pendingMs`, no flash, `pendingMinMs` continuity. +5. Failures / boundaries + Redirect precedence, loader error vs notFound precedence, boundary ownership. +6. Hydration modes + `SERVER_DOM`, `DATA_ONLY`, `CLIENT_ONLY` semantics. +7. Context coherence + Child visibility of parent `beforeLoad` context and invalidation behavior. +8. Adapter gate behavior + React/Solid/Vue consume semantic render facts rather than inventing lifecycle. + +## Remaining Simplification Opportunities + +Even with a correct phase-3 implementation, these areas are worth simplifying further if they still grow too large. + +- resource acquisition / reuse logic +- shell-level notFound representation +- route context runtime plumbing +- duplicated freshness bookkeeping that could be derived from age plus invalidation + +But simplification should still follow the same rule: + +reduce semantic duplication first, not just file size. + ## What Must Be Preserved ### Committed Tree Coherence From 32c5010bc0ffb92d17c762cd736ff216a8444e82 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Apr 2026 09:28:31 +0200 Subject: [PATCH 8/9] jfc --- docs/router/route-match-loading-phase-3.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/router/route-match-loading-phase-3.md b/docs/router/route-match-loading-phase-3.md index c4a193683e..ab6978f280 100644 --- a/docs/router/route-match-loading-phase-3.md +++ b/docs/router/route-match-loading-phase-3.md @@ -896,6 +896,8 @@ These files should be treated as legacy reference material, not as the skeleton Do not start by reshuffling the current code. +Never access anything through router.state or useRouterState for internal adapter/runtime work, these are low performance public API only. + Start by implementing explicit semantic state in router-core that matches the model suite. Then make React consume that state. Only after the semantic core is stable should you align the other adapters and remove obsolete legacy machinery. If you find yourself preserving the broad structure of `load-matches.ts` or reproducing the current many-branch `Match.tsx` control flow, stop and reset toward a cleaner first-principles design. From 87793ac2577250a8fdce8a22e2811ca77fc36c75 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Apr 2026 09:47:19 +0200 Subject: [PATCH 9/9] plan again jfc --- docs/router/route-match-loading-phase-3.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/router/route-match-loading-phase-3.md b/docs/router/route-match-loading-phase-3.md index ab6978f280..8e8b705863 100644 --- a/docs/router/route-match-loading-phase-3.md +++ b/docs/router/route-match-loading-phase-3.md @@ -298,11 +298,9 @@ If a failing test is about observable behavior, fix the implementation. If a failing test is about deleted architecture, rewrite the test. -### Exact update counts are fragile; upper bounds are better +### Exact update counts may break, this is OK. -Store-update count tests can still be useful, but exact-count assertions are brittle across a rewrite like phase 3. - -If update counts go down, that is usually a good outcome, not a regression. +Store-update count tests can still be useful, but exact-count assertions are brittle across a rewrite like phase 3. If update counts go down, that is usually a good outcome, not a regression. ### Practical anti-patterns to avoid immediately @@ -465,7 +463,7 @@ In particular, these tests caught real observable regressions and should be trea - `packages/react-router/tests/store-updates-during-navigation.test.tsx` Helped distinguish good reductions in update count from brittle exact-count assertions. -Phase 3 should run full `router-core` and `react-router` unit suites early and repeatedly, not only after the rewrite feels complete. +Phase 3 should run full `router-core` and `react-router` unit suites when it gets close to finishing phase 3 for these packages, to obtain information. But for a major rewrite like this it is expected that during some segments of work most tests will be broken. Do not overly focus on fixing tests until approaching completion. ### Preserve observable behavior even when internal phase distinctions change