Skip to content

fix(event): send a failed handler's writes after its last yield - #7696

Merged
masenf merged 4 commits into
reflex-dev:mainfrom
FarhanAliRaza:farhan/flush-delta-on-failed-handler
Nov 8, 2026
Merged

masenf merged 4 commits into
reflex-dev:mainfrom
FarhanAliRaza:farhan/flush-delta-on-failed-handler

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Related to #7248. Follows #7412.

Problem

A foreground handler can change state after its last yield, for example in an except asyncio.CancelledError block when a supersedes=True call cancels it, or just before it raises. Nothing sends those changes to the frontend.

  • Memory and disk send them late, with the next handler's first delta. The next handler gets the same state object, and that object still marks the vars as dirty.
  • Redis stores them (fix(state): persist cancelled redis handler updates #7412), but never sends them. The next handler unpickles a fresh copy, and _init_bookkeeping clears the dirty marks. The frontend shows the old value until the var changes again or the page reloads.

Fix

When process_event raises or is cancelled, _execute_event flushes the delta with chain_updates(None, root_state=...) before the exception propagates. The flush runs under the state lock, before release_lock(), so it reaches the frontend before any delta from the next handler and before the error toast.

  • The flush runs only when a write is pending. A handler whose own delta failed already cleaned the state, so a second delta would only fail again and log a duplicate traceback.
  • If the flush fails, it is logged and the handler's own exception propagates.
  • Background handlers are not changed. They already flush in their finally.

docs/events/yield_events.md now says that these writes reach the frontend when the handler raises or is cancelled.

Tests

  • test_failed_handler_emits_writes_after_last_yield: memory, disk and redis, each cancelled and raising. All 6 cases fail on main and pass with the fix.
  • test_failed_handler_flush_error_keeps_handler_exception: a computed var makes the flush fail. The handler's RuntimeError is reported and the flush error is logged.
  • test_failed_delta_is_not_flushed_again: an uncached computed var makes the handler's own delta fail. The error is reported once and no flush runs.

Checked in an example app on memory and real Redis: raise before and after a yield, cancelled supersedes=True handler, background task, chained event, failing on_load, and a backend exception handler that returns events. The frontend, the backend state and a page reload agree in every case.

View guided diff

A foreground handler that is cancelled or raises could leave changes it
made after its last yield unsent. Memory and disk carried them in the
next handler's delta, but a state manager that loads a fresh copy, as
redis does, dropped the dirty marks, so the frontend never received
them until the var changed again or the page reloaded.

Flush the delta under the state lock before the exception propagates.
A flush failure is logged so the handler's own exception still
propagates.
@FarhanAliRaza
FarhanAliRaza requested a review from a team as a code owner October 29, 2026 17:08
@FarhanAliRaza FarhanAliRaza added on deck PRs lined up to review / merge next breaking Public API facing change considered for minor release bump pre-v1.0 labels Oct 29, 2026

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

No issues found across 3 files

View guided diff | Re-trigger cubic

@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; the remaining cancellation-test gap is non-blocking.

Findings

  1. P2 Cancellation test skips completion ▶

Summary

Sends pending foreground state changes before a failed or cancelled handler releases its lock.

  • Failed foreground handlers send their last state writes to the page.

Reviews (3) · Last reviewed commit: "fix(event): skip the flush when a failed..." · Reviewed by Greptile

@codspeed

codspeed Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

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

✅ 148 untouched benchmarks


Comparing FarhanAliRaza:farhan/flush-delta-on-failed-handler (8505c81) with main (31951ab)

Open in CodSpeed

…on-failed-handler

# Conflicts:
#	tests/units/reflex_base/event/processor/test_base_state_processor.py

@masenf masenf left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

code change looks fine, but the tests are failing still

…on-failed-handler

# Conflicts:
#	packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py
A handler whose own delta fails has its state cleaned by that delta, so
the flush only recomputed the failing delta and logged a second traceback
for the same error. The flush now runs only when a write is pending.

Also update the yield events docs: writes after the last yield now reach
the frontend when the handler raises or is cancelled.
@FarhanAliRaza
FarhanAliRaza requested a review from Alek99 as a code owner November 6, 2026 14:51

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

All reported issues were addressed across 3 files (changes from recent commits).

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

View guided diff | Re-trigger cubic

Comment thread docs/events/yield_events.md Resolved
@masenf
masenf merged commit cd96154 into reflex-dev:main Nov 8, 2026
182 of 184 checks passed
FarhanAliRaza added a commit that referenced this pull request Nov 11, 2026
…rame (#7808)

* fix(upload): answer a failing upload handler with a 500 or an error frame

An upload handler that raised made the exception escape the streamed
/_upload response: the server cut the chunked body mid-stream and logged
the exception a second time. Since #7696 a failing handler's writes are
streamed before its exception, so the body had always started.

- DisconnectAwareStreamingResponse holds http.response.start until the
  first body message, so a body that fails before yielding can still be
  answered with an error status.
- The upload stream catches the handler's exception (already reported by
  the event processor): before any update it raises HTTPException(500),
  after one it ends with an {"error": ...} frame. Nothing escapes to the
  server, so the exception is logged once.
- upload.js reports an error frame by rejecting the upload instead of
  passing it to the state listener.
- The backend exception handler gets the traceback the handler raised
  with: a caller awaiting the event's future (the upload stream) re-raised
  it first and replaced the handler's frames.

FINDING-044 from the reflex 0.11.0a1 pre-release testing.

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

* fix(upload): keep the delayed response start in the upload module; let unreported errors through

Review follow-ups for #7808:

- Move the response-start hold from reflex-base's
  DisconnectAwareStreamingResponse into an upload-only subclass in
  _upload.py. reflex-components-core no longer relies on an unreleased
  reflex-base change: its reflex-base floor cannot exclude the published
  0.11.0a1, since main builds reflex-base as 0.10.2.devN.
- Narrow the upload stream's catch to the event processor's stream.
  Serializing an update and creating the stream now fail outside it, and a
  processor that is not running (QueueShutDown) is re-raised. Errors the
  processor never reported now reach the server log, as they did before.
- Correct the traceback docstrings: CPython's C asyncio.Future re-raises an
  awaited exception with only the awaiting frames (the pure-Python future
  prepends them).

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

* fix(upload): don't parse a non-2xx upload response as update chunks

An error response (the 500 for a handler that fails before any update,
or a 400) has a plain-text body. upload.js parsed it as an ndjson chunk
and logged "Error parsing chunk ..." before the real "Upload error".
Skip chunk parsing unless the status is 2xx; onload reports the error.

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Farhan <[email protected]>
masenf added a commit that referenced this pull request Nov 11, 2026
…rame (#7808)

* fix(upload): answer a failing upload handler with a 500 or an error frame

An upload handler that raised made the exception escape the streamed
/_upload response: the server cut the chunked body mid-stream and logged
the exception a second time. Since #7696 a failing handler's writes are
streamed before its exception, so the body had always started.

- DisconnectAwareStreamingResponse holds http.response.start until the
  first body message, so a body that fails before yielding can still be
  answered with an error status.
- The upload stream catches the handler's exception (already reported by
  the event processor): before any update it raises HTTPException(500),
  after one it ends with an {"error": ...} frame. Nothing escapes to the
  server, so the exception is logged once.
- upload.js reports an error frame by rejecting the upload instead of
  passing it to the state listener.
- The backend exception handler gets the traceback the handler raised
  with: a caller awaiting the event's future (the upload stream) re-raised
  it first and replaced the handler's frames.

FINDING-044 from the reflex 0.11.0a1 pre-release testing.

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

* fix(upload): keep the delayed response start in the upload module; let unreported errors through

Review follow-ups for #7808:

- Move the response-start hold from reflex-base's
  DisconnectAwareStreamingResponse into an upload-only subclass in
  _upload.py. reflex-components-core no longer relies on an unreleased
  reflex-base change: its reflex-base floor cannot exclude the published
  0.11.0a1, since main builds reflex-base as 0.10.2.devN.
- Narrow the upload stream's catch to the event processor's stream.
  Serializing an update and creating the stream now fail outside it, and a
  processor that is not running (QueueShutDown) is re-raised. Errors the
  processor never reported now reach the server log, as they did before.
- Correct the traceback docstrings: CPython's C asyncio.Future re-raises an
  awaited exception with only the awaiting frames (the pure-Python future
  prepends them).

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

* fix(upload): don't parse a non-2xx upload response as update chunks

An error response (the 500 for a handler that fails before any update,
or a 400) has a plain-text body. upload.js parsed it as an ndjson chunk
and logged "Error parsing chunk ..." before the real "Upload error".
Skip chunk parsing unless the status is 2xx; onload reports the error.

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Farhan <[email protected]>
(cherry picked from commit 20e9f1a)
FarhanAliRaza added a commit that referenced this pull request Nov 13, 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
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 on deck PRs lined up to review / merge next

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants