Skip to content

First-class way to enqueue an event that outlives the on_load chain that started it (detached events) #7239

Open

Description

@Darksinian

Describe the Enhancement you want

Since #6593, OnLoadInternalState.on_load_internal is @event(supersedes=True): a new page load cancels the previous page's unfinished on_load chain, children included. There is currently no way for a handler to say "the event I am about to enqueue is not part of my chain and must not be cancelled with it".

  • Which feature do you want to improve, and what problem does it have?

    Event chaining from on_load. Every backend event a handler yields is enqueued through EventContext.fork(), which always sets parent_txid, so it is registered as a child of the yielding chain (parent_future.add_child(tracked) in EventProcessor.enqueue). _on_future_done cascades a cancellation to every child future and to the running task in _tasks.

    So a handler reached from a page's on_load that does yield rx.redirect("/b") and then keeps working, or chains more work, is cancelled by the navigation its own redirect caused: the /b page's on_load_internal supersedes the still-running chain for the same token. The work dies with a CancelledError that nothing logs. The intent of Long running on_load events continue running after page navigation #6593 (a user leaving a page should stop its stale load) is right; a chain that issued the redirect is not stale.

    Two things that look like escape hatches are not:

    • background=True does not help. The task is parented in enqueue before is_background is consulted in the queue loop, and _create_event_task registers it in _tasks either way, so the cascade cancels it.
    • EventContext.get().enqueue(event) from inside the handler is the same path a yield takes (_route_events → ctx.enqueue), so the event is a child too.

    The only server-side workaround is to build a parent-less EventContext by hand and set it as the current context around the enqueue, which reaches into reflex_base internals. The client-side workaround is rx.call_script("null", callback=event), so the browser sends the event back as a root chain, which is a round trip to express something the server should be able to say directly.

  • What is the benefit of the enhancement?

    A handler that starts work the user navigates toward can do so from on_load without being silently cancelled and without either workaround. The common shape is: a page's on_load creates a record, redirects to that record's page so the user lands there immediately, and continues with a slower follow-up (validation, a network call, a queued job). Today the follow-up is cancelled the moment the redirect lands, leaving the record created and the rest never run, with no error surfaced.

  • Show an example / use case where the improvement is needed.

    Proposed shape, either of:

    @rx.event(detached=True)
    async def start_job(self, data: dict):
        ...  # this chain is a root of its own, whichever chain yielded it

    or a context-level API, e.g. EventContext.enqueue_detached(*events), for callers that decide per call site.

    Internally this is parent_txid=None plus a fresh txid when forking the context for the enqueued event, so enqueue finds no parent future and registers the chain as a root. The following runs against the real EventProcessor with no mocks and shows all three cases (chained: cancelled; chained + background=True: cancelled; parent-less: completes):

    import asyncio, dataclasses, uuid
    from reflex_base.event import BACKGROUND_TASK_MARKER, SUPERSEDES_MARKER, Event, EventHandler
    from reflex_base.event.context import EventContext
    from reflex_base.event.processor.event_processor import EventProcessor
    from reflex_base.registry import RegisteredEventHandler, RegistrationContext
    
    TOKEN = "client-1"
    
    def registered(fn, *, supersedes=False, background=False):
        if supersedes: setattr(fn, SUPERSEDES_MARKER, True)
        if background: setattr(fn, BACKGROUND_TASK_MARKER, True)
        return RegisteredEventHandler(handler=EventHandler(fn=fn), states=())
    
    async def enqueue_detached(event):          # what detached=True would do
        ctx = EventContext.get()
        root_like = dataclasses.replace(ctx, txid=uuid.uuid4().hex[:12], parent_txid=None)
        tok = EventContext.set(root_like)
        try:
            await root_like.enqueue(event)
        finally:
            EventContext.reset(tok)
    
    async def page_load(page, mode="chained"):   # plays on_load_internal
        if page == "a":
            ev = Event(name="start", payload={"mode": mode})
            await (enqueue_detached(ev) if mode == "detached" else EventContext.get().enqueue(ev))
    
    async def start(mode):                       # plays the handler that redirects and keeps working
        try:
            await asyncio.sleep(0.10)
            await EventContext.get().enqueue(Event(name="work"))
        except asyncio.CancelledError:
            print(f"  start[{mode}] CANCELLED"); raise
    
    async def work():                            # background=True, the slow follow-up
        try:
            await asyncio.sleep(0.5); print("  work DONE")
        except asyncio.CancelledError:
            print("  work CANCELLED"); raise
    
    async def scenario(mode):
        RegistrationContext.set(RegistrationContext(event_handlers={
            "page_load": registered(page_load, supersedes=True),
            "start": registered(start, background=(mode == "background")),
            "work": registered(work, background=True),
        }))
        proc = EventProcessor().configure(); await proc.start()
        await proc.enqueue(TOKEN, Event(name="page_load", payload={"page": "a", "mode": mode}))
        await asyncio.sleep(0.05)                # the browser follows the redirect
        await proc.enqueue(TOKEN, Event(name="page_load", payload={"page": "b"}))
        await asyncio.sleep(1.0); await proc.stop(graceful_shutdown_timeout=0)
    
    async def main():
        for mode in ("chained", "background", "detached"):
            print(f"== {mode}"); await scenario(mode)
    
    asyncio.run(main())

    Output on 0.9.11.post1:

    == chained
      start[chained] CANCELLED
    == background
      start[background] CANCELLED
    == detached
      work DONE
    

Additional context

  • reflex 0.9.11.post1 (the behaviour is present from 0.9.10.post1, where Long running on_load events continue running after page navigation #6593 landed; 0.9.8 has no supersedes).

  • The workaround we are running in an app today, called from inside the on_load-reached handler with the bound event it would otherwise have yielded. It is the repro's enqueue_detached with the spec-to-Event conversion a real handler needs, and it is the shape a first-class version could take internally:

    async def enqueue_detached(event: EventSpec | EventCallback[()]) -> None:
        ctx = EventContext.get()
        # A fresh txid, or the fork below parents the event on this handler.
        detached = dataclasses.replace(ctx, txid=uuid.uuid4().hex[:12], parent_txid=None)
        token = EventContext.set(detached)
        try:
            await detached.enqueue(
                *Event.from_event_type(event, router_data=ctx.router_data)
            )
        finally:
            EventContext.reset(token)

    cached_states is init=False on EventContext, so dataclasses.replace gives the new context an empty one rather than sharing the dying chain's. The reason this belongs in the framework rather than in apps is that it depends on EventContext being a dataclass with these exact fields and on enqueue forking from the current context when handed none, neither of which is a promised interface.

  • A detached handler is still on the per-token sequential queue if it is a foreground handler, so the redirect target's on_load waits behind its remaining body. That matches how a client-dispatched event behaves today, so it is not a regression, but worth stating in the docs for the flag.

  • Related: Supersedes does not cancel events from different chains. #7041 discusses supersedes across chains; this is about a chain being cancelled by the navigation it itself caused.

Activity

  1. added
    enhancement
    on Sep 21, 2026
  2. deleted a comment from linear-code on Sep 21, 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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions