Repository navigation
ENG-9028: Move event queue to backend - #6267
Merged
Merged
Conversation
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.
And don't register it as middleware, because it's not middleware technically (even though it worked the way it was).
The returned top level app should always continue to be a Starlette instance for compatibility.
increase chances of actually getting a single chunk processed before the cancel takes place.
avoid overhead in stop() and join() paths
adhami3310
previously approved these changes
Apr 6, 2026
adhami3310
reviewed
Apr 6, 2026
adhami3310
approved these changes
Apr 7, 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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 forBaseStateclasses andEventHandlers, 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(inheritsBaseContext) holding per-event metadata: token, state manager ref, enqueue/emit/delta callbacksevent/processor/— NewBaseStateEventProcessorandEventProcessorclasses that own the full event lifecycle (previously spread acrossAppandStatemethods)context/base.py— GenericBaseContextContextVar wrapperBreaking Changes (0.9.0)
Event.tokenfield removed —Eventno longer carries atoken; the token lives inEventContextEvent.substate_tokenreplaced byEvent.state_clsproperty (resolved via the registry)Deltatype refined fromdict[str, Any]→dict[str, dict[str, Any]](nested by substate name)StateManager.create()no longer takes astate=arg — state classes are discovered from the registryStateTokenintroduced (reflex/istate/manager/token.py) — typed generic token replacing raw"client_token_substate"strings in all state managers (disk, memory, redis)EventHandlerSetVar.state_cls→.statefield rename to align with EventHandler change.fix_eventsremoved from sortof public event API, replaced byEvent.from_event_type()get_hydrate_eventremoved — replaced by internal rehydration; simulated pre-hydrated states removedApp._background_tasksreplaced byApp.event_processor._tasks(processor manages background task lifecycle in the same way as normal event tasks)AppHarness(reflex/testing.py) simplified —state_managerproperty and related methods removedState Manager Changes
StateToken[BaseState]instead of raw string tokensclose()old locks properlyOPLOCK_ENABLEDsupport in state manager close/testsFrontend (
state.js)Test Infrastructure
conftest.pyforEventProcessor, registry, and contextget_app/mock_appdependencies removed from tests in favor of the new processor-based approach