Skip to content

Commit 33de3dc

Browse files
committed
Properly propagate CancelledError in wait()
When a `BackgroundService.wait()` is used, it should also propage `CancelledError`s, as is it not always normal that a background service is cancelled unless `stop()` is called, which uses `cancel()` to stop the tasks. When `stop()` is used, we properly filter out all `CancelledError`s too, as in that case we triggered the cancellation, so it is normal. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 098e48d commit 33de3dc

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/frequenz/sdk/actor/_background_service.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,22 @@ async def stop(self, msg: str | None = None) -> None:
141141
Raises:
142142
BaseExceptionGroup: If any of the tasks spawned by this service raised an
143143
exception.
144+
145+
# noqa: DAR401 rest
144146
"""
145147
if not self._tasks:
146148
return
147149
self.cancel(msg)
148-
await self.wait()
150+
try:
151+
await self.wait()
152+
except BaseExceptionGroup as exc_group:
153+
# We want to ignore CancelledError here as we explicitly cancelled all the
154+
# tasks.
155+
_, rest = exc_group.split(asyncio.CancelledError)
156+
if rest is not None:
157+
# We are filtering out from an exception group, we really don't want to
158+
# add the exceptions we just filtered by adding a from clause here.
159+
raise rest # pylint: disable=raise-missing-from
149160

150161
async def __aenter__(self) -> Self:
151162
"""Enter an async context.
@@ -197,10 +208,12 @@ async def wait(self) -> None:
197208

198209
exceptions: list[BaseException] = []
199210
for task in done:
200-
if task.cancelled():
201-
continue
202-
if exception := task.exception():
203-
exceptions.append(exception)
211+
try:
212+
# This will raise a CancelledError if the task was cancelled or any
213+
# other exception if the task raised one.
214+
_ = task.result()
215+
except BaseException as error: # pylint: disable=broad-except
216+
exceptions.append(error)
204217
if exceptions:
205218
raise BaseExceptionGroup(
206219
f"Error while stopping background service {self}", exceptions

0 commit comments

Comments
 (0)