-
Notifications
You must be signed in to change notification settings - Fork 1.7k
ContextVar-based Registry for Registered Objects (Config, State, EventHandler, Field, etc.) #6249
Description
Summary
Replace module-level globals used to track registered framework objects (e.g. Config, State, EventHandler, Field) with a contextvars.ContextVar-backed registry. Each logical application context gets its own isolated registry instance instead of sharing mutable module state.
Motivation
Currently, framework-wide registries for core objects live in module globals. This causes several problems:
Multi-app coexistence — When multiple Reflex apps run in the same process, their registered objects collide in shared global state. A ContextVar-based registry gives each app its own isolated namespace, so apps don't interfere with each other.
Test isolation — Tests currently rely on extensive manual resetting to "clear the slate" between test cases. With a ContextVar registry, resetting state is as simple as attaching a fresh registry context — no more fragile teardown logic.
Per-task / per-page isolation — ContextVar naturally scopes to asyncio tasks, which opens up useful patterns during compilation. For example, a separate registry per page can identify which states or event handlers are created while evaluating that page, making it possible to determine which pages must still be re-evaluated in backend-only mode.
Design
- Define a
Registryclass (or similar) that holds all currently-global registries (state classes, event handlers, fields, config, etc.) - Store the active
Registryin acontextvars.ContextVarwith a default instance that preserves current behavior for simple single-app usage - Provide a context manager or utility to run code against a specific registry (e.g.
with fresh_registry():for tests, or per-page evaluation during compile) - Update all registration call sites to read/write from the context-local registry instead of module globals
Affected Areas
Statesubclass registrationEventHandlerglobal registryFielddescriptor trackingConfigsingleton- Any other module-level collections of framework objects (components, middleware, etc.)