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

GH-111693: Propagate correct asyncio.CancelledError instance out of asyncio.Condition.wait() #111694

Merged
merged 14 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 0 additions & 3 deletions Lib/asyncio/futures.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,6 @@ def _make_cancelled_error(self):
exc = exceptions.CancelledError()
else:
exc = exceptions.CancelledError(self._cancel_message)
exc.__context__ = self._cancelled_exc
# Remove the reference since we don't need this anymore.
self._cancelled_exc = None
gvanrossum marked this conversation as resolved.
Show resolved Hide resolved
return exc

def cancel(self, msg=None):
Expand Down
41 changes: 26 additions & 15 deletions Lib/asyncio/locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@ async def acquire(self):
This method blocks until the lock is unlocked, then sets it to
locked and returns True.
"""
# Implement fair scheduling, where thread always waits
# its turn.
# Jumping the queue if all are cancelled is an optimization.
if (not self._locked and (self._waiters is None or
all(w.cancelled() for w in self._waiters))):
self._locked = True
Expand All @@ -105,19 +108,20 @@ async def acquire(self):
fut = self._get_loop().create_future()
self._waiters.append(fut)

# Finally block should be called before the CancelledError
# handling as we don't want CancelledError to call
# _wake_up_first() and attempt to wake up itself.
gvanrossum marked this conversation as resolved.
Show resolved Hide resolved
try:
try:
await fut
finally:
self._waiters.remove(fut)
except exceptions.CancelledError:
except BaseException:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm still not very comfortable with widening this exception net for the purpose of sneaking in support for your library. If we want that to be supported we should make it an explicit feature, everywhere, rather than just tweaking an except clause here and there until your tests pass. Without any comments explaining the intended guarantee, what's to stop the next clever maintainer from narrowing the exception being caught to CancelledError again?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point. I quite understand that you are reluctant to touch this just to humour an eccentric experimental library which is trying to push the envelope of the original design. And I'm happy to have this rejected as long as we have had the chance to discuss it. I'll add a comment here in the mean time, just for safety.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC you're planning to make your library to use a subclass of CancelledError, so you don't need this to be more general anyway. So I'd like to see CancelledError here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure. Of course, IMO, it would be even greater if in some future version, we would have something like:

class InterruptError(BaseException):
    pass

class CancelledError(InterruptError):
   pass

but that is future music :)

# Ensure the lock invariant: If lock is not claimed (or about to be by us)
# and there is a Task in waiters,
# ensure that that Task (now at the head) will run.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice comment! It doesn't immediately alleviate my fear that the future now at the head is already cancelled, and nothing will be woken up. The explanation is, of course, that all cancelled tasks in the waiters list are already woken up and are just waiting to run. Maybe you could add a hint about that?

(And maybe reflow the text, pretty please? In comments, you have to do the rendering in your head. :-)

if not self._locked:
self._wake_up_first()
raise

# assert self._locked is False
self._locked = True
return True

Expand Down Expand Up @@ -269,17 +273,22 @@ async def wait(self):
self._waiters.remove(fut)

finally:
# Must reacquire lock even if wait is cancelled
cancelled = False
# Must reacquire lock even if wait is cancelled.
gvanrossum marked this conversation as resolved.
Show resolved Hide resolved
# We only catch CancelledError here, since we don't want any
# other (fatal) errors with the future to cause us to spin.
gvanrossum marked this conversation as resolved.
Show resolved Hide resolved
err = None
while True:
try:
await self.acquire()
break
except exceptions.CancelledError:
cancelled = True
except exceptions.CancelledError as e:
err = e

if cancelled:
raise exceptions.CancelledError
if err:
try:
raise err # Re-raise most recent exception instance
finally:
err = None # Break reference cycles

async def wait_for(self, predicate):
"""Wait until a predicate becomes true.
Expand Down Expand Up @@ -378,16 +387,17 @@ async def acquire(self):
fut = self._get_loop().create_future()
self._waiters.append(fut)

# Finally block should be called before the CancelledError
# handling as we don't want CancelledError to call
# _wake_up_first() and attempt to wake up itself.
try:
try:
await fut
finally:
self._waiters.remove(fut)
except exceptions.CancelledError:
if not fut.cancelled():
except BaseException:
if fut.done() and not fut.cancelled():
gvanrossum marked this conversation as resolved.
Show resolved Hide resolved
# Our Future was successfully set to True via _wake_up_next(),
# but we are not about to successfully acquire(). Therefore we
# must undo the bookkeeping already done and attempt to wake
# up someone else.
self._value += 1
self._wake_up_next()
raise
Expand All @@ -414,6 +424,7 @@ def _wake_up_next(self):
if not fut.done():
self._value -= 1
fut.set_result(True)
# assert fut.true() and not fut.cancelled()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd remove that -- I don't think there's such a thing as fut.true() and the semantics of set_result() ensure that if the future was cancelled it will raise an exception.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Ditto if it already had another result, or an exception.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, I added that as an explanation to what the state ought to be, to mirror the other test we make, but it is really redundant (and incorrect).

return


Expand Down
57 changes: 57 additions & 0 deletions Lib/test/test_asyncio/test_locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,63 @@ async def test_timeout_in_block(self):
with self.assertRaises(asyncio.TimeoutError):
await asyncio.wait_for(condition.wait(), timeout=0.5)

async def test_cancelled_error_wakeup(self):
"""Test that a cancelled error, received when awaiting wakeup
will be re-raised un-modified.
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please convert the docstrings on the tests to comments -- test docstrings tend to be printed by the test runner, messing up the neat output. Note how no other tests here have docstrings.

wake = False
raised = None
cond = asyncio.Condition()

async def func():
nonlocal raised
async with cond:
with self.assertRaises(asyncio.CancelledError) as err:
await cond.wait_for(lambda: wake)
raised = err.exception
raise raised

task = asyncio.create_task(func())
await asyncio.sleep(0)
# Task is waiting on the condition, cancel it there
task.cancel(msg="foo")
with self.assertRaises(asyncio.CancelledError) as err:
await task
self.assertEqual(err.exception.args, ("foo",))
# we should have got the _same_ exception instance as the one originally raised
self.assertIs(err.exception, raised)

async def test_cancelled_error_re_aquire(self):
"""Test that a cancelled error, received when re-aquiring lock,
will be re-raised un-modified.
"""
wake = False
raised = None
cond = asyncio.Condition()

async def func():
nonlocal raised
async with cond:
with self.assertRaises(asyncio.CancelledError) as err:
await cond.wait_for(lambda: wake)
raised = err.exception
raise raised

task = asyncio.create_task(func())
await asyncio.sleep(0)
# Task is waiting on the condition
await cond.acquire()
wake = True
cond.notify()
await asyncio.sleep(0)
# task is now trying to re-acquire the lock, cancel it there
task.cancel(msg="foo")
cond.release()
with self.assertRaises(asyncio.CancelledError) as err:
await task
self.assertEqual(err.exception.args, ("foo",))
# we should have got the _same_ exception instance as the one originally raised
self.assertIs(err.exception, raised)

class SemaphoreTests(unittest.IsolatedAsyncioTestCase):

Expand Down