Repository navigation
Keep hydrating when a computed var raises - #8011
FarhanAliRaza wants to merge 11 commits into
Conversation
A frontend computed var that raises while hydrate_and_load builds its snapshot aborts the whole snapshot, so is_hydrated never becomes true and the page's on_load handlers are never queued (#8002). Claude-Session: https://claude.ai/code/session_01LwJUCTLa6ssVoX8zHH7QyW
hydrate_and_load built its snapshot with BaseState.dict(), which computes every frontend computed var of every state. One that raised aborted the whole snapshot, so is_hydrated never became true and the page's on_load handlers were never queued, on every page of the tab (#8002). While the snapshot is built, dict() now leaves out a computed var (sync or async) that raises and records its error. hydrate_and_load passes each error to the app's backend exception handler and returns the events it gives back ahead of on_load_internal. Claude-Session: https://claude.ai/code/session_01LwJUCTLa6ssVoX8zHH7QyW
Confidence Score: 5/5
[Medium impact] The PR appears safe to merge within its documented scope. SummaryKeeps hydration moving when a frontend computed var raises.
The earlier browser-storage finding is addressed: error capture now covers Reviews (6) · Last reviewed commit: "Look up the hydration error collector pe..." · Reviewed by Greptile |
There was a problem hiding this comment.
1 issue found across 5 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="news/+hydrate-raising-computed-var.bugfix.md">
<violation number="1" location="news/+hydrate-raising-computed-var.bugfix.md:1">
P2: Qualify this as a frontend computed var failing during `hydrate_and_load`; the current wording implies that every computed-var failure and every hydration path is protected, which is not true.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| @@ -0,0 +1 @@ | |||
| A computed var that raises no longer breaks page loads for every page in the browser tab: hydration leaves that var out, reports its error to the backend exception handler, and still runs the page's `on_load` handlers. | |||
There was a problem hiding this comment.
P2: Qualify this as a frontend computed var failing during hydrate_and_load; the current wording implies that every computed-var failure and every hydration path is protected, which is not true.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At news/+hydrate-raising-computed-var.bugfix.md, line 1:
<comment>Qualify this as a frontend computed var failing during `hydrate_and_load`; the current wording implies that every computed-var failure and every hydration path is protected, which is not true.</comment>
<file context>
@@ -0,0 +1 @@
+A computed var that raises no longer breaks page loads for every page in the browser tab: hydration leaves that var out, reports its error to the backend exception handler, and still runs the page's `on_load` handlers.
</file context>
| A computed var that raises no longer breaks page loads for every page in the browser tab: hydration leaves that var out, reports its error to the backend exception handler, and still runs the page's `on_load` handlers. | |
| A frontend computed var that raises while `hydrate_and_load` builds a snapshot no longer breaks page loads across the browser tab: hydration leaves that var out, reports its error to the backend exception handler, and still runs the page's `on_load` handlers. |
Merging this PR will degrade performance by 5.28%1 warning
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing Footnotes
|
FarhanAliRaza
left a comment
There was a problem hiding this comment.
Review notes from running this in a real app. These need addressing before merge.
The issue's exact repro is fixed. After the backend login expires, reloading /b on this branch gives on_load count 2 and is_hydrated=true; main gives 0 and false. The regression test fails on main with KeyError: 'user' and passes here.
The guard only covers the dict() snapshot, though. hydrate_and_load computes vars in more places than that.
1. A raising var that depends on a cookie or LocalStorage var still breaks hydration (reflex/state.py:2805)
auth: str = rx.Cookie("ok")
@rx.var
def user(self) -> str:
return {"ok": "alice"}[self.auth]With the cookie set to expired, the snapshot skips user. Then _get_client_storage_delta → _get_resolved_delta computes it again with no guard, and it raises. The snapshot has already gone out with is_hydrated=False, so on_load is never queued. In the live app, /b shows loads=0, hydrated=false on every reload. This is the expired-login case the issue describes.
2. A raising var that reads is_hydrated still breaks hydration (reflex/state.py:2779, :2799)
Setting is_hydrated = False after _clean() leaves the var dirty. The _get_resolved_delta() call at 2799 then recomputes it with no guard. Example: return f"{self.is_hydrated}:{self._data['user']}", the usual pattern for "loading…" labels. hydrate_and_load raises KeyError, sends no snapshot and runs no on_load.
3. cache=False vars hit the same gap through build_delta at 2799. The description lists this as a known limit, but the cause is the same as 1 and 2. An uncached var puts its state in _always_dirty_substates, so it breaks hydration on every page.
4. Layering. state.py:2789-2795 calls app.backend_exception_handler directly. That bypasses BaseStateEventProcessor._handle_backend_exception (base_state_processor.py:1067), which restores the event context, attaches the OTel span and normalises the return value through chain_updates. It also duplicates the isinstance(handled, list) logic. In production the processor and the app use the same handler (reflex/app.py:1283), so 1 and 2 report each error twice. The test hides this by giving them different handlers. If the handler itself raises (:2791), the snapshot is never emitted.
5. One failure is reported once per dependent. When greeting reads user, a single failure produces N toasts, or N redirects with a redirect-to-login handler. The new test asserts two redirects for one cause.
Suggested direction: set the error collector around the whole hydration body: the snapshot plus both follow-up deltas. Route build_delta's computed-var reads through the same skip-and-record helper. Report the collected errors once, through the processor's exception path. That covers 1–5, and could extend to State.hydrate (state.py:2718) and HydrateMiddleware (hydrate_middleware.py:47), which still call a plain dict().
Smaller:
hydrate_and_loadis now C901 9. Extracting the error-reporting loop fixes it.- The test checks the snapshot by one key (
test_base_state_processor.py:2676) rather than comparing it in full. _snapshot_value/_await_snapshot_valuehave no tests intests/units/istate/test_delta.py.- The news fragment says
on_load"still runs" without qualification, which overclaims given 1–3.
Generated by Claude Code
… one The cookie-dependent var raises again in the client storage delta and stops hydrate_and_load before on_load is queued. A var reading a raising var, and an async var with the same cause, each send their own redirect. The test now gives the processor and the app the same handler, as an app does, and build_delta gets tests of leaving raising vars out while errors are collected.
Collect the errors around the whole hydration body: the snapshot, the delta carrying the is_hydrated guard and the client storage delta. build_delta reads computed vars through the same skip-and-record helper while errors are collected. Report only the first error, as an event that raises does, and only after the deltas went out, so a handler that raises cannot hold the snapshot back. This also brings hydrate_and_load from C901 9 to 6. An uncached var, or one that reads is_hydrated, is computed again by the deltas of the events that finish the page load, outside hydrate_and_load; the docs and news fragment now say so.
…ion handler raises
Reading the collector once per state in build_delta and dict cost every delta and snapshot a call per state: instruction counts under callgrind put it at +5% on the computed fan-out and hydration snapshot benchmarks that CodSpeed flagged. build_delta now reads it inline, only for a computed var it has to compute, and dict reads it per frontend computed var, so a state without computed vars pays nothing.
closes #8002
Why
hydrate_and_loadbuilt its snapshot withBaseState.dict(), which computes every frontend computed var of every state, not only the current page's. One var that raised (for example aKeyErrorafter a backend login expired) aborted the whole snapshot.is_hydratednever became true and the page'son_loadhandlers were never queued. The client token lives insessionStorage, so every full page load in that tab failed the same way, including pages that don't use the broken state.What changed
hydrate_and_loadbuilds its deltas (the snapshot, the delta carrying theis_hydratedguard, and the client storage delta), a frontend computed var (sync or async) that raises is left out and its error is recorded (_snapshot_errors/_snapshot_valueinreflex/istate/delta.py).dict()andbuild_deltaread computed vars through that helper while errors are collected. The frontend merges deltas per key, so it keeps whatever value it already had for that var.hydrate_and_loadpasses the first recorded error to the app'sbackend_exception_handlerand returns the events it gives back (the default toast, or e.g. a redirect to login) ahead ofon_load_internal. A var reading a raising var fails for the same cause, so one error is reported, as for an event that raises.dict()andbuild_deltabehave as before.docs/vars/computed_vars.mdnow says a page load computes every frontend computed var, which vars it leaves out, and that computed vars should return a fallback instead of raising.Verification
test_hydrate_and_load_survives_raising_computed_vars(sync, async and dependent vars, one report, processor and app sharing one handler as in an app),test_hydrate_and_load_survives_raising_cookie_dependent_var(a var on anrx.Cookiethe browser sends as an expired value), andbuild_delta/_snapshot_valuetests intests/units/istate/test_delta.py./, then load and reload/bin the same tab./bhydrates, itson_loadruns on every load, a healthyrx.LocalStoragevalue is replayed, and the handler is called once per load. With the auth cookie set toexpiredin the browser,/balso hydrates and runson_load, with one report.ruff check,ruff format --checkandpyrighton the changed files are clean.Known limits
cache=Falsevar (every event's delta recomputes it, includinghydrate_and_load's own final delta), or one that readsis_hydrated(on_load_internalandset_is_hydratedchange it). Fixing these needs the event processor to tolerate a raising var in an event's delta._diff_against_initial_statecomputes when no compile ran in the process still raises for a var that raises on default values.State.hydrate(used when shared state re-links) andHydrateMiddlewarestill calldict()without this protection.Type of change
https://claude.ai/code/session_01LwJUCTLa6ssVoX8zHH7QyW
Generated by Claude Code