Skip to content

Stream event handler yield and return values to the frontend caller - #7761

Open
FarhanAliRaza wants to merge 9 commits into
mainfrom
farhan/amazing-bardeen-8ddaa1
Open

FarhanAliRaza wants to merge 9 commits into
mainfrom
farhan/amazing-bardeen-8ddaa1

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

closes #7608 (ENG-13447)

Type of change

  • New feature (non-breaking change which adds functionality)
  • Breaking change: a single-event trigger now returns a result stream that settles when the handler finishes, not a promise that resolved once the event was sent
  • This change requires a documentation update (included)

What it does

Frontend code can dispatch a backend event and get back every value the handler yields or returns:

for await (const hit of addEvents([searchEvent])) render(hit);
const rows = await addEvents([loadRowsEvent]); // the last value; rejects if the handler raised

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

  • Frontend to backend: one new field on each sent event, id (a random per-page-load prefix plus a counter).
  • Backend to frontend: a results field 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_event reads id from the wire fields, like traceparent, and checks that it is a string of at most 64 characters. It is not added to Event: events are serialized as dataclasses when sent to the browser, so every event would otherwise carry "id": null. An event sent without an id calls enqueue(token, event) exactly as before.
  • EventContext gains request_id, which fork() does not inherit, so chained events report nothing. It also gains an emit_result channel wired in configure.
  • Yields and returns share one classifier, _is_result, built on main's _is_invalid_result:
    • None flushes the delta, and events chain as before;
    • any other value is a result;
    • events mixed with values, unawaited coroutines, and mistaken events (self.handler, an uncalled rx.redirect) still raise TypeError.
    • ENG-13665 can build on the same function.
  • Only the processor's top-level run gets request_id. A handler run with await inside another shares its caller's context, so reading the id from the context would have leaked its values into the caller's stream.
  • Each request completes exactly once (EventContext.result_sent, set only after its record was sent):
    • success and error are sent inside the handler's task, so they reach the browser before the next event for the same tab emits its delta;
    • cancellation, whether queued or running (including during the completion send), is reported from the future's done callback, which also covers events cancelled before their task started.
  • In prod mode the error text is generic, matching default_backend_exception_handler. The backend exception handler and its toast still run.
  • The dev-mode "returned value is dropped" warning (Fix uncalled rx.toast hint and dropped-result warning lookup #7796) now applies only to an event sent without a request id.

Separate vs merged completion, measured. The issue asked to merge done into 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):

clients baseline (no id) separate done message done merged into the final delta
1 242–253 ev/s 219 (−14%), p50 2.0 ms 243 (same), p50 1.5 ms
10 584–600 421 (−30%), p50 20.1 ms 541 (−7%), p50 14.7 ms
50 762–791 495 (−35%), p50 92 ms 720 (−9%), p50 60 ms

Merged it is. The done record 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 merged done has already gone out; see the "failed saves" thread.

Frontend (packages/reflex-frontend: src/utils/state.js, new src/utils/event_results.js)

  • ResultStream is an async iterator and a thenable rather than a Promise, so a failing dispatch nobody awaits never reports an unhandled rejection (hence the noThenProperty lint suppression). Batches merge in arrival order.
  • The module has no npm imports; its vitest suite is packages/reflex-frontend/tests/event_results.test.js.
  • Each dispatch queues its own copies of the events, each carrying its stream; the request id is registered only once the send succeeded. Events queued while offline keep waiting, a send that throws fails its stream, and frontend-only events and uploads complete immediately.
  • A disconnect fails every request that was sent and not completed.
  • Debounce: every call in one window gets the same stream, bound to the dispatch that fires. Throttle: a dropped call shares the last open dispatch, or gets an already-completed stream; a settled one is forgotten.

Compatibility

  • An old frontend sends no id, so it gets no results and no overhead (_execute_event runs directly), and handlers that yield values just run.
  • A plain 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.
  • reflex now requires reflex-base >= 0.11.1.dev0.

Tests

  • test_base_state_processor.py (backend processor):
    • ordering of deltas and values;
    • bare done;
    • no-id drop;
    • dev/prod error text;
    • an inline awaited handler stays with its caller;
    • queued and running cancellation reported once, including a cancellation during the completion send and at shutdown;
    • background handler;
    • yield self.handler still raises.
  • test_context.py, test_app.py (on_event forwards and validates the id, keeps the legacy enqueue call without one, and warns about dropped values only without one), test_state.py (rewrote test_state_with_invalid_yield; results serialization).
  • state.js runtime 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 real event_results.js.
  • packages/reflex-frontend: vitest for the stream module; main's debounce test now asserts the shared stream.
  • Playwright (tests_playwright/test_event_results.py, new app; no existing one fit): for await and await, rejection after partial values, two concurrent requests keep their own results, two calls in one debounce window share one dispatch.
  • Registered the ignore_console_error marker (already used, never registered).

Known limits

  • A trigger with several events, or with event actions applied to the whole trigger, compiles to a {a; b;} block and returns nothing. This is documented.
  • Values from events the handler chains are not included (no wait_all, as scoped).

Checks

  • Unit tests pass, coverage 81.8%. Unrelated: the reflex_cli tests fail in this environment on a clean checkout too.
  • ruff check, ruff format, pyright reflex tests, pre-commit, and npm run check in packages/reflex-frontend pass
  • Playwright tests pass
  • Docs (yield_events.md, chaining_events.md, browser_javascript.md, wrapping-react/props.md) and news fragments for reflex and reflex-base

https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH

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
@FarhanAliRaza
FarhanAliRaza requested review from a team and Alek99 as code owners November 6, 2026 19:36
@greptile-apps

greptile-apps Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[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.

Findings

  1. P1 Failed saves look successful ▶
  2. P2 New error checks are incomplete ▶

Summary

This PR sends handler values back to frontend callers through a stream that can be awaited or read one value at a time.

  • Backend handlers send yielded values and completion to the matching caller.
  • Browser event calls return streams of handler values.

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

Comment on lines +656 to +660
await ctx.emit_result(
_done_record(request_id, events),
delta=await _resolve_delta(ctx, flush_root),
)
ctx.mark_result_sent()

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.

P1 Failed saves look successful

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

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.

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
@codspeed

codspeed Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 3 benchmarks

2 warnings

⚠️ 12 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

⚠️ 5 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 improved benchmarks
❌ 3 regressed benchmarks
✅ 138 untouched benchmarks
⏩ 8 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_route_matching[1000] 92.1 ms 98.8 ms -6.81%
❌ test_route_matching[100] 9.6 ms 10.3 ms -6.68%
❌ test_route_matching[10] 1.3 ms 1.3 ms -5.5%
⚡ test_state_update_dataclass_serialization 4 ms 2.4 ms +65.74%
⚡ test_state_update_wire_serialization[scalar_100b] 3.1 ms 2.9 ms +6.26%

Tip

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


Comparing farhan/amazing-bardeen-8ddaa1 (08a6507) with main (8e5bb84)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@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.

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(

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.

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>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Comment thread reflex/state.py Resolved
Comment thread reflex/app.py Resolved
Comment thread news/+event-results.feature.md Resolved
Comment thread docs/wrapping-react/props.md Resolved
Comment thread docs/events/yield_events.md Resolved
…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

@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.

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
@FarhanAliRaza FarhanAliRaza added breaking Public API facing change considered for minor release bump pre-v1.0 enhancement Anything you want improved labels Nov 12, 2026 — with ChatGPT Codex Connector
@FarhanAliRaza FarhanAliRaza added the on deck PRs lined up to review / merge next label Nov 12, 2026
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

Copy link
Copy Markdown
Contributor Author

CodSpeed on 08a6507:

  • test_state_update_dataclass_serialization was a real regression from the new StateUpdate.results field (−12% on acf3c88). It is fixed in 08a6507, which reads the fields directly instead of looping with getattr, and CodSpeed now shows it +65.7% faster than main.
  • test_route_matching[10/100/1000] (−5.5% to −6.8%) is not from this PR. The benchmark only calls reflex.route.get_router, and reflex/route.py and tests/benchmarks/test_routes.py are byte-identical on main (8e5bb84) and this head. CodSpeed also reports that the significantly changed benchmarks ran on different hardware than their base. On 6d446d7, compared with the previous main, the same benchmarks showed no change.

Generated by Claude Code

@masenf masenf added the documentation Improvements or additions to documentation label Nov 16, 2026
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: ")

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.

P2 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)

@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 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

Comment on lines +5809 to +5812
assert any(
delta is not None and delta.get(name, {}).get(f"m{FIELD_MARKER}") == 1
for delta, _ in messages
)

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.

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>
Suggested change
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: ")

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.

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>
Suggested change
assert records[0]["error"].startswith("TypeError: ")
assert records[0]["error"] == f"TypeError: {future.exception()}"

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking Public API facing change considered for minor release bump pre-v1.0 documentation Improvements or additions to documentation enhancement Anything you want improved on deck PRs lined up to review / merge next

Projects

None yet

Development

Successfully merging this pull request may close these issues.

EventHandler return values: stream yielded/returned values to the frontend

2 participants