Issue 30508: "Task exception was never retrieved" reported for a canceled task (original) (raw)

I am seeing a strange issue that occurs when a task that is awaiting an asyncio.wait_for() is cancelled. I created a simple example that I think demonstrates the issue, even though it isn't exactly how it manifests on my application.

When I run the attached script never-retrieved.py I get the following error:

Task exception was never retrieved future: <Task finished coro=<crash() done, defined at never-retrieved.py:4> exception=ZeroDivisionError('division by zero',)> Traceback (most recent call last): File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step result = coro.send(None) File "never-retrieved.py", line 5, in crash a = 1/0 ZeroDivisionError: division by zero

You can see in the script that the future was cancelled, but the cancel() call was made after the task finished in a zero division error. I think the cancel() call should update the internal state of the future so that the "exception was never retrieved" error does not appear.

My application has a more complex setup that I have been unable to reproduce with a simple example. I have a task that is waiting on asyncio.wait_for(fut, timeout), with fut subsequently waiting on a websocket server's receive function. When the websocket client closes the connection, a bunch of cancellations happen, but this future inside the wait_for call crashes before wait_for gets to call cancel() on it. Even though I need to investigate this crash, the fact is that wait_for did cancel this future, but because it already ended in an error the "never retried" error is reported anyway.