From 3311f20f4d34c64e9749335ef9469acb0fe9e0e6 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Tue, 24 Nov 2026 16:47:08 +0000 Subject: [PATCH 1/2] Fix `MonotonicTimer.ready()` ignoring cancellation After waking up, `ready()` cancels the task it is no longer waiting for and awaits it, catching its `CancelledError`. If the task running `ready()` is itself cancelled while it awaits there, the `except` clause catches that cancellation too. After a reset, `ready()` then goes back to sleeping until the next tick, so a `select()` or service being stopped can hang for a whole timer interval. After a tick, the cancellation is lost and `ready()` returns as if nothing happened. Wait for the cancelled tasks with `asyncio.wait()` instead. It doesn't raise the tasks' exceptions, but it still raises `CancelledError` when the task running `ready()` is cancelled. The new test cancels `ready()` at several loop iterations after a reset and after a tick, so it doesn't depend on exactly when the cleanup happens. Without the fix, it fails for 3 and 4 iterations in both cases. The deprecated `Timer` is an alias of `MonotonicTimer`, so it's fixed too. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 2 +- src/frequenz/channels/timer.py | 10 +++++---- tests/test_timer.py | 38 +++++++++++++++++++++++++++++++++- 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 96a0240b..95d2cb37 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -14,4 +14,4 @@ ## Bug Fixes - +- Cancelling a task that waits on a `MonotonicTimer` (or the deprecated `Timer`), directly or through `select()`, is no longer ignored when it arrives right after the timer was reset or ticked. Before, the task could keep waiting until the next tick, so stopping a service could hang for a whole timer interval. diff --git a/src/frequenz/channels/timer.py b/src/frequenz/channels/timer.py index 8249faff..c8251d61 100644 --- a/src/frequenz/channels/timer.py +++ b/src/frequenz/channels/timer.py @@ -740,10 +740,12 @@ async def ready(self) -> bool: # noqa: DOC502 ) for task in pending: task.cancel() - try: - await task - except asyncio.CancelledError: - pass + # Awaiting each task and catching its `CancelledError` would also + # catch a cancellation of this task, making `ready()` ignore it. + # `asyncio.wait()` doesn't raise the tasks' exceptions, but still + # raises when this task is cancelled. + if pending: + await asyncio.wait(pending) self._reset_event.clear() now = self._now() diff --git a/tests/test_timer.py b/tests/test_timer.py index b8c65f19..08028cda 100644 --- a/tests/test_timer.py +++ b/tests/test_timer.py @@ -7,7 +7,7 @@ import enum import re from datetime import timedelta -from typing import Any +from typing import Any, Literal import async_solipsism import hypothesis @@ -409,6 +409,42 @@ async def test_timer_close_receiver() -> None: await timer.receive() +@pytest.mark.parametrize("wake_up_by", ["reset", "tick"]) +@pytest.mark.parametrize("loop_iterations", range(10)) +async def test_timer_ready_cancel_after_wake_up( + wake_up_by: Literal["reset", "tick"], loop_iterations: int +) -> None: + """Test that cancelling `ready()` right after it wakes up is not ignored. + + When the timer is reset or ticks, `ready()` cleans up the task it was + waiting on before going on. A cancellation arriving during that cleanup + must still cancel `ready()`, instead of being ignored. Every + `loop_iterations` value cancels at a different point after the wake-up, + so some of them hit the cleanup. + """ + interval = timedelta(hours=1) + timer = MonotonicTimer(interval, SkipMissedAndResync()) + + ready = asyncio.create_task(timer.ready()) + await asyncio.sleep(0) # Let `ready()` start waiting + match wake_up_by: + case "reset": + timer.reset(interval=interval) + case "tick": + await asyncio.sleep(interval.total_seconds()) + for _ in range(loop_iterations): + await asyncio.sleep(0) + + if not ready.cancel(): + # After a tick, `ready()` can finish before the cancellation arrives. + assert wake_up_by == "tick" + assert ready.result() is True + return + await asyncio.wait([ready]) + + assert ready.cancelled() + + async def test_timer_autostart() -> None: """Test the autostart of a periodic timer.""" event_loop = asyncio.get_running_loop() From a95d25b30a12624d4e3ff07bc1541cc9de583482 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Wed, 25 Nov 2026 09:04:45 +0000 Subject: [PATCH 2/2] Prepare the release notes for v1.13.1 Add a summary and remove the template comments and the empty sections, as the release process requires before tagging. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 95d2cb37..2847672e 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,15 +2,7 @@ ## Summary - - -## Upgrading - - - -## New Features - - +This release fixes timers ignoring the cancellation of a task waiting on them, which could make stopping a service hang for a whole timer interval. ## Bug Fixes