@@ -181,20 +181,19 @@ def _interleave_addrinfos(addrinfos, first_address_family_count=1):
181181 return reordered
182182
183183
184- _run_until_complete_running = contextvars .ContextVar (
185- '_run_until_complete_running' , default = True )
186-
187-
188184def _run_until_complete_cb (fut ):
189185 if not fut .cancelled ():
190186 exc = fut .exception ()
191187 if isinstance (exc , (SystemExit , KeyboardInterrupt )):
192188 # Issue #22429: run_forever() already finished, no need to
193189 # stop it.
194190 return
195- if not _run_until_complete_running .get ():
196- return
197- futures ._get_loop (fut ).stop ()
191+ loop = futures ._get_loop (fut )
192+ # gh-158406: the callback can outlive the run_until_complete() call
193+ # that registered it; it must not stop a later run of the loop.
194+ current = loop ._run_until_complete_fut
195+ if current is not None and current .done ():
196+ loop .stop ()
198197
199198
200199if hasattr (socket , 'TCP_NODELAY' ):
@@ -431,6 +430,7 @@ def __init__(self):
431430 self ._timer_cancelled_count = 0
432431 self ._closed = False
433432 self ._stopping = False
433+ self ._run_until_complete_fut = None
434434 self ._ready = collections .deque ()
435435 self ._scheduled = []
436436 self ._default_executor = None
@@ -713,12 +713,9 @@ def run_until_complete(self, future):
713713 # is no need to log the "destroy pending task" message
714714 future ._log_destroy_pending = False
715715
716- # gh-158406: A queued callback can outlive this call. Only let
717- # it stop the loop while this call is running.
718- context = contextvars .copy_context ()
719- context .run (_run_until_complete_running .set , True )
716+ future .add_done_callback (_run_until_complete_cb )
717+ self ._run_until_complete_fut = future
720718 try :
721- future .add_done_callback (_run_until_complete_cb , context = context )
722719 self .run_forever ()
723720 except :
724721 if new_task and future .done () and not future .cancelled ():
@@ -728,7 +725,7 @@ def run_until_complete(self, future):
728725 future .exception ()
729726 raise
730727 finally :
731- context . run ( _run_until_complete_running . set , False )
728+ self . _run_until_complete_fut = None
732729 future .remove_done_callback (_run_until_complete_cb )
733730 if not future .done ():
734731 raise RuntimeError ('Event loop stopped before Future completed.' )
0 commit comments