Skip to content

ENG-9028: Move event queue to backend - #6267

Merged
masenf merged 88 commits into
mainfrom
masenf/event-context-rb
Apr 7, 2026
Merged

masenf merged 88 commits into
mainfrom
masenf/event-context-rb

Conversation

@masenf

@masenf masenf commented Apr 1, 2026 •

Copy link
Copy Markdown
Collaborator

This patch moves the primary responsibility of chaining/queueing events to the backend. Previously the frontend was responsible for sending events to the backend. This created additional round-trip latency when chaining events using yield.

Summary: Event Processing & State Management Overhaul

Contexts are King

Instead of relying on ClassVar, module globals, and other hacks to track reflex objects, this PR introduces contextvars to the code base and leverages them to manage global state safely from anywhere in the app.

New Modules (in reflex_base)

  • registry.py — ContextVar-based registry for BaseState classes and EventHandlers, replacing implicit global lookups. Currently used for states, events and stateful components. Eventually will be used for DECORATED_PAGES and other weird globals.
  • event/context.py — EventContext (inherits BaseContext) holding per-event metadata: token, state manager ref, enqueue/emit/delta callbacks
  • event/processor/ — New BaseStateEventProcessor and EventProcessor classes that own the full event lifecycle (previously spread across App and State methods)
  • context/base.py — Generic BaseContext ContextVar wrapper

Breaking Changes (0.9.0)

  • Event.token field removed — Event no longer carries a token; the token lives in EventContext
  • Event.substate_token replaced by Event.state_cls property (resolved via the registry)
  • Delta type refined from dict[str, Any] → dict[str, dict[str, Any]] (nested by substate name)
  • StateManager.create() no longer takes a state= arg — state classes are discovered from the registry
  • StateToken introduced (reflex/istate/manager/token.py) — typed generic token replacing raw "client_token_substate" strings in all state managers (disk, memory, redis)
  • EventHandlerSetVar.state_cls → .state field rename to align with EventHandler change.
  • fix_events removed from sortof public event API, replaced by Event.from_event_type()
  • get_hydrate_event removed — replaced by internal rehydration; simulated pre-hydrated states removed
  • App._background_tasks replaced by App.event_processor._tasks (processor manages background task lifecycle in the same way as normal event tasks)
  • AppHarness (reflex/testing.py) simplified — state_manager property and related methods removed

State Manager Changes

  • All three managers (disk, memory, redis) refactored to use StateToken[BaseState] instead of raw string tokens
  • State managers now close() old locks properly
  • OPLOCK_ENABLED support in state manager close/tests

Frontend (state.js)

  • Params passed around as a ref instead of inline values
  • StateUpdate only includes non-empty fields, reducing bytes over the wire.

Test Infrastructure

  • Large test suite overhaul: new fixtures in conftest.py for EventProcessor, registry, and context
  • get_app / mock_app dependencies removed from tests in favor of the new processor-based approach
  • New unit tests for registry, event context, base state processor, and event processor
  • Integration tests updated to replace all backend state assertions with in-app equivalents.

masenf added 30 commits March 17, 2026 15:03
Special case access patterns for BaseState retrieval to allow for other types
of state that have different semantics.
Update all unit test cases to use the new StateToken / BaseStateToken API
Create the EventProcessor class to manage the backend event queue.

Move event processing logic out of the BaseState and into a separate module.
* No tasks start until `.start()` is called
* add graceful shutdown timeout to allow tasks to finish before cancellation
* use more keyword only parameters
* move BaseState-specific processing to new BaseStateEventProcessor subclass
* add test fixtures for `mock_event_processor` that can process simple registered events
make Event.substate_token no longer work, because we're deprecating `token` as
an Event field, so we cannot rely on it under the covers.
Use the new mock_base_state_event_processor fixture to process arbitrary events
and assert on emitted events or deltas.
…Handler

This allows better control over which states and events are part of a given app
and avoiding true global variables makes cleanup and testing much simpler.
remove null/default fields when serializing Event from the frontend and
StateUpdate from the backend.
Fix issue with background task delta calculation not starting from the root state
remove extra `event_context` ContextVar being passed around
EventProcessor.enqueue now returns a Future that tracks the completion of the
event (and can be used to cancel the event)

EventProcessor.enqueue_stream_delta overrides the default emit_delta
implementation and instead yields deltas directly to the caller as the event is
processing.
The function () => params.current baked inside the ensureSocketConnected
function was getting a stale reference and the early events (hydrate, on load,
client state) were missing the query parameters in their router_data and thus
on_load was not working correctly.
Store the state_full_name to substate mapping in RegistrationContext

Make it easier to register / re-register select states and event handlers in a
new RegistrationContext

Store StatefulComponent cached components in RegistrationContext for easier
resetting/dropping after compilation or for use in testing.
FarhanAliRaza

This comment was marked as resolved.

adhami3310
adhami3310 previously approved these changes Apr 6, 2026
Comment thread reflex/istate/manager/__init__.py Resolved
@masenf
masenf merged commit ea90a03 into main Apr 7, 2026
40 checks passed
@masenf
masenf deleted the masenf/event-context-rb branch April 7, 2026 00:13
@masenf masenf added the perf Performance-improving changes label Sep 29, 2026
kr1shna-exe added a commit to kr1shna-exe/reflex that referenced this pull request Oct 7, 2026
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.
FarhanAliRaza added a commit that referenced this pull request Oct 13, 2026
* fix(state): recover from unknown frontend substates

* fix(state): report unknown substates again after a reconnect

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.

* refactor(state): pull unknown substate handling out of the event handler

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 #6267, so the flush only
ever sent an empty list, and it would have been skipped anyway if the
root state itself were unknown.

* refactor(state): simplify unknown substate handling and trim tests

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.

* test(state): cover an unknown substate in the hydrate delta

---------

Co-authored-by: Farhan <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

perf Performance-improving changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants