Repository navigation
Description
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 throughEventContext.fork(), which always setsparent_txid, so it is registered as a child of the yielding chain (parent_future.add_child(tracked)inEventProcessor.enqueue)._on_future_donecascades a cancellation to every child future and to the running task in_tasks.So a handler reached from a page's
on_loadthat doesyield rx.redirect("/b")and then keeps working, or chains more work, is cancelled by the navigation its own redirect caused: the/bpage'son_load_internalsupersedes the still-running chain for the same token. The work dies with aCancelledErrorthat nothing logs. The intent of Long runningon_loadevents 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=Truedoes not help. The task is parented inenqueuebeforeis_backgroundis consulted in the queue loop, and_create_event_taskregisters it in_taskseither way, so the cascade cancels it.EventContext.get().enqueue(event)from inside the handler is the same path ayieldtakes (_route_events→ctx.enqueue), so the event is a child too.
The only server-side workaround is to build a parent-less
EventContextby hand and set it as the current context around the enqueue, which reaches intoreflex_baseinternals. The client-side workaround isrx.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_loadwithout being silently cancelled and without either workaround. The common shape is: a page'son_loadcreates 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=Noneplus a freshtxidwhen forking the context for the enqueued event, soenqueuefinds no parent future and registers the chain as a root. The following runs against the realEventProcessorwith 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_loadevents continue running after page navigation #6593 landed; 0.9.8 has nosupersedes). -
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'senqueue_detachedwith the spec-to-Eventconversion 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_statesisinit=FalseonEventContext, sodataclasses.replacegives 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 onEventContextbeing a dataclass with these exact fields and onenqueueforking 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_loadwaits 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
supersedesacross chains; this is about a chain being cancelled by the navigation it itself caused.
Activity