Skip to content

Raise when an event handler is awaited outside any client's event - #7821

Merged
FarhanAliRaza merged 4 commits into
mainfrom
fix/await-handler-without-token
Nov 11, 2026
Merged

FarhanAliRaza merged 4 commits into
mainfrom
fix/await-handler-without-token

Conversation

@masenf

@masenf masenf commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Found in the reflex 0.11.0a1 pre-release testing (FINDING-010).

Stacked on #7796 (merge that first). Until #7796 merges, this PR's diff also contains its commits. The change here is the last commit, 83a3043.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

What was wrong. _RootMiddleware attaches the event processor's root EventContext to every request, and that context's token is "". execute_event_inline only raised when no context existed at all. So an API route that ran await State.handler() outside app.modify_state enqueued the event under the empty token. Every caller of that route shared one state: in the pre-release run, a counter route returned 1, 2, 3, 4 to callers with different tokens, and each caller read the previous caller's stored value, also across workers on prod + Redis. Browser sessions were not exposed, because a socket is never linked to an empty token.

The fix. A context without a token now counts as no context. Awaiting raises the existing EventHandlerTypeError: "Event handler … can only be awaited from an event handler or inside app.modify_state; use it as an event trigger or yield it instead." Inside app.modify_state, the context is forked to the token being modified, so awaiting there still works. That matches the rule docs/events/chaining_events.md already states ("awaiting a handler anywhere else raises an error"). The docs bullet now names the API-route case.

Tests (tests/units/reflex_base/event/processor/test_base_state_processor.py):

  • test_await_from_a_request_outside_any_event_raises: a request goes through _RootMiddleware with the real processor's root context. await State.add(1) raises, and the empty-token state is unchanged. This test failed before the fix.
  • test_await_inside_app_modify_state_runs_on_that_token: awaiting inside app.modify_state(BaseStateToken(...)) returns the handler's values and writes to that token's state.
  • The existing tests still cover awaiting inside a foreground or background event handler.

Checks:

  • uv run pytest tests/units --cov (without the Chromium-only reflex_bench/drivers/test_browser.py): 15665 passed, 66 skipped, 81.44% coverage.
  • ruff check and ruff format are clean.
  • pyright reflex tests reports 0 errors.

Generated by Claude Code

View guided diff Turn on auto-fix

…result is dropped

Since handlers may return a value to the backend code awaiting them (#7673),
any non-event return value became the handler's result. That silently swallowed
the classic mistakes 0.10.1 reported with "must only return/yield": returning
`self.other_handler` (meant `type(self).other_handler`), an uncalled event
creator such as `rx.redirect`, or a list holding one. The chained handler never
ran and nothing was logged.

Those values can never be a meaningful result, so they raise the 0.10.1
TypeError again, naming the user's handler:
- a handler function bound to its state (or a background task's state proxy),
  and the stand-in a background handler binds to, now marked so it can be
  recognized;
- a callable annotated to return an EventSpec (every rx.* event creator,
  rx.toast included), since reflex does not otherwise mark event creators;
- a sequence holding either.

Any other value stays the result. In dev mode, on_event warns once per handler
when a handler the frontend triggered returns a value, which nothing receives;
the frontend discards that future, so the check is exact and costs nothing in
prod.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
When a handler returns or yields an event creator without calling it, the
0.10.1 "must only return/yield" message now ends with
"Did you mean to call it: rx.redirect(...)?", naming the creator as `rx.<name>`
when reflex exports it under that name, else by its qualified name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
- on_event benchmark: the mocked enqueue returned a MagicMock, so the dev-mode
  done callback on the event's future ran as an AsyncMock call per event
  (call recording plus a never-awaited coroutine), doubling the measured time.
  enqueue now returns a resolved future, as the real EventFuture is; the
  callback's real cost is a few microseconds per event, in dev only.
- The dropped-result warning goes through the module logger with a
  once-per-handler set; console.warn is deprecated and added its own notice.
- The "call it" hint names a creator from its own function, without scanning
  module globals; rx.toast now reads Toaster.send_toast(...).
- The dropped-result test runs in a clean registration context.
- News fragment and docs limit the dropped-value wording to non-event values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
Every request to the app carries the event processor's root context, whose
token is empty. `execute_event_inline` only raised when no EventContext existed,
so `await State.handler()` in an API route outside `app.modify_state` enqueued
the event under the empty token: every caller of the route shared one state,
reading and writing each other's values.

A context without a token now counts as no context and raises the existing
EventHandlerTypeError, which already says to await handlers only inside an
event handler or `app.modify_state`, as the docs state.

Found in the reflex 0.11.0a1 pre-release testing (FINDING-010).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
@masenf
masenf requested review from a team and Alek99 as code owners November 11, 2026 09:40
@masenf masenf added this to the v0.11.0 milestone Nov 11, 2026
@masenf masenf added the on deck PRs lined up to review / merge next label Nov 11, 2026
@greptile-apps

greptile-apps Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking issues were found.

Summary

Awaiting a handler without a client token now raises instead of using state shared by unrelated API callers.

  • Requests without a client token cannot await state handlers.
  • Handlers flag mistaken event references instead of returning them as values.
  • Frontend-triggered handlers warn when their returned values are dropped.

No actionable issues found. Tests were inspected but not run.

Reviews (2) · Last reviewed commit: "Raise when a handler is awaited outside ..." · Reviewed by Greptile

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 10 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py">

<violation number="1" location="packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py:158">
P3: The "Did you mean to call" hint names the wrong callable for `rx.toast`. `_creator_reference` checks the function's `__name__` (`send_toast`) against the `reflex` module, which doesn't export it, so it falls back to `Toaster.send_toast(...)`. Look up the namespace attribute the user actually wrote, or fall back to the `rx.`-prefixed name of the namespace.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

@codspeed

codspeed Bot commented Nov 11, 2026

Copy link
Copy Markdown

Merging this PR will degrade performance by 7.32%

2 warnings

⚠️ 15 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 2 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

❌ 2 regressed benchmarks
✅ 149 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_on_event_router_data 1.8 ms 2 ms -9.52%
❌ test_route_matching[1000] 47.8 µs 50.3 µs -5.07%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix/await-handler-without-token (83a3043) with main (2d71015)

Open in CodSpeed

@masenf

masenf commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

On the CodSpeed report: test_on_event_router_data (−9.5%) comes from #7796's commits, which this stacked PR includes. It is the dev-mode done callback described in #7796 (comment) and the correction below it. This PR's own change is one extra not ctx.token check in execute_event_inline. test_route_matching[1000] (−5%) is flagged "ran on different hardware" and shows the same drift on every open PR this morning, including docs-only ones.


Generated by Claude Code

@FarhanAliRaza
FarhanAliRaza merged commit 554eb10 into main Nov 11, 2026
169 of 171 checks passed
@FarhanAliRaza
FarhanAliRaza deleted the fix/await-handler-without-token branch November 11, 2026 13:42
masenf added a commit that referenced this pull request Nov 11, 2026
)

* Raise again for mistaken handler return values; warn when a frontend result is dropped

Since handlers may return a value to the backend code awaiting them (#7673),
any non-event return value became the handler's result. That silently swallowed
the classic mistakes 0.10.1 reported with "must only return/yield": returning
`self.other_handler` (meant `type(self).other_handler`), an uncalled event
creator such as `rx.redirect`, or a list holding one. The chained handler never
ran and nothing was logged.

Those values can never be a meaningful result, so they raise the 0.10.1
TypeError again, naming the user's handler:
- a handler function bound to its state (or a background task's state proxy),
  and the stand-in a background handler binds to, now marked so it can be
  recognized;
- a callable annotated to return an EventSpec (every rx.* event creator,
  rx.toast included), since reflex does not otherwise mark event creators;
- a sequence holding either.

Any other value stays the result. In dev mode, on_event warns once per handler
when a handler the frontend triggered returns a value, which nothing receives;
the frontend discards that future, so the check is exact and costs nothing in
prod.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

* Hint to call an uncalled event creator in the invalid return/yield error

When a handler returns or yields an event creator without calling it, the
0.10.1 "must only return/yield" message now ends with
"Did you mean to call it: rx.redirect(...)?", naming the creator as `rx.<name>`
when reflex exports it under that name, else by its qualified name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

* Address review feedback; give the on_event benchmark a real future

- on_event benchmark: the mocked enqueue returned a MagicMock, so the dev-mode
  done callback on the event's future ran as an AsyncMock call per event
  (call recording plus a never-awaited coroutine), doubling the measured time.
  enqueue now returns a resolved future, as the real EventFuture is; the
  callback's real cost is a few microseconds per event, in dev only.
- The dropped-result warning goes through the module logger with a
  once-per-handler set; console.warn is deprecated and added its own notice.
- The "call it" hint names a creator from its own function, without scanning
  module globals; rx.toast now reads Toaster.send_toast(...).
- The dropped-result test runs in a clean registration context.
- News fragment and docs limit the dropped-value wording to non-event values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

* Raise when a handler is awaited outside any client's event

Every request to the app carries the event processor's root context, whose
token is empty. `execute_event_inline` only raised when no EventContext existed,
so `await State.handler()` in an API route outside `app.modify_state` enqueued
the event under the empty token: every caller of the route shared one state,
reading and writing each other's values.

A context without a token now counts as no context and raises the existing
EventHandlerTypeError, which already says to await handlers only inside an
event handler or `app.modify_state`, as the docs state.

Found in the reflex 0.11.0a1 pre-release testing (FINDING-010).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

---------

Co-authored-by: Claude <[email protected]>
(cherry picked from commit 554eb10)
@masenf masenf added the release-train Issues found during agentic /prerelease-testing fanout, not necessarily validated bugs. label Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

on deck PRs lined up to review / merge next release-train Issues found during agentic /prerelease-testing fanout, not necessarily validated bugs.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants