Skip to content

Commit dbba29d

Browse files
authored
Fixed 100% CPU spin on cancel scope misuse (#1217)
Fixes #1111.
1 parent 6bbc6c3 commit dbba29d

3 files changed

Lines changed: 43 additions & 0 deletions

File tree

‎docs/versionhistory.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
3434
reserved for the woken waiter right away, so the non-blocking acquire correctly
3535
raises ``WouldBlock``
3636
(`#1170 <https://github.com/agronholm/anyio/issues/1170>`_; PR by @gaoflow)
37+
- Fixed unnecessary CPU spin when delivering cancellation from ``CancelScope`` on
38+
asyncio under certain conditions, including improper cancel scope nesting
39+
(`#1111 <https://github.com/agronholm/anyio/issues/1111>`_)
3740

3841
**4.14.1**
3942

‎src/anyio/_backends/_asyncio.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,10 @@ def _deliver_cancellation(self, origin: CancelScope) -> bool:
592592
should_retry = False
593593
current = current_task()
594594
for task in self._tasks:
595+
# Always skip tasks that are already done (see issue #1111)
596+
if task.done():
597+
continue
598+
595599
should_retry = True
596600
if task._must_cancel: # type: ignore[attr-defined]
597601
continue

‎tests/test_taskgroups.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
import pytest
1717
from pytest import FixtureRequest, MonkeyPatch
18+
from pytest_mock import MockerFixture
1819

1920
import anyio
2021
from anyio import (
@@ -360,6 +361,41 @@ async def middle_task() -> None:
360361
assert len(outer_cancel_spy.call_args_list) < 10
361362

362363

364+
@pytest.mark.parametrize("anyio_backend", asyncio_params)
365+
async def test_no_spin_on_done_task_in_cancel_scope(mocker: MockerFixture) -> None:
366+
"""Regression test for #1111.
367+
368+
When a task group is entered but never exited (e.g. it is abandoned because
369+
the task owning it finishes without unwinding it), its cancel scope is left
370+
with the now-finished host task still in its set of contained tasks.
371+
Cancelling such a scope used to make ``_deliver_cancellation`` treat that
372+
finished task as still cancellable and reschedule itself via ``call_soon``
373+
forever, pinning the event loop at 100% CPU.
374+
"""
375+
from anyio._backends import _asyncio
376+
377+
# To allow the mocker to override a @final class
378+
class EditableCancelScope(_asyncio.CancelScope):
379+
pass
380+
381+
async def owner() -> EditableCancelScope:
382+
return cast(EditableCancelScope, EditableCancelScope().__enter__())
383+
384+
scope = await asyncio.create_task(owner())
385+
spy = mocker.spy(scope, "_deliver_cancellation")
386+
scope.cancel()
387+
388+
# Give any rescheduled _deliver_cancellation callbacks the chance to fire.
389+
# With the bug present this reschedules forever (the test timeout would
390+
# trip); the fix leaves no pending cancellation callback since the only
391+
# remaining task is done.
392+
for _ in range(5):
393+
await checkpoint()
394+
395+
assert scope._cancel_handle is None
396+
spy.assert_called_once()
397+
398+
363399
@pytest.mark.parametrize("return_handle", [False, True])
364400
async def test_start_exception_delivery(return_handle: bool) -> None:
365401
def task_fn(*, task_status: TaskStatus[str] = TASK_STATUS_IGNORED) -> None:

0 commit comments

Comments
 (0)