Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/events/chaining_events.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,12 @@ state.
```md alert info
# Rules for awaiting event handlers

- Only inside an event handler (or `app.modify_state`); awaiting a handler anywhere else raises an error.
- Only inside an event handler (or `app.modify_state`); awaiting a handler anywhere else, such as in an API route outside `app.modify_state`, raises an error.
- Calling the handler, like `State.add(5)`, only binds its arguments. Nothing runs until it is awaited, so it can still be returned or yielded as before. Each `await` runs it again.
- A background task awaiting a handler outside `async with self` queues the event and waits for it to finish; inside `async with self` the handler runs right away on the locked state.
- A background handler cannot be awaited while the state lock is held, as it would wait for that lock. `yield` it instead.
- Frontend-only events like `rx.redirect` cannot be awaited. `yield` or return them.
- Only backend code that awaits a handler receives a non-event return value. When the handler runs from an event trigger, such as `on_click`, such a value is dropped, and in dev mode a warning says so; returned events are still chained.
- An awaited handler passes through the app's middleware like any other event. If a middleware blocks it, the handler does not run and the `await` returns `None`.
- Awaiting several handlers at once with `asyncio.gather` works, but they run concurrently on the same state and interleave at every `await` inside them. Await them one at a time when order matters.
- A task started from a handler, like `asyncio.ensure_future(State.add(1))`, keeps the state lock held until it finishes when it starts before the handler returns. If the handler returns first, the task's handler is queued like a yielded event and runs under its own lock.
Expand All @@ -108,6 +109,8 @@ In Reflex, event handlers run synchronously, so only one event handler can run a

```md alert info
# Be sure to use the class name `State` (or any substate) rather than `self` when returning events.

Returning `self.handler` instead of `type(self).handler`, or an event like `rx.redirect` without calling it, raises an error naming your handler.
```

Try entering an integer in the input below then clicking out.
Expand Down
1 change: 1 addition & 0 deletions news/+mistaken-handler-return-values.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
An event handler may return a value that is not an event, which backend code that `await`s the handler receives; returned events still chain and a returned coroutine still raises. Returning `self.other_handler` (meant `type(self).other_handler`), an uncalled event creator such as `rx.redirect`, or a list holding one raises the "must only return/yield" `TypeError` again, as in 0.10, instead of silently doing nothing; for an uncalled event creator the error asks "Did you mean to call it: rx.redirect(...)?". A non-event value returned by a handler that an event trigger such as `on_click` ran is dropped, and in dev mode a warning names the handler once.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Awaiting an event handler in an API route or other request code outside `app.modify_state` now raises `EventHandlerTypeError` instead of running it on one state shared by every caller.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
An event handler may return a value that is not an event, which backend code that `await`s the handler receives; returned events still chain and a returned coroutine still raises. Returning `self.other_handler` (meant `type(self).other_handler`), an uncalled event creator such as `rx.redirect`, or a list holding one raises the "must only return/yield" `TypeError` again, as in 0.10, instead of silently doing nothing; for an uncalled event creator the error asks "Did you mean to call it: rx.redirect(...)?". A non-event value returned by a handler that an event trigger such as `on_click` ran is dropped, and in dev mode a warning names the handler once.
44 changes: 39 additions & 5 deletions packages/reflex-base/src/reflex_base/event/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,11 @@ def temporal(self) -> Self:
)


# Set on the stand-in a background handler binds to on a state instance, so a
# returned or yielded `self.background_handler` is recognized as a mistake.
_BOUND_BACKGROUND_TASK_MARKER = "_reflex_bound_background_task"


def _no_chain_background_task(state: "BaseState", fn: Callable) -> Callable:
"""Protect against directly chaining a background task from another event handler.

Expand All @@ -491,17 +496,45 @@ def _no_chain_background_task(state: "BaseState", fn: Callable) -> Callable:
async def _no_chain_background_task_co(*args, **kwargs): # noqa: RUF029
raise RuntimeError(message)

return _no_chain_background_task_co
if inspect.isasyncgenfunction(fn):
no_chain = _no_chain_background_task_co
elif inspect.isasyncgenfunction(fn):

async def _no_chain_background_task_gen(*args, **kwargs): # noqa: RUF029
yield
raise RuntimeError(message)

return _no_chain_background_task_gen
no_chain = _no_chain_background_task_gen
else:
msg = f"{fn} is marked as a background task, but is not async."
raise TypeError(msg)
setattr(no_chain, _BOUND_BACKGROUND_TASK_MARKER, True)
return no_chain


def _is_bound_event_handler(value: Any) -> bool:
"""Whether a value is an event handler accessed through a state instance.

That is what ``self.handler`` evaluates to (see ``EventHandler.__get__``):
returned or yielded as an event, it is a mistake for ``type(self).handler``.
An inherited handler accessed through a background task's state proxy is a
``functools.partial`` and is not recognized.

msg = f"{fn} is marked as a background task, but is not async."
raise TypeError(msg)
Args:
value: The value to check.

Returns:
True for a handler's function bound to its state, or to a proxy of it,
and for the stand-in a background handler binds to.
"""
if type(value) is not types.MethodType:
Comment thread
masenf marked this conversation as resolved.
Resolved
return getattr(value, _BOUND_BACKGROUND_TASK_MARKER, None) is True
func = value.__func__
handlers = getattr(value.__self__, "event_handlers", None)
return (
isinstance(handlers, dict)
and (handler := handlers.get(func.__name__)) is not None
and handler.fn is func
)


def _base_state_type() -> type:
Expand Down Expand Up @@ -3544,6 +3577,7 @@ class EventNamespace:
resolve_upload_chunk_handler_param
)
_values_returned_from_event = staticmethod(_values_returned_from_event)
_is_bound_event_handler = staticmethod(_is_bound_event_handler)
_check_event_args_subclass_of_callback = staticmethod(
_check_event_args_subclass_of_callback
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,21 @@
import functools
import inspect
import logging
import sys
import warnings
from collections.abc import Mapping, Sequence
from enum import Enum
from importlib.util import find_spec
from time import perf_counter
from types import FunctionType, MethodType
from typing import TYPE_CHECKING, Any

from reflex.istate.manager.token import BaseStateToken
from reflex.istate.proxy import StateProxy
from reflex.utils import types
from reflex_base import otel
from reflex_base.constants import CompileVars
from reflex_base.event import Event, EventHandler, EventSpec
from reflex_base.event import Event, EventHandler, EventSpec, _is_bound_event_handler
from reflex_base.event.context import EventContext
from reflex_base.event.processor.event_processor import EventProcessor, EventQueueEntry
from reflex_base.event.processor.future import EventFuture
Expand Down Expand Up @@ -101,21 +103,99 @@ def _is_empty_sequence(value: Any) -> bool:
return is_non_string_sequence(value) and len(value) == 0


def _holds_events_or_coroutines(value: Any) -> bool:
"""Whether a sequence holds an event or an unawaited coroutine.
def _creator_function(value: Any) -> Any:
"""The function that runs when a callable is called.

Args:
value: A callable.

Returns:
The callable itself for a function or method, else its class's
``__call__`` (for a callable object such as ``rx.toast``).
"""
return (
value if isinstance(value, (FunctionType, MethodType)) else type(value).__call__
)


def _is_event_creator(value: Any) -> bool:
"""Whether a callable is declared to return an EventSpec, like ``rx.redirect``.

Reflex does not mark its event creators, but each one (``rx.redirect``,
``rx.call_script``, ``rx.toast`` ...) is annotated to return the EventSpec it
creates, as are helpers wrapping them. Returned uncalled, such a callable is a
mistake for the event it would create, never a result.

Args:
value: The callable a handler returned.

Returns:
True if the function, or the ``__call__`` of a callable object such as
``rx.toast``, is annotated to return an EventSpec.
"""
try:
returns = _creator_function(value).__annotations__.get("return")
except (AttributeError, NameError):
# Not annotated (a builtin, a class), or a deferred annotation naming
# something undefined.
return False
if isinstance(returns, str):
return returns.rpartition(".")[2] == "EventSpec"
return isinstance(returns, type) and issubclass(returns, EventSpec)


def _creator_reference(creator: Any) -> str:
"""How to name an event creator in the hint to call it.

Args:
creator: The uncalled event creator.

Returns:
``rx.<name>`` when reflex exports the creator's function under its own
name, as for ``rx.redirect``, else the function's qualified name.
"""
fn = _creator_function(creator)
if getattr(sys.modules.get("reflex"), fn.__name__, None) is creator:
Comment thread
masenf marked this conversation as resolved.
Resolved
return f"rx.{fn.__name__}"
return fn.__qualname__


def _is_mistaken_event(value: Any) -> bool:
"""Whether a value can only be an event its handler failed to reference or call.

Args:
value: The value a handler returned.

Returns:
True for a sequence ``_is_event_like`` rejects that still holds an
event (mixed with other values) or a coroutine.
True for ``self.handler`` (meant ``type(self).handler``) and for an
uncalled event creator such as ``rx.redirect``.
"""
return callable(value) and (
_is_bound_event_handler(value) or _is_event_creator(value)
)


def _is_invalid_result(value: Any) -> bool:
"""Whether a return value ``_is_event_like`` rejects is a bug rather than a result.

Args:
value: The value a handler returned.

Returns:
True for a coroutine that was never awaited, a mistaken event, and a
sequence that holds an event (mixed with other values), a coroutine or
a mistaken event.
"""
if inspect.iscoroutine(value) or _is_mistaken_event(value):
return True
if not is_non_string_sequence(value):
return False
try:
return any(
isinstance(e, _EVENT_LIKE_TYPES) or inspect.iscoroutine(e) for e in value
isinstance(e, _EVENT_LIKE_TYPES)
or inspect.iscoroutine(e)
or _is_mistaken_event(e)
for e in value
)
except TypeError:
return False
Expand Down Expand Up @@ -152,6 +232,15 @@ def _check_valid_yield(events: Any, handler_name: str = "unknown") -> Any:
f"Your handler {handler_name} must only return/yield: None, Events or other EventHandlers referenced by their class (i.e. using `type(self)` or other class references)."
f" Returned events of types {', '.join(map(str, map(type, events)))!s}."
)
if creators := [
e
for e in events
if callable(e) and not isinstance(e, _EVENT_LIKE_TYPES) and _is_event_creator(e)
]:
msg += (
f" Did you mean to call {'it' if len(creators) == 1 else 'them'}: "
f"{', '.join(f'{_creator_reference(c)}(...)' for c in creators)}?"
)
raise TypeError(msg)


Expand Down Expand Up @@ -483,22 +572,28 @@ async def execute_event_inline(spec: EventSpec) -> Any:
The handler's return value.

Raises:
EventHandlerTypeError: If there is no active EventContext, the spec is
a frontend-only or upload event, or a background handler is
awaited while the state lock is held (which would deadlock).
EventHandlerTypeError: If there is no active EventContext for a
client (outside an event handler and ``app.modify_state``), the
spec is a frontend-only or upload event, or a background handler
is awaited while the state lock is held (which would deadlock).
"""
from reflex_base.registry import RegistrationContext
from reflex_base.utils.exceptions import EventHandlerTypeError

try:
ctx = EventContext.get()
except LookupError as le:
except LookupError:
ctx = None
# The event processor's root context, which every request to the app
# carries, belongs to no client: running there would share one state
# between every caller.
if ctx is None or not ctx.token:
msg = (
f"Event handler `{format_event_handler(spec.handler)}` can only be "
"awaited from an event handler or inside `app.modify_state`; use it "
"as an event trigger or yield it instead."
)
raise EventHandlerTypeError(msg) from le
raise EventHandlerTypeError(msg)
event = spec._to_event(ctx.router_data)
name = event.name
if spec.client_handler_name:
Expand Down Expand Up @@ -621,10 +716,11 @@ async def process_event(
handler_name=handler_name,
)
return None
# A coroutine that was never awaited, or events mixed with other values,
# is a bug, not a result: chain_updates flushes the delta and then raises
# for it, as it does for any invalid yield.
invalid = inspect.iscoroutine(events) or _holds_events_or_coroutines(events)
# A coroutine that was never awaited, a mistaken event like `self.handler`
# or `rx.redirect`, or events mixed with other values, is a bug, not a
# result: chain_updates flushes the delta and then raises for it, as it
# does for any invalid yield.
invalid = _is_invalid_result(events)
await chain_updates(
events if invalid else None,
root_state=ensure_locked(state, root_state),
Expand Down
44 changes: 41 additions & 3 deletions reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2314,6 +2314,12 @@ def __init__(self, namespace: str, app: App):
self._client_error_window_start = 0.0
self._client_error_window_count = 0

# In dev, warn about values that handlers triggered from the frontend
# return, which nothing receives. Read once: on_event is the hot path.
self._warn_dropped_results = not is_prod_mode()
# The handlers already warned about, so each warns once.
self._warned_dropped_results: set[str] = set()

@property
def token_to_sid(self) -> Mapping[str, str]:
"""Token to SID mapping for backward compatibility.
Expand Down Expand Up @@ -2598,10 +2604,42 @@ async def on_event(self, sid: str, data: Any):
else "404"
).removeprefix("/")
if not otel.enabled:
await self.app.event_processor.enqueue(token, event)
future = await self.app.event_processor.enqueue(token, event)
else:
with otel.remote_context(fields):
future = await self.app.event_processor.enqueue(token, event)
if self._warn_dropped_results:
future.add_done_callback(
functools.partial(self._warn_dropped_result, event.name)
)

def _warn_dropped_result(self, name: str, future: asyncio.Future) -> None:
"""Warn once per handler that a frontend event's return value is dropped.

The frontend event discards its future, so only backend code awaiting
the handler receives what it returns.

Args:
name: The name of the event the frontend sent.
future: The event's future, done.
"""
if future.cancelled() or future.exception() is not None:
return
result = future.result()
# An empty list is how a handler said "no events" before return
# values were results.
if result is None or (is_non_string_sequence(result) and not result):
return
with otel.remote_context(fields):
await self.app.event_processor.enqueue(token, event)
if name in self._warned_dropped_results:
return
self._warned_dropped_results.add(name)
handler = self.app._registration_context.event_handlers[name].handler
logger.warning(
f"Event handler {handler.fn.__qualname__} returned a value, but it was "
"triggered from the frontend, so the value is dropped: only backend "
"code that awaits the handler receives its return value. Return None "
"or events to chain from a handler used as an event trigger."
)

async def on_ping(self, sid: str):
"""Event for testing the API endpoint.
Expand Down
9 changes: 7 additions & 2 deletions tests/benchmarks/test_event_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,8 +437,14 @@ def on_event_harness():
"""
from reflex.app import App, EventNamespace

loop = asyncio.new_event_loop()
# A real, already resolved future, like the EventFuture enqueue returns:
# the mock's default return value would bill on_event's use of the future
# (a done callback in dev mode) as mock call bookkeeping.
done = loop.create_future()
done.set_result(None)
app = App()
app._event_processor = mock.Mock(enqueue=mock.AsyncMock())
app._event_processor = mock.Mock(enqueue=mock.AsyncMock(return_value=done))
namespace = EventNamespace("/event", app)

sid = "benchmark-sid"
Expand Down Expand Up @@ -478,7 +484,6 @@ async def run_events(num_events: int) -> None:
},
)

loop = asyncio.new_event_loop()
loop.run_until_complete(namespace.on_connect(sid, environ))
yield run_events, loop
loop.close()
Expand Down
Loading
Loading