perf: split router into per-field base vars; gather connection-static router data at connect - #7068
perf: split router into per-field base vars; gather connection-static router data at connect#7068masenf wants to merge 12 commits into
Conversation
β¦onnect Reimagines #6906 without touching the delta machinery: instead of eliding unchanged RouterData fields during delta serialization, the router is no longer a single serialized base var. Each kind of router data lives in its own base var on the root state (router_session, router_headers, router_page, router_url, router_route_id), so the existing per-var delta machinery naturally re-sends only what changed: - a navigation dirties only page/url/route_id (measured: 1898 -> 619 bytes, -67%, on a realistic connection; session and headers ship once per connection instead of on every page change) - a reconnect dirties only the session - an event without a route change re-sends no router vars at all State.router remains as a switchboard. On instances it is a property that composes a RouterData view from the per-field vars (and decomposes on assignment), so all existing reads/writes keep working. On classes it returns RouterDataVar, whose attributes resolve directly to the per-field base vars, so State.router.session.client_token and friends compile to the new var names with no frontend changes needed. ComputedVar dependency tracking recurses into the property getter, so vars reading self.router depend on the per-field vars; an explicit legacy deps=["router"] is expanded to all of them with a deprecation warning. The URL is stored as URLData, a dataclass mirroring ReflexURL's parsed components: json.dumps serializes str subclasses natively (bypassing the serializer registry), so a bare ReflexURL field would reach the frontend as a string instead of the component dict. Also move the static per-connection router_data gathering (headers, client IP, session id) from on_event to on_connect: they cannot change without going through on_connect again, so decoding every header on every event was wasted work. on_event now merges a per-sid cached fragment (~4.4x faster router_data prep, benchmarked by test_on_event_router_data), falling back to the connection environ if the connect was not seen; the cache is dropped on disconnect. Old pickled states are discarded by the existing schema check (the root state's base vars changed); __setstate__ drops the legacy router entry so unpickling them does not crash before that check. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
There was a problem hiding this comment.
1 issue found across 13 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid β if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="reflex/istate/shared.py">
<violation number="1" location="reflex/istate/shared.py:109">
P2: When a client has a linked shared state, every `modify_state_with_links` event enters `_patch_state` and marks all five router base vars dirty. This resends connection-static session and headers (and unchanged navigation fields) on ordinary shared-state events, defeating the per-field delta optimization; invalidate dependent computed vars without marking unchanged router base vars for emission.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| # Apply the updates into the existing state tree for rehydrate. | ||
| root_state = original_state._get_root_state() | ||
| root_state.dirty_vars.add("router") | ||
| root_state.dirty_vars.update(ROUTER_VARS) |
There was a problem hiding this comment.
P2: When a client has a linked shared state, every modify_state_with_links event enters _patch_state and marks all five router base vars dirty. This resends connection-static session and headers (and unchanged navigation fields) on ordinary shared-state events, defeating the per-field delta optimization; invalidate dependent computed vars without marking unchanged router base vars for emission.
Prompt for AI agents
Check if this issue is valid β if so, understand the root cause and fix it. At reflex/istate/shared.py, line 109:
<comment>When a client has a linked shared state, every `modify_state_with_links` event enters `_patch_state` and marks all five router base vars dirty. This resends connection-static session and headers (and unchanged navigation fields) on ordinary shared-state events, defeating the per-field delta optimization; invalidate dependent computed vars without marking unchanged router base vars for emission.</comment>
<file context>
@@ -106,7 +106,7 @@ async def _patch_state(
# Apply the updates into the existing state tree for rehydrate.
root_state = original_state._get_root_state()
- root_state.dirty_vars.add("router")
+ root_state.dirty_vars.update(ROUTER_VARS)
root_state.dirty_vars.add(ROUTER_DATA)
root_state._mark_dirty()
</file context>
There was a problem hiding this comment.
Not changing this one in this PR β it's a faithful translation, not a regression, and I'd rather not alter shared-state rehydrate semantics speculatively. Flagging it for @masenf to decide.
On main this line is root_state.dirty_vars.add("router"), and router was the single var holding session, headers, page, url and route_id β so main already re-sends all of that on the same events. dirty_vars.update(ROUTER_VARS) produces an identical payload; the per-field split neither improves nor worsens this path.
You're right that it leaves value on the table: a client with a linked shared state doesn't get the delta reduction on ordinary events. But the reason those vars are marked dirty is to invalidate computed vars that depend on the router for the patched tree β _mark_dirty_computed_vars drives that off dirty_vars, so decoupling "invalidate dependents" from "emit the var" needs a mechanism that doesn't exist yet. Doing that safely deserves its own change with shared-state test coverage rather than riding along here.
Happy to do it as a follow-up if you'd like it in scope.
Generated by Claude Code
β¦factor-7j1305 # Conflicts: # tests/units/test_app.py
β¦ations test_router_var_dep and test_router_var_dep_legacy_string define state classes locally, which register themselves in State's class-level _var_dependencies / _potentially_dirty_states and outlive the test. A later test that dirties a router var on a fresh State tree then resolves the stale entry and raises on the missing substate -- which already made test_chained_event_keeps_originating_router_data fail whenever it ran after test_state.py. Drop the registrations at the end of each test. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
The changelog check requires a news fragment under every package whose source the PR touches; this change also edits reflex-base's route constants and event processor. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
Merging this PR will improve performance by 3.17%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| β‘ | test_var_access[mutable_dict] |
47 ms | 45.6 ms | +3.17% |
| π | test_on_event_router_data |
N/A | 1.9 ms | N/A |
Tip
Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.
Comparing claude/router-vars-refactor-7j1305 (9c270ca) with main (5d9724e)
Footnotes
-
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. β©
dataclasses.replace() on the existing router_session value rejects anything that is not a dataclass instance, which broke the redis token manager tests: they drive on_connect with a mocked state whose router_session is a Mock. Rebuilding from router_data (as the pre-split code did, and as the event processor does) keeps the session var and router_data in step and works with the mocked state. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
_update_router_vars gated on the router_data keys each var derives from, then assigned unconditionally. Different keys can still yield an equal value -- an absent key and an empty one both produce the default -- so a router_data update that changed nothing observable still dirtied the var, which marked the state touched and persisted it to redis. That showed up as an extra token in test_redis_token_manager_enumerate_tokens. The pre-split code compared the rebuilt RouterData before assigning; restore that, keeping the key check as the cheap gate that avoids rebuilding HeaderData on every navigation. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
EventNamespace's token manager is redis-backed when a redis URL is configured, so linking a token in these tests left it visible to test_redis_token_manager_enumerate_tokens, which asserts an exact token count. Tear the namespace down the way the token manager tests' own factory does. Also stop expecting router_route_id in every on_load delta of test_dynamic_route_var_route_change_completed_on_load: those navigations all match the same route, so the route pattern only changes on the first. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
|
CI caught three things on the first push, all genuinely this PR's. Fixed and pushed ( 1. Missing news fragment for 2. 3. A var could be dirtied when its value had not changed. That last one also sharpens the delta table in the description: a navigation now dirties These only reproduce with redis configured ( Generated by Claude Code |
There was a problem hiding this comment.
All reported issues were addressed across 7 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
Whole-router dependency (greptile P1, cubic P2): deps=[State.router] registered only router_url, because VarData.merge surfaces the first non-empty field name, so a cached var declaring the whole router went stale when any other router field changed. Vars now name the state fields a dependency must track via _dependency_field_names(); RouterDataVar names all five. Non-composite vars keep their existing behaviour. Cached headers aliasing (greptile P2, cubic P2): the cached headers dict was shared with every event and, through it, with the mutable state.router_data, so a handler mutating self.router_data["headers"] corrupted the connection cache. Copy it per event -- measured at 0.081us against the 1.347us decode it replaced, so the cache still pays for itself 17x over. My note on the PR claiming the copy was the cost being removed was simply wrong. Omitted static keys (cubic P2): a router_data carrying only the navigation keys says nothing about the session or headers, but _update_router_vars read the omission as a change and reset them to their defaults. A key absent from the new payload is now left alone. Non-origin headers (cubic P2): only the origin header feeds the page and URL, so a cookie change no longer rebuilds the navigation vars. Hardcoded identifiers (greptile P2): the router field names are now named constants, used at the lookup sites and in the dynamic route dependency. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
There was a problem hiding this comment.
All reported issues were addressed across 11 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
Both reviewers flagged this as P1. Rebuilding SessionData from router_data left router_session.client_token empty until the first event filled it in, and duplicate-token handling makes that worse: the state is loaded under a freshly issued token, so anything reading client_token in the meantime -- a background task, a shared-state link -- addresses the wrong state tree. Record the identity the state was actually loaded under. Also make the EventNamespace fixture async so its token-manager teardown awaits on the test's own event loop, rather than driving a redis client bound to that loop from a fresh one via asyncio.run. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
|
Second review round addressed in Fixed
Fixture teardown ran on a fresh event loop (cubic P2). Now a Verified, no change
Not this PR's
CodSpeed "Performance Regression: -0.07%" β flagged on VerificationFull Generated by Claude Code |
There was a problem hiding this comment.
All reported issues were addressed across 11 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
The previous commit stopped an absent key from being read as a change, but the constructors still read the incoming dict directly, so a payload holding only some navigation keys rebuilt page and url without the origin header that gives them their host. Merge the new data over what the state last saw and build from that; the merged dict is also what the caller now stores, so a partial payload does not drop keys for the next comparison either. Merging additionally makes an absent key compare equal to what it replaced, so the explicit presence check is no longer needed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
serialize_router_data and RouterDataVar independently spelled out the five keys of the serialized router shape, and the two have to agree: the literal a whole-router render produces is the object a component reads, and it must match what the delta carries. Name them once and use them in both places, with a test pinning the rendered keys to the serializer's and to what actually reaches the client. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
There was a problem hiding this comment.
All reported issues were addressed across 12 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
A partial payload is never equal to the full dict the state holds, so it always reaches the merge -- and when it merges to what is already there, assigning it still dirtied router_data, marked the state touched, and persisted it for an event that moved nothing. Same class of bug as the spurious var dirtying fixed earlier, reached through the router_data assignment instead. Assign only when the merge actually differs. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh
|
Follow-up on the Windows 3.14 unit-tests job, because my earlier note named a specific test and mechanism that do not explain this second occurrence β leaving that standing would misattribute it. What failed on The test monkeypatches Why I'm confident it isn't this PR's:
I did not determine the precise Windows-specific cause, and I'd rather say that than guess. What I can say is that both failures involve the per-machine Reflex user directory or a globally-patched module attribute β shared session state β which is where I'd look if it keeps recurring. Worth its own issue rather than riding on this PR. Re-run: not spent deliberately. The branch has advanced twice since ( Generated by Claude Code |
Correction: the Windows unit-test failure is a pre-existing suite-wide race, and I had the pattern wrongI said I'd report what Windows did on
That is falsified. On Three commits, three different tests in Root cause
Every test in Telemetry is not disabled for the unit suite β there is no Evidence1. Real telemetry work is queued during the unit run. Wrapping
Identical. The 23 come from 2. The mechanism reproduces. Running just that file with one extra thread calling Two different tests from the three CI hit β which is the point: the victim is whichever assertion the background write lands beside. 3. The diff is unrelated. It touches no part of I'm not claiming this is impossible to have been nudged by timing changes here β CI on Proposed patch (not pushed here)Keeping the unit suite off the shared worker fixes it at the source. In def _drop_telemetry_job(fn, /, *args, **kwargs) -> None:
"""Discard a telemetry job instead of queueing it on the worker thread.
Args:
fn: The callable the caller wanted to run in the worker.
args: Positional arguments the caller passed.
kwargs: Keyword arguments the caller passed.
"""
@pytest.fixture(autouse=True)
def no_background_telemetry(request) -> Generator[None, None, None]:
"""Keep the unit suite off the process-wide telemetry worker thread.
``telemetry.send`` hands the event to a single background worker that
resolves ``REFLEX_DIR`` (creating the installation id and its semantics
marker) and then POSTs to PostHog. Tests that ``monkeypatch.setenv`` that
directory mutate the process-global environment, so an in-flight telemetry
job can write into another test's ``tmp_path`` and race its assertions.
``test_telemetry`` exercises the worker on purpose and drains it itself.
Args:
request: The active pytest request, used to spot ``test_telemetry``.
Yields:
None, once the telemetry worker is neutralized for this test.
"""
if request.module.__name__.rpartition(".")[2] == "test_telemetry":
yield
return
original_submit = telemetry._submit
telemetry._submit = _drop_telemetry_job
try:
yield
finally:
telemetry._submit = original_submitVerified on a clean Two notes on the shape: it restores This belongs outside this PR rather than widening it. Happy to open it as its own PR if you want it β say the word and I'll do that instead of leaving it as a patch here. NextSpending the one re-run on Generated by Claude Code |
|
Re-run result, as promised: That is consistent with the race diagnosis above rather than proof of it; the reproduction and the identical 31-submission telemetry count on No merge conflict against Generated by Claude Code |
Supersedes #6906, reworked along the lines of #6906 (review): rather than special-casing the delta computation to elide unchanged
RouterDatafields, the router is no longer a single serialized base var. There is no partial-payload format, no frontend merge logic, and no version/capability gate β the existing per-var delta machinery does the work.What
RouterDatawas one base var, so every navigation reassigned it and re-shipped the whole object β session block and every request header (twice, viaraw_headers) β on every page change, even though none of that can change without a reconnect.Each kind of router data now lives in its own base var on the root state (
router_session,router_headers,router_page,router_url,router_route_id), so dirty tracking is naturally scoped to what actually changed:page,url,route_idpage,urlsessionheadersMeasured on a realistic connection (a few cookies, normal UA): the navigation router delta drops 1898 β 619 bytes (β67%).
A var is assigned only when its rebuilt value actually differs, so a
router_dataupdate that changes nothing observable does not dirty anything, does not mark the state touched, and does not persist it.State.routerstays a switchboardThe top-level
RouterDataremains the public API and keeps working unchanged in both positions:BaseStatecomposes aRouterDataview over the per-field vars, and assignment decomposes one back into them. Existingself.router.session.client_tokenreads andstate.router = ...writes are untouched.RouterDataVarwhose.session/.headers/.page/.url/.route_idresolve directly to the underlying per-field base var, soState.router.session.client_tokencompiles tostate.router_session�.["client_token"]. RenderingState.routeritself still emits an object literal matching the pre-split shape, so passing the whole router to a component keeps working.Dependency tracking covers the whole router in both forms.
self.routerin a computed var auto-deps through the property getter onto the per-field vars.deps=[State.router]covers all five too: a Var now names the state fields a dependency must track via_dependency_field_names()(defaulting to the single field from itsVarData), whichRouterDataVaroverrides β otherwiseVarData.mergewould surface one field name and leave the computed var stale when any of the others changed. An explicit legacydeps=["router"]is expanded to all five with aconsole.deprecate()warning (deprecated 0.9.9, removal 1.0). A computed var namedrouternow raisesComputedVarShadowsBaseVarsErrorrather than silently shadowing the descriptor.One new type:
URLData, a dataclass mirroringReflexURL's parsed components. It exists becausejson.dumpsserializesstrsubclasses natively and never invokes thedefault=serializehook β a bareReflexURLbase var would reach the frontend as a plain href string instead of the component dict, breakingrouter.url.pathand friends on the client.self.router.urlstill hands back aReflexURL.on_eventβon_connectToken, sid, headers, and client IP cannot change without going through
on_connectagain, so decoding every request header from the ASGI scope on every single event was wasted work. Those entries are now built once per connection inon_connectand cached per sid (dropped inon_disconnect);on_eventmerges the cached fragment and only computes the genuinely dynamicPATH/QUERY. If a socket was never seen byon_connect,on_eventfalls back to the connection environ and caches the result.The headers mapping is copied into each event, so a handler mutating
self.router_data["headers"]cannot corrupt the connection cache. That copy measures 0.081Β΅s against the 1.347Β΅s decode it replaced, so the cache still pays for itself ~17x over.Per-event
router_datapreparation: 2.85Β΅s β 0.65Β΅s (~4.4x faster). The processor side benefits too β_update_router_varsonly rebuilds the dataclasses whose backing keys changed, soHeaderData.from_router_datano longer runs on every navigation.Compatibility
State.router.*/self.router.*API is unchanged.__setstate__drops the legacyrouterentry so unpickling one doesn't crash before reaching that check.router_datapayload carrying only the navigation keys leaves the connection-scoped vars alone, rather than reading the omission as a reset to defaults (which is what the pre-split code did).All Submissions:
Type of change
deps=["router"]is deprecated, not removed.Changes To Core Features:
test_navigation_delta_elides_connection_scoped_router_varsβ end-to-end through the processor, asserts exactly which router vars land in the delta for first event / navigation / no-op / reconnect. Verified it fails onmain.test_update_router_vars_granular_deltaβ per-field dirty tracking, including keys that differ but derive equal values.test_update_router_vars_ignores_omitted_static_keys,test_update_router_vars_non_origin_header_leaves_navigation_cleanβ payloads that must not disturb unrelated vars.test_router_var_dep_whole_router,test_router_var_dep_legacy_stringβ whole-router dependency coverage in both the Var and legacy string forms.test_router_var_resolves_to_per_field_base_vars,test_router_var_renders_composed_object,test_router_var_carries_state_var_data,test_url_data_serializes_like_reflex_urlβ the switchboard var and URL serialization.test_on_event_uses_connect_time_router_data,test_on_event_falls_back_to_environ_without_connect,test_on_event_does_not_share_the_cached_headersβ the connect-time cache, its fallback, and its isolation.test_on_event_router_dataβ new codspeed benchmark for the per-event path.tests/unitsin a clean checkout with redis configured, matching the ubuntu CI jobs: 8365 passed, 0 failed (mainunder the same setup: 8352 passed, 0 failed β the difference is this PR's new tests).tests/integration/tests_playwright/test_router_query.py: 6/6 pass in dev and prod β real browser, router-dependent computed vars reactive across navigation and redirects.uv run ruff check .,uv run ruff format --check .,uv run pyright reflex tests, and the fullpre-commitrun: all clean.News fragments added under
news/andpackages/reflex-base/news/.Reviewer notes
Two of the judgment calls I originally flagged here were called out in review, and the reviewers were right β both are now fixed rather than argued for (
c7a08e5): the whole-routerdeps=[State.router]dependency covered only one field, and the cached headers dict was shared by reference (I had claimed the defensive copy was the cost being removed; measuring showed it costs ~6% of what the cache saves).Two things I deliberately did not change, for you to weigh in on:
_patch_statemarks all five router vars dirty on every linked-shared-state event (thread). Onmainthis isdirty_vars.add("router")β the single var holding all five fields β so the emitted payload is identical and this is not a regression. Reducing it means invalidating dependent computed vars without marking the base vars for emission, which needs a mechanism that doesn't exist yet; that deserves its own change with shared-state coverage.router_pagestill ships as its own var even thoughpageis deprecated (removal 1.0), because dynamic route args readpage.params. It could fold intourloncepageis gone.π€ Generated with Claude Code
https://claude.ai/code/session_01Mwk1pagH3KZ884Xw55BNMh