From 655fb565b3f5c4a611cbe3237b42f3d20741719c Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Sun, 22 Nov 2026 11:13:49 +0100 Subject: [PATCH 1/2] fix(state): let a background handler call the one it overrides through super() `super().handler` in a background handler hands the task's StateProxy to EventHandler.__get__, which walks `parent_state` through it to find the state the handler is bound to. The proxy refuses that outside `async with self`, so the call raised ImmutableStateError. Overriding a mixin's background handler and extending it through super() worked in 0.10, when `@rx.event` left a plain function on the mixin; since 0.11 it returns an EventHandler there too. For a handler of a parent state it failed since #7312. The proxy now binds what super() reaches like the handlers its own __getattr__ returns: to itself, or to the ancestor declaring it through _call_on_ancestor. Without the guard against chaining a background task: the overriding handler extends the other one in its own task. --- news/+super-background-handler.bugfix.md | 1 + .../news/+super-background-handler.bugfix.md | 1 + .../src/reflex_base/event/__init__.py | 13 +++ reflex/istate/proxy.py | 23 ++++- tests/units/istate/test_proxy.py | 83 +++++++++++++++++++ 5 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 news/+super-background-handler.bugfix.md create mode 100644 packages/reflex-base/news/+super-background-handler.bugfix.md diff --git a/news/+super-background-handler.bugfix.md b/news/+super-background-handler.bugfix.md new file mode 100644 index 00000000000..8644d068fc8 --- /dev/null +++ b/news/+super-background-handler.bugfix.md @@ -0,0 +1 @@ +A background event handler that overrides one from a mixin or a parent state can call it with `await super().handler()` again, instead of raising `ImmutableStateError`. diff --git a/packages/reflex-base/news/+super-background-handler.bugfix.md b/packages/reflex-base/news/+super-background-handler.bugfix.md new file mode 100644 index 00000000000..8644d068fc8 --- /dev/null +++ b/packages/reflex-base/news/+super-background-handler.bugfix.md @@ -0,0 +1 @@ +A background event handler that overrides one from a mixin or a parent state can call it with `await super().handler()` again, instead of raising `ImmutableStateError`. diff --git a/packages/reflex-base/src/reflex_base/event/__init__.py b/packages/reflex-base/src/reflex_base/event/__init__.py index 63844816912..3ac2898606f 100644 --- a/packages/reflex-base/src/reflex_base/event/__init__.py +++ b/packages/reflex-base/src/reflex_base/event/__init__.py @@ -14,6 +14,7 @@ TYPE_CHECKING, Annotated, Any, + ClassVar, Generic, Literal, NoReturn, @@ -572,6 +573,11 @@ class EventHandler(EventActionsMixin): state: "type[BaseState] | None" = dataclasses.field(default=None, repr=False) + # The StateProxy type, installed by reflex.istate.proxy, which binds the + # handlers `super()` reaches from a background task. Until then nothing is one: + # isinstance against () is always false. + _state_proxy: ClassVar[Any] = () + _type_hints: dict[str, Any] | None = dataclasses.field( default=None, repr=False, compare=False ) @@ -784,6 +790,13 @@ def __get__(self, instance: Any, owner: type | None = None) -> Any: if not isinstance(instance, self.state): # Held by a class that is not its state, nor a substate of it. return self + if isinstance(instance, EventHandler._state_proxy): + # Only `super()` hands a background task's proxy to the descriptor + # (the proxy binds its own attributes), to run the overridden + # handler in the same task. + return EventHandler._state_proxy._bind_overridden_handler( + instance, self.fn, self.state + ) state = ( instance if type(instance) is self.state diff --git a/reflex/istate/proxy.py b/reflex/istate/proxy.py index 6b5b7b75540..5690acb1974 100644 --- a/reflex/istate/proxy.py +++ b/reflex/istate/proxy.py @@ -38,7 +38,7 @@ import wrapt from reflex_base import constants -from reflex_base.event import Event +from reflex_base.event import Event, EventHandler from reflex_base.event.context import EventContext from reflex_base.utils.exceptions import ImmutableStateError from reflex_base.utils.serializers import ( @@ -422,6 +422,26 @@ def __getattr__(self, name: str) -> Any: ) return value + def _bind_overridden_handler( + self, fn: Callable, owner: type[BaseState] + ) -> Callable: + """Bind the function of a handler that `super()` reached through this proxy. + + Bound like the handlers `__getattr__` returns, but without the guard + against calling a background task directly: an overriding background + handler runs the one it extends in its own task. + + Args: + fn: The function of the overridden handler. + owner: The state class or mixin declaring the overridden handler. + + Returns: + The function bound to this proxy, or to the ancestor declaring it. + """ + if owner._mixin or type(self.__wrapped__) is owner: + return MethodType(fn, self) + return functools.partial(_call_on_ancestor, self, fn, owner) + def __setattr__(self, name: str, value: Any) -> None: """Set the attribute on the underlying state instance. @@ -1359,3 +1379,4 @@ def _dirty_state(self) -> BaseState: Field._proxy = MutableProxy +EventHandler._state_proxy = StateProxy diff --git a/tests/units/istate/test_proxy.py b/tests/units/istate/test_proxy.py index f229c25603a..69062d90835 100644 --- a/tests/units/istate/test_proxy.py +++ b/tests/units/istate/test_proxy.py @@ -554,6 +554,89 @@ async def test_inherited_handler_runs_on_its_state( assert substate.count == 10 # pyright: ignore [reportAttributeAccessIssue] +class SuperBackgroundMixin(BaseState, mixin=True): + """A mixin whose background handler a state overrides.""" + + steps: list[str] = [] + + @rx.event(background=True) + async def save(self): + """Record the mixin's step.""" + async with self: + self.steps.append("mixin") + + +class SuperBackgroundMixinUser(SuperBackgroundMixin, BaseState): + """A state extending the mixin's background handler through super().""" + + @rx.event(background=True) + async def save(self): + """Record this state's step, then the mixin's.""" + async with self: + self.steps.append("user") + await super().save() + + +class SuperBackgroundParent(BaseState): + """A state whose background handler its substate overrides.""" + + steps: list[str] = [] + + @rx.event(background=True) + async def save(self): + """Record the parent's step.""" + async with self: + self.steps.append("parent") + + +class SuperBackgroundChild(SuperBackgroundParent): + """A substate extending its parent's background handler through super().""" + + @rx.event(background=True) + async def save(self): + """Record this state's step, then the parent's.""" + async with self: + self.steps.append("child") + await super().save() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("state_cls", "steps_owner", "steps"), + [ + (SuperBackgroundMixinUser, SuperBackgroundMixinUser, ["user", "mixin"]), + (SuperBackgroundChild, SuperBackgroundParent, ["child", "parent"]), + ], +) +async def test_background_handler_extends_its_base_through_super( + token: str, + state_manager: StateManager, + attached_mock_event_context: EventContext, + state_cls: type[BaseState], + steps_owner: type[BaseState], + steps: list[str], +) -> None: + """A background handler calling super() runs the overridden handler in the same task. + + Args: + token: The client token. + state_manager: The state manager to exercise. + attached_mock_event_context: The attached event context. + state_cls: The state overriding the background handler. + steps_owner: The state storing the recorded steps. + steps: The steps both handlers record, in order. + """ + state_token = BaseStateToken(ident=token, cls=state_cls) + async with state_manager.modify_state(state_token) as root: + proxy = StateProxy(root.get_substate(state_cls.get_full_name().split("."))) + + await state_cls.save.fn(proxy) # pyright: ignore [reportAttributeAccessIssue] + + async with state_manager.modify_state(state_token) as root: + owner = root.get_substate(steps_owner.get_full_name().split(".")) + assert owner.steps == steps # pyright: ignore [reportAttributeAccessIssue] + + @pytest.mark.asyncio @pytest.mark.parametrize("proxy_cls", [StateProxy, ReadOnlyStateProxy]) @pytest.mark.parametrize("state_cls", [RouterProxyState, RouterProxySubState]) From 5f1a74a7151397b4995b695b299f214f39668c6b Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Sun, 22 Nov 2026 11:29:34 +0100 Subject: [PATCH 2/2] perf(event): keep the super() proxy check off attribute access The isinstance check against StateProxy ran on every handler lookup, and for a state it reads `__class__` through BaseState.__getattribute__: test_state_access[get_handler] got 8.9% slower. Attribute access passes the instance's own type as `owner`, while super() through a proxy passes the wrapped state's class, so the type check now runs only when the two differ, and on the type rather than the instance. --- .../src/reflex_base/event/__init__.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/reflex-base/src/reflex_base/event/__init__.py b/packages/reflex-base/src/reflex_base/event/__init__.py index 3ac2898606f..13794cead68 100644 --- a/packages/reflex-base/src/reflex_base/event/__init__.py +++ b/packages/reflex-base/src/reflex_base/event/__init__.py @@ -790,18 +790,22 @@ def __get__(self, instance: Any, owner: type | None = None) -> Any: if not isinstance(instance, self.state): # Held by a class that is not its state, nor a substate of it. return self - if isinstance(instance, EventHandler._state_proxy): + instance_type = type(instance) + if instance_type is self.state: + state = instance + elif instance_type is not owner and issubclass( + instance_type, EventHandler._state_proxy + ): # Only `super()` hands a background task's proxy to the descriptor # (the proxy binds its own attributes), to run the overridden - # handler in the same task. + # handler in the same task. Attribute access passes the instance's + # own type as `owner`, so the check stays off that path; `super()` + # passes the wrapped state's class. return EventHandler._state_proxy._bind_overridden_handler( instance, self.fn, self.state ) - state = ( - instance - if type(instance) is self.state - else _owner_state(instance, self.state) - ) + else: + state = _owner_state(instance, self.state) if self.is_background: return _no_chain_background_task(state, self.fn) return types.MethodType(self.fn, state)