diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index d4546f4..41d7a0b 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -15,3 +15,7 @@ ## Bug Fixes + +* Fixed stopping the dispatcher while it was still managing actors for a dispatch type. The managed types are now stopped too, one by one so that one failing to stop cannot keep the others running, and waiting for the dispatcher does not block forever any more. Asking a type to stop that is already stopping now waits for that stop instead of interrupting it half way, which used to leave actors running. +* Fixed the dispatch stream being left running after the dispatcher was stopped. Its task kept calling the dispatch API again and again in the background. +* Fixed actors being left running when the `ActorDispatcher` that started them is stopped. Nothing else could stop them, because the `ActorDispatcher` owns the channels they get their dispatch updates from. Each actor is stopped on its own, so one actor failing to stop cannot keep the others running, and such a failure is reported when the `ActorDispatcher` is stopped. Stopping an actor also finishes closing the channel it reads from when the `ActorDispatcher` is cancelled in the middle of it. diff --git a/src/frequenz/dispatch/__init__.py b/src/frequenz/dispatch/__init__.py index c1cb594..b305f37 100644 --- a/src/frequenz/dispatch/__init__.py +++ b/src/frequenz/dispatch/__init__.py @@ -16,9 +16,9 @@ """ -from ._actor_dispatcher import ActorDispatcher, ContinuationCapable, DispatchInfo +from ._actor_dispatcher import ActorDispatcher, DispatchInfo from ._bg_service import MergeStrategy -from ._continuation import is_exact_continuation +from ._continuation import ContinuationCapable, is_exact_continuation from ._dispatch import Dispatch from ._dispatcher import Dispatcher from ._event import Created, Deleted, DispatchEvent, Updated diff --git a/src/frequenz/dispatch/_actor_dispatcher.py b/src/frequenz/dispatch/_actor_dispatcher.py index 0c52d94..9f8a06d 100644 --- a/src/frequenz/dispatch/_actor_dispatcher.py +++ b/src/frequenz/dispatch/_actor_dispatcher.py @@ -9,13 +9,12 @@ """ import asyncio -import enum import logging from collections.abc import Callable, Mapping from copy import copy from dataclasses import dataclass from datetime import datetime, timedelta, timezone -from typing import Any, Awaitable, Protocol, runtime_checkable +from typing import Any, Awaitable from warnings import warn from frequenz.channels import Broadcast, Receiver, Sender, select @@ -23,56 +22,16 @@ from frequenz.client.dispatch.types import DispatchId, TargetComponents from frequenz.core.id import BaseId from frequenz.sdk.actor import Actor, BackgroundService -from typing_extensions import deprecated +from typing_extensions import deprecated, override +from ._continuation import ContinuationCapable, _ContinuationOutcome from ._dispatch import Dispatch from ._merge_helpers import _other_running_dispatches +from ._stopping import stop_actors _logger = logging.getLogger(__name__) -class _ContinuationOutcome(enum.Enum): - """The result of trying to hand a dispatch over to a predecessor's actor.""" - - ACCEPTED = enum.auto() - """The actor adopted the new dispatch; it's now running under its identity.""" - - REFUSED = enum.auto() - """The actor explicitly declined; it keeps running under its own dispatch.""" - - UNKNOWN = enum.auto() - """`accept_continuation()` timed out or raised; the actor's state is unknown.""" - - -@runtime_checkable -class ContinuationCapable(Protocol): - """An actor that can accept or refuse a continuation update. - - `ActorDispatcher` only reuses a running actor for a new, unrelated - dispatch (see `continuation_predicate`) when the actor's class implements - this protocol. An actor that does not implement it is never reused: a - fresh actor is started for the new dispatch instead, exactly as if no - continuation had been attempted. - """ - - async def accept_continuation(self, update: "DispatchInfo") -> bool: - """Accept or refuse a continuation update. - - If this returns `True`, the actor must already be acting on - `update.dispatch` as its new dispatch before returning. - - Args: - update: The continuation update. `update.continuation_of` is the - dispatch id this actor is currently running under, and - `update.dispatch` is the new dispatch to adopt. - - Returns: - `True` to accept `update` and adopt it as the current dispatch. - `False` to refuse; the caller then starts a separate, fresh actor - for the new dispatch and leaves this one running as before. - """ - - class DispatchActorId(BaseId, str_prefix="DA"): """An ID for a dispatch actor.""" @@ -493,11 +452,43 @@ def __init__( # pylint: disable=too-many-arguments, too-many-positional-argumen time that happens, so it can't grow without bound. """ self._merge_context: ActorDispatcher._MergeContext | None = None + self._stop_errors: list[Exception] = [] + """The errors from stopping the actors, reported by `wait()`.""" def start(self) -> None: """Start the background service.""" self._tasks.add(asyncio.create_task(self._run())) + # The noqa is needed because pydoclint cannot tell that the exceptions of + # a caught `BaseExceptionGroup` are re-raised in a new one below. + @override + async def wait(self) -> None: # noqa: DOC503 + """Wait until this service is done, and report failed actor stops. + + An actor that fails to stop cannot be reported while the service is + stopping, because raising there would replace the cancellation that + asked it to stop. The errors are kept and reported here instead, so + that they also reach a caller that only ever uses + [`stop()`][frequenz.sdk.actor.BackgroundService.stop]. + + Raises: + BaseExceptionGroup: If a task of this service failed, or if one of + its actors failed to stop. Cancellations are reported the way + the base class reports them. + """ + errors: list[BaseException] = [] + + try: + await super().wait() + except BaseExceptionGroup as group: + errors += group.exceptions + + errors += self._stop_errors + self._stop_errors.clear() + + if errors: + raise BaseExceptionGroup(f"Error while stopping {self}", errors) + def _set_merge_context( self, dispatch_filter: Callable[[Mapping[DispatchId, Dispatch], Dispatch], bool], @@ -721,8 +712,9 @@ async def _discard_unresponsive_predecessor( predecessor: The predecessor actor-and-channel entry to stop. """ del self._actors[predecessor_identity] - await predecessor.actor.stop("continuation outcome unknown") - await predecessor.channel.aclose() + self._stop_errors += await stop_actors( + [(predecessor.actor, predecessor.channel)], "continuation outcome unknown" + ) async def _try_handover( self, dispatch: Dispatch @@ -846,8 +838,9 @@ async def _stop_actor( ) if actor_and_channel is not None: _logger.info("Stopping actor for dispatch type %r", stopping_dispatch.type) - await actor_and_channel.actor.stop(msg) - await actor_and_channel.channel.aclose() + self._stop_errors += await stop_actors( + [(actor_and_channel.actor, actor_and_channel.channel)], msg + ) elif identity in self._recently_continued: # A continuation handover already moved this identity's actor # elsewhere (see `_continue_actor`); its own stop arriving here @@ -866,6 +859,27 @@ async def _stop_actor( async def _run(self) -> None: """Run the background service.""" + try: + await self._dispatch_loop() + finally: + # Nothing else can stop the actors this service started: it owns + # the channels they get their updates from. Every actor is + # stopped on its own, and the failures are kept for `wait()` + # instead of raised, so a failing actor can neither leave the + # others running nor replace the cancellation that asked this + # service to stop. + running = [ + (pair.actor, pair.channel) + for status in self._actors.values() + if (pair := status.actor_and_channel) is not None + ] + self._actors.clear() + self._stop_errors += await stop_actors( + running, "The actor dispatcher was stopped" + ) + + async def _dispatch_loop(self) -> None: + """Handle dispatches until the running status receiver is closed.""" async for selected in select(self._retry_timer_rx, self._dispatch_rx): if self._retry_timer_rx.triggered(selected): failed_dispatches = [ diff --git a/src/frequenz/dispatch/_bg_service.py b/src/frequenz/dispatch/_bg_service.py index f60ccdb..784ff6d 100644 --- a/src/frequenz/dispatch/_bg_service.py +++ b/src/frequenz/dispatch/_bg_service.py @@ -10,7 +10,7 @@ import logging from abc import ABC, abstractmethod from collections.abc import Mapping -from contextlib import closing +from contextlib import AsyncExitStack, closing from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from heapq import heapify, heappop, heappush @@ -271,17 +271,29 @@ async def _run(self) -> None: # pylint: disable=too-many-branches ) # Streaming updates - with closing( - MonotonicTimer( - timedelta(seconds=100), SkipMissedAndResync(), auto_start=False + async with AsyncExitStack() as stack: + next_event_timer = stack.enter_context( + closing( + MonotonicTimer( + timedelta(seconds=100), SkipMissedAndResync(), auto_start=False + ) + ) ) - ) as next_event_timer: + # Initial fetch await self._fetch(next_event_timer) # pylint: disable-next=protected-access streamer = self._client._get_stream(microgrid_id=self._microgrid_id) + # The client keeps the stream running until someone stops it, and + # disconnecting the client does not do that. So the service that + # asked for the stream has to stop it again, or its task keeps + # retrying the call forever after this service is gone. + stack.push_async_callback(streamer.stop) stream = streamer.new_receiver(include_events=True) + # Closed before the stream is stopped, so it is not left reading + # from a channel that is being closed under it. + stack.callback(stream.close) # We track stream start events linked to retries to avoid re-fetching # dispatches that were already retrieved during an initial stream start. diff --git a/src/frequenz/dispatch/_continuation.py b/src/frequenz/dispatch/_continuation.py index 3684657..170265e 100644 --- a/src/frequenz/dispatch/_continuation.py +++ b/src/frequenz/dispatch/_continuation.py @@ -21,6 +21,9 @@ from __future__ import annotations +import enum +from typing import TYPE_CHECKING, Protocol, runtime_checkable + from frequenz.client.dispatch.types import ( BatteryType, EvChargerType, @@ -31,6 +34,51 @@ from ._dispatch import Dispatch +if TYPE_CHECKING: + from ._actor_dispatcher import DispatchInfo + + +class _ContinuationOutcome(enum.Enum): + """The result of trying to hand a dispatch over to a predecessor's actor.""" + + ACCEPTED = enum.auto() + """The actor adopted the new dispatch; it's now running under its identity.""" + + REFUSED = enum.auto() + """The actor explicitly declined; it keeps running under its own dispatch.""" + + UNKNOWN = enum.auto() + """`accept_continuation()` timed out or raised; the actor's state is unknown.""" + + +@runtime_checkable +class ContinuationCapable(Protocol): + """An actor that can accept or refuse a continuation update. + + `ActorDispatcher` only reuses a running actor for a new, unrelated + dispatch (see `continuation_predicate`) when the actor's class implements + this protocol. An actor that does not implement it is never reused: a + fresh actor is started for the new dispatch instead, exactly as if no + continuation had been attempted. + """ + + async def accept_continuation(self, update: "DispatchInfo") -> bool: + """Accept or refuse a continuation update. + + If this returns `True`, the actor must already be acting on + `update.dispatch` as its new dispatch before returning. + + Args: + update: The continuation update. `update.continuation_of` is the + dispatch id this actor is currently running under, and + `update.dispatch` is the new dispatch to adopt. + + Returns: + `True` to accept `update` and adopt it as the current dispatch. + `False` to refuse; the caller then starts a separate, fresh actor + for the new dispatch and leaves this one running as before. + """ + def _canonical_target(target: object) -> frozenset[tuple[object, ...]]: """Canonicalize a dispatch target into an order-independent, class-aware set. diff --git a/src/frequenz/dispatch/_dispatcher.py b/src/frequenz/dispatch/_dispatcher.py index db5a9ee..0bb401a 100644 --- a/src/frequenz/dispatch/_dispatcher.py +++ b/src/frequenz/dispatch/_dispatcher.py @@ -10,6 +10,7 @@ import warnings from asyncio import Event from datetime import timedelta +from functools import partial from typing import Awaitable, Callable, Self from frequenz.channels import Receiver @@ -22,6 +23,7 @@ from ._bg_service import DispatchScheduler, MergeStrategy from ._dispatch import Dispatch from ._event import DispatchEvent +from ._stopping import cancel_service, stop_all, stop_service _logger = logging.getLogger(__name__) @@ -276,14 +278,64 @@ def is_running(self) -> bool: """Whether the local dispatch service is running.""" return self._bg_service.is_running + # The noqa is needed because pydoclint counts the bare `raise` below, which + # only re-raises what we caught, as raising `BaseException`. @override - async def wait(self) -> None: - """Wait until all actor dispatches are stopped and client is disconnected.""" + async def wait(self) -> None: # noqa: DOC503 + """Wait until all actor dispatches are stopped and client is disconnected. + + The managed dispatch types are stopped before this returns, and that + takes as long as their actors take to stop. Cancelling this wait does + not abandon that: the types still left are stopped, and the + cancellation is raised afterwards. The caller then sees the + cancellation and not whatever error was already on its way out, which + is attached to it as its `__context__`. Waiting ends in a cancellation + because the caller asked for it, so that is left as it is. + + Raises: + BaseExceptionGroup: If the local dispatch service failed, or if + stopping a managed dispatch type failed. + """ if self._disconnecting_future is not None: await self._disconnecting_future - await asyncio.gather(self._bg_service.wait(), self._empty_event.wait()) + try: + await asyncio.gather(self._bg_service.wait(), self._empty_event.wait()) + except BaseException: + # The failures are logged. They must not replace the error that + # is already on its way out, which is normally the cancellation + # that asked us to stop. + await self._stop_managed_types() + raise + + if errors := await self._stop_managed_types(): + raise BaseExceptionGroup( + "Error while stopping the managed dispatch types", errors + ) + + async def _stop_managed_types(self) -> list[Exception]: + """Stop every managed dispatch type and forget all of them. + + `cancel()` only asks the managed dispatchers to stop, and + `stop_managing()` was maybe never called for them at all. Stopping + them here also makes sure the actors they started are stopped before + `wait()` returns. Every type is stopped on its own, so one failing + type cannot leave another one running. + + Returns: + The errors raised while stopping, in order, already logged. + """ + managed = list(self._actor_dispatchers.items()) self._actor_dispatchers.clear() + return await stop_all( + ( + ( + f"the managed dispatch type {dispatch_type!r}", + partial(stop_service, instance, "The dispatcher was stopped"), + ) + for dispatch_type, instance in managed + ) + ) def cancel(self, msg: str | None = None) -> None: """Stop the local dispatch service and initiate client disconnection. @@ -291,10 +343,16 @@ def cancel(self, msg: str | None = None) -> None: Args: msg: An optional message to include in the cancellation. """ - self._bg_service.cancel(msg) + cancel_service(self._bg_service, msg) - for instance in self._actor_dispatchers.values(): - instance.cancel() + for instance in list(self._actor_dispatchers.values()): + cancel_service(instance) + + # `wait()` blocks on this event until every managed dispatch type was + # stopped with `stop_managing()`. We just cancelled all of them, so + # there is nothing left to wait for and `wait()` must not block on it + # any more. Without this, waiting after a stop blocks forever. + self._empty_event.set() # Initiate client disconnection asynchronously self._disconnecting_future = asyncio.ensure_future(self._client.disconnect()) @@ -413,15 +471,21 @@ def id_identity(dispatch: Dispatch) -> DispatchActorId: self._actor_dispatchers[dispatch_type] = dispatcher dispatcher.start() - async def stop_managing(self, dispatch_type: str) -> None: + # The noqa is needed because pydoclint cannot see what `stop_service` + # raises through the call. + async def stop_managing(self, dispatch_type: str) -> None: # noqa: DOC502 """Stop managing actors for a given dispatch type. Args: dispatch_type: The type of the dispatch to stop managing. + + Raises: + BaseExceptionGroup: If the actor dispatcher for this type failed, + or if one of its actors failed to stop. """ dispatcher = self._actor_dispatchers.pop(dispatch_type, None) if dispatcher is not None: - await dispatcher.stop() + await stop_service(dispatcher, f"Stopped managing {dispatch_type!r}") if not self._actor_dispatchers: self._empty_event.set() diff --git a/src/frequenz/dispatch/_stopping.py b/src/frequenz/dispatch/_stopping.py new file mode 100644 index 0000000..adf2a61 --- /dev/null +++ b/src/frequenz/dispatch/_stopping.py @@ -0,0 +1,136 @@ +# License: MIT +# Copyright © 2025 Frequenz Energy-as-a-Service GmbH + +"""Helpers to stop several things without one failure skipping the rest.""" + +import asyncio +import logging +from collections.abc import Awaitable, Callable, Iterable +from functools import partial +from typing import Any + +from frequenz.channels import Broadcast +from frequenz.sdk.actor import Actor, BackgroundService + +_logger = logging.getLogger(__name__) + +_Stop = tuple[str, Callable[[], Awaitable[Any]]] +"""One thing to stop: what it is, for the logs, and how to stop it.""" + + +# The noqa is needed because pydoclint cannot tell that `cancellation` below +# is a `BaseException` instance. +async def stop_all(stops: Iterable[_Stop]) -> list[Exception]: # noqa: DOC503 + """Run every stop, in order, even if an earlier one failed. + + A cancellation does not skip the remaining stops either. They all run, + and the cancellation is raised again once they are done. Giving up half + way is exactly what a cleanup is there to prevent, and the stops this is + used with are bounded: they wait for tasks that were already asked to + stop. + + Args: + stops: What to stop, and how. + + Returns: + The errors the stops raised, in order. They are logged as they + happen, so a caller that has no way to report them, like the + cleanup of a cancelled task, can ignore them. + + Raises: + BaseException: The cancellation, if one arrived while stopping, once + every stop has run. + """ + errors: list[Exception] = [] + cancellation: BaseException | None = None + + for description, stop in stops: + try: + await stop() + except Exception as error: # pylint: disable=broad-except + _logger.error("Failed to stop %s", description, exc_info=error) + errors.append(error) + except BaseException as error: # pylint: disable=broad-except + _logger.warning( + "Cancelled while stopping %s, finishing the rest first", description + ) + cancellation = error + + if cancellation is not None: + raise cancellation + + return errors + + +def cancel_service(service: BackgroundService, msg: str | None = None) -> None: + """Cancel a service, unless it is already being cancelled. + + `BackgroundService.cancel()` always cancels the service's tasks. Cancelling + a task that is already being cancelled interrupts the cleanup the first + cancellation started, which would leave half of it undone. So a service + that is already being cancelled is left alone here. + + Otherwise the service's own `cancel()` is used, so that everything else it + does stays done. An `Actor`, for example, also remembers there that it was + cancelled, and without that it gets restarted when its cleanup fails. + + Args: + service: The service to cancel. + msg: The message to pass to the tasks being cancelled. + """ + if any(task.cancelling() for task in service.tasks): + return + + service.cancel(msg) + + +# The noqa is needed because pydoclint cannot tell that `rest` below is +# a `BaseExceptionGroup` instance. +async def stop_service(service: BackgroundService, msg: str) -> None: # noqa: DOC503 + """Stop a service, without interrupting a stop that is already running. + + Args: + service: The service to stop. + msg: The message to pass to the tasks being cancelled. + + Raises: + BaseExceptionGroup: If a task of the service failed. Cancellations are + not failures and are not reported. + """ + cancel_service(service, msg) + + try: + await service.wait() + except BaseExceptionGroup as group: + if (rest := group.split(asyncio.CancelledError)[1]) is not None: + # Filtering out the cancellations we asked for ourselves, so this + # really is a new error, not the one we just filtered. + raise rest # pylint: disable=raise-missing-from + + +async def stop_actors( + actors: Iterable[tuple[Actor, Broadcast[Any]]], msg: str +) -> list[Exception]: + """Stop every actor and close the channel it got its updates from. + + Closing a channel is a step of its own, so it still happens when stopping + the actor failed, or when the caller was cancelled in the middle of it. + An actor cancels itself as the first thing its `stop()` does, before + anything is awaited there, so a cancellation of the caller cannot leave + an actor running that nobody holds any more either. + + Args: + actors: The actors to stop, each with the channel it reads from. + msg: The message to pass to the actors being stopped. + + Returns: + The errors raised while stopping, in order, already logged. + """ + stops: list[_Stop] = [] + for actor, channel in actors: + stops += [ + (f"actor {actor.name!r}", partial(actor.stop, msg)), + (f"the update channel of actor {actor.name!r}", channel.aclose), + ] + + return await stop_all(stops) diff --git a/tests/test_shutdown.py b/tests/test_shutdown.py new file mode 100644 index 0000000..e42ec28 --- /dev/null +++ b/tests/test_shutdown.py @@ -0,0 +1,695 @@ +# License: MIT +# Copyright © 2025 Frequenz Energy-as-a-Service GmbH + +"""Tests that stopping the dispatcher cleans everything it started up again.""" + +import asyncio +import gc +from collections.abc import Awaitable, Callable +from contextlib import suppress +from dataclasses import replace +from datetime import datetime, timedelta, timezone +from typing import Any, cast +from unittest.mock import patch + +import async_solipsism +import pytest +from frequenz.channels import Broadcast, Receiver, Sender +from frequenz.client.common.microgrid import MicrogridId +from frequenz.client.dispatch.recurrence import RecurrenceRule +from frequenz.client.dispatch.test.client import FakeClient +from frequenz.client.dispatch.test.generator import DispatchGenerator +from frequenz.client.dispatch.types import Dispatch as BaseDispatch +from frequenz.client.dispatch.types import DispatchId +from frequenz.sdk.actor import Actor +from pytest import fixture +from typing_extensions import override + +from frequenz.dispatch import ActorDispatcher, Dispatch, Dispatcher, DispatchInfo +from frequenz.dispatch._actor_dispatcher import DispatchActorId +from frequenz.dispatch._bg_service import DispatchScheduler +from frequenz.dispatch._stopping import cancel_service, stop_actors + +_TIMEOUT = 30.0 +"""How long to wait for a shutdown before calling it a hang. + +The tests run on a simulated clock, so this is not real waiting time, it only +turns a hang into a failed test instead of a test that never ends. +""" + +_SLOW_STOP = 5.0 +"""How long an actor in these tests takes to stop, in simulated seconds. + +Stopping is deliberately slow, so that a caller that stops an actor without +waiting for it fails these tests instead of passing by luck. +""" + +_ActorFactory = Callable[[DispatchInfo, Receiver[DispatchInfo]], Awaitable[Actor]] + + +@fixture +def event_loop_policy() -> async_solipsism.EventLoopPolicy: + """Set the event loop policy to use async_solipsism.""" + policy = async_solipsism.EventLoopPolicy() + asyncio.set_event_loop_policy(policy) + return policy + + +def _now() -> datetime: + """Return the current time in UTC.""" + return datetime.now(tz=timezone.utc) + + +class _SleepingActor(Actor): + """An actor that runs until it is stopped, and is slow to stop.""" + + def __init__( + self, initial_dispatch: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> None: + """Initialize the actor. + + Args: + initial_dispatch: The dispatch that started this actor. + receiver: The receiver for dispatch updates. + """ + super().__init__(name="SleepingActor") + self.initial_dispatch = initial_dispatch + self.receiver = receiver + + async def _run(self) -> None: + try: + while True: + await asyncio.sleep(1) + finally: + await asyncio.sleep(_SLOW_STOP) + + +class _FailingStopActor(_SleepingActor): + """An actor that fails to stop, and keeps running when asked to stop.""" + + @override + async def stop(self, msg: str | None = None) -> None: + """Fail to stop. + + Args: + msg: The message that was meant for the actor. + + Raises: + RuntimeError: Always. + """ + raise RuntimeError("Stopping this actor fails on purpose") + + async def force_stop(self) -> None: + """Stop the actor for real, so a test can clean it up.""" + await super(_SleepingActor, self).stop("Test over") + + +class _FailingCleanupActor(_SleepingActor): + """An actor whose own cleanup fails when it is stopped.""" + + @override + async def _run(self) -> None: + try: + while True: + await asyncio.sleep(1) + finally: + raise RuntimeError("The cleanup of this actor fails on purpose") + + +def _recording_factory( + actors: list[Actor], *, first_fails_to_stop: bool = False +) -> _ActorFactory: + """Return an actor factory that records every actor it creates. + + Args: + actors: The list to record the created actors in. + first_fails_to_stop: Whether the first actor should fail to stop. + + Returns: + The actor factory. + """ + + async def factory( + initial_dispatch: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> Actor: + actor: Actor + if first_fails_to_stop and not actors: + actor = _FailingStopActor(initial_dispatch, receiver) + else: + actor = _SleepingActor(initial_dispatch, receiver) + actors.append(actor) + return actor + + return factory + + +def _started_dispatch( + generator: DispatchGenerator, + dispatch_type: str, + dispatch_id: int = 1, + *, + active: bool = True, +) -> BaseDispatch: + """Return a dispatch of the given type that is running right now. + + Args: + generator: The generator to create the dispatch with. + dispatch_type: The type of the dispatch. + dispatch_id: The ID of the dispatch. + active: Whether the dispatch is active. An inactive one is a stop. + + Returns: + A started dispatch, or a stop for one. + """ + return replace( + generator.generate_dispatch(), + id=DispatchId(dispatch_id), + type=dispatch_type, + active=active, + dry_run=False, + start_time=_now() - timedelta(minutes=1), + duration=timedelta(minutes=10), + recurrence=RecurrenceRule(), + ) + + +def _channel_of(service: ActorDispatcher, dispatch_id: int) -> Broadcast[DispatchInfo]: + """Return the update channel of the actor for the given dispatch. + + Args: + service: The actor dispatcher that started the actor. + dispatch_id: The ID of the dispatch the actor was started for. + + Returns: + The channel the actor gets its dispatch updates from. + """ + # pylint: disable-next=protected-access + status = service._actors[DispatchActorId(dispatch_id)] + assert status.actor_and_channel is not None + return status.actor_and_channel.channel + + +async def _running_actor_dispatcher( + factory: _ActorFactory, dispatch_ids: tuple[int, ...] +) -> tuple[ActorDispatcher, Sender[Dispatch]]: + """Return a started actor dispatcher with one actor per given dispatch. + + Args: + factory: The factory to create the actors with. + dispatch_ids: The IDs of the dispatches to start actors for. + + Returns: + The actor dispatcher and the sender its dispatches come from. + """ + channel = Broadcast[Dispatch](name="shutdown test channel") + service = ActorDispatcher( + actor_factory=factory, + running_status_receiver=channel.new_receiver(), + dispatch_identity=lambda dispatch: DispatchActorId(dispatch.id), + ) + service.start() + await asyncio.sleep(1) + + generator = DispatchGenerator() + sender = channel.new_sender() + for dispatch_id in dispatch_ids: + await sender.send( + Dispatch(_started_dispatch(generator, "SHUTDOWN_TEST", dispatch_id)) + ) + await asyncio.sleep(1) + + return service, sender + + +class _FakeDispatchClient(FakeClient): + """A fake client that accepts the arguments the dispatcher passes.""" + + # pylint: disable=too-many-arguments,unused-argument + def __init__( + self, + *, + server_url: str, + auth_key: str | None = None, + key: str | None = None, + sign_secret: str | None = None, + call_timeout: timedelta, + stream_timeout: timedelta, + ) -> None: + """Initialize the fake client. + + Args: + server_url: The server URL, only checked to be set. + auth_key: The authentication key, only checked to be set. + key: The deprecated key, ignored. + sign_secret: The signing secret, ignored. + call_timeout: The call timeout, only checked to be set. + stream_timeout: The stream timeout, only checked to be set. + """ + assert server_url + assert auth_key or key + assert call_timeout + assert stream_timeout + super().__init__() + + # pylint: enable=too-many-arguments,unused-argument + + +async def test_stopping_actor_dispatcher_stops_its_actors() -> None: + """Test that stopping the actor dispatcher stops the actors it started.""" + actors: list[Actor] = [] + service, _ = await _running_actor_dispatcher(_recording_factory(actors), (1,)) + + assert len(actors) == 1 + assert actors[0].is_running is True + + await asyncio.wait_for(service.stop(), timeout=_TIMEOUT) + + assert actors[0].is_running is False + + +async def test_actor_dispatcher_stops_every_actor_even_if_one_fails( + caplog: pytest.LogCaptureFixture, +) -> None: + """Test that one actor failing to stop does not keep another one running.""" + actors: list[Actor] = [] + service, _ = await _running_actor_dispatcher( + _recording_factory(actors, first_fails_to_stop=True), (1, 2) + ) + + assert len(actors) == 2 + assert actors[0].is_running is True + assert actors[1].is_running is True + + failing_channel = _channel_of(service, 1) + + # The failure is reported here, not raised while the service was stopping. + with pytest.raises(BaseExceptionGroup) as stop_error: + await asyncio.wait_for(service.stop(), timeout=_TIMEOUT) + + assert [type(error) for error in stop_error.value.exceptions] == [RuntimeError] + assert actors[1].is_running is False + assert failing_channel.is_closed is True + # pylint: disable-next=protected-access + assert service._actors == {} + assert "Failed to stop actor" in caplog.text + + # The failing actor was never stopped, so stop it for real. + await asyncio.wait_for( + cast(_FailingStopActor, actors[0]).force_stop(), timeout=_TIMEOUT + ) + + +async def test_actor_dispatcher_stop_keeps_the_cancellation() -> None: + """Test that an actor failing to stop does not swallow the cancellation.""" + actors: list[Actor] = [] + service, _ = await _running_actor_dispatcher( + _recording_factory(actors, first_fails_to_stop=True), (1,) + ) + + assert len(actors) == 1 + task = next(iter(service.tasks)) + + with pytest.raises(BaseExceptionGroup): + await asyncio.wait_for(service.stop(), timeout=_TIMEOUT) + + # The actor failing to stop is reported, but the task is still cancelled: + # the report must not take the place of the cancellation. + assert task.cancelled() is True + + await asyncio.wait_for( + cast(_FailingStopActor, actors[0]).force_stop(), timeout=_TIMEOUT + ) + + +async def test_cancel_while_stopping_an_actor_closes_its_channel() -> None: + """Test that a cancel while an actor stops still closes its channel.""" + actors: list[Actor] = [] + service, sender = await _running_actor_dispatcher(_recording_factory(actors), (1,)) + channel = _channel_of(service, 1) + + # A stop event takes the actor out of the dispatcher's own bookkeeping, so + # from here on nothing else could close its channel any more. + await sender.send( + Dispatch(_started_dispatch(DispatchGenerator(), "SHUTDOWN_TEST", active=False)) + ) + await asyncio.sleep(2) + + assert channel.is_closed is False + assert actors[0].is_running is True + + # The actor is half way through stopping, and now the dispatcher itself is + # asked to stop. + await asyncio.wait_for(service.stop(), timeout=_TIMEOUT) + + assert channel.is_closed is True + + await asyncio.sleep(_SLOW_STOP) + assert actors[0].is_running is False + + +async def test_stopping_actors_survives_a_pending_cancellation() -> None: + """Test that a cancellation already pending cannot leave an actor behind.""" + dispatch = Dispatch(_started_dispatch(DispatchGenerator(), "SHUTDOWN_TEST")) + channel = Broadcast[DispatchInfo](name="pending cancellation test channel") + actor = _SleepingActor( + DispatchInfo(target=dispatch.target, dry_run=False, options={}, _src=dispatch), + channel.new_receiver(), + ) + actor.start() + await asyncio.sleep(1) + + assert actor.is_running is True + + async def stopping() -> None: + current = asyncio.current_task() + assert current is not None + # Pending from here on: the very next await raises it, before the + # actor has been asked to stop anything. + current.cancel() + await stop_actors([(actor, channel)], "The actor dispatcher was stopped") + + task = asyncio.create_task(stopping()) + with pytest.raises(asyncio.CancelledError): + await task + + assert channel.is_closed is True + + await asyncio.sleep(_SLOW_STOP) + assert actor.is_running is False + + +async def test_stopping_an_actor_whose_cleanup_fails_does_not_restart_it() -> None: + """Test that stopping an actor whose cleanup fails really stops it.""" + dispatch = Dispatch(_started_dispatch(DispatchGenerator(), "SHUTDOWN_TEST")) + channel = Broadcast[DispatchInfo](name="failing cleanup test channel") + actor = _FailingCleanupActor( + DispatchInfo(target=dispatch.target, dry_run=False, options={}, _src=dispatch), + channel.new_receiver(), + ) + actor.start() + await asyncio.sleep(1) + + assert actor.is_running is True + + cancel_service(actor, "The actor dispatcher was stopped") + + # An actor that is not told that it was cancelled, but only has its task + # cancelled, restarts itself when its cleanup fails. + await asyncio.sleep(Actor.RESTART_DELAY.total_seconds() + 1) + restarted = actor.is_running + + # Leave nothing running behind, whatever happened above. + actor.cancel() + with suppress(BaseException): + await asyncio.wait_for( + asyncio.gather(*actor.tasks, return_exceptions=True), timeout=_TIMEOUT + ) + + assert restarted is False + + +async def test_stop_without_stop_managing_does_not_hang() -> None: + """Test that the dispatcher stops when a type is still being managed.""" + with patch("frequenz.dispatch._dispatcher.DispatchApiClient", _FakeDispatchClient): + dispatcher = Dispatcher( + microgrid_id=MicrogridId(1), + server_url="grpc://test-url", + auth_key="test-key", + ) + client = cast(FakeClient, dispatcher.client) + client.set_dispatches( + MicrogridId(1), [_started_dispatch(DispatchGenerator(), "SHUTDOWN_TEST")] + ) + + actors: list[Actor] = [] + dispatcher.start() + await dispatcher.wait_for_initialization() + + await dispatcher.start_managing( + dispatch_type="SHUTDOWN_TEST", + actor_factory=_recording_factory(actors), + ) + await asyncio.sleep(1) + + assert len(actors) == 1 + assert actors[0].is_running is True + + # No stop_managing() call here on purpose: stopping the dispatcher has + # to work on its own. + await asyncio.wait_for(dispatcher.stop(), timeout=_TIMEOUT) + + assert dispatcher.is_managed("SHUTDOWN_TEST") is False + assert actors[0].is_running is False + + # Waiting for a dispatcher that was stopped has to return right away. + await asyncio.wait_for(dispatcher.wait(), timeout=_TIMEOUT) + + +async def test_dispatcher_stops_every_managed_type_even_if_one_fails( + caplog: pytest.LogCaptureFixture, +) -> None: + """Test that one managed type failing to stop does not keep another one.""" + with patch("frequenz.dispatch._dispatcher.DispatchApiClient", _FakeDispatchClient): + dispatcher = Dispatcher( + microgrid_id=MicrogridId(1), + server_url="grpc://test-url", + auth_key="test-key", + ) + generator = DispatchGenerator() + cast(FakeClient, dispatcher.client).set_dispatches( + MicrogridId(1), + [ + _started_dispatch(generator, "FAILING_TYPE", 1), + _started_dispatch(generator, "HEALTHY_TYPE", 2), + ], + ) + + actors: list[Actor] = [] + dispatcher.start() + await dispatcher.wait_for_initialization() + + for dispatch_type in ("FAILING_TYPE", "HEALTHY_TYPE"): + await dispatcher.start_managing( + dispatch_type=dispatch_type, + actor_factory=_recording_factory(actors), + ) + await asyncio.sleep(1) + + assert len(actors) == 2 + + # pylint: disable-next=protected-access + failing = dispatcher._actor_dispatchers["FAILING_TYPE"] + failing_task = next(iter(failing.tasks)) + + async def failing_stop(msg: str | None = None) -> None: + raise RuntimeError("Stopping this managed type fails on purpose") + + # Both, so that the test keeps failing the type however the dispatcher + # stops it. The log check below catches it if neither is used. + setattr(failing, "stop", failing_stop) + setattr(failing, "wait", failing_stop) + + await asyncio.wait_for(dispatcher.stop(), timeout=_TIMEOUT) + + assert actors[1].is_running is False + assert dispatcher.is_managed("FAILING_TYPE") is False + assert dispatcher.is_managed("HEALTHY_TYPE") is False + assert "Failed to stop the managed dispatch type 'FAILING_TYPE'" in caplog.text + + # The failing type was left behind, so wait for its cancelled task. + await asyncio.wait_for( + asyncio.gather(failing_task, return_exceptions=True), timeout=_TIMEOUT + ) + + +async def test_stop_managing_waits_for_a_stop_already_running() -> None: + """Test that stop_managing does not interrupt a stop already running.""" + with patch("frequenz.dispatch._dispatcher.DispatchApiClient", _FakeDispatchClient): + dispatcher = Dispatcher( + microgrid_id=MicrogridId(1), + server_url="grpc://test-url", + auth_key="test-key", + ) + generator = DispatchGenerator() + cast(FakeClient, dispatcher.client).set_dispatches( + MicrogridId(1), + [ + _started_dispatch(generator, "SHUTDOWN_TEST", 1), + _started_dispatch(generator, "SHUTDOWN_TEST", 2), + ], + ) + + actors: list[Actor] = [] + dispatcher.start() + await dispatcher.wait_for_initialization() + + await dispatcher.start_managing( + dispatch_type="SHUTDOWN_TEST", + actor_factory=_recording_factory(actors), + ) + await asyncio.sleep(1) + + assert len(actors) == 2 + assert [actor.is_running for actor in actors] == [True, True] + + # Asking to stop starts stopping the first actor, which takes a while. + dispatcher.cancel() + await asyncio.sleep(2) + assert [actor.is_running for actor in actors] == [True, True] + + await asyncio.wait_for( + dispatcher.stop_managing("SHUTDOWN_TEST"), timeout=_TIMEOUT + ) + + assert [actor.is_running for actor in actors] == [False, False] + + # The type is gone from the dispatcher now, so a later stop can no + # longer reach its actors. They have to be stopped already. + await asyncio.wait_for(dispatcher.stop(), timeout=_TIMEOUT) + + assert [actor.is_running for actor in actors] == [False, False] + + +async def test_stop_after_cancel_still_stops_the_actors() -> None: + """Test that stopping after a cancel does not interrupt the cancel.""" + with patch("frequenz.dispatch._dispatcher.DispatchApiClient", _FakeDispatchClient): + dispatcher = Dispatcher( + microgrid_id=MicrogridId(1), + server_url="grpc://test-url", + auth_key="test-key", + ) + generator = DispatchGenerator() + cast(FakeClient, dispatcher.client).set_dispatches( + MicrogridId(1), + [ + _started_dispatch(generator, "SHUTDOWN_TEST", 1), + _started_dispatch(generator, "SHUTDOWN_TEST", 2), + ], + ) + + actors: list[Actor] = [] + dispatcher.start() + await dispatcher.wait_for_initialization() + + await dispatcher.start_managing( + dispatch_type="SHUTDOWN_TEST", + actor_factory=_recording_factory(actors), + ) + await asyncio.sleep(1) + + assert [actor.is_running for actor in actors] == [True, True] + + # Asking to stop starts stopping the first actor, which takes a while. + dispatcher.cancel() + await asyncio.sleep(2) + + # `stop()` asks again, and that must not interrupt the first ask. + await asyncio.wait_for(dispatcher.stop(), timeout=_TIMEOUT) + + assert [actor.is_running for actor in actors] == [False, False] + + +async def test_wait_cancelled_during_cleanup_keeps_the_original_error() -> None: + """Test that a cancelled wait still carries the error it was stopping for.""" + with patch("frequenz.dispatch._dispatcher.DispatchApiClient", _FakeDispatchClient): + dispatcher = Dispatcher( + microgrid_id=MicrogridId(1), + server_url="grpc://test-url", + auth_key="test-key", + ) + cast(FakeClient, dispatcher.client).set_dispatches( + MicrogridId(1), [_started_dispatch(DispatchGenerator(), "SHUTDOWN_TEST")] + ) + + actors: list[Actor] = [] + dispatcher.start() + await dispatcher.wait_for_initialization() + + await dispatcher.start_managing( + dispatch_type="SHUTDOWN_TEST", + actor_factory=_recording_factory(actors), + ) + await asyncio.sleep(1) + + original = RuntimeError("The local dispatch service failed") + + async def failing_wait() -> None: + raise original + + # pylint: disable-next=protected-access + instance = dispatcher._actor_dispatchers["SHUTDOWN_TEST"] + instance_task = next(iter(instance.tasks)) + # pylint: disable-next=protected-access + setattr(dispatcher._bg_service, "wait", failing_wait) + dispatcher.cancel() + + waiting = asyncio.create_task(dispatcher.wait()) + await asyncio.sleep(1) + + # The cleanup is stopping the actor now, which takes a while. + assert waiting.done() is False + assert actors[0].is_running is True + + waiting.cancel() + with pytest.raises(asyncio.CancelledError) as cancelled: + await waiting + + assert cancelled.value.__context__ is original + + # pylint: disable-next=protected-access + delattr(dispatcher._bg_service, "wait") + await asyncio.wait_for(dispatcher.stop(), timeout=_TIMEOUT) + await asyncio.wait_for( + asyncio.gather(instance_task, return_exceptions=True), timeout=_TIMEOUT + ) + + assert actors[0].is_running is False + + +async def test_stopping_scheduler_stops_the_dispatch_stream() -> None: + """Test that stopping the scheduler also stops the stream it started.""" + reported: list[dict[str, Any]] = [] + asyncio.get_running_loop().set_exception_handler( + lambda _loop, context: reported.append(context) + ) + + microgrid_id = MicrogridId(1) + client = FakeClient() + + # Created before the scheduler starts, so that the receiver the scheduler + # takes from it can be recorded. The scheduler gets this very same stream. + # pylint: disable-next=protected-access + streamer = client._get_stream(microgrid_id=microgrid_id) + receivers: list[Receiver[Any]] = [] + new_receiver = streamer.new_receiver + + def recording_new_receiver(**kwargs: Any) -> Receiver[Any]: + receiver = new_receiver(**kwargs) + receivers.append(receiver) + return receiver + + setattr(streamer, "new_receiver", recording_new_receiver) + + service = DispatchScheduler(microgrid_id=microgrid_id, client=client) + service.start() + await service.wait_for_initialization() + await asyncio.sleep(1) + + assert streamer.is_running is True + assert len(receivers) == 1 + + await asyncio.wait_for(service.stop(), timeout=_TIMEOUT) + + assert streamer.is_running is False + + # The receiver has to be closed too, or it is left reading from a channel + # that was closed under it, which leaves its own tasks behind. + # pylint: disable-next=protected-access + assert receivers[0]._pending == set() + + # Anything the shutdown left behind shows up as a task whose exception was + # never retrieved, so make sure nothing was reported. + del receivers[:] + gc.collect() + await asyncio.sleep(1) + assert not reported, f"The shutdown left something behind: {reported}"