Skip to content

asyncio event loop hangs if an eager task fails to start #157301

Closed

Description

@deadlovelll

Bug report

Bug description:

Repro 1 - context not a context:

import asyncio

async def child(): 
    return 1

async def main():
    asyncio.Task(child(), loop=asyncio.get_running_loop(),
                 eager_start=True, context=2.14)

asyncio.run(main())

Actually the repro will hang, and the displayed exception is not readable and informative about what was wrong:

➜  cpython git:(main) ✗ ./python.exe repro.py
Exception in callback <_asyncio.TaskStepMethWrapper object at 0x104911ba0>()
handle: <Handle <_asyncio.TaskStepMethWrapper object at 0x104911ba0>()>
Traceback (most recent call last):
  File "/Users/timofeiivankov/cpython/Lib/asyncio/events.py", line 91, in _run
    self._context.run(self._callback, *self._args)
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Invalid attempt to leave task <Task finished name='Task-1' coro=<main() done, defined at /Users/timofeiivankov/cpython/repro.py:6> exception=TypeError('an instance of Context was expected')> while task <Task pending name='Task-2' coro=<child() running at /Users/timofeiivankov/cpython/repro.py:3>> is entered.

Repro 2 - a valid Context that is already entered

import asyncio, contextvars

async def child():
    return 1

async def main():
    loop = asyncio.get_running_loop()
    ctx = contextvars.copy_context()
    ctx.run(lambda: asyncio.Task(child(), loop=loop, eager_start=True, context=ctx))

asyncio.run(main())

Also hangs - type check alone doesn't cover this path

Expected behaviour: the constructor raises and the loop stays usable

TypeError: a contextvars.Context was expected, got float

Proposed fix: add type check for context, and restore the current task in the _PyContext_Enter failure branch of task_eager_start.

I have fix for this already

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added 2 commits that reference this issue on Sep 19, 2026
  2. moved this from Todo to Done in asyncioon Sep 19, 2026
  3. added a commit that references this issue on Sep 28, 2026
  4. added a commit that references this issue on Sep 29, 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

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions