Skip to content

If an exception is raised inside async with self block, changes prior to the exception are not persisted #6122

Closed

Description

@masenf

Describe the bug
If an exception is raised inside async with self block, changes prior to the exception are not persisted, but the backend still sends a delta with the changes. Subsequent events or async with self blocks do NOT see the changes from the block that raised.

To Reproduce

⚠️ MUST USE redis

import reflex as rx


class State(rx.State):
    count: int = 0

    @rx.event
    def increment(self):
        self.count += 1

    @rx.event
    def increment_with_error(self):
        self.count += 1
        raise ValueError("This is an error!")

    @rx.event(background=True)
    async def increment_with_error_bg(self):
        async with self:
            self.count += 1
        raise ValueError("This is an error in the background task!")

    @rx.event(background=True)
    async def increment_with_error_in_context_bg(self):
        async with self:
            self.count += 1
            raise ValueError("This is an error in the background task async with self ctx!")


def index() -> rx.Component:
    return rx.container(
        rx.color_mode.button(position="top-right"),
        rx.vstack(
            rx.button(
                f"Increment ({State.count})",
                on_click=State.increment,
            ),
            rx.button(
                "Increment with error",
                on_click=State.increment_with_error,
            ),
            rx.button(
                "Increment with error in background task",
                on_click=State.increment_with_error_bg,
            ),
            rx.button(
                "Increment with error in background task async with self ctx",
                on_click=State.increment_with_error_in_context_bg,
            ),
        ),
    )


app = rx.App()
app.add_page(index)

Expected behavior
When any of the four buttons are clicked, the counter should be incremented. When refreshing the page, the count should remain the same.

What actually happens when clicking the fourth button "Increment with error in background task async with self ctx" is the count temporarily increases, the default error toast is shown, then refreshing the page causes the count to revert back to the prior value.

Specifics (please complete the following information):

  • Python Version: 3.14
  • Reflex Version: 0.8.26

Additional Context

This bug is kind of a weird edge case.

The bug behavior described here makes sense semantically if we consider async with self to be a "transaction" in that we take the lock, yield control to the block, then persist the changes, send updates, and release the lock. If you understand that, then it makes sense why raising the exception inside the context block could end up not persisting the changes (although it's also a bit weird that we do get the update 🤔).

But from a uniformity perspective, i think it's important to not have a behavior difference between memory/disk and redis state managers.

So either redis papers over this difference and persists regardless of an exception in the block, or we do something with memory/disk manager such that we always give a copy of the state to the event and require set_state to be called for those implementations. Ultimately it might be better for the memory/disk managers to work more like the redis manager to help find bugs like this in local dev mode, but that would probably be a breaking 0.9 change.

Activity

  1. benedikt-bartscher commented on Feb 10, 2026

    @benedikt-bartscher
    Contributor

    My personal opinion: It should be like a transaction and i'd prefer having no delta sent to the client and adjustment of disk/memory managers to match the redis behaviour.

  2. masenf commented on Oct 7, 2026

    @masenf
    CollaboratorAuthor

    Independent re-verification on reflex 0.10.0a2 (with 0.9.12, 0.10.0a1, 0.9.0 and 0.8.26 baselines), in case it helps scope the fix:

    • Confirmed exactly for a generator that yields (the browser shows the flushed value) then raises, and for a raise inside async with self in a background task after a flushed change: the browser keeps the delivered value, a reload shows the pre-event value. Reproduces on a2 dev, a2 prod with 1 and with 9 workers, a1, and 0.9.12 dev and prod. For superseded (cancelled) handlers (A cancelled foreground supersedes=True handler loses all of its state writes under StateManagerRedis but keeps them under the in-memory manager #7248) the divergence is permanent only when the superseding call does not rewrite the same var.
    • Narrowed: it is default Redis config only. With REFLEX_OPLOCK_ENABLED=true the failed event's changes stay in the cached state object and Redis behaves like the disk manager (stale until the next event, no divergence). Failures that never flushed (plain raise, chained handler, backend vars, on_load) are atomic and consistent on both sides; the harm is flush-then-rollback. A custom backend_exception_handler that chains a no-op event does not help on Redis; catching the exception inside the handler does.
    • Mechanism (published a2): istate/manager/redis.py ~L535-537 (also ~L569-570, ~L595-596) — yield state then set_state(..., lock_id=...) is skipped on any exception, the object is discarded and re-read from Redis, while the deltas already sent at yields or in StateProxy.__aexit__ (istate/proxy.py ~L295-304, delta emitted before __aexit__(*exc_info)) are on the wire. PR fix(state): persist cancelled redis handler updates #7412's own test keeps discarding on non-cancellation exceptions, so these two cases would remain after it.

    Full matrix, fixture and frame captures: https://github.com/reflex-dev/reflex/blob/claude/reflex-prerelease-testing-t0sd90/prerelease_testing/2026-10-07/events/verification/NOTES.md (finding N-021 in the same directory's FINDINGS.md).


    Generated by Claude Code

  3. masenf commented on Nov 12, 2026

    @masenf
    CollaboratorAuthor

    Fixed in 0.11.0a1 by #7412 and #7696, and re-verified on the published 0.11.0a2 against 0.10.1.

    Setup:

    • The app from this issue, unchanged.
    • The two cases from the comments: a generator that yields and then raises, and a supersedes=True handler cancelled by a second call that does not touch count.
    • Redis with the default config and with REFLEX_OPLOCK_ENABLED=true, in dev and in prod with 9 workers.

    Results:

    • 0.11.0a2: in all 30 case/configuration combinations, the page value matches the value after a full reload, and the next increment builds on what the page shows.
    • 0.10.1, default Redis: still diverges. A raise inside async with self shows page 5 but 4 after a reload. A yield-then-raise shows 6 vs 5, and the superseded handler 7 vs 6.

    The semantics chosen: a failed or cancelled handler's writes are kept and sent, so Redis now behaves like the memory and disk managers. They are not rolled back as a transaction, which was the alternative suggested above. A handler that should leave no trace on failure needs to restore its own state (for example in except/finally) before re-raising.

    Closing as completed.


    Generated by Claude Code

  4. added a commit that references this issue on Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions