Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

'async with' somehow suppresses unawaited coroutine warnings #76884

Closed
njsmith opened this issue Jan 29, 2018 · 13 comments
Closed

'async with' somehow suppresses unawaited coroutine warnings #76884

njsmith opened this issue Jan 29, 2018 · 13 comments
Labels
3.7 (EOL) end of life 3.8 only security fixes interpreter-core (Objects, Python, Grammar, and Parser dirs)

Comments

@njsmith
Copy link
Contributor

njsmith commented Jan 29, 2018

BPO 32703
Nosy @ncoghlan, @giampaolo, @njsmith, @asvetlov, @1st1, @xgid
PRs
  • bpo-32703: Fix coroutine resource warning in case where there's an error #5410
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = <Date 2018-01-29.19:32:15.527>
    created_at = <Date 2018-01-29.04:06:16.801>
    labels = ['interpreter-core', '3.7', '3.8']
    title = "'async with' somehow suppresses unawaited coroutine warnings"
    updated_at = <Date 2018-01-31.17:10:01.083>
    user = 'https://github.com/njsmith'

    bugs.python.org fields:

    activity = <Date 2018-01-31.17:10:01.083>
    actor = 'xgdomingo'
    assignee = 'none'
    closed = True
    closed_date = <Date 2018-01-29.19:32:15.527>
    closer = 'yselivanov'
    components = ['Interpreter Core']
    creation = <Date 2018-01-29.04:06:16.801>
    creator = 'njs'
    dependencies = []
    files = []
    hgrepos = []
    issue_num = 32703
    keywords = ['patch']
    message_count = 13.0
    messages = ['311052', '311053', '311058', '311060', '311061', '311062', '311064', '311065', '311066', '311071', '311072', '311157', '311158']
    nosy_count = 6.0
    nosy_names = ['ncoghlan', 'giampaolo.rodola', 'njs', 'asvetlov', 'yselivanov', 'xgdomingo']
    pr_nums = ['5410']
    priority = 'normal'
    resolution = 'fixed'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = None
    url = 'https://bugs.python.org/issue32703'
    versions = ['Python 3.5', 'Python 3.6', 'Python 3.7', 'Python 3.8']

    @njsmith
    Copy link
    Contributor Author

    njsmith commented Jan 29, 2018

    Example (minimal version of python-trio/trio#425):

    -----

    async def open_file():
        pass
    
    async def main():
        async with open_file():  # Should be 'async with await open_file()'
            pass
    
    coro = main()
    coro.send(None)

    Here we accidentally left out an 'await' on the call to 'open_file', so the 'async with' tries to look up 'CoroutineType.__aexit__', which obviously doesn't exist, and the program crashes with an AttributeError("__aexit__"). Yet weirdly, this doesn't trigger a warning about 'open_file' being unawaited. It should!

    Yury's theory: maybe BEFORE_ASYNC_WITH's error-handling path is forgetting to DECREF the object.

    @njsmith njsmith added topic-asyncio 3.7 (EOL) end of life 3.8 only security fixes labels Jan 29, 2018
    @njsmith
    Copy link
    Contributor Author

    njsmith commented Jan 29, 2018

    Yury's theory: maybe BEFORE_ASYNC_WITH's error-handling path is forgetting to DECREF the object.

    Nope, that doesn't seem to be it. This version prints "refcount: 2" twice, *and* prints a proper "was never awaited" warning:

    -----

    import sys
    
    async def open_file():
        pass
    
    async def main():
        open_file_coro = open_file()
        print("refcount:", sys.getrefcount(open_file_coro))
    try:
        async with open_file_coro:
            pass
    except:
        pass
    
        print("refcount:", sys.getrefcount(open_file_coro))
    
    coro = main()
    try:
        coro.send(None)
    except:
        pass

    @1st1 1st1 added interpreter-core (Objects, Python, Grammar, and Parser dirs) and removed topic-asyncio labels Jan 29, 2018
    @ncoghlan
    Copy link
    Contributor

    Looking at the ceval code, I think Yury's theory is plausible, and we may also be leaving the interpreter's internal stack in a dubious state. Things then get cleaned up if you wrap the async with in a try/except or try/finally:

    ==============

    >>> async def try_main():
    ...     try:
    ...         async with open_file():
    ...             pass
    ...     finally:
    ...         pass
    ... 
    >>> try_main().send(None)
    sys:1: RuntimeWarning: coroutine 'open_file' was never awaited
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in try_main
    AttributeError: __aexit__

    ==============

    Unfortunately for that theory, adding braces and "Py_DECREF(POP());" to the relevant error handling branch *doesn't* fix the problem.

    I also found another way to provoke similar misbehaviour without async with:

    ==========

    >>> async def open_file():
    ...     pass
    ... 
    >>> open_file()
    <coroutine object open_file at 0x7f92fe19c548>
    >>> _
    <coroutine object open_file at 0x7f92fe19c548>
    >>> 1
    __main__:1: RuntimeWarning: coroutine 'open_file' was never awaited
    1
    >>> open_file()
    <coroutine object open_file at 0x7f92fe19c548>
    >>> del _
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name '_' is not defined
    >>> _
    <coroutine object open_file at 0x7f92fe19c548>
    >>> 1
    1
    >>> _
    1
    >>>

    ==========

    @1st1
    Copy link
    Member

    1st1 commented Jan 29, 2018

    Changing

      async def main():
        async with open_file():
          pass

    to

      async def main():
        c = open_file()
        async with c:
          pass

    also makes it print the warning :)

    Also I've made a test out of this snippet and running tests in refleak mode shows that there's indeed no refleak here.

    @1st1
    Copy link
    Member

    1st1 commented Jan 29, 2018

    The difference between these two functions is two extra opcodes: STORE_FAST/LOAD_FAST before BEFORE_ASYNC_WITH. With them we have a warning.

    @1st1
    Copy link
    Member

    1st1 commented Jan 29, 2018

    So refactoring it into "c = open_file(); async with c" just prolongs the life of the coroutine so that it's GCed outside of WITH_CLEANUP_START/WITH_CLEANUP_FINISH block. Something weird is going on in that block.

    @1st1
    Copy link
    Member

    1st1 commented Jan 29, 2018

    Ah, we should never really get to WITH_CLEANUP_START; the exception should be raised in BEFORE_ASYNC_WITH

    @1st1
    Copy link
    Member

    1st1 commented Jan 29, 2018

    So the problem was that _PyGen_Finalize wasn't issuing any warnings if there's any error set in the current tstate. And in Nathaniel's case, the current error was an AttributeError('__aexit__').

    This check is weird, because right before raising the warning, we call PyErr_Fetch to temporarily reset the current exception if any, specifically to raise the warning :)

    The PR just removes the check. Unless I'm missing something this should fix the issue.

    @njsmith
    Copy link
    Contributor Author

    njsmith commented Jan 29, 2018

    Well, I feel silly then: bpo-32605

    @ncoghlan
    Copy link
    Contributor

    Ah, and in my REPL example, the NameError was pending when the internal result storage was getting set back to None.

    I'm not sure I even knew the "Don't complain when an exception is pending" check existed, so it would have taken me a long time to find that.

    @1st1
    Copy link
    Member

    1st1 commented Jan 29, 2018

    I knew about that "if", but it never fully registered to me why it's there and what it is protecting us from ;) So I had to debug half of ceval loop before I stumbled upon it again ;)

    @1st1
    Copy link
    Member

    1st1 commented Jan 29, 2018

    New changeset 2a2270d by Yury Selivanov in branch 'master':
    bpo-32703: Fix coroutine resource warning in case where there's an error (GH-5410)
    2a2270d

    @1st1
    Copy link
    Member

    1st1 commented Jan 29, 2018

    Merged; closing this issue.

    @1st1 1st1 closed this as completed Jan 29, 2018
    @ezio-melotti ezio-melotti transferred this issue from another repository Apr 10, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    3.7 (EOL) end of life 3.8 only security fixes interpreter-core (Objects, Python, Grammar, and Parser dirs)
    Projects
    None yet
    Development

    No branches or pull requests

    3 participants