Repository navigation
Stream event handler yield and return values to the frontend caller - #7761
FarhanAliRaza wants to merge 9 commits into
Conversation
Each event the frontend dispatches through addEvents carries a request id. A non-event value the handler yields or returns is sent back as a result record riding the existing "event" StateUpdate (results field), after the delta of the changes made before it, and the request completes exactly once with done, error, or done+cancelled. addEvents returns a ResultStream: an async iterator over the values and a thenable resolving with the last one, rejecting when the handler raised or the connection dropped. Backend: - the frontend's id is read from the wire fields in on_event (not added to Event) and becomes EventContext.request_id, which fork() does not inherit; - yields and returns share one classifier (_is_result): None flushes, events chain, values are results, and events mixed with values, coroutines and callables (yield self.handler) still raise TypeError; - only the processor's top-level run reports, so a handler awaited inline does not leak values into its caller's stream; - completion rides the final delta flush. Measured on the production Socket.IO load app (200 events per client, two rounds), a separate completion message cost 14/30/35% throughput at 1/10/50 clients; riding the final delta stays within noise at 1 client and 7-9% at 10-50. - cancellation (superseded, queued or running) is reported from the future, covering events cancelled before their task started. Frontend: the stream lives in utils/event_results.js, free of npm imports so vitest covers it. Calls in one debounce window share the stream of the dispatch that fires; a throttled-out call shares the last open dispatch. Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
[High impact] The change reaches the shared event-dispatch path used by browser triggers and async callback props. The PR should wait for the failed-save outcome to be fixed or explicitly accepted, and for the new error checks to satisfy the test guide. FindingsSummaryThis PR sends handler values back to frontend callers through a stream that can be awaited or read one value at a time.
FarhanAliRaza confirmed that a failed state save can still look successful to the caller and left that decision open because separate completion messages reduced throughput. The latest change adds a partial error-message check that violates the test guide. Reviews (10) · Last reviewed commit: "Complete a request that chains events wi..." · Reviewed by Greptile |
| await ctx.emit_result( | ||
| _done_record(request_id, events), | ||
| delta=await _resolve_delta(ctx, flush_root), | ||
| ) | ||
| ctx.mark_result_sent() |
There was a problem hiding this comment.
The foreground path sends done and sets result_sent before leaving modify_state_with_links. Redis still saves the state when that context exits. If the save raises, for example because the lock expired, _execute_reporting_result skips the error record because result_sent is already true. The caller sees success even though the changes were not saved.
Complete the request only after the state context exits successfully, so save failures can still reject the stream.
There was a problem hiding this comment.
Confirmed. StateManagerRedis can raise LockExpiredError from set_state when modify_state_with_links exits, which happens after process_event has sent the merged done. In that case _execute_reporting_result skips the error record, so the stream resolves while the backend exception handler (and its toast) still runs. The state delta itself has already reached the client either way, because it is emitted before the save in every design.
The fix is to send done only after the state context exits. That is the "separate completion message" variant, which I measured on the production load app at −14%, −30% and −35% throughput at 1, 10 and 50 clients. Emitting the merged message after the lock is released instead would let another holder's newer delta arrive first and be overwritten by our stale one.
This is a trade-off between that cost and the stream's outcome when a save fails after a successful handler, so I'm leaving the decision to the PR author and keeping this thread open until they decide.
Generated by Claude Code
There was a problem hiding this comment.
Thanks for confirming the failure path and the measured cost. I’d favor sending completion only after the state context exits: a stream that resolves successfully should mean the event’s state was saved, and a set_state failure should reject it. The already-emitted delta does not change that outcome. The throughput regression is significant, but it is preferable to reporting success for a failed save; the finding remains open until that behavior is changed or explicitly accepted as the intended contract.
…streams addEvents attached each event's ResultStream to the caller's event object, so an object passed twice (addEvents([e, e])), or dispatched again before it was sent, had its first stream overwritten and never settled; the shared object also kept a stale request id and router_data from its first send. Each dispatch now queues shallow copies carrying their own stream. The throttle bookkeeping kept the last stream per key, values included, until the next dispatch for that key; it now forgets a stream once it settles. Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
Merging this PR will regress 3 benchmarks2 warnings
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing Footnotes
|
There was a problem hiding this comment.
2 issues found and verified against the latest diff
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:152">
P2: A synchronous event handler returning an awaitable is rejected or serialized instead of being awaited, so its frontend request fails rather than receiving the eventual value. Detect `inspect.isawaitable` after invoking the handler and await it unless the value is an `EventSpec` or `EventHandler` describing an event.
(Based on your team's feedback about awaitable handler results.) .</violation>
<violation number="2" location="packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py:656">
P1: Move this completion emission until after `modify_state_with_links` exits successfully; otherwise a Redis save failure leaves the frontend request completed despite unsaved changes.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| # request costs no message of its own: sent separately, it cut | ||
| # throughput by a third under load. | ||
| ctx = EventContext.get() | ||
| await ctx.emit_result( |
There was a problem hiding this comment.
P1: Move this completion emission until after modify_state_with_links exits successfully; otherwise a Redis save failure leaves the frontend request completed despite unsaved changes.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. 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. At packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py, line 656:
<comment>Move this completion emission until after `modify_state_with_links` exits successfully; otherwise a Redis save failure leaves the frontend request completed despite unsaved changes.</comment>
<file context>
@@ -567,32 +633,38 @@ async def process_event(
+ # request costs no message of its own: sent separately, it cut
+ # throughput by a third under load.
+ ctx = EventContext.get()
+ await ctx.emit_result(
+ _done_record(request_id, events),
+ delta=await _resolve_delta(ctx, flush_root),
</file context>
There was a problem hiding this comment.
Same finding as Greptile's on lines 656–660; see that thread for the trace and the measured cost of sending completion after the state context exits (−14% to −35% throughput). The PR author is deciding between that fix and documenting the current contract, so this thread stays open until then.
Generated by Claude Code
…orts - applyEvent gives the event its request id before sending but registers the stream only once socket.emit returned, so a send that throws leaves the stream on the event for processEvent to fail instead of hanging; no record can arrive in between. addEvents logs a failed dispatch with console.error instead of dropping the rejected promise. - stop() yields once after cancelling the remaining futures, whose done callbacks create the cancellation reports on the next iteration, and drains them until none are left. - on_event calls enqueue(token, event) as before when the frontend sent no id, so an enqueue override that predates request ids keeps working. - StateUpdate.results comes after the deprecated final field, keeping the positional signature. - Docs and news: frontend-only events are still sent, events mixed with values and unawaited coroutines still raise, the call_script example is attached to a button. Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
There was a problem hiding this comment.
Review completed against the latest diff
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
_execute_reporting_result marked the request completed before awaiting the done (or error) record, so a cancellation landing during that send skipped the error path while _report_cancelled_request saw it as completed: the frontend stream never settled. The mark now follows a successful send; a cancellation during the send is reported as cancelled, and the frontend ignores a second record for an id it already settled. Docs: the browser JS section says yielded or returned events are chained, not streamed; the awaitable-handlers news says an awaited stateless handler runs under the caller's lock. Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
Resolutions: - The frontend moved to packages/reflex-frontend (#7794): event_results.js lives in src/utils, its vitest suite in tests, and the state.js harnesses load it from there. The thenable ResultStream carries a biome-ignore for noThenProperty, and main's debounce test asserts the shared stream. - Stateless handlers were reverted (#7770): their execution path and the stateless result test go; the cancelled-while-sending test uses a background handler returning outside `async with self` instead. - _is_result builds on main's _is_invalid_result, so yields and returns share its rules for mistaken events (self.handler, an uncalled rx.redirect); the foreground path keeps main's flush on failure (#7696). - EventContext keeps both request_id/emit_result_impl and main's middleware. - The dropped-result warning (#7796) now applies only to an event sent without a request id; the chaining docs say where the value goes instead. - The awaitable-handlers news fragments were released with 0.11.0. - reflex now needs reflex-base >= 0.11.1.dev0 for the request id API. Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
…uest - An event whose handler is not registered (a stale frontend calling a removed handler) only logged the failed lookup: its future never finished and the request's stream waited forever. _process_queue now fails the future, and the request gets an error record. - A running request's cancellation was reported from the future callback, racing the handler task's final flush (_flush_failed_handler): with an async computed var to resolve, the cancelled record overtook the delta. The task now reports its own cancellation after that flush; the callback (_report_unfinished_request) covers only what no task reports: an event cancelled before its task started, a failed lookup, or a record a task failed to send. - Result record keys are named constants. - New assertions compare full messages (CLAUDE.md). Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
The state.js harnesses link two special cases now: main's self-import of $/utils/state for server-provided scripts (#7870), and the real event_results.js module. Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
The new results field made serialize_state_update's getattr loop over the dataclass fields about 28% slower (CodSpeed: test_state_update_dataclass_serialization -12%). Reading the four fields directly is about twice as fast as the three-field loop on main, and the output is unchanged: each field is included only when truthy. Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
|
CodSpeed on 08a6507:
Generated by Claude Code |
A handler that returned events sent its completion record in a message of its own after the delta. Validate the returned events first, then send the completion with the final delta and route the events after it, so a handler that changes state and chains costs no extra message.
|
|
||
| records = _records(wire_log, "r") | ||
| assert len(records) == 1 | ||
| assert records[0]["error"].startswith("TypeError: ") |
There was a problem hiding this comment.
New error checks are incomplete. The new Python test accepts any message starting with
TypeError: , even if the handler name or explanation is wrong. The pytest.raises check above also matches only part of the message.
The repository guide requires checked error messages to match in full. Compare both messages with the complete expected text.
Context Used: CLAUDE.md (source)
There was a problem hiding this comment.
1 existing issue remains and 2 new issues found across 2 files (changes from recent commits).
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="tests/units/reflex_base/event/processor/test_base_state_processor.py">
<violation number="1" location="tests/units/reflex_base/event/processor/test_base_state_processor.py:5809">
P2: The test does not enforce the required completion-before-chained-event ordering. Assert the message index of the chained delta is greater than the completion message index.</violation>
<violation number="2" location="tests/units/reflex_base/event/processor/test_base_state_processor.py:5854">
P2: This assertion does not verify the complete mixed-return error sent to the frontend. Compare the serialized record with the full expected exception message so changes to error reporting cannot pass silently.</violation>
</file>
Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.
Tip: Review your code locally with the cubic CLI to iterate faster.
View guided diff | Turn on auto-fix | Re-trigger cubic
| assert any( | ||
| delta is not None and delta.get(name, {}).get(f"m{FIELD_MARKER}") == 1 | ||
| for delta, _ in messages | ||
| ) |
There was a problem hiding this comment.
P2: The test does not enforce the required completion-before-chained-event ordering. Assert the message index of the chained delta is greater than the completion message index.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. 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. At tests/units/reflex_base/event/processor/test_base_state_processor.py, line 5809:
<comment>The test does not enforce the required completion-before-chained-event ordering. Assert the message index of the chained delta is greater than the completion message index.</comment>
<file context>
@@ -5744,6 +5744,123 @@ def nothing(self):
+ assert done[0] is not None
+ assert done[0][name][f"n{FIELD_MARKER}"] == 1
+ # The chained event still ran, reporting nothing.
+ assert any(
+ delta is not None and delta.get(name, {}).get(f"m{FIELD_MARKER}") == 1
+ for delta, _ in messages
</file context>
| assert any( | |
| delta is not None and delta.get(name, {}).get(f"m{FIELD_MARKER}") == 1 | |
| for delta, _ in messages | |
| ) | |
| completion_index = next( | |
| i | |
| for i, (_, results) in enumerate(messages) | |
| if {"id": "c", "done": True} in results | |
| ) | |
| chained_index = next( | |
| i | |
| for i, (delta, _) in enumerate(messages) | |
| if delta is not None and delta.get(name, {}).get(f"m{FIELD_MARKER}") == 1 | |
| ) | |
| assert chained_index > completion_index |
|
|
||
| records = _records(wire_log, "r") | ||
| assert len(records) == 1 | ||
| assert records[0]["error"].startswith("TypeError: ") |
There was a problem hiding this comment.
P2: This assertion does not verify the complete mixed-return error sent to the frontend. Compare the serialized record with the full expected exception message so changes to error reporting cannot pass silently.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. 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. At tests/units/reflex_base/event/processor/test_base_state_processor.py, line 5854:
<comment>This assertion does not verify the complete mixed-return error sent to the frontend. Compare the serialized record with the full expected exception message so changes to error reporting cannot pass silently.</comment>
<file context>
@@ -5744,6 +5744,123 @@ def nothing(self):
+
+ records = _records(wire_log, "r")
+ assert len(records) == 1
+ assert records[0]["error"].startswith("TypeError: ")
+ error_at = wire_log.index(("result", records[0]))
+ key = f"value{FIELD_MARKER}"
</file context>
| assert records[0]["error"].startswith("TypeError: ") | |
| assert records[0]["error"] == f"TypeError: {future.exception()}" |
closes #7608 (ENG-13447)
Type of change
What it does
Frontend code can dispatch a backend event and get back every value the handler
yields orreturns:A trigger made of one event handler returns the stream too, so it can be passed straight to a React prop that expects an async callback (
loadOptions,getRows, ...).Wire protocol
id(a random per-page-load prefix plus a counter).resultsfield on the existing"event"StateUpdate:{id, value},{id, done},{id, error},{id, done, cancelled}. Results therefore keep the message's ordering, lost-and-found routing and disconnect handling.Backend (
reflex-base,reflex)on_eventreadsidfrom the wire fields, liketraceparent, and checks that it is a string of at most 64 characters. It is not added toEvent: events are serialized as dataclasses when sent to the browser, so every event would otherwise carry"id": null. An event sent without an id callsenqueue(token, event)exactly as before.EventContextgainsrequest_id, whichfork()does not inherit, so chained events report nothing. It also gains anemit_resultchannel wired inconfigure._is_result, built on main's_is_invalid_result:Noneflushes the delta, and events chain as before;self.handler, an uncalledrx.redirect) still raiseTypeError.request_id. A handler run withawaitinside another shares its caller's context, so reading the id from the context would have leaked its values into the caller's stream.EventContext.result_sent, set only after its record was sent):default_backend_exception_handler. The backend exception handler and its toast still run.Separate vs merged completion, measured. The issue asked to merge
doneinto the final delta where possible. I built both and ran them on the production Socket.IO load app (200 events per client, average of two rounds):donemessagedonemerged into the final deltaMerged it is. The
donerecord rides with the handler's final delta, also when the handler ends by chaining events (the events are validated first and routed after it), so a handler that changes state costs no extra message. A handler that changes no state still costs one message per event ({results: [{id, done}]}), where it cost none before: measured with 20 dispatches each, a no-op handler sends 0 messages on main and 20 here. A yielded value also rides with the delta flushed just before it. Open question in review: with a state manager whose save can fail on exit (Redis lock expiry), the mergeddonehas already gone out; see the "failed saves" thread.Frontend (
packages/reflex-frontend:src/utils/state.js, newsrc/utils/event_results.js)ResultStreamis an async iterator and a thenable rather than a Promise, so a failing dispatch nobody awaits never reports an unhandled rejection (hence thenoThenPropertylint suppression). Batches merge in arrival order.packages/reflex-frontend/tests/event_results.test.js.Compatibility
id, so it gets no results and no overhead (_execute_eventruns directly), and handlers that yield values just run.yield []is now a value rather than an empty event list. This matches Make event handlers awaitable and register them through @rx.event #7673's rule for return values.reflexnow requiresreflex-base >= 0.11.1.dev0.Tests
test_base_state_processor.py(backend processor):yield self.handlerstill raises.test_context.py,test_app.py(on_eventforwards and validates theid, keeps the legacyenqueuecall without one, and warns about dropped values only without one),test_state.py(rewrotetest_state_with_invalid_yield;resultsserialization).state.jsruntime harness (client_state_updates.mjs): records routed by id after the delta, frontend-only events complete at once, disconnect rejects, an event object dispatched twice, a send that throws. The harnesses load the realevent_results.js.packages/reflex-frontend: vitest for the stream module; main's debounce test now asserts the shared stream.tests_playwright/test_event_results.py, new app; no existing one fit):for awaitandawait, rejection after partial values, two concurrent requests keep their own results, two calls in one debounce window share one dispatch.ignore_console_errormarker (already used, never registered).Known limits
{a; b;}block and returns nothing. This is documented.wait_all, as scoped).Checks
reflex_clitests fail in this environment on a clean checkout too.ruff check,ruff format,pyright reflex tests, pre-commit, andnpm run checkinpackages/reflex-frontendpassyield_events.md,chaining_events.md,browser_javascript.md,wrapping-react/props.md) and news fragments forreflexandreflex-basehttps://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH