Skip to content

fix(state): recover from unknown frontend substates - #7435

Merged
FarhanAliRaza merged 5 commits into
reflex-dev:mainfrom
kr1shna-exe:fix/7247-unknown-substate-recovery
Oct 13, 2026
Merged

FarhanAliRaza merged 5 commits into
reflex-dev:mainfrom
kr1shna-exe:fix/7247-unknown-substate-recovery

Conversation

@kr1shna-exe

@kr1shna-exe kr1shna-exe commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #7247.

When a backend delta named a substate the page never registered, the frontend latched backend_state_mismatch and stopped applying updates and sending events for the rest of the session. This skips unknown substates so the rest of the delta still applies and the session stays usable.

What changed

  • Apply known state and browser storage updates while excluding unknown substates.
  • Report each unknown substate name once per connection through the existing frontend exception handler.
  • Cover mixed deltas, hydration, returned events and continued clicks with runtime and browser regressions.
  • Update the exception handler docs and add news fragments for reflex and reflex-base.

Verification

  • Full unit suite: 11,186 passed, 155 skipped, 78.96% coverage.
  • Playwright integration tests in test_client_error.py: eight passed across dev and prod.
  • Ruff, pyright reflex tests, Ty, Biome, stub generation and the staged pre-commit hooks pass.
  • Full pre-commit run --all-files reports six type errors from Linux-only CPU affinity APIs in benchmark files this PR doesn't touch. They reproduce on unchanged main on macOS.

Deployment notes

The frontend needs a rebuild to pick up the runtime change. Recovery only skips unknown substates; it does not reconcile other incompatible state definitions between frontend and backend.

Review in cubic

@kr1shna-exe
kr1shna-exe requested review from a team and Alek99 as code owners October 6, 2026 04:44
@greptile-apps

greptile-apps Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with a non-blocking loss of production-mode test coverage.

Summary

This PR skips unknown frontend substates instead of stopping the session.

  • The frontend skips unknown substates and keeps known updates moving.
  • Backend reports explain when a state update was skipped.

Reviews (4) · Last reviewed commit: "test(state): cover an unknown substate i..." · 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 11 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Clear the reported-substates set when the socket connects, so each new
connection hears about an unknown substate once. Also reword the backend
log: the frontend now skips the substate instead of failing the update.
@masenf masenf added bug Something isn't working documentation Improvements or additions to documentation labels Oct 6, 2026
@codspeed

codspeed Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

⚠️ 11 benchmarks spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 148 untouched benchmarks


Comparing kr1shna-exe:fix/7247-unknown-substate-recovery (dc8d8fe) with main (dd41524)

Open in CodSpeed

The event handler now asks a small helper for the known part of the delta
and hands any newly seen unknown substates to a separate reporter, so the
dispatch loop is back to a plain loop.

Also drop the on_hydrated_queue flush. Nothing has pushed to that queue
since the event queue moved to the backend in reflex-dev#6267, so the flush only
ever sent an empty list, and it would have been skipped anyway if the
root state itself were unknown.
@masenf masenf added the on deck PRs lined up to review / merge next label Oct 9, 2026 — with ChatGPT Codex Connector
Collect unknown substates in one pass and report them from the same helper.
Keep only tests that fail before the fix: two runtime tests for the event
handler, the existing Playwright mismatch test rewritten to assert recovery,
and the backend log wording. Merge the root news fragments.

@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 10 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

@greptile-apps

greptile-apps Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings could not be posted inline.

  • P2 Production tests no longer run tests/integration/tests_playwright/test_client_error.py:79 ▶

    Switching client_error_app from app_harness_env.create(...) to AppHarness.create(...) drops the production runs of these browser tests. app_harness_env runs each test with both AppHarness and AppHarnessProd; the direct call only runs development mode. This leaves failures in the exported frontend unchecked. Restore the fixture dependency to keep both modes covered.

@FarhanAliRaza
FarhanAliRaza merged commit 5d454e2 into reflex-dev:main Oct 13, 2026
146 checks passed
FarhanAliRaza added a commit that referenced this pull request Oct 13, 2026
Resolve the conflicts with the final form of #7435: the frontend now skips
an unknown substate instead of stopping, so the connect-level JS tests move
to the client_state_updates.mjs harness main added, the Playwright module
keeps main's renamed tests next to the new dev and prod mismatch tests, and
the docs fold the detection into main's state mismatch subsection.

Review findings addressed:
- Key the frontend schema cache by the registration context as well as the
  root class: apps in one process run on forked contexts that share the root
  State but not its substates. Regression test:
  test_frontend_schema_is_per_registration_context.
- Raise the reflex-base floor to 0.10.1.dev0: reflex now needs the
  state_schema template parameter and the new constants.
- Scope the on_connect log assertions to the reflex.app logger at WARNING.
- Also drop a test-defined substate from RegistrationContext.base_states.
- Say in the reflex-base news fragment that the reload and banner are
  production behavior and that development only warns.

Claude-Session: https://claude.ai/code/session_01EYJS7NPEz1gNkXZdqQDTA3
masenf pushed a commit that referenced this pull request Oct 14, 2026
… a reload (#7553)

The compiled frontend and the backend can come from different builds: a
redeploy with a page kept open, mixed backend versions behind a load
balancer, or an api_url pointing at another backend. The #7435 fallback
skips deltas for unknown substates, but the skew stays hidden from users
and a changed var in a known state is never detected.

BaseState._to_frontend_schema() hashes what the compiled frontend depends
on over the whole tree: each state's full name, its frontend var names and
types (base and computed), and its event handler names. Defaults and values
are left out. It is lru-cached like _to_schema() and cleared with it, so a
state registered later invalidates the cached root. The compiler writes the
hash into the context module as stateSchema; the frontend sends it in the
socket.io CONNECT auth under state_schema on the first connect and every
reconnect; EventNamespace.on_connect compares it with the backend's hash,
emits one state_mismatch event to that client, logs one warning, and still
hydrates. A missing hash (old frontend) is ignored, and an old backend
ignores the new auth key.

On a mismatch in prod the page reloads once, guarded by the existing
reflex_last_reloaded_on_error cooldown, so mixed versions cannot loop; a
mismatch inside the cooldown shows a banner with a reload button. In dev
only a console warning is logged, since a backend hot reload can reconnect
before Vite serves the rebuilt bundle.

Closes #7552.

Claude-Session: https://claude.ai/code/session_01EYJS7NPEz1gNkXZdqQDTA3
benedikt-bartscher added a commit to benedikt-bartscher/reflex that referenced this pull request Oct 17, 2026
Ported upstream changes into the resolver-aware code:

- Context template: hydrate_and_load (reflex-dev#7064) gets a resolved wire name in
  InternalNames (replacing hydrate), alongside upstream's state schema and
  initial state hashes. state.js reads app.hydrate_and_load and
  app.update_vars_internal instead of hardcoded default names, and the
  handshake query (token + scheme) is built for the warm-up socket too.
- State reads use upstream's useStateContext (reflex-dev#7441), keyed by the
  state's resolved full name, into the branch's prefixed local.
- Upstream made unknown substates non-fatal (reflex-dev#7435) and dropped
  backend_state_mismatch; the fatal minification scheme mismatch keeps its
  own flag (backend_scheme_mismatch) gating events, updates and reconnects.
- The frontend state schema hash (reflex-dev#7553) hashes resolver-independent names;
  the scheme digest already covers the wire names.
- The processor's hydrate/hydrate_and_load/on_load_internal lookups cache
  handlers, not names, so they follow a resolver installed later.
- BaseStateToken._state_key and client storage application
  (_apply_client_storage_vars) use default names and wire var keys.
- get_substate keeps upstream's loop but only lets the first segment name
  the state itself; get_name/get_full_name stay function-wide caches so a
  resolver install clears every class, and also clears _get_substate_path.
- on_connect sets up per-SID state before upstream's new first await.
- pyStrAt avoids Array.prototype.at, which the state.js tests forbid.
benedikt-bartscher added a commit to benedikt-bartscher/reflex that referenced this pull request Oct 17, 2026
…inification

Ported upstream changes into the resolver-aware code:

- Context template: hydrate_and_load (reflex-dev#7064) gets a resolved wire name in
  InternalEventNames (replacing hydrate), alongside upstream's state schema
  and initial state hashes. state.js reads app.hydrate_and_load and
  app.update_vars_internal instead of hardcoded default names, and the
  handshake query (token + scheme) is built for the warm-up socket too.
- State reads use upstream's useStateContext (reflex-dev#7441), keyed by the
  state's resolved full name, into the prefixed local.
- Upstream made unknown substates non-fatal (reflex-dev#7435) and dropped
  backend_state_mismatch; the fatal minification scheme mismatch keeps its
  own flag (backend_scheme_mismatch) gating events, updates and reconnects.
- The frontend state schema hash (reflex-dev#7553) hashes resolver-independent names;
  the scheme digest already covers the wire names.
- The processor's hydrate/hydrate_and_load/on_load_internal lookups cache
  handlers, not names, so they follow a resolver installed later.
- BaseStateToken._state_key keys by the resolver-independent name.
- get_substate keeps upstream's loop but only lets the first segment name
  the state itself; get_name/get_full_name stay function-wide caches so a
  resolver install clears every class, and also clears _get_substate_path.
- on_connect sets up per-SID state before upstream's new first await.
- pyStrAt avoids Array.prototype.at, which the state.js tests forbid.
FarhanAliRaza added a commit that referenced this pull request Nov 10, 2026
* Let React Compiler optimize generated components

Replays #7272 onto main. That PR auto-closed when its base branch was
deleted after #7234 merged; its own changes were the diff between the
base-branch head it last merged (07aa53c) and its head (4f3e5db),
covering commits c01f4d4, 755ddba and 4f3e5db.

Change the patterns Reflex emits that made React Compiler bail out:
register refs through a useRegisteredRef hook instead of writing to
refs during render, wrap generateUUID in an inline useMemo callback,
list only referenced bindings as useCallback dependencies, disable
function outlining, and describe Emotion's jsx() to the compiler as
JSX. Pin the experimental compiler, which accepts refs passed to jsx().

Add an auto_memoize config option (default True). False removes
MemoizeStatefulPlugin from page compilation so the compiler memoizes
whole pages; app-root memoization is unchanged.

Conflicts with main: #7586 removed hook positions, so the ref hook no
longer passes VarData(position=INTERNAL); #7435 removed
backend_state_mismatch from state.js, so it stays removed.

Claude-Session: https://claude.ai/code/session_01LwJUCTv3FVWzi1UoUpyMLT

* Tie the callback prune pattern to Python names, tidy tests and fragment

Export GENERATED_EVENT_CALLBACK from the React Compiler adapter and test it
against the names get_memoized_event_triggers produces, so a rename on either
side fails a test instead of silently restoring compiler bailouts.

Drop the Unicode stale-callback claim from the reflex-base fragment: main never
had that bug. Move inline test imports to module level.

* Run the auto_memoize compile_app test as a dry run

Without dry_run, REFLEX_SKIP_COMPILE or a leftover .web/nocompile file made
compile_app return before building the page plugins, and the test wrote into
the working directory's .web.

* Derive the client counter test's JS from the var's real identifier (#7741)

test_memo_client_counter hard-coded the JavaScript name a client state
var binds its value to ("Δcounter + 1"). Merging main brought in #6936,
which drops the name of a legacy ClientStateVar created with
global_ref=False and suffixes the emitted identifier with RxClientState,
so the hook now reads `const [cs$0RxClientState, setCs$0] = ...` while
the click handler still read `Δcounter`. That bare identifier resolved
to the button carrying id="Δcounter" through the browser's named
element access, and the counter rendered "[object HTMLButtonElement]1".

Build the increment expression from str(counter.value) instead, with a
{value} placeholder for the direct read and a {source} placeholder for
the eval'd reads, so the test follows whatever identifier Reflex emits.
Use rx.client_state(0) and .set(...) in place of the deprecated
ClientStateVar.create / set_value entry points. rx.client_state rejects
non-ASCII names, so the Unicode case becomes a plain scoped counter;
test_react_compiler_callback_dependencies still covers Unicode bindings
in the Babel dependency prune.


Claude-Session: https://claude.ai/code/session_01ESN8Dfnc4fUrUVcPsqaLGk

Co-authored-by: Claude <[email protected]>

* Keep lifecycle events in their branch when auto_memoize is off

Without memo wrappers, on_mount and on_unmount hooks were hoisted to the
page function. A hidden rx.cond branch fired on_mount on page load, and an
rx.foreach item hook read the loop variable outside the loop.

Render the events as a MountEffect element beside the component instead.

* Warn once that react_compiler is experimental

* Render lifecycle events as elements in every compile mode

An on_mount inside rx.foreach was hoisted to the Foreach memo body, where
the loop variable does not exist, so the page crashed. Run
InlineLifecyclePlugin with auto-memoization on as well, and rewrite a
snapshot subtree before the memoize plugin seals it.

* Limit the lifecycle element plugin to the experimental options

Default apps keep the generated code they have on main. The plugin runs
with react_compiler=True or auto_memoize=False.

* Keep scope wrappers when auto_memoize is off; remove MountEffect

The MountEffect element kept one instance across an rx.cond branch switch,
so no lifecycle event fired, and its fragment hid the child from an
as_child parent.

With auto_memoize=False, still wrap a component that has a lifecycle event
or hooks of its own in a memo component. A wrapper has its own identity and
forwards props, and it keeps the hooks in their rx.cond branch.

* Test rx.foreach item lifecycle with auto_memoize off; complete the docstring

- An item's lifecycle hook compiles into a wrapper inside the loop body and
  receives the loop variable when auto_memoize is off.
- default_page_plugins names the snapshot boundary and ALWAYS exceptions.

Claude-Session: https://claude.ai/code/session_01LwJUCVweoEhh1JsZA7emsa

* Keep lifecycle of prop components in a wrapper when auto_memoize is off

With auto_memoize off, a lifecycle event of a component held in a prop moved
into the page function, so it fired on page load even inside a hidden
rx.cond branch. The scope-only rule now uses _has_instance_hooks, which also
checks components held in props.

Claude-Session: https://claude.ai/code/session_01LwJUCVweoEhh1JsZA7emsa

---------

Co-authored-by: Masen Furer <[email protected]>
Co-authored-by: Claude <[email protected]>
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

One delta naming a substate the page never registered latches backend_state_mismatch and deadens the whole frontend for the rest of the session

3 participants