Skip to content

Commit 34cabac

Browse files
Stop raising exception when actor is stopped.
BacgroundService raises BaseExceptionGroup. We can check if it was cancelled by checking if all exceptions on BaseGroupException are CancelledError. Signed-off-by: Elzbieta Kotulska <[email protected]>
1 parent 855a181 commit 34cabac

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

RELEASE_NOTES.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,5 @@
1717
## Bug Fixes
1818

1919
- Fixed bug with formulas raising exception when stopped.
20+
21+
- Fix a bug that raised `CancelledError` when actor was started with `frequenz.sdk.actor.run` and stopped.

src/frequenz/sdk/actor/_run_utils.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import asyncio
88
import logging
9+
from typing import Any
910

1011
from ._actor import Actor
1112

@@ -43,7 +44,7 @@ async def run(*actors: Actor) -> None:
4344
for task in done_tasks:
4445
# Cancellation needs to be checked first, otherwise the other methods
4546
# could raise a CancelledError
46-
if task.cancelled():
47+
if _was_cancelled(task):
4748
_logger.info("Actor %s: Cancelled while running.", task.get_name())
4849
elif exception := task.exception():
4950
_logger.error(
@@ -55,3 +56,13 @@ async def run(*actors: Actor) -> None:
5556
_logger.info("Actor %s: Finished normally.", task.get_name())
5657

5758
_logger.info("All %s actor(s) finished.", len(actors))
59+
60+
61+
def _was_cancelled(task: asyncio.Task[Any]) -> bool:
62+
if task.cancelled():
63+
return True
64+
65+
exc = task.exception()
66+
return isinstance(exc, BaseExceptionGroup) and all(
67+
isinstance(err, asyncio.CancelledError) for err in exc.exceptions
68+
)

tests/actor/test_actor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,6 @@ async def cancel_actor() -> None:
390390
(*RUN_INFO, "Actor EchoActor[EchoActor]: Starting..."),
391391
(*ACTOR_INFO, "Actor EchoActor[EchoActor]: Started."),
392392
(*ACTOR_INFO, "Actor EchoActor[EchoActor]: Cancelled."),
393-
(*RUN_ERROR, "Actor EchoActor[EchoActor]: Raised an exception while running."),
393+
(*RUN_INFO, "Actor EchoActor[EchoActor]: Cancelled while running."),
394394
(*RUN_INFO, "All 1 actor(s) finished."),
395395
]

0 commit comments

Comments
 (0)