Repository navigation
Description
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__ = Ato mimic what would have happened if these were actually nestedwithblocks - 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(becausesplit()preserves the__context__) - This
Cbecomes thecombined_error_from_nurserythat 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 setsC.__context__.__context__ = B. Oops, that's the same thing asA.__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
oremanj commentedon Feb 24, 2023
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.
oremanj commentedon Feb 24, 2023
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 nestedwithstatements. (cc @belm0)prints:
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?
oremanj commentedon Feb 24, 2023
Filed python/cpython#102201 upstream. Not sure if there's anything more to be done on the Trio side of things. @njsmith @belm0