[New-bugs-announce] [issue39032] wait_for and Condition.wait still not playing nicely

Chris report at bugs.python.org
Thu Dec 12 17:11:47 EST 2019

New submission from Chris <chrisriches42 at gmail.com>:

This is related to https://bugs.python.org/issue22970, https://bugs.python.org/issue33638, and https://bugs.python.org/issue32751. I've replicated the issue on Python 3.6.9, 3.7.4, and 3.8.0. Looking at the source, I'm fairly sure the bug is still in master right now.

The problem is yet another case of wait_for returning early, before the child has been fully cancelled and terminated. The issue arises if wait_for itself is cancelled. Take the following minimal example:

cond = asyncio.Condition()
async def coro():
    async with cond:
        await asyncio.wait_for(cond.wait(), timeout=999)

If coro is cancelled a few seconds after being run, wait_for will cancel the cond.wait(), then immediately re-raise the CancelledError inside coro, leading to "RuntimeError: Lock is not acquired."

Relevant source code plucked from the 3.8 branch is as follows:

        # wait until the future completes or the timeout
            await waiter
        except exceptions.CancelledError:

        if fut.done():
            return fut.result()
            # We must ensure that the task is not running
            # after wait_for() returns.
            # See https://bugs.python.org/issue32751
            await _cancel_and_wait(fut, loop=loop)
            raise exceptions.TimeoutError()

Note how if the timeout occurs, the method waits for the future to complete before raising. If CancelledError is thrown, it doesn't.

A simple fix seems to be replacing the "fut.cancel()" with "await _cancel_and_wait(fut, loop=loop)" so the behaviour is the same in both cases, however I'm only superficially familiar with the code, and am unsure if this would cause other problems.

components: asyncio
messages: 358307
nosy: asvetlov, criches, yselivanov
priority: normal
severity: normal
status: open
title: wait_for and Condition.wait still not playing nicely
type: behavior
versions: Python 3.6, Python 3.7, Python 3.8

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list