Skip to content

Use initial_value for computed var dependencies when building the initial state dict - #7905

Open
FarhanAliRaza wants to merge 9 commits into
mainfrom
claude/fix-5767-initial-value-dependency
Open

FarhanAliRaza wants to merge 9 commits into
mainfrom
claude/fix-5767-initial-value-dependency

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

Problem

BaseState.dict(initial=True) (used by compile_state and by _diff_against_initial_state) substitutes initial_value only for the computed vars it lists itself. A computed var without an initial value is still evaluated, and when its getter reads self.other_var, ComputedVar.__get__ runs other_var's getter even though it has an initial_value. With the repro from #5767 (return annotations added, which are required now), compile_state still raises var1: This should never happen at compile time on main.

Fix

  • reflex_base.vars.base gets a private ContextVar, _initial_dict_cache. The outermost BaseState.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 a finally. 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 an initial_value yields 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.
  • A var without an 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_type runs on the values computed there, as it does at runtime.
  • The context var is set and reset inside one synchronous call, and a ContextVar is local to the task, so a live session never sees it: at runtime self.var1 runs the getter or uses its cache as before.
  • reflex now imports a symbol that only exists in unreleased reflex-base. The floor main already has, reflex-base >= 0.11.1.dev0, covers it, so pyproject.toml is unchanged.

Behaviour change

A dependent of a var with initial_value is now compiled from that initial value, so its getter must accept it: @rx.var(initial_value=None) def name(self) -> str read as self.name.upper() compiled on main and 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.md gains an "Initial Values" section that explains it, and a root breaking fragment 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

  • Async computed vars: their coroutines are awaited later by _resolve_delta, outside dict(), so a read of a computed var from inside an async getter is not covered here. The docs and the fragment say so.
  • The top-level substitution in dict(initial=True) and is_computed_var are left as they are.
  • No integration test: there is nothing to observe in a browser beyond what the initial dict contains.

Tests

tests/units/test_state.py::test_initial_dict_uses_initial_value_of_computed_var_dependencies builds the initial dict of a state and its substate and compares it in full: dependents of a cached and of an uncached var with initial_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 that dict() returns the runtime values (nothing from the initial pass was cached on the state). It fails on main (101/1002/1106/1106 instead of 110/1020/1160/1160).

test_initial_dict_does_not_share_mutable_initial_values builds 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_value pins 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 passed
  • uv run ruff check and uv run ruff format --check on the changed files — clean
  • uv run pyright reflex/state.py packages/reflex-base/src/reflex_base/vars/base.py tests/units/test_state.py — 0 errors
  • The issue's repro through compile_state: raises without the fix, returns {'var1': True, 'var2': None} with it

https://claude.ai/code/session_01LwJUCUfMV8TRZsr6ehRyuR

closes #5767

…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
@FarhanAliRaza
FarhanAliRaza requested a review from a team as a code owner November 15, 2026 09:09
@greptile-apps

greptile-apps Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge; no new blocking issues were found.

Summary

Computed vars now use their dependencies’ initial_value while Reflex builds the initial state, without saving those results for runtime use.

  • Computed vars use dependency initial values during state compilation.

No new actionable issues found.

Reviews (5) · Last reviewed commit: "Split the behaviour change of initial va..." · Reviewed by Greptile

@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.

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

@codspeed

codspeed Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 16 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

✅ 146 untouched benchmarks
⏩ 8 skipped benchmarks1


Comparing claude/fix-5767-initial-value-dependency (f0918fc) 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. ↩

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
@masenf masenf added the bug Something isn't working label Nov 16, 2026

@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 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_value first, since most vars don't set it.
  • The comprehension in state.py:2131-2140 now duplicates what __get__ does and could just call self.get_value(prop_name).
  • Tests don't cover 1–4.

Generated by Claude Code

@FarhanAliRaza FarhanAliRaza added the on deck PRs lined up to review / merge next label Nov 30, 2026
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.

@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.

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

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

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 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 "B" that accesses another computed var "A" with initial_value causes "A" to be computed at compile time

2 participants