Skip to content

ENG-9350: App.modify_state can directly modify SharedState tokens - #6336

Merged
adhami3310 merged 10 commits into
mainfrom
masenf/shared-state-direct-mod
Apr 20, 2026
Merged

adhami3310 merged 10 commits into
mainfrom
masenf/shared-state-direct-mod

Conversation

@masenf

@masenf masenf commented Apr 16, 2026

Copy link
Copy Markdown
Collaborator

When a SharedState is modified directly by its shared token (e.g. from an API route webhook), propagate dirty vars to all clients linked to that shared state — matching the behavior that already exists when modifying shared state through a private client token.

  • Add _collect_shared_token_updates on SharedStateBaseInternal to detect the shared-token case inside _modify_linked_states and propagate to linked clients via the existing _do_update_other_tokens mechanism
  • Add App.set_contexts / App._set_contexts_internal to centralize pushing RegistrationContext and EventContext into the current contextvars scope, replacing the old _registration_context_middleware
  • App.modify_state now calls set_contexts so out-of-band callers (API routes, webhooks) get the necessary contexts automatically
  • Integration test: API endpoint modifies two SharedState subclasses by shared token, asserts both propagate to two linked browser tabs, and verifies normal event handlers still work afterward
  • Unit tests for set_contexts covering all combinations of pre-existing / absent contexts, no-event-processor, and reset-on-exit behavior

Closes #6335

When a SharedState is modified directly by its shared token (e.g. from an
API route webhook), propagate dirty vars to all clients linked to that
shared state — matching the behavior that already exists when modifying
shared state through a private client token.

- Add _collect_shared_token_updates on SharedStateBaseInternal to detect
  the shared-token case inside _modify_linked_states and propagate to
  linked clients via the existing _do_update_other_tokens mechanism
- Add App.set_contexts / App._set_contexts_internal to centralize pushing
  RegistrationContext and EventContext into the current contextvars scope,
  replacing the old _registration_context_middleware
- App.modify_state now calls set_contexts so out-of-band callers (API
  routes, webhooks) get the necessary contexts automatically
- Integration test: API endpoint modifies two SharedState subclasses by
  shared token, asserts both propagate to two linked browser tabs, and
  verifies normal event handlers still work afterward
- Unit tests for set_contexts covering all combinations of pre-existing /
  absent contexts, no-event-processor, and reset-on-exit behavior

Closes #6335
@linear

linear Bot commented Apr 16, 2026

Copy link
Copy Markdown

@codspeed

codspeed Bot commented Apr 16, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 9 untouched benchmarks


Comparing masenf/shared-state-direct-mod (f5d94b7) with main (328e892)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR enables App.modify_state to target a SharedState by its shared token directly (e.g. from an API-route webhook), propagating dirty vars to all private clients linked to that token — behaviour that previously only worked when going through a private client token. The implementation adds _collect_shared_token_updates for the empty-_reflex_internal_links case, centralises context injection into set_contexts / _set_contexts_internal, and patches the shared root state's client_token so that get_state calls resolve correctly in the new path.

Confidence Score: 5/5

Safe to merge; all remaining findings are minor style suggestions.

No P0/P1 issues found. The core logic for detecting direct shared-token modifications and propagating updates to linked clients is correct. Context lifecycle (set on entry, reset on exit) is handled properly in set_contexts(). The two outstanding comments are style-only: an inline dataclasses import and a redundant get_state + isinstance indirection that could be simplified to a direct method call.

reflex/istate/shared.py — minor style nits only.

Important Files Changed

Filename Overview
reflex/istate/shared.py Adds _collect_shared_token_updates to detect direct shared-token modifications and propagate dirty vars to all linked clients; called from _modify_linked_states when _reflex_internal_links is empty. Also patches router.session.client_token on the linked root state so get_state resolves correctly in the direct-token path. Two P2 style issues: inline dataclasses import and a redundant get_state + isinstance roundtrip.
reflex/app.py Extracts _set_contexts_internal / set_contexts from the old _registration_context_middleware, now covering both RegistrationContext and EventContext. modify_state wraps its body in with self.set_contexts() so API-route / webhook callers get necessary contexts automatically, with proper teardown via ExitStack.
reflex/state.py Extends State._get_state_from_redis to delegate to SharedStateBaseInternal._resolve_linked_state when the requested state class appears in _reflex_internal_links, enabling linked-state lookup from arbitrary event handlers.
tests/integration/test_linked_state.py New integration test opens two browser tabs linked to the same shared token, calls an API route that modifies SharedState and SharedNotes by shared token, and asserts both tabs propagate both updates; also verifies normal event handlers still work afterward.
tests/units/test_app.py Adds parametrized unit tests for App.set_contexts covering all 4 combinations of pre-set/absent RegistrationContext and EventContext, plus a dedicated test for the no-event-processor case.

Sequence Diagram

sequenceDiagram
    participant API as API Route
    participant App as App.modify_state
    participant SC as set_contexts
    participant MSWL as modify_state_with_links
    participant MLS as _modify_linked_states
    participant CST as _collect_shared_token_updates
    participant DUT as _do_update_other_tokens
    participant BrowserA as Browser Tab A
    participant BrowserB as Browser Tab B

    API->>App: modify_state(shared_token)
    App->>SC: enter set_contexts()
    SC-->>App: RegistrationContext + EventContext injected
    App->>MSWL: modify_state_with_links(shared_token)
    MSWL->>MLS: _modify_linked_states(reflex_internal_links={})
    MLS-->>API: yield root_state
    API->>API: mutate SharedState and SharedNotes
    API-->>MLS: context body exits
    MLS->>CST: _collect_shared_token_updates
    CST-->>MLS: affected_tokens and dirty_vars populated
    MLS->>DUT: _do_update_other_tokens(affected_tokens, dirty_vars)
    DUT->>BrowserA: modify_state(private_token_a, previous_dirty_vars)
    DUT->>BrowserB: modify_state(private_token_b, previous_dirty_vars)
Loading

Reviews (2): Last reviewed commit: "remove superfluous `run_isolated` fixtur..." | Re-trigger Greptile

Comment thread reflex/istate/shared.py Outdated
Comment on lines +426 to +431
if substate._previous_dirty_vars:
current_dirty_vars[substate.get_full_name()] = set(
substate._previous_dirty_vars
)
if substate._get_was_touched() or substate._previous_dirty_vars:
affected_tokens.update(substate._linked_from)

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 Truthiness check diverges from the existing is not None pattern

The existing collection loop (lines 376–383) uses is not None to decide whether to populate current_dirty_vars and affected_tokens, treating an empty set() the same as a populated one. This new method uses a truthiness check, so an empty _previous_dirty_vars = set() (the field's initialiser value) skips the current_dirty_vars entry even when _get_was_touched() is True.

In practice _previous_dirty_vars will be non-empty whenever vars were actually modified, so this is unlikely to surface as a bug; but aligning with the is not None guard used in the sibling loop keeps the two paths consistent and easier to reason about.

Suggested change
if substate._previous_dirty_vars:
current_dirty_vars[substate.get_full_name()] = set(
substate._previous_dirty_vars
)
if substate._get_was_touched() or substate._previous_dirty_vars:
affected_tokens.update(substate._linked_from)
if substate._previous_dirty_vars is not None:
current_dirty_vars[substate.get_full_name()] = set(
substate._previous_dirty_vars
)
if substate._get_was_touched() or substate._previous_dirty_vars is not None:
affected_tokens.update(substate._linked_from)

masenf added 5 commits April 17, 2026 11:28
set an initial value for the shared state to provide affirmative proof that the
state was linked _before_ the API call was made.

if only one state was linked when the HTTP request was made, then only one
state would be updated by such request resulting in the observed behavior.
but actually set the value on the newly linked state, not the old private
state. derpy easy to make mistake with this _link_to mechanism =/
Using BaseState.get_state(...) with a linked state that _is_ linked, but not
currently cached should fetch the linked state instance, not the private state
instance.
In an `app.modify_state(...)` context where the passed token is a shared token,
handle the case where `.get_state(...)` is used to fetch _another_ shared state
with the same token as the original shared state token.

Basically if some code is modifying "tokenA" for "Shared1" and calls
`shared_1.get_state(Shared2)`, then the retrieved state will also be associated
with "tokenA", as expected.
@masenf
masenf force-pushed the masenf/shared-state-direct-mod branch from 4e5aef8 to 83bd799 Compare April 18, 2026 04:33
masenf added 3 commits April 17, 2026 18:49
Starting from the SharedStateBaseInternal, recurse into each pre-cached
instance and collect affected tokens and dirty vars.
just use `isolated_context.run` for simplicity
@masenf

masenf commented Apr 20, 2026

Copy link
Copy Markdown
Collaborator Author

@greptile-apps re-review this PR

@adhami3310
adhami3310 merged commit b977e62 into main Apr 20, 2026
48 checks passed
@adhami3310
adhami3310 deleted the masenf/shared-state-direct-mod branch April 20, 2026 17:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support modifying SharedState by shared token and propagating to all linked clients

2 participants