GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — asyncio.run_coroutine_threadsafe leaves underlying cancelled asyncio task running · Issue #105836 · python/cpython

asyncio.run_coroutine_threadsafe leaves underlying cancelled asyncio task running #105836

New issue
Copy link
New issue
Copy link
Closed
Closed
asyncio.run_coroutine_threadsafe leaves underlying cancelled asyncio task running#105836
Copy link
Assignees
gvanrossum
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error

Description

@gh-andre
gh-andre
opened on Jun 15, 2023
Issue body actions

Bug report

When an asyncio task is created from another thread via asyncio.run_coroutine_threadsafe, a concurrent.futures.Future is returned, which wraps an underlying asyncio.Task.

In a typical use future.result() or future.exception() can be used to wait for completion. However, when the returned future is cancelled, no built-in mechanism is provided to wait for the underlying asyncio task to complete, leaving it running when application is terminated, possibly accessing dangling data.

This is an example that reproduces what is described above. There's no way to make it smaller without losing some aspect of what's going on.

The output of this code is as follows:

About to create an asyncio task
asyncio task is set up
asyncio task is running
Task cancelled (callback)
Cancelled?: True
Done?: True
Cannot access task.result()
Cannot access task.exception()
All done. No app code should run after this.
asyncio task is cancelled; rethrowing...   <-- runs after the app is shut down
Setting the asyncio task event             <-- same

Perhaps concurrent.futures.Future.cancelled() should have a timeout to wait for the underlying asyncio task to complete or some additional method provided for that.

Here's the sample code.

import asyncio
import concurrent.futures
import threading

class MyApp:
    def __init__(self) -> None:
        self.task: concurrent.futures.Future[int]|None = None

        self.task_event = asyncio.Event()
        self.task_event.clear()

    # An asyncio task that runs in the specified event loop
    async def process_task(self) -> int:
        try:
            self.task_event.clear()
            print("asyncio task is running")
            await asyncio.sleep(10)
            print("asyncio task is finished")
            return 123
        except asyncio.CancelledError:
            print("asyncio task is cancelled; rethrowing...")
            raise
        finally:
            print("Setting the asyncio task event")
            self.task_event.set()

    # Called immediately from task.cancel(), before the underlying
    # asyncio task completes.
    def task_done(self, future: concurrent.futures.Future[int]) -> None:
        if future.cancelled():
            print("Task cancelled (callback)")
        elif future.exception() is not None:
            print("Task error %s (callback)" % future.exception())
        else:
            print("Task is done with result %d (callback)" % future.result())

    def start_async_task(self, thread_event: threading.Event) -> None:

        print("About to create an asyncio task")

        self.task = asyncio.run_coroutine_threadsafe(self.process_task(), asyncio.get_running_loop())
        self.task.add_done_callback(self.task_done)

        print("asyncio task is set up")
        thread_event.set()

    # This method is supposed to be the last call to the application,
    # which shuts down all services and cancels all outstanding work.
    async def shutdown(self) -> None:

        # Calls the done callback immediately and returns before the
        # future cancels the underlying asyncio task, rendering the
        # future unusable via standard methods.
        self.task.cancel()

        # This event compensates for lack of ability to wait for the
        # underlying asyncio task. Without this wait, asyncio task
        # runs after the code that manages all this is gone.
        #
        # Perhaps Future.cancel() should provide this functionality?
        #
        #print("Waiting for a task to complete")
        #await self.task_event.wait()

        # returns True, while underlying asyncio task is still running
        print("Cancelled?: %s" % self.task.cancelled())
        print("Done?: %s" % self.task.done())

        # supposed to wait for result, but because it's cancelled, will throw
        try:
            print("Result?: %d" % self.task.result())
        except concurrent.futures.CancelledError:
            print("Cannot access task.result()")

        # or wait for exception, but because it's cancelled, will throw as well
        try:
            print("Exception?: %s" % str(self.task.exception()))
        except concurrent.futures.CancelledError:
            print("Cannot access task.exception()")

async def main() -> None:
    myapp = MyApp()

    thread_event = threading.Event()
    thread_event.clear()

    # emulates some worker thread (e.g. APScheduler)
    runner = threading.Thread(target=myapp.start_async_task, args=[thread_event])
    runner.run()

    thread_event.wait()

    await asyncio.sleep(1)

    await myapp.shutdown()

    await asyncio.sleep(0)

    print("All done. No app code should run after this.")

asyncio.run(main())

If the wait call under Waiting for a task to complete is uncommented, which would simulate having waiting implemented in Future.cancelled(), it would work as expected.

Your environment

  • CPython versions tested on: 3.10.10
  • Operating system and architecture: Microsoft Windows [Version 10.0.19045.3086]

Linked PRs

  • gh-105836: Fix asyncio.run_coroutine_threadsafe leaving underlying cancelled asyncio task running #141696
  • [3.14] gh-105836: Fix asyncio.run_coroutine_threadsafe leaving underlying cancelled asyncio task running (GH-141696) #142358
  • [3.13] gh-105836: Fix asyncio.run_coroutine_threadsafe leaving underlying cancelled asyncio task running (GH-141696) #142359

Activity

Next
  1. gh-andre
    added
    type-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
    on Jun 15, 2023
  2. AlexWaygood
    added
    topic-asyncio
    on Jun 15, 2023
  3. github-project-automation
    added this to asyncioon Jun 15, 2023
  4. github-project-automation
    moved this to Todo in asyncioon Jun 15, 2023
  5. gvanrossum commented on Jun 16, 2023

    @gvanrossum
    gvanrossum
    on Jun 16, 2023
    Member
    More actions

    Thanks for the clear explanation of the problem. As you probably already know, there is not that much code in run_coroutine_threadsafe. Perhaps you are interested in submitting a PR that fixes your issue?

  6. gh-andre commented on Jun 17, 2023

    @gh-andre
    gh-andre
    on Jun 17, 2023
    Author
    More actions

    @gvanrossum Thanks for commenting. I had a look today and it's more intricate in the way that it manages futures, tasks, loops and callbacks than I would want to engage with. I also suspect your architects would need to design a consistent way to handle cancellation, as there could be a few different ways.

    For example, cancel() can return right away and then the done callback can be called when it's done, or cancelled() can be reworked to use a timeout, similar to result(), or a new method may be introduced to wait for the cancellation, or cancel() may return an event to wait on, etc.

  7. gvanrossum commented on Jun 17, 2023

    @gvanrossum
    gvanrossum
    on Jun 17, 2023
    Member
    More actions

    That's fair. Alas, I haven't looked at this code in nearly a decade. And in all that time, nobody has reported this problem before. I'm not sure I feel very motivated to prioritize a fix now. Sorry!

  8. gh-andre commented on Jun 17, 2023

    @gh-andre
    gh-andre
    on Jun 17, 2023
    Author
    More actions

    @gvanrossum Sure. I worked it around with an event, like in the example. I guess anyone who stumbles on this issue can copy the approach. I just thought you might like to know. I will close it now then.

  9. gh-andre
    closed this as completedon Jun 17, 2023
  10. github-project-automation
    moved this from Todo to Done in asyncioon Jun 17, 2023
  11. gvanrossum commented on Jun 17, 2023

    @gvanrossum
    gvanrossum
    on Jun 17, 2023
    Member
    More actions

    Someone might want to fix it. Reopening.

  12. gvanrossum
    reopened this on Jun 17, 2023
  13. github-project-automation
    moved this from Done to In Progress in asyncioon Jun 17, 2023
  14. rkooo567 commented on Oct 4, 2023

    @rkooo567
    rkooo567
    on Oct 4, 2023
    More actions

    I faced the same issue while developing a feature from https://github.com/ray-project/ray. Basically, future.result() (returned by run_coroutine_threadsafe) raises an exception immediately if future.cancel() is called although the underlying coroutine still runs. I also worked around the issue using asyncio.Event. I think this behavior is a little unintuitive.

    Reacted by Andre
  15. edoakes
    added a commit that references this issue on Apr 11, 2024

    [serve] Prevent ASGI `receive()` from hanging on disconnects (#44647)

    905ca61
  16. 5 remaining items

  17. gvanrossum commented on Nov 18, 2025

    @gvanrossum
    gvanrossum
    on Nov 18, 2025
    Member
    More actions

    Thank you! Looking forward to your contribution.

  18. iaalm commented on Nov 24, 2025

    @iaalm
    iaalm
    on Nov 24, 2025
    Contributor
    More actions

    Could anyone help to review the PR?

  19. gvanrossum commented on Nov 24, 2025

    @gvanrossum
    gvanrossum
    on Nov 24, 2025
    Member
    More actions

    On it!

  20. gvanrossum
    self-assigned this
    on Nov 25, 2025
  21. picnixz
    added
    stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
    on Nov 25, 2025
  22. iaalm commented on Nov 25, 2025

    @iaalm
    iaalm
    on Nov 25, 2025
    Contributor
    More actions

    PR updated. Except the PR, there's one more thing I want to double check (should I open another issue?)

    For following code:

    import asyncio
    
    
    async def process_task():
        try:
            await asyncio.sleep(0.1)
            return 123
        except asyncio.CancelledError:
            print("Inner task is cancelled; rethrowing...")
            raise
    
    def task_done(future):
        print("Done callback called.")
    
    
    async def main():
        t = asyncio.run_coroutine_threadsafe(process_task(), asyncio.get_running_loop())
        # Following code gives expected result
        # t = asyncio.create_task(process_task())
        t.add_done_callback(task_done)
        await asyncio.sleep(0.05)
        t.cancel()
    
        await asyncio.sleep(0.05)
    
        print("All done. No app code should run after this.")
    
    asyncio.run(main())

    Gives

    Done callback called.
    Inner task is cancelled; rethrowing...
    All done. No app code should run after this.
    

    People use add_done_callback to claim the task is done or maybe do some clean up. It seems wired that callback is called before actually task cancelled. asyncio.create_task gives correct behavior IMO.

    I also checked the code and see in concurrent.futures.Future.cancel calls all done callback directly. But in my opinion, asyncio.Future.cancel just means the "trigger" of cancellation. Is it same for concurrent.futures.Future.cancel?

    I'm happy to make/update PR for this, just confirm this behavior is not expected.

  23. sergey-miryanov commented on Nov 25, 2025

    @sergey-miryanov
    sergey-miryanov
    on Nov 25, 2025
    Contributor
    More actions

    cc @kumaraditya303

  24. gvanrossum commented on Nov 25, 2025

    @gvanrossum
    gvanrossum
    on Nov 25, 2025
    Member
    More actions

    Except the PR, there's one more thing I want to double check (should I open another issue?)

    In that example, the two different ways to construct t return different object types. The code as shown sets t to a concurrent.futures.Future. The commented-out code sets to to an asyncio.Future. These are not the same type! (Just partial duck types for each other.) So you also set the done callback on that t. (I know. The APIs are -- intentionally -- compatible, but this can cause confusion. Try adding print(future) to task_done.

    In both cases the task gets scheduled on the current loop (which feels like a somewhat odd way of using run_coroutine_threadsafe). When you schedule the task directly using create_task, you cancel the task directly, and the flow is as follows:

    • process_task(), which is awaiting the sleep(0.1), catches the CancelledError, prints its message, and re-raises it.
    • the re-raise ends the task, marks it as cancelled, and calls its done callback (task_done).

    But when you create a concurrent.futures.Future, the thing you cancel is that Future, and upon cancellation, it schedules the cancellation of the asyncio task. This is done by _chain_future which sets callbacks that pass state between the c.f.Future and the asyncio.Future, in each direction -- e.g. cancelling one future/task when the other is cancelled.

    So what you observe is expected. If you wanted the asyncio task to be cancelled first, ideally you'd cancel the inner task, but short of the inner task calling asyncio.current_task() and saving that in a global, there's no way to access that task.

    Reacted by Kaisheng Xu
  25. kumaraditya303
    added a commit that references this issue on Dec 6, 2025

    gh-105836: Fix `asyncio.run_coroutine_threadsafe` leaving underlying …

    14715e3
  26. miss-islington
    added 2 commits that reference this issue on Dec 6, 2025

    pythongh-105836: Fix `asyncio.run_coroutine_threadsafe` leaving under…

    1863bd2

    pythongh-105836: Fix `asyncio.run_coroutine_threadsafe` leaving under…

    8bb3a35
  27. kumaraditya303
    added 2 commits that reference this issue on Dec 9, 2025

    [3.13] gh-105836: Fix `asyncio.run_coroutine_threadsafe` leaving unde…

    b2fff0e

    [3.14] gh-105836: Fix `asyncio.run_coroutine_threadsafe` leaving unde…

    5d5d92b
  28. kumaraditya303
    closed this as completedon Dec 9, 2025
  29. github-project-automation
    moved this from Todo to Done in asyncioon Dec 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

  • @gvanrossum
    gvanrossum

Labels

stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error

Projects

  • asyncio
    Status
    Done
    Show more project fields

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.