Repository navigation
Closed
Description
Consider this program:
import trio
import contextlib
async def background():
assert False
async def main():
async with contextlib.AsyncExitStack() as stack:
n = await stack.enter_async_context(trio.open_nursery())
n.start_soon(background)
await trio.sleep_forever()
trio.run(main)
We get an AssertionError as expected, but the traceback looks like this:
Traceback (most recent call last):
File "/Users/dphoyes/devel/experiment.py", line 11, in main
await trio.sleep_forever()
File "/Users/dphoyes/devel/venv/lib/python3.9/site-packages/trio/_timeouts.py", line 40, in sleep_forever
await trio.lowlevel.wait_task_rescheduled(lambda _: trio.lowlevel.Abort.SUCCEEDED)
File "/Users/dphoyes/devel/venv/lib/python3.9/site-packages/trio/_core/_traps.py", line 166, in wait_task_rescheduled
return (await _async_yield(WaitTaskRescheduled(abort_func))).unwrap()
File "/Users/dphoyes/devel/venv/lib/python3.9/site-packages/outcome/_impl.py", line 138, in unwrap
raise captured_error
File "/Users/dphoyes/devel/venv/lib/python3.9/site-packages/trio/_core/_run.py", line 1172, in raise_cancel
raise Cancelled._create()
trio.Cancelled: Cancelled
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/dphoyes/devel/experiment.py", line 13, in <module>
trio.run(main)
File "/Users/dphoyes/devel/venv/lib/python3.9/site-packages/trio/_core/_run.py", line 1932, in run
raise runner.main_task_outcome.error
File "/Users/dphoyes/devel/experiment.py", line 11, in main
await trio.sleep_forever()
File "/opt/homebrew/Cellar/[email protected]/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 651, in __aexit__
raise exc_details[1]
File "/opt/homebrew/Cellar/[email protected]/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 634, in __aexit__
cb_suppress = await cb(*exc_details)
File "/Users/dphoyes/devel/venv/lib/python3.9/site-packages/trio/_core/_run.py", line 815, in __aexit__
raise combined_error_from_nursery
File "/Users/dphoyes/devel/experiment.py", line 5, in background
assert False
AssertionError
In other words, the AssertionError's __context__ is being set to that of the Cancelled exception. If we swap the use of AsyncExitStack out for the equivalent async with trio.open_nursery() as n:, we get the much simpler traceback that we'd expect.
This is admittedly a relatively benign issue, and it's not clear to me whether it's actually Trio at fault here or contextlib. In my real app though, there's enough nesting of cancellations to make this turn a 46 line traceback into a 42227 line one, which makes debugging a bit "interesting". I've worked around it by eliminating all usage of AsyncExitStack, but I thought it worth sharing anyway.
Metadata
Metadata
Assignees
Labels
No labels
Activity
m-u-xyz commentedon May 8, 2021
Uh, it may be benign but it's really blowing up our tracebacks. This is a comparatively simple example, you can easily build one where the real problem is buried in a veritable avalance of cancellations.
njsmith commentedon May 8, 2021
That output sucks, yeah.
I'm not sure if there's anything we can do about it, short of like, monkeypatching contextlib somehow... I think this is the line where the
__context__is getting added:Maybe contextlib would be up for fixing this upstream? The hack would be something like:
belm0 commentedon Jul 8, 2021
Is the next step to file something to bpo? (I don't think I could describe this well myself)
Isn't this obviously a contextlib bug-- I mean shouldn't
enter_async_context()be equivalent to an explicitasync with?what makes it a hack?
parity3 commentedon Jul 9, 2021
This should probably be in documentation somewhere right? It's gotten me several times when dealing with frameworks that started out as asyncio but were modified to work for trio and therefore have separate async setup and teardown methods.
I was using
AsyncExitStackto manage multiple separate sub-components within this framework (quart-trio). Now it makes sense why I never once got anything helpful in a traceback and had to start putting log.exception('') in wrapped try-blocks everywhere in the sub-components.I later avoided the setup/teardown hooks altogether and I do all my setup outside of asgi before even calling into hypercorn. Works perfectly.
belm0 commentedon Jul 10, 2021
I've tried opening a bpo issue: https://bugs.python.org/issue44594
belm0 commentedon Jul 12, 2021
how about changing the existing code to
raise from None?belm0 commentedon Jul 12, 2021
This doesn't seem to fix the problem (at least in my naive attempt to apply it to contextlib.py)--
__context__still ends up asCancelled.python/cpython#27089
belm0 commentedon Jul 12, 2021
To clarify the problem case, I believe Trio is doing this:
Neither ExitStack nor AsyncExcitStack are preserving the
Nonecontext.belm0 commentedon Jul 12, 2021
So back to this fix, it doesn't seem to work because
__context__is already notNonebefore raising.There may be an issue with
_fix_exception_context().https://github.com/python/cpython/blob/e14d5ae5447ae28fc4828a9cee8e9007f9c30700/Lib/contextlib.py#L667-L682
And I think the existing contextlib code is already trying to override
__context__:belm0 commentedon Jul 12, 2021
Looking at
_fix_exception_context(), there is not much wiggle room. Ultimately it's always going to overwrite__context__ofnew_excunless__context__is already set to the old exception.The only way out seems to modify the
Nonehandling, from:to
but I'm not sure whether that change can be rationalized. I suspect that
__context__will already be filled in by the time ExitStack gets the exception, so the implementation's current handling ofNoneis not necessary, and not handling the case they thought it was.belm0 commentedon Sep 30, 2021
I'll try being histrionic:
this is destroying our developer experience, killing tooling such as aggregation of unhandled exceptions by Sentry, and undoing all the effort of https://vorpus.org/blog/beautiful-tracebacks-in-trio-v070/
belm0 commentedon Oct 1, 2021
we're literally having 150,000 line backtraces in our app
belm0 commentedon Oct 5, 2021
contextlib fix is merged to cpython head for python 3.11, and will be backported to 3.10 and 3.9
For earlier versions (which are retired or only accepting security patches), monkeypatch of
AsyncExitStack.__aexit__or derived class like the following will work (confirmed on Python 3.8).Zac-HD commentedon Mar 21, 2025
Closing this as partially fixed in python/cpython#27089, with future work described in python/cpython#102201.