Skip to content

Keep hydrating when a computed var raises - #8011

Open
FarhanAliRaza wants to merge 11 commits into
mainfrom
farhan/busy-bohr-n2kub8
Open

FarhanAliRaza wants to merge 11 commits into
mainfrom
farhan/busy-bohr-n2kub8

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

closes #8002

Why

hydrate_and_load built its snapshot with BaseState.dict(), which computes every frontend computed var of every state, not only the current page's. One var that raised (for example a KeyError after a backend login expired) aborted the whole snapshot. is_hydrated never became true and the page's on_load handlers were never queued. The client token lives in sessionStorage, so every full page load in that tab failed the same way, including pages that don't use the broken state.

What changed

  • While hydrate_and_load builds its deltas (the snapshot, the delta carrying the is_hydrated guard, 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_value in reflex/istate/delta.py). dict() and build_delta read 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.
  • After the deltas went out, hydrate_and_load passes the first recorded error to the app's backend_exception_handler and returns the events it gives back (the default toast, or e.g. a redirect to login) ahead of on_load_internal. A var reading a raising var fails for the same cause, so one error is reported, as for an event that raises.
  • Outside hydration, dict() and build_delta behave as before.
  • Docs: docs/vars/computed_vars.md now 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

  • Regression tests, committed before each fix: 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 an rx.Cookie the browser sends as an expired value), and build_delta / _snapshot_value tests in tests/units/istate/test_delta.py.
  • The issue's repro in a dev app in Chromium, with a counting backend exception handler: expire on /, then load and reload /b in the same tab. /b hydrates, its on_load runs on every load, a healthy rx.LocalStorage value is replayed, and the handler is called once per load. With the auth cookie set to expired in the browser, /b also hydrates and runs on_load, with one report.
  • ruff check, ruff format --check and pyright on the changed files are clean.

Known limits

  • A raising var that the events finishing the page load compute again still stops it: a cache=False var (every event's delta recomputes it, including hydrate_and_load's own final delta), or one that reads is_hydrated (on_load_internal and set_is_hydrated change it). Fixing these needs the event processor to tolerate a raising var in an event's delta.
  • The default snapshot _diff_against_initial_state computes 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) and HydrateMiddleware still call dict() without this protection.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • This change requires a documentation update

https://claude.ai/code/session_01LwJUCTLa6ssVoX8zHH7QyW


Generated by Claude Code

View guided diff Turn on auto-fix

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
@FarhanAliRaza
FarhanAliRaza requested review from a team and Alek99 as code owners November 26, 2026 00:24
@FarhanAliRaza FarhanAliRaza added bug Something isn't working documentation Improvements or additions to documentation labels Nov 26, 2026 — with ChatGPT Codex Connector
@greptile-apps

greptile-apps Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge within its documented scope.

Summary

Keeps hydration moving when a frontend computed var raises.

  • A computed var error no longer blocks page hydration.

The earlier browser-storage finding is addressed: error capture now covers _get_client_storage_delta(). The latest getter refactor introduces no actionable issues.

Reviews (6) · Last reviewed commit: "Look up the hydration error collector pe..." · Reviewed by Greptile

Comment thread reflex/state.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread reflex/state.py Resolved
Comment thread docs/vars/computed_vars.md Resolved
@@ -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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
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.

Comment thread reflex/state.py Resolved
@codspeed

codspeed Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 5.28%

1 warning

⚠️ 17 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

❌ 2 regressed benchmarks
✅ 144 untouched benchmarks
⏩ 8 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_computed_dependency_fanout[2] 4.8 ms 5.2 ms -6.47%
❌ test_proxy_list_mutation 9.3 ms 9.6 ms -4.07%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing farhan/busy-bohr-n2kub8 (05ec39b) with main (8e0e881)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@FarhanAliRaza FarhanAliRaza left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_load is 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_value have no tests in tests/units/istate/test_delta.py.
  • The news fragment says on_load "still runs" without qualification, which overclaims given 1–3.

Generated by Claude Code

FarhanAliRaza and others added 3 commits November 30, 2026 19:56
… 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.
@FarhanAliRaza FarhanAliRaza added the priority: P1 High: confirmed bug with repro in a common feature, or high demand label Nov 30, 2026 — with Claude
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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working documentation Improvements or additions to documentation on deck PRs lined up to review / merge next priority: P1 High: confirmed bug with repro in a common feature, or high demand

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A computed var that raises in one page's state breaks hydration of every page in the tab

1 participant