anyio: Assertion error when `current_task()` returns an instance of `_asyncio.Task`

Things to check first

  • I have searched the existing issues and didn’t find my bug already reported there

  • I have checked that my bug is still present in the latest release

AnyIO version

4.7.0

Python version

3.12.8

What happened?

It seems that sometimes when asyncio.current_task() is called in

https://github.com/agronholm/anyio/blob/97f064295b65dc1d7a2ded6fd24ba5be46d4c4f4/src/anyio/_backends/_asyncio.py#L2367

an instance of _asyncio.Task is returned. This then causes an assertion to be raised in

https://github.com/agronholm/anyio/blob/97f064295b65dc1d7a2ded6fd24ba5be46d4c4f4/src/anyio/_backends/_asyncio.py#L685-L694

How can we reproduce the bug?

This is triggered in our test suite (fastapi, httpx, pytest-asyncio) after upgrading to anyio 4.7.0, but I haven’t been able to come up with a MRE so hopefully this is enough to point maintainers to the potential fix.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 16 (10 by maintainers)

Commits related to this issue

Most upvoted comments

We also found related issue in our project. Here it is: https://github.com/taskiq-python/taskiq/issues/387

As people claim, it only happens on 4.7.0.

I could narrow down the MRE to this code:

import asyncio
import nest_asyncio
import anyio


async def test_func():
    await asyncio.sleep(1)


async def main():
    nest_asyncio.apply()
    async with anyio.create_task_group() as tg:
        tg.start_soon(test_func)


if __name__ == "__main__":
    asyncio.run(main())

Here is the setup:

Python 3.12.7

anyio==4.7.0
nest-asyncio==1.6.0

I tried running this code on anyio==4.6.2 and it worked out.

Would you mind verifying that the linked PR works for you?

I figured out what’s happening here. It seems that nest_asyncio.apply() replaces the asyncio modules in sys.modules with its own implementations, but not before they’ve already been imported by AnyIO. That’s why the isinstance checks fail even though the MRO looks identical to real asyncio. I could confirm this by moving nest_asyncio.apply() to the module level:

import asyncio
import nest_asyncio
import anyio


async def test_func():
    await asyncio.sleep(1)


async def main():
    async with anyio.create_task_group() as tg:
        tg.start_soon(test_func)


if __name__ == "__main__":
    nest_asyncio.apply()
    asyncio.run(main())

The above snippet works fine.

Did you run nest-asyncio or something similar that replaced asyncio.Task with PyTask?

I think the assertion should be less strict and support anything hashable with a get_coro method