Skip to content

asyncio exception handler called with incorrect context #96704

Description

@kumaraditya303

Reproducer:

import asyncio
import contextvars

name = contextvars.ContextVar('name', default='foo')


def exc_handler(*args):
    assert name.get() == 'bar'


async def task():
    name.set('bar')
    1/0


async def main():
    loop = asyncio.get_running_loop()
    loop.set_exception_handler(exc_handler)
    asyncio.create_task(task())

asyncio.run(main())

On main:

Unhandled error in exception handler
context: {'message': 'Task exception was never retrieved', 'exception': ZeroDivisionError('division by zero'), 'future': <Task finished name='Task-2' coro=<task() done, defined at /workspaces/cpython/main.py:11> exception=ZeroDivisionError('division by zero')>}
Traceback (most recent call last):
  File "/workspaces/cpython/Lib/asyncio/base_events.py", line 1797, in call_exception_handler
    self._exception_handler(self, context)
  File "/workspaces/cpython/main.py", line 8, in exc_handler
    assert name.get() == 'bar'
AssertionError

The exception handler is called with incorrect context hence the AssertionError. It should called with the same context as the task.
My use case is retrieving the current request id from the context var if there are any unhandled error but because of this bug, I always get the default value.

Activity

  1. gvanrossum commented on Sep 10, 2022

    @gvanrossum
    Member

    Maybe you can retrieve the task from the dict arg to the handler and use its ‘_context’ attribute? Or maybe we need to add a ‘get_context()’ method to Task? That’s a complex API change b/c custom task implementations though. Otherwise the implementation seems far from easy, given how many places call this?

  2. kumaraditya303 commented on Sep 11, 2022

    @kumaraditya303
    ContributorAuthor

    I only care about correct context in the task finalizer so that exception handler is called with correct context. I don't want to rely on any private attribute and it can change.

  3. added a commit that references this issue on Sep 11, 2022
  4. gvanrossum commented on Sep 11, 2022

    @gvanrossum
    Member

    Your wish is my command. :-) (Sorry if you had a PR already, if you did we can compare notes, if you didn't you can review mine. :-)

  5. added 2 commits that reference this issue on Oct 4, 2022
  6. Repository owner moved this from Todo to Done in asyncioon Oct 5, 2022
  7. added a commit that references this issue on Oct 6, 2022
  8. added a commit that references this issue on Oct 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

3.10 (EOL)end of life3.11only security fixes3.12only security fixestopic-asynciotype-bugAn unexpected behavior, bug, or error

Projects

  • Status
    Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions