Resource created after hydration reads another resource's SSR data (`read_data` ignores `during_hydration`; SSR allocates IDs repeatedly for components inside a `Suspend`)
Describe the bug
A Resource created by a client-side navigation after hydration can pick up the serialized value of
a different resource from the initial page load, and then never fetches. It happens when the initial
SSR render created resources inside the body of a move || Suspend::new(async move { … }) closure under
a <Suspense> — for example a parent route that waits for a session and then renders <Outlet/>.
Two things combine:
SSR allocates IDs more than once for everything created inside the
Suspendbody.SuspenseBoundary::to_html_async_with_buf(leptos/src/suspense_component.rs) callsself.children.dry_resolve(), thenchildren.dry_resolve()again in its "double-checking" effect, thenchildren.resolve(). For a reactive closure,dry_resolveisself.invoke().dry_resolve()(tachys/src/reactive_graph/mod.rs), so the closure runs again each time. Once the awaited resource is ready (by the time the double-check runs), theSuspendbody runs in the double-check and again inresolve. EveryResource::new/<Suspense>in that body callsnext_id()more than once: twice in our app, three times in the minimal repro below (in the repro the firstdry_resolveapparently already reaches the body). Every instance callswrite_async, so every slot ends up in__RESOLVED_RESOURCES, and the resource's fetcher runs once per instance on the server. The client hydrates the body once, so its counter ends up lower than the server's.The client keeps handing out IDs after hydration and
read_datastill answers.HydrateSharedContext::next_idkeeps counting afterhydration_complete(), andHydrateSharedContext::read_datareturns__RESOLVED_RESOURCES[id]without checkingduring_hydration(hydration_context/src/hydrate.rs).ArcResource::new_with_options(leptos_server/src/resource.rs) always callsinitial_value. So the first resources created after hydration get the IDs of the discarded server instance from (1). They get that instance's data as their initial value,is_readyis true, and nothing is fetched.
Hydration itself only works by accident: the client's single instance reads the discarded server instance's slot, and that slot holds the same data.
If the stale slot doesn't deserialize into the new resource's type, the decode fails, the resource
fetches normally, and there are no visible symptoms. If it does deserialize (same type, or a
serde-compatible one), the page silently shows wrong data. In our app that meant the editor showing
character X under the URL of character Y. It also meant a DM roster (Vec<CharacterSummary>) showing
the user's own character list (also Vec<CharacterSummary>) from the previous page.
Leptos Dependencies
leptos = "0.8.20" # also checked: 0.8.21 — unchanged in the relevant code
leptos_router = "0.8.14"
leptos_axum = "0.8.7"
leptos_server = "0.8.7" # 0.8.8: resource.rs unchanged
tachys = "0.2.17" # 0.2.19 / main: closure dry_resolve unchanged
reactive_graph = "0.2.14"
hydration_context = "0.3.1" # latest; main: read_data unchangedTo Reproduce
Standalone repro crate, verified with exactly the versions above in Chromium and Firefox (can be
published as a repo). src/lib.rs:
use leptos::prelude::*;
use leptos_router::{
components::{A, Outlet, ParentRoute, Route, Router, Routes},
path,
};
#[server]
pub async fn get_item(which: String) -> Result<String, ServerFnError> {
Ok(format!("data for {which}"))
}
#[server]
pub async fn check_session() -> Result<bool, ServerFnError> {
Ok(true)
}
#[component]
pub fn App() -> impl IntoView {
view! {
<Router>
<nav><A href="/a">"page a"</A>" | "<A href="/b">"page b"</A></nav>
<Routes fallback=|| "not found">
<ParentRoute path=path!("") view=Gate>
<Route path=path!("/a") view=|| view! { <Page which="a"/> }/>
<Route path=path!("/b") view=|| view! { <Page which="b"/> }/>
</ParentRoute>
</Routes>
</Router>
}
}
/// "Wait for the session, then render the child route."
#[component]
fn Gate() -> impl IntoView {
let session = Resource::new(|| (), |()| check_session());
view! {
<Suspense>
{move || Suspend::new(async move {
let _ = session.await;
view! { <Outlet/> }
})}
</Suspense>
}
}
#[component]
fn Page(which: &'static str) -> impl IntoView {
let item = Resource::new(move || which.to_string(), get_item);
view! {
<h1>{format!("page {which}")}</h1>
<Suspense>
<p id="item">{move || Suspend::new(async move { item.await.unwrap_or_default() })}</p>
</Suspense>
}
}Standard axum setup (generate_route_list + leptos_routes, default out-of-order streaming,
shell with <HydrationScripts/>, hydrate() = hydrate_body(App)).
- Load
/adirectly (full page load). - Click "page b" (client-side navigation).
Expected behavior
/b shows data for b, fetched via the get_item server function.
Observed behavior
/b shows the <h1> "page b", but #item shows data for a, and no get_item request is made.
The SSR HTML of /a holds three copies of page a's data. The page's resource was created three
times on the server, and once on the client during hydration:
__RESOLVED_RESOURCES[0] = "{\"Ok\":true}" // session (Gate)
__RESOLVED_RESOURCES[2] = "{\"Ok\":\"data for a\"}" // Page a, discarded server instance
__RESOLVED_RESOURCES[4] = "{\"Ok\":\"data for a\"}" // Page a, discarded server instance
__RESOLVED_RESOURCES[6] = "{\"Ok\":\"data for a\"}" // Page a, rendered server instanceThe client hydrates with IDs 0–3. After the navigation, page b's resource is created with ID 4 and
gets "data for a". With the workaround below, the same click fetches data for b in both browsers.
ID trace from our app, where the structure is the same (instrumented next_id / read_data):
server, direct load of /editor/X:
next_id 0 Resource (session, App)
next_id 1 Suspense (gate)
next_id 2 Resource (page) <- created inside dry_resolve (discarded)
next_id 3 Suspense (page)
next_id 4 Resource (page) <- created inside resolve (rendered)
next_id 5 Suspense (page)
write_async 0, 2, 4 -> __RESOLVED_RESOURCES has slots 0, 2, 4 (2 and 4: same data)
client:
hydration: next_id 0 HIT, 1, 2 HIT, 3, hydration_complete()
navigate to /editor/Y: next_id 4 -> read_data 4 -> HIT (X's data), during_hydration=false
-> Resource initial = Some(X), no requestChromium and Firefox behave the same. Mode: default out-of-order streaming; the affected routes had no
explicit ssr mode.
Additional context / proposed fix
- Minimal fix in
hydration_context: haveHydrateSharedContext::read_datareturnNoneonceduring_hydration()is false. At that point nothing can legitimately need serialized data any more. If a resource created from aSuspendthat was still pending during hydration ever needs the data, it currently gets it by chance; with this change it would fetch instead of reading a possibly wrong slot. - Deeper fix: make SSR ID allocation idempotent across
dry_resolve/resolve. The closure could be invoked once and the resulting view reused, or the ID counter reset/replayed per invocation. That would also stop the fetcher from running twice on the server. - Related, but a different cause: #4881 (keyed
<For>hydration order, fixed in #4882), #4733.
Our workaround, right after hydrate_body:
leptos::mount::hydrate_body(App);
if let Ok(resolved) = js_sys::Reflect::get(&js_sys::global(), &"__RESOLVED_RESOURCES".into())
&& let Some(resolved) = resolved.dyn_ref::<js_sys::Array>()
{
resolved.set_length(0);
}This clears the same Array object that hydration_context holds through its thread_local static.
Source: leptos-rs/leptos