Skip to content

Trio + standard contextlib tools can create an exception __context__ cycle -> interpreter hang #2577

Closed

Description

@oremanj

Consider the following program:

import trio
from contextlib import asynccontextmanager, AsyncExitStack

class DummyResource(trio.abc.AsyncResource):
    async def aclose(self):
        await trio.lowlevel.checkpoint()

@asynccontextmanager
async def nested():
    async with trio.open_nursery():
        yield

async def raiser(v):
    raise ValueError(v)

async def main():
    async with AsyncExitStack() as stack:
        await stack.enter_async_context(nested())
        nursery = await stack.enter_async_context(trio.open_nursery())
        nursery.start_soon(raiser, 1)
        nursery.start_soon(raiser, 2)
        scope = stack.enter_context(trio.CancelScope())
        await stack.enter_async_context(DummyResource())
        scope.cancel()

try:
    trio.run(main)
except Exception as ex:
    print(ex.__context__.__context__.__context__.__context__ is ex.__context__.__context__)

If you run it on Python before 3.11, it will print True, i.e., it creates a __context__ cycle. If you raise another exception within the except clause, the interpreter will hang. (3.11 refuses to create the cycle because of python/cpython@d5c2174, but AFAICT the behavior that would have generated the cycle still exists.)

The execution proceeds as follows:

  • DummyResource.aclose() raises Cancelled; call this exception object "A"
  • The cancel scope doesn't suppress the Cancelled because its parent (the inner nursery with the 'raiser' tasks) is also cancelled (due to the errors that were raised there)
  • The inner nursery with the 'raiser' tasks raises (from its __aexit__) a MultiError with two ValueErrors; call this exception object "B"
  • AsyncExitStack sets B.__context__ = A to mimic what would have happened if these were actually nested with blocks
  • The current exception (B) gets thrown into nested() and presents itself as a nested-child exception to the outer nursery's __aexit__
  • Aggregating the nested-child exception with the other task exceptions (none) produces B again (since strict_exception_groups=False)
  • Splitting off the Cancelled exceptions (none) from B produces another MultiError, which we'll call "C", with the same contents and the same C.__context__ = A (because split() preserves the __context__)
  • This C becomes the combined_error_from_nursery that gets raised out of __aexit__. __aexit__ carefully avoids changing its __context__.
  • AsyncExitStack sees that C.__context__ is already set, so it chases the pointer and sets C.__context__.__context__ = B. Oops, that's the same thing as A.__context__ = B. Boom, there's your cycle.

You can unbreak this specific example by making exceptiongroup.ExceptionGroup.split() return the original exception group object, rather than a copy, if nothing was split off from it. But this doesn't match what the built-in ExceptionGroup in 3.11 does, and it seems like it is probably possible to make that split() non-trivial which would break this again, e.g. by putting the CancelScope outside the 'raiser' nursery so that it mixes in a Cancelled with the ValueErrors.

I'm at a loss for the "right" way to fix this. Anyone got an idea?

Activity

  1. oremanj commented on Feb 24, 2023

    @oremanj
    MemberAuthor

    Apparently this is only an issue on 3.8, because 3.9 and later have python/cpython#88760, which happens to resolve this. See also #2001.

  2. oremanj commented on Feb 24, 2023

    @oremanj
    MemberAuthor

    While the fix for python/cpython#88760 happened to fix this, that fix is not fully correct: it can result in missing __context__ compared to the equivalent nested with statements. (cc @belm0)

    $ cat chainer.py
    from contextlib import contextmanager, ExitStack
    import traceback
    
    class raise_on_exit:
        def __init__(self, ty): self._ty = ty
        def __enter__(self): pass
        def __exit__(self, *exc): raise self._ty()
    
    def example_regular():
        with raise_on_exit(KeyError):
            with raise_on_exit(ValueError):
                pass
    
    def example_stacked():
        with ExitStack() as stack:
            stack.enter_context(raise_on_exit(KeyError))
            stack.enter_context(raise_on_exit(ValueError))
    
    try:
        example_regular()
    except Exception:
        traceback.print_exc()
    print("--------")
    try:
        example_stacked()
    except Exception:
        traceback.print_exc()
    

    prints:

    $ python3.10 chainer.py
    Traceback (most recent call last):
      File "/mnt/scooter/scratchq/infra/oremanj/remote/dev/chainer.py", line 16, in example_regular
        with raise_on_exit(ValueError):
      File "/mnt/scooter/scratchq/infra/oremanj/remote/dev/chainer.py", line 12, in __exit__
        raise self._ty()
    ValueError
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "[...]/chainer.py", line 25, in <module>
        example_regular()
      File "[...]/chainer.py", line 15, in example_regular
        with raise_on_exit(KeyError):
      File "[...]/chainer.py", line 12, in __exit__
        raise self._ty()
    KeyError
    --------
    Traceback (most recent call last):
      File "[...]/chainer.py", line 32, in <module>
        example_stacked()
      File "[...]/chainer.py", line 20, in example_stacked
        with ExitStack() as stack:
      File "/usr/lib/python3.10/contextlib.py", line 576, in __exit__
        raise exc_details[1]
      File "/usr/lib/python3.10/contextlib.py", line 561, in __exit__
        if cb(*exc_details):
      File "[...]/chainer.py", line 12, in __exit__
        raise self._ty()
    KeyError
    

    The problem is that, when there is no active exception entering ExitStack.__exit__ (which includes the example upthread), you can't tell the difference between "None in the context chain means you wanted to chain with the exception that was passed to your __exit__" and "None in the context chain means you didn't want to chain". So, fixing the regression in this comment would re-break the example in the issue description.

    Is there anything Trio itself can do about this?

  3. oremanj commented on Feb 24, 2023

    @oremanj
    MemberAuthor

    Filed python/cpython#102201 upstream. Not sure if there's anything more to be done on the Trio side of things. @njsmith @belm0

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions