Skip to content

gh-158406: Fix run_until_complete making the next run stop early - #158450

Open
tjkuson wants to merge 3 commits into
python:mainfrom
tjkuson:gh-158406
Open

tjkuson wants to merge 3 commits into
python:mainfrom
tjkuson:gh-158406

Conversation

@tjkuson

@tjkuson tjkuson commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

run_until_complete() now registers its done callback with a copy of the current context in which a private contextvar marks the call as running (and is cleared when the call returns). Thus, a callback that is still queued when the call returns no longer stops a later run_until_complete() or run_forever().

The registered callback is still _run_until_complete_cb. My first attempt used a closure instead, which is simpler, but subtly broke AnyIO (anyio.to_thread started a new thread per task and anyio.to_process jobs could fail). With this version AnyIO behaves as it does on main.

Closes gh-158406.

@tjkuson tjkuson changed the title gh-158406: Fix asyncio run_until_complete making the next run stop early gh-158406: Fix run_until_complete making the next run stop early Sep 29, 2026
@tjkuson
tjkuson marked this pull request as ready for review October 2, 2026 20:55
Comment thread Lib/test/test_asyncio/test_runners.py Resolved
future._log_destroy_pending = False

future.add_done_callback(_run_until_complete_cb)
# gh-158406: A queued callback can outlive this call. Only let

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.

hmmm, you said in the pr that anyio relies on the _run_until_complete_cb. I think there should be a way to fix this and keep the same callback. Maybe use contextvars? did you try that?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I didn't try that but it seems to work (pushed in 3945a34, can revert the commit if we want to go back to the closure approach).

The callback approach is more compatible with AnyIO and easier to backport than my first closure attempt, but at the cost of being the code being more complex (IMO).

@tjkuson

tjkuson commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the review, @deadlovelll!

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

There is a much simpler fix for this:

@@ -188,7 +188,11 @@ def _run_until_complete_cb(fut):
             # Issue #22429: run_forever() already finished, no need to
             # stop it.
             return
-    futures._get_loop(fut).stop()
+    loop = futures._get_loop(fut)
+    # gh-158406: the callback can outlive the run_until_complete() call
+    # that registered it; it must not stop a later run of the loop.
+    if loop._run_until_complete_fut is fut:
+        loop.stop()
 
 
@@ -431,6 +435,7 @@ def __init__(self):
         self._timer_cancelled_count = 0
         self._closed = False
         self._stopping = False
+        self._run_until_complete_fut = None
         self._ready = collections.deque()
         self._scheduled = []
         self._default_executor = None
@@ -713,6 +718,7 @@ def run_until_complete(self, future):
             future._log_destroy_pending = False
 
         future.add_done_callback(_run_until_complete_cb)
+        self._run_until_complete_fut = future
         try:
             self.run_forever()
         except:
@@ -723,6 +729,7 @@ def run_until_complete(self, future):
                 future.exception()
             raise
         finally:
+            self._run_until_complete_fut = None
             future.remove_done_callback(_run_until_complete_cb)
         if not future.done():
             raise RuntimeError('Event loop stopped before Future completed.')

@bedevere-app

bedevere-app Bot commented Nov 26, 2026

Copy link
Copy Markdown

A Python core developer has requested some changes be made to your pull request before we can consider merging it. If you could please address their requests along with any other requests in other reviews from core developers that would be appreciated.

Once you have made the requested changes, please leave a comment on this pull request containing the phrase I have made the requested changes; please review again. I will then notify any core developers who have left a review that you're ready for them to take another look at this pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

asyncio: interrupting run_until_complete makes the next run stop early

3 participants