Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,8 @@

## Summary

<!-- Here goes a general summary of what this release is about -->

## Upgrading

<!-- Here goes notes on how to upgrade from previous versions, including deprecations and what they should be replaced with -->

## New Features

<!-- Here goes the main new features and examples or instructions on how to use them -->
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

<!-- Here goes notable bug fixes that are worth a special mention or explanation -->
- Cancelling a task that waits on a `MonotonicTimer`, 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.
10 changes: 6 additions & 4 deletions src/frequenz/channels/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -736,10 +736,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()
Expand Down
38 changes: 37 additions & 1 deletion tests/test_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down