Repository navigation
Description
What happened?
Cancelling a task that is waiting in MonotonicTimer.ready() (for example the pending task select() cancels on exit) sometimes has no effect. The task keeps sleeping until the next tick, which can be minutes or hours away. A service using select() with a timer then hangs on stop() or on event loop shutdown for the whole interval.
Repro (hangs with N=3 on 1.13.0 and 2.0.0):
import asyncio, sys
from datetime import timedelta
from frequenz.channels.timer import MonotonicTimer, SkipMissedAndResync
async def main(n: int) -> None:
timer = MonotonicTimer(timedelta(hours=1), SkipMissedAndResync())
ready = asyncio.create_task(timer.ready())
await asyncio.sleep(0)
timer.reset(interval=timedelta(hours=1))
for _ in range(n):
await asyncio.sleep(0)
ready.cancel()
done, _ = await asyncio.wait([ready], timeout=2)
print("ok" if done else "ready() ignored cancel()")
asyncio.run(main(int(sys.argv[1])))What did you expect instead?
Cancelling the task waiting in ready() should always cancel it right away.
Affected version(s)
v1.6.1 to v1.13.0, v2.0.0
Affected part(s)
Utilities (Event, FileWatcher, Timer, etc.) (part:utilities)
Extra information
After asyncio.wait(..., FIRST_COMPLETED), ready() cleans up the other task with:
for task in pending:
task.cancel()
try:
await task
except asyncio.CancelledError:
passIf the task running ready() is cancelled while suspended in await task, the except catches that cancellation too. The while loop then sleeps again for the whole remaining interval. This runs after every reset and every tick, so the window is short but hit regularly.
Proposed fix: cancel the pending tasks, then await asyncio.wait(pending). That waits for them without raising their CancelledError, but still propagates a cancellation of the caller. With this change, I saw no hangs in 96 stress runs that previously hung about one run in three.
Affected: MonotonicTimer and the old Timer, at least from v1.6.1 to v2.0.0. I'll fix it in v1.13.1 and v2.0.1.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Effort
Affected Version
Activity
[-]`MonotonicTimer.ready()` can swallow its own cancellation and sleep for a full interval[/-][+]`MonotonicTimer.ready()` can swallow its own cancellation[/+]Fix timers ignoring cancellation (#625)