Skip to content
Open
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
4 changes: 4 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@
## Bug Fixes

<!-- Here goes notable bug fixes that are worth a special mention or explanation -->

* 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.
4 changes: 2 additions & 2 deletions src/frequenz/dispatch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
112 changes: 63 additions & 49 deletions src/frequenz/dispatch/_actor_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,70 +9,29 @@
"""

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
from frequenz.channels.timer import MonotonicTimer, SkipMissedAndDrift
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."""

Expand Down Expand Up @@ -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],
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 = [
Expand Down
22 changes: 17 additions & 5 deletions src/frequenz/dispatch/_bg_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
48 changes: 48 additions & 0 deletions src/frequenz/dispatch/_continuation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down
Loading