Repository navigation
Use initial_value for computed var dependencies when building the initial state dict - #7905
FarhanAliRaza wants to merge 9 commits into
Conversation
…dict BaseState.dict(initial=True) substituted initial_value only for the computed vars it listed itself. A computed var without an initial value was still evaluated, and any computed var its getter read ran its own getter, so compiling or exporting an app failed when that getter needed a database or a request. While the initial dict is built, ComputedVar.__get__ now yields the initial value of a computed var that has one, and caches nothing derived from it. Regular reads are unchanged. Fixes #5767 Claude-Session: https://claude.ai/code/session_01LwJUCUfMV8TRZsr6ehRyuR
Confidence Score: 5/5
[Medium impact] The PR appears safe to merge; no new blocking issues were found. SummaryComputed vars now use their dependencies’
No new actionable issues found. Reviews (5) · Last reviewed commit: "Split the behaviour change of initial va..." · Reviewed by Greptile |
There was a problem hiding this comment.
All reported issues were addressed across 6 files
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
Merging this PR will not alter performance1 warning
Comparing Footnotes
|
Values computed from initial values are kept in a cache that lives for one dict(initial=True) call, so a cached computed var read several times runs its getter once, as it does at runtime, and still never reaches the instance cache. The return type check runs on those values too. Claude-Session: https://claude.ai/code/session_01LwJUCUfMV8TRZsr6ehRyuR
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 mechanism is right. Substituting initial_value inside ComputedVar.__get__ behind a context var covers both builders of the initial dict, compile_state and _diff_against_initial_state. The issue's repro now compiles, and the page hydrates to the runtime values. The regression test fails on the parent commit and passes here. Computing dependents from placeholder values does introduce new problems, though.
1. Apps that compile on main now fail to compile (packages/reflex-base/src/reflex_base/vars/base.py:3033-3036, :3074-3075)
@rx.var(initial_value=None)
def name(self) -> str: ...
@rx.var
def shout(self) -> str:
return self.name.upper()Main compiles this. The branch fails with AttributeError: 'NoneType' object has no attribute 'upper'. Placeholders often don't match the getter's return type: None, 0, or "🔒 log in…", which the enterprise docs recommend. The same error is raised inside hydrate_and_load → _diff_against_initial_state (reflex/state.py:2850) in a backend process that never compiled, so a broken dependent would block hydration on every page. This is a deliberate change in what gets compiled. It needs documenting in docs/vars/computed_vars.md and the news fragment, plus a test that pins it.
2. A dependent that mutates the value it reads corrupts the shared default (base.py:3036, :3075). Both lines return the class-level _initial_value object itself. With @rx.var(initial_value=[]) def items and a dependent that does self.items.append(99), three dict(initial=True) calls give [99], [99, 99], [99, 99, 99]. The compiled initialState for items is wrong as a result. Copy the value before handing it out.
3. "Computed once per initial-dict build" doesn't hold across substates (reflex/state.py:2129-2143). The context var is set and then reset before recursing into substates, so each substate starts with an empty cache. A parent cached var read by three substates runs its getter 4 times here versus once on the parent commit, which multiplies DB or network calls at compile time. Set the context var once in the outermost call.
4. Async computed vars still evaluate the dependency. AsyncComputedVar.__get__ doesn't check the context var, and _resolve_delta awaits after it has been reset. The root news fragment claims reflex export/reflex run "no longer fail", so it should be scoped to sync vars.
5. Compiled initialState changes for existing apps even when nothing raises. Examples: a dependent of a backend var with an initial value (shown 10 → 70), a dependent of an interval var (doubled 198 → 6). Hydration corrects them, but anything rendered before hydration shows different text. Worth a line in the fragment.
Smaller:
- This conflicts textually with #8011 in
BaseState.dict. ContextVar.get()now runs on every runtime read of an uncached computed var (159 → 175–200 ns). Check_initial_valuefirst, since most vars don't set it.- The comprehension in
state.py:2131-2140now duplicates what__get__does and could just callself.get_value(prop_name). - Tests don't cover 1–4.
Generated by Claude Code
A getter that mutated an initial value it read changed the class-level default, so each initial dict built after it showed the mutation. Hand out a deep copy instead. The build cache was set and reset per state, so a cached parent var read by N substates ran its getter N+1 times. Set it once in the outermost dict() call, which also leaves the computed var comprehension as it was on main. Pin that a getter which cannot handle the initial value it reads now fails to build the initial dict.
Explain initial_value in the computed vars docs, including that a dependent is compiled from the initial value and must accept it. The fragments now say that only synchronous computed vars are covered, and that compiled values of dependents change.
Deep-copying on every read made a getter that indexes an initial list in a loop quadratic, and gave two reads in one getter different objects. Keep the copy in the build cache, keyed like the computed values, so every read in a build sees the same copy.
There was a problem hiding this comment.
All reported issues were addressed across 6 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
Both initial-dict hooks in ComputedVar.__get__ now take the same path, so an uncached computed var without an initial value runs its getter once per build, like a cached one, instead of once per read.
The root bugfix fragment keeps the fix. The breaking fragment states that a getter reading a computed var with an initial value must accept that value, and how to adapt one that does not. The reflex-base fragment notes that the other computed vars read during the build run once per build.
All Submissions:
Type of change
Changes To Core Features:
Problem
BaseState.dict(initial=True)(used bycompile_stateand by_diff_against_initial_state) substitutesinitial_valueonly for the computed vars it lists itself. A computed var without an initial value is still evaluated, and when its getter readsself.other_var,ComputedVar.__get__runsother_var's getter even though it has aninitial_value. With the repro from #5767 (return annotations added, which are required now),compile_statestill raisesvar1: This should never happen at compile timeonmain.Fix
reflex_base.vars.basegets a privateContextVar,_initial_dict_cache. The outermostBaseState.dict(initial=True)call sets it to an empty dict, builds the dict of the state and all its substates inside it, and resets it in afinally. Substates share one build cache.ComputedVar.__get__checks it only where it is about to call the getter (uncached var, or cache miss), so a read that hits the cache costs nothing extra. While it is set, a var with aninitial_valueyields a deep copy of that value, made once per build, and its getter does not run. A getter that mutates the value it reads therefore leaves the class-level default intact.initial_value, cached or not, is computed once per initial-dict build (across substates too) into that build-local cache, and never written to the instance cache, so repeated reads do not rerun the getter and nothing derived from initial values can be served later. Both hooks in__get__take this same path._check_deprecated_return_typeruns on the values computed there, as it does at runtime.ContextVaris local to the task, so a live session never sees it: at runtimeself.var1runs the getter or uses its cache as before.reflexnow imports a symbol that only exists in unreleasedreflex-base. The floormainalready has,reflex-base >= 0.11.1.dev0, covers it, sopyproject.tomlis unchanged.Behaviour change
A dependent of a var with
initial_valueis now compiled from that initial value, so its getter must accept it:@rx.var(initial_value=None) def name(self) -> strread asself.name.upper()compiled onmainand now fails to compile. Its compiled value (shown until the page hydrates) also changes. This is the behaviour #5767 asks for.docs/vars/computed_vars.mdgains an "Initial Values" section that explains it, and a rootbreakingfragment states it with the fix (give the initial value the getter's type, or handle it in the reading getter). There is no runtime fallback: it would have to catch exceptions from user getters and rebuild the dict the old way, which hides the type mismatch the docs ask users to fix.Deliberately not changed
_resolve_delta, outsidedict(), so a read of a computed var from inside anasyncgetter is not covered here. The docs and the fragment say so.dict(initial=True)andis_computed_varare left as they are.Tests
tests/units/test_state.py::test_initial_dict_uses_initial_value_of_computed_var_dependenciesbuilds the initial dict of a state and its substate and compares it in full: dependents of a cached and of an uncached var withinitial_value, transitive dependents, and a substate reading inherited vars all see the initial values. No getter of a var with an initial value is called, and the cached and the uncached var without one, each read by the state and its substate, run their getters once. It then reads the vars normally and checks that the getters run, in the exact order expected, and thatdict()returns the runtime values (nothing from the initial pass was cached on the state). It fails onmain(101/1002/1106/1106instead of110/1020/1160/1160).test_initial_dict_does_not_share_mutable_initial_valuesbuilds the initial dict twice for a getter that appends to the[]initial values it reads, and checks that the defaults stay[]and that both reads in one getter see the same copy.test_initial_dict_raises_when_a_getter_cannot_handle_an_initial_valuepins the behaviour change above.Run locally:
uv run pytest tests/units/test_state.py tests/units/vars tests/units/reflex_base/vars tests/units/compiler tests/units/istate -q— 1643 passeduv run ruff checkanduv run ruff format --checkon the changed files — cleanuv run pyright reflex/state.py packages/reflex-base/src/reflex_base/vars/base.py tests/units/test_state.py— 0 errorscompile_state: raises without the fix, returns{'var1': True, 'var2': None}with ithttps://claude.ai/code/session_01LwJUCUfMV8TRZsr6ehRyuR
closes #5767