← 输入框|github.com|刷新
Skip to content

Self-referential exception.__context__ #162738

Backlog

Description

@m-u-xyz

Bug report

IMHO exc.__context__ is exc should not happen.

This reproducer might seem somewhat convoluted, but its conditions can occur naturally in sufficiently-complex programs.

"""Natural reproducer for anyio's task_done hang: a task-group child whose
CancelledError ends up with a self-referential __context__ — created
entirely by asyncio's cancellation delivery, contextlib's
AsyncExitStack/_fix_exception_context, and the interpreter. The test code
never touches __context__."""
import contextlib
from asyncio import TaskGroup, Event, current_task, sleep, run


class ReRaise:
    """Mirrors anyio's TaskGroup.__aexit__ / CancelScope.__exit__:
    re-raises the propagating exception ('raise exc_val')."""

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc, tb):
        if exc is not None:
            raise exc


async def child(evt):
    # The child uses an AsyncExitStack with a re-raising exit plus a callback
    # that re-raises the second cancellation caught below
    s = contextlib.AsyncExitStack()
    s.push_async_exit(ReRaise())  # runs LAST: re-raises the pending exception
    held = []

    async def re_raise_second(*args):
        # Re-raises the second cancellation caught below, the way nested
        # application cleanup re-raises a caught exception
        if held:
            raise held[0]

    s.push_async_callback(re_raise_second)  # runs FIRST
    try:
        async with s:
            try:
                e = Event()
                await e.wait()  # cancelled (e1) by the task-level cancel
            except BaseException:
                # caught → active. Second cancellation: host-task
                # cancellation delivered at the next await:
                task = current_task()
                task.cancel("host-cancel")  # e2 — delivered by asyncio below
                try:
                    await evt.wait()  # e2 delivered here by asyncio,
                                      # chained to e1 (asyncio's assignment)
                except BaseException as exc:
                    held.append(exc)
                # e2 caught and held; re-raise e1 out of the with-block so
                # the stack unwinds with it via the async-with protocol; the
                # re-raise of the held e2 by the first callback and the
                # re-raise of the pending exception by the last exit handler
                # then make contextlib's context repair reference the
                # exception itself
                raise
    except BaseException as e:
        if e.__context__ == e:
            raise Exception("Exception Cycle")
        raise


async def main():
    async with TaskGroup() as tg:
        e = Event()
        t = tg.create_task(child(e))
        await sleep(0.1)
        t.cancel()              # first cancellation (e1) for the child
        await sleep(0.1)


if __name__ == "__main__":
    run(main())
    print("OK: exited cleanly", flush=True)

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Nov 27, 2026
  2. added
    stdlib
    on Nov 27, 2026
  3. deadlovelll commented on Nov 28, 2026

    @deadlovelll
    Contributor

    hey. i just checked out, i think this is legit bug

    I just got a simpler repro for this

    import asyncio
    from contextlib import AsyncExitStack
    
    async def reraise(exc_type, exc, tb):
        raise exc
    
    async def cleanup():
        int("x")
    
    async def main():
        try:
            async with AsyncExitStack() as stack:
                stack.push_async_exit(reraise)
                stack.push_async_callback(cleanup)
                raise RuntimeError("body")
        except ValueError as exc:
            print(exc.__context__ is exc)
    
    asyncio.run(main())

    AsyncExitStack (aka ExitStack) docs says that it behaves like nested with blocks, but if we try it:

    import asyncio
    from contextlib import AbstractAsyncContextManager
    
    class Reraise(AbstractAsyncContextManager):
        async def __aexit__(self, exc_type, exc, tb):
            raise exc
    
    class Cleanup(AbstractAsyncContextManager):
        async def __aexit__(self, exc_type, exc, tb):
            int("x")
    
    async def main():
        try:
            async with Reraise():
                async with Cleanup():
                    raise RuntimeError("body")
        except ValueError as exc:
            print(exc.__context__ is exc)
            print(repr(exc.__context__))
    
    asyncio.run(main())

    We don't get the cycle

    False
    RuntimeError('body')
    
  4. deadlovelll commented on Nov 28, 2026

    @deadlovelll
    Contributor

    @m-u-xyz are you planning to work on this issue? otherwise i can pick it up if you don't mind =)

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

    stdlibtopic-asynciotype-bug

    Projects

    • Status
      Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions