From 23ce8088dda6d0d099f7cf7f3ae728a0b5fb5b65 Mon Sep 17 00:00:00 2001 From: "Mathias L. Baumann" Date: Thu, 15 Oct 2026 18:35:20 +0200 Subject: [PATCH 1/3] Avoid a zero timer interval for back-to-back dispatches When one dispatch stops exactly when another starts, the wait for the second event was 0, which raised ZeroDivisionError in the timer. Use the smallest interval the timer accepts instead, and park the timer for an hour when no events are queued. Signed-off-by: Mathias L. Baumann --- src/frequenz/dispatch/_bg_service.py | 34 ++++++++++++++++++++++- tests/test_dispatcher_scheduler.py | 40 ++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/src/frequenz/dispatch/_bg_service.py b/src/frequenz/dispatch/_bg_service.py index 67239d5f..dd7aaa2c 100644 --- a/src/frequenz/dispatch/_bg_service.py +++ b/src/frequenz/dispatch/_bg_service.py @@ -545,8 +545,40 @@ def _update_timer(self, timer: Timer) -> None: """Update the timer to the next event.""" if self._scheduled_events: due_at: datetime = self._scheduled_events[0].time - timer.reset(interval=due_at - datetime.now(timezone.utc)) + interval = due_at - datetime.now(timezone.utc) + # Two scheduled events landing at (or within microseconds of) the + # exact same instant -- e.g. one dispatch's stop and another's + # start sharing a boundary -- is a normal, expected shape (see + # `QueueItem`'s own docstring on same-time start/stop ordering). + # Once the first of the pair is processed, this recomputed + # interval for the second can be exactly zero or slightly + # negative. `Timer.reset()` accepts that value without complaint, + # but a zero interval later crashes the timer's OWN drift + # correction with a `ZeroDivisionError` in + # `MissedTickPolicy.calculate_next_tick_time` (`drift % interval`). + # Floor it to the smallest positive interval `Timer` itself + # accepts, instead: the due event is already due, so it fires on + # the very next tick either way, but doesn't poison the timer's + # internal state. + min_interval = timedelta(microseconds=1) + interval = max(interval, min_interval) + timer.reset(interval=interval) _logger.debug("Next event scheduled at %s", self._scheduled_events[0].time) + else: + # With nothing queued, leave the timer running at its last + # interval, which can be as small as the microsecond floor above. + # `Timer` is periodic, so it then keeps firing at that interval + # until a new dispatch event is scheduled -- potentially for + # hours, burning CPU for no reason. Park it at a long interval + # instead; the next call to `_update_timer()` (from whichever + # caller schedules something new) resets it to the real due + # time as soon as something is queued. + # Stay strictly below `asyncio.base_events.MAXIMUM_SELECT_TIMEOUT` + # (1 day): `asyncio`'s own selector treats a timeout at or above + # that as "sleep forever" and some test event loops (e.g. + # `async_solipsism`) raise for it. + timer.reset(interval=timedelta(hours=1)) + _logger.debug("No events scheduled, parking the timer") def _remove_scheduled(self, dispatch: Dispatch) -> "QueueItem | None": """Remove a dispatch from the scheduled events. diff --git a/tests/test_dispatcher_scheduler.py b/tests/test_dispatcher_scheduler.py index 833c9f6a..a7db07d3 100644 --- a/tests/test_dispatcher_scheduler.py +++ b/tests/test_dispatcher_scheduler.py @@ -14,11 +14,13 @@ import async_solipsism import time_machine from frequenz.channels import Receiver +from frequenz.channels.timer import Timer from frequenz.client.common.microgrid import MicrogridId from frequenz.client.dispatch.recurrence import RecurrenceRule from frequenz.client.dispatch.test.client import FakeClient, to_create_params from frequenz.client.dispatch.test.generator import DispatchGenerator from pytest import fixture +from pytest_mock import MockerFixture from frequenz.dispatch import Dispatch, DispatchEvent from frequenz.dispatch._bg_service import DispatchScheduler @@ -50,6 +52,44 @@ def _now() -> datetime: return datetime.now(tz=timezone.utc) +def test_update_timer_floors_already_due_interval( + generator: DispatchGenerator, + microgrid_id: MicrogridId, + client: FakeClient, + mocker: MockerFixture, +) -> None: + """Keep a same-boundary follow-up timer interval strictly positive.""" + scheduler = DispatchScheduler(microgrid_id=microgrid_id, client=client) + dispatch = Dispatch(generator.generate_dispatch()) + scheduler._scheduled_events.append( # pylint: disable=protected-access + DispatchScheduler.QueueItem( + time=_now() - timedelta(microseconds=1), + dispatch=dispatch, + stop_event=False, + ) + ) + timer = mocker.create_autospec(Timer, instance=True) + + scheduler._update_timer(timer) # pylint: disable=protected-access + + assert timer.reset.call_args.kwargs["interval"] == timedelta(microseconds=1) + + +def test_update_timer_parks_timer_when_queue_is_empty( + microgrid_id: MicrogridId, + client: FakeClient, + mocker: MockerFixture, +) -> None: + """Don't leave a tiny interval behind once no events are queued.""" + scheduler = DispatchScheduler(microgrid_id=microgrid_id, client=client) + timer = mocker.create_autospec(Timer, instance=True) + + scheduler._update_timer(timer) # pylint: disable=protected-access + + timer.reset.assert_called_once() + assert timer.reset.call_args.kwargs["interval"] >= timedelta(minutes=1) + + @fixture def microgrid_id() -> MicrogridId: """Return a random microgrid ID.""" From 11b71d6b6f0ca28f684a51b7dbc0c71cef572699 Mon Sep 17 00:00:00 2001 From: "Mathias L. Baumann" Date: Thu, 15 Oct 2026 18:35:39 +0200 Subject: [PATCH 2/3] Add opt-in support for continuation handovers ActorDispatcher stopped and restarted the actor between two back-to-back dispatches for the same target, even when the new dispatch continues the same work. Add continuation_predicate on Dispatcher.start_managing() to reuse the actor instead, when it implements ContinuationCapable. Otherwise, stop/start as before. Signed-off-by: Mathias L. Baumann --- src/frequenz/dispatch/__init__.py | 5 +- src/frequenz/dispatch/_actor_dispatcher.py | 561 +++++++++++++++++-- src/frequenz/dispatch/_bg_service.py | 15 + src/frequenz/dispatch/_continuation.py | 164 ++++++ src/frequenz/dispatch/_dispatcher.py | 24 +- tests/test_continuation.py | 324 +++++++++++ tests/test_continuation_handover.py | 382 +++++++++++++ tests/test_continuation_realclock.py | 606 +++++++++++++++++++++ 8 files changed, 2045 insertions(+), 36 deletions(-) create mode 100644 src/frequenz/dispatch/_continuation.py create mode 100644 tests/test_continuation.py create mode 100644 tests/test_continuation_handover.py create mode 100644 tests/test_continuation_realclock.py diff --git a/src/frequenz/dispatch/__init__.py b/src/frequenz/dispatch/__init__.py index d2e5dffc..c1cb594e 100644 --- a/src/frequenz/dispatch/__init__.py +++ b/src/frequenz/dispatch/__init__.py @@ -16,8 +16,9 @@ """ -from ._actor_dispatcher import ActorDispatcher, DispatchInfo +from ._actor_dispatcher import ActorDispatcher, ContinuationCapable, DispatchInfo from ._bg_service import MergeStrategy +from ._continuation import is_exact_continuation from ._dispatch import Dispatch from ._dispatcher import Dispatcher from ._event import Created, Deleted, DispatchEvent, Updated @@ -31,8 +32,10 @@ "Updated", "Dispatch", "ActorDispatcher", + "ContinuationCapable", "DispatchInfo", "MergeStrategy", "MergeByType", "MergeByTypeTarget", + "is_exact_continuation", ] diff --git a/src/frequenz/dispatch/_actor_dispatcher.py b/src/frequenz/dispatch/_actor_dispatcher.py index cb79d636..6111bb66 100644 --- a/src/frequenz/dispatch/_actor_dispatcher.py +++ b/src/frequenz/dispatch/_actor_dispatcher.py @@ -1,15 +1,21 @@ # License: All rights reserved # Copyright © 2024 Frequenz Energy-as-a-Service GmbH -"""Helper class to manage actors based on dispatches.""" +"""Helper class to manage actors based on dispatches. + +See [`ActorDispatcher`][frequenz.dispatch.ActorDispatcher]'s "Continuation +handovers" section for an explanation and a worked example of reusing an +actor across an exact continuation. +""" import asyncio +import enum import logging from collections.abc import Callable, Mapping from copy import copy from dataclasses import dataclass -from datetime import timedelta -from typing import Any, Awaitable +from datetime import datetime, timedelta, timezone +from typing import Any, Awaitable, Protocol, runtime_checkable from warnings import warn from frequenz.channels import Broadcast, Receiver, Sender, select @@ -25,6 +31,48 @@ _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.""" @@ -63,6 +111,32 @@ def components(self) -> TargetComponents: _src: Dispatch """The dispatch that triggered this update.""" + @property + def dispatch(self) -> Dispatch: + """The dispatch that triggered this update. + + A public alias for the same dispatch the private `_src` field holds, + so an actor's `accept_continuation` can read the new dispatch (for + example, to get its id or payload) without reaching into a private + attribute. + """ + return self._src + + continuation_of: DispatchId | None + """If set, this update continues a previous dispatch with this id. + + Only ever set by `ActorDispatcher`, when `dispatch` is an exact, + compatible continuation of a dispatch the actor is already running + under (see `continuation_predicate`). A `ContinuationCapable` actor may + accept this update and adopt `dispatch` as its new dispatch, after + checking that `continuation_of` matches the dispatch id it is currently + running under, even though `dispatch.id` differs from that id. + + An actor that does not look at this field is unaffected: it defaults to + `None`, and an actor that only checks `dispatch.id` against its own + dispatch id keeps rejecting cross-id updates exactly as before. + """ + def __init__( self, *, @@ -71,6 +145,7 @@ def __init__( dry_run: bool, options: dict[str, Any], _src: Dispatch, + continuation_of: DispatchId | None = None, ) -> None: """Initialize a new instance. @@ -80,6 +155,8 @@ def __init__( dry_run: Whether this is a dry run. options: The additional options. _src: The dispatch that triggered this update. + continuation_of: If set, the id of a previous dispatch this update + continues. See the `continuation_of` attribute for details. Raises: ValueError: If both `target` and `components` are set, or if neither is set. @@ -102,9 +179,12 @@ def __init__( object.__setattr__(self, "dry_run", dry_run) object.__setattr__(self, "options", options) object.__setattr__(self, "_src", _src) + object.__setattr__(self, "continuation_of", continuation_of) -class ActorDispatcher(BackgroundService): +class ActorDispatcher( + BackgroundService +): # pylint: disable=too-many-instance-attributes """A helper class to manage actors based on dispatches. Example: @@ -203,9 +283,97 @@ async def main(): await run(managing_actor) ``` + + ## Continuation handovers + + By default, when one dispatch stops and a different dispatch starts, + `ActorDispatcher` always stops the old actor and starts a new one, even + if the two dispatches are for the exact same target, back-to-back in + time. For an actor that holds some running state (a power proposal, an + open connection), that stop/start pair is wasted work, and the small + gap between stop and start can matter. + + A continuation handover lets `ActorDispatcher` reuse the SAME actor for + a new dispatch instead, when the new dispatch is an exact, compatible + continuation of the one the actor is already running under: same type, + same target, same `dry_run` mode, and starting exactly when the + predecessor ends. + + This is entirely opt-in and changes nothing by default: + + * The caller must pass `continuation_predicate` to + [`Dispatcher.start_managing`][frequenz.dispatch.Dispatcher.start_managing] + (normally [`is_exact_continuation`][frequenz.dispatch.is_exact_continuation]). + * The actor's class must implement + [`ContinuationCapable`][frequenz.dispatch.ContinuationCapable]. + + When both are true and exactly one matching dispatch is found, the + actor receives a [`DispatchInfo`][frequenz.dispatch.DispatchInfo] with + `continuation_of` set, through + [`ContinuationCapable.accept_continuation`] + [frequenz.dispatch.ContinuationCapable.accept_continuation], instead of + being stopped. In every other case -- the predicate isn't set, the + actor doesn't implement `ContinuationCapable`, the match is ambiguous, + the actor refuses, or `accept_continuation` raises or times out -- + `ActorDispatcher` falls back to the normal stop/start. + + Example: Reusing an actor across an exact continuation + ```python + from typing import Self + + from frequenz.channels import Receiver + from frequenz.client.dispatch.types import DispatchId + from frequenz.dispatch import Dispatcher, DispatchInfo, is_exact_continuation + from frequenz.sdk.actor import Actor + + class MyActor(Actor): + def __init__( + self, + current_dispatch_id: DispatchId, + target_power_w: float, + receiver: Receiver[DispatchInfo], + *, + name: str | None = None, + ) -> None: + super().__init__(name=name) + self.current_dispatch_id = current_dispatch_id + self.target_power_w = target_power_w + self._receiver = receiver + + @classmethod + async def new_with_dispatch( + cls, initial_dispatch: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> Self: + return cls( + initial_dispatch.dispatch.id, + initial_dispatch.options["target_power_w"], + receiver, + ) + + async def accept_continuation(self, update: DispatchInfo) -> bool: + if update.continuation_of != self.current_dispatch_id: + return False # Not continuing the dispatch we're running. + self.current_dispatch_id = update.dispatch.id + self.target_power_w = update.options["target_power_w"] + # Submit self.target_power_w through the existing proposal here. + return True + + async def _run(self) -> None: + # Submit self.target_power_w through the proposal here, then: + async for update in self._receiver: + self.target_power_w = update.options["target_power_w"] + # Submit the updated self.target_power_w here too. + + async def manage(dispatcher: Dispatcher) -> None: + await dispatcher.start_managing( + "MY_TYPE", + actor_factory=MyActor.new_with_dispatch, + continuation_predicate=is_exact_continuation, + ) + ``` """ - @dataclass(frozen=True, kw_only=True) + @dataclass(kw_only=True) class ActorAndChannel: """An actor and its dispatch update sender.""" @@ -218,6 +386,16 @@ class ActorAndChannel: sender: Sender[DispatchInfo] """The sender for dispatch updates.""" + current_dispatch: Dispatch + """The most recent dispatch this actor is known to be running under. + + Updated on every ordinary same-identity update AND on every successful + continuation, so that `continuation_predicate` always compares a new + dispatch against the FRESHEST known state of a running actor (this is + what makes multi-step continuation chains work: a third dispatch is + compared against the second, not the first). + """ + @dataclass(frozen=True, kw_only=True) class ActorStatus: """The running actor or failed dispatch for one actor identity.""" @@ -247,9 +425,18 @@ def __init__( # pylint: disable=too-many-arguments, too-many-positional-argumen running_status_receiver: Receiver[Dispatch], dispatch_identity: Callable[[Dispatch], DispatchActorId] | None = None, retry_interval: timedelta = timedelta(seconds=60), + continuation_predicate: Callable[[Dispatch, Dispatch], bool] | None = None, + dispatches_snapshot: Callable[[], Mapping[DispatchId, Dispatch]] | None = None, + continuation_accept_timeout: timedelta = timedelta(seconds=5), ) -> None: """Initialize the dispatch handler. + `continuation_predicate` and `dispatches_snapshot` are both for + continuation handovers -- see the module docstring. They can only be + enabled through `Dispatcher.start_managing()`, which supplies a + matching pair of both; building this class directly with only one of + them is an error. + Args: actor_factory: A callable that creates an actor with some initial dispatch information. @@ -257,17 +444,54 @@ def __init__( # pylint: disable=too-many-arguments, too-many-positional-argumen dispatch_identity: A function to identify to which actor a dispatch refers. By default, it uses the dispatch ID. retry_interval: How long to wait until trying to start failed actors again. + continuation_predicate: Opt-in, default `None`. Called as + `continuation_predicate(current_dispatch, new_dispatch)` to + decide whether a newly-started dispatch continues the + dispatch an existing actor is already running under. Normally + `is_exact_continuation`. + dispatches_snapshot: Opt-in, default `None`. A zero-argument + callable returning a live, read-only view of every dispatch + currently known, used together with `continuation_predicate` + to confirm a unique predecessor/successor pair. + continuation_accept_timeout: How long to wait for a candidate + actor's `accept_continuation()` before giving up on it. This + is NOT the same as a refusal: a refused actor keeps running + as before, but a timed-out one is stopped (after the + successor has started), because its state can no longer be + trusted. + + Raises: + ValueError: If exactly one of `continuation_predicate` and + `dispatches_snapshot` is given. """ + if (continuation_predicate is None) != (dispatches_snapshot is None): + raise ValueError( + "continuation_predicate and dispatches_snapshot must be given " + "together, or not at all. Continuations can only be enabled " + "through Dispatcher.start_managing()." + ) + super().__init__() self._dispatch_identity: Callable[[Dispatch], DispatchActorId] = ( dispatch_identity if dispatch_identity else lambda d: DispatchActorId(d.id) ) + self._continuation_predicate = continuation_predicate + self._dispatches_snapshot = dispatches_snapshot + self._continuation_accept_timeout = continuation_accept_timeout self._dispatch_rx = running_status_receiver self._retry_timer_rx = Timer(retry_interval, SkipMissedAndDrift()) self._actor_factory = actor_factory self._actors: dict[DispatchActorId, ActorDispatcher.ActorStatus] = {} self._dispatch_status: dict[DispatchId, ActorDispatcher.DispatchStatus] = {} + self._recently_continued: set[DispatchActorId] = set() + """Identities whose actor was just re-keyed away by a continuation. + + The predecessor dispatch's own stop event still arrives later and + finds no actor at its identity -- expected, so it's logged at DEBUG + instead of WARNING. Each identity is removed from this set the first + time that happens, so it can't grow without bound. + """ self._merge_context: ActorDispatcher.MergeContext | None = None def start(self) -> None: @@ -285,6 +509,252 @@ def _set_merge_context( known_dispatches=known_dispatches, ) + def _find_unique_continuation_candidate( + self, dispatch: Dispatch + ) -> tuple[DispatchActorId, "ActorDispatcher.ActorAndChannel"] | None: + """Find the single running actor `dispatch` exactly continues, if any. + + Args: + dispatch: The newly-arrived dispatch, not already matched by + `dispatch_identity` to an existing actor. + + Returns: + The `(identity, actor_and_channel)` of the unique continuation + pair, or `None` if either side of the pair is not unique, or no + running actor implementing `ContinuationCapable` matches. + """ + if self._continuation_predicate is None or self._dispatches_snapshot is None: + return None + + candidates = [ + (identity, actor_status.actor_and_channel) + for identity, actor_status in self._actors.items() + if actor_status.actor_and_channel is not None + and isinstance(actor_status.actor_and_channel.actor, ContinuationCapable) + and self._continuation_predicate( + actor_status.actor_and_channel.current_dispatch, dispatch + ) + ] + + if len(candidates) != 1: + if len(candidates) > 1: + _logger.warning( + "Dispatch %s matches %d continuation predecessor candidates " + "(%s); refusing to guess, starting an independent actor instead", + dispatch.id, + len(candidates), + [identity for identity, _ in candidates], + ) + return None + + predecessor_identity, predecessor = candidates[0] + snapshot = self._dispatches_snapshot() + predecessor_candidates = self._matching_predecessors(dispatch, snapshot) + if ( + len(predecessor_candidates) != 1 + or predecessor_candidates[0].id != predecessor.current_dispatch.id + ): + _logger.warning( + "Dispatch %s matches %d snapshot predecessor candidates (%s); " + "refusing a one-sided actor match and starting an independent " + "actor instead", + dispatch.id, + len(predecessor_candidates), + [candidate.id for candidate in predecessor_candidates], + ) + return None + + successor_candidates = self._matching_successors( + predecessor.current_dispatch, snapshot + ) + if len(successor_candidates) != 1 or successor_candidates[0].id != dispatch.id: + _logger.warning( + "Dispatch %s's predecessor %s matches %d successor candidates " + "(%s); refusing a one-sided match and starting an independent " + "actor instead", + dispatch.id, + predecessor.current_dispatch.id, + len(successor_candidates), + [candidate.id for candidate in successor_candidates], + ) + return None + + return predecessor_identity, predecessor + + def _matching_successors( + self, predecessor: Dispatch, snapshot: Mapping[DispatchId, Dispatch] + ) -> list[Dispatch]: + """Return all already-started snapshot successors of `predecessor`.""" + assert self._continuation_predicate is not None + now = datetime.now(timezone.utc) + return [ + other + for other in snapshot.values() + if other.id != predecessor.id + and other.started_at(now) + and self._continuation_predicate(predecessor, other) + ] + + def _matching_predecessors( + self, successor: Dispatch, snapshot: Mapping[DispatchId, Dispatch] + ) -> list[Dispatch]: + """Return all snapshot predecessors exactly continued by `successor`.""" + assert self._continuation_predicate is not None + return [ + other + for other in snapshot.values() + if other.id != successor.id + and self._continuation_predicate(other, successor) + ] + + async def _continue_actor( + self, + predecessor_identity: DispatchActorId, + predecessor: "ActorDispatcher.ActorAndChannel", + dispatch: Dispatch, + ) -> "_ContinuationOutcome": + """Try to route `dispatch` to `predecessor`'s actor as a continuation. + + The caller already verified `predecessor.actor` implements + `ContinuationCapable` (see `_find_unique_continuation_candidate`). + + Args: + predecessor_identity: The predecessor actor's current identity key. + predecessor: The predecessor actor-and-channel entry. + dispatch: The new dispatch continuing the predecessor. + + Returns: + `ACCEPTED` if the actor adopted `dispatch` and was re-indexed + under its identity; the caller does nothing more. + `REFUSED` if the actor explicitly declined. It is left running + exactly as before: it correctly handled the update, and its + own stop event will stop it normally when it arrives. The + caller must still start a fresh actor for `dispatch`. + `UNKNOWN` if `accept_continuation()` timed out or raised. The + actor's state can no longer be trusted. The caller must + start a fresh actor for `dispatch` FIRST, then stop this + predecessor (`_discard_unresponsive_predecessor`), so the + target is never left without an actor for longer than + necessary. + """ + # The caller only ever finds this predecessor through + # `_find_unique_continuation_candidate`, which already checked this. + assert isinstance(predecessor.actor, ContinuationCapable) + + continuation_update = DispatchInfo( + target=dispatch.target, + dry_run=dispatch.dry_run, + options=dispatch.payload, + _src=dispatch, + continuation_of=predecessor.current_dispatch.id, + ) + + try: + accepted = await asyncio.wait_for( + predecessor.actor.accept_continuation(continuation_update), + timeout=self._continuation_accept_timeout.total_seconds(), + ) + except TimeoutError: + _logger.error( + "Dispatch %s's actor did not respond to a continuation from " + "dispatch %s within %s; starting %s fresh and then stopping " + "the predecessor, since its state can no longer be trusted", + predecessor.current_dispatch.id, + dispatch.id, + self._continuation_accept_timeout, + dispatch.id, + ) + return _ContinuationOutcome.UNKNOWN + except Exception as e: # pylint: disable=broad-except + _logger.error( + "Failed to deliver a continuation update from dispatch %s to " + "dispatch %s; starting %s fresh and then stopping the " + "predecessor, since its state can no longer be trusted", + predecessor.current_dispatch.id, + dispatch.id, + dispatch.id, + exc_info=e, + ) + return _ContinuationOutcome.UNKNOWN + + if not accepted: + _logger.info( + "Dispatch %s's actor explicitly refused the continuation from " + "dispatch %s; starting %s fresh and leaving the predecessor " + "running for its own stop event", + predecessor.current_dispatch.id, + dispatch.id, + dispatch.id, + ) + return _ContinuationOutcome.REFUSED + + new_identity = self._dispatch_identity(dispatch) + del self._actors[predecessor_identity] + predecessor.current_dispatch = dispatch + self._actors[new_identity] = ActorDispatcher.ActorStatus( + actor_and_channel=predecessor + ) + self._recently_continued.add(predecessor_identity) + _logger.info( + "Dispatch %s continues dispatch %s: reused its actor instead of " + "stopping and restarting", + dispatch.id, + continuation_update.continuation_of, + ) + return _ContinuationOutcome.ACCEPTED + + async def _discard_unresponsive_predecessor( + self, + predecessor_identity: DispatchActorId, + predecessor: "ActorDispatcher.ActorAndChannel", + ) -> None: + """Stop and remove a predecessor whose continuation outcome is unknown. + + Only used for `_ContinuationOutcome.UNKNOWN` (a timeout or an + exception): the actor's internal state can't be trusted, so it's + stopped defensively. An explicit `REFUSED` does NOT go through this + -- that actor correctly declined and is left running for its own, + normal stop event. + + Args: + predecessor_identity: The predecessor actor's current identity key. + predecessor: The predecessor actor-and-channel entry to stop. + """ + del self._actors[predecessor_identity] + await predecessor.actor.stop("continuation outcome unknown") + await predecessor.channel.close() + + async def _try_handover( + self, dispatch: Dispatch + ) -> tuple[bool, tuple[DispatchActorId, "ActorDispatcher.ActorAndChannel"] | None]: + """Try a continuation handover for `dispatch`. + + Args: + dispatch: The newly-arrived dispatch that may continue a + running actor's predecessor. + + Returns: + `(True, None)` if the handover succeeded; `_start_actor` does + nothing more. `(False, predecessor)` if `_start_actor` must + start a fresh actor, where `predecessor` is `None` (no + candidate, or an explicit refusal) or the predecessor to + discard AFTER starting the fresh actor (a timeout or an + exception, see `_continue_actor`). + """ + candidate = self._find_unique_continuation_candidate(dispatch) + if candidate is None: + return False, None + + predecessor_identity, predecessor = candidate + outcome = await self._continue_actor( + predecessor_identity, predecessor, dispatch + ) + if outcome is _ContinuationOutcome.ACCEPTED: + return True, None + if outcome is _ContinuationOutcome.UNKNOWN: + return False, (predecessor_identity, predecessor) + return False, None # REFUSED: left running for its own stop event. + async def _start_actor(self, dispatch: Dispatch, identity: DispatchActorId) -> None: """Start the actor the given dispatch refers to. @@ -306,43 +776,56 @@ async def _start_actor(self, dispatch: Dispatch, identity: DispatchActorId) -> N if actor_and_channel: await actor_and_channel.sender.send(dispatch_update) + actor_and_channel.current_dispatch = dispatch _logger.info( "Actor for dispatch type %r is already running, " "sent a dispatch update instead of creating a new actor", dispatch.type, ) - else: - try: - _logger.info("Starting actor for dispatch type %r", dispatch.type) - channel = Broadcast[DispatchInfo]( - name=f"dispatch_updates_channel_instance={identity}", - resend_latest=True, - ) - actor = await self._actor_factory( - dispatch_update, - channel.new_receiver(limit=1, warn_on_overflow=False), - ) + return - actor.start() + handed_over, predecessor_to_discard = await self._try_handover(dispatch) + if handed_over: + return - except Exception as e: # pylint: disable=broad-except - _logger.error( - "Failed to start actor for dispatch type %r", - dispatch.type, - exc_info=e, - ) - self._actors[identity] = ActorDispatcher.ActorStatus( - failed_dispatch=dispatch - ) - else: - # No exception occurred, so we can add the actor to the list - self._actors[identity] = ActorDispatcher.ActorStatus( - actor_and_channel=ActorDispatcher.ActorAndChannel( - actor=actor, - channel=channel, - sender=channel.new_sender(), - ) + try: + _logger.info("Starting actor for dispatch type %r", dispatch.type) + channel = Broadcast[DispatchInfo]( + name=f"dispatch_updates_channel_instance={identity}", + resend_latest=True, + ) + actor = await self._actor_factory( + dispatch_update, + channel.new_receiver(limit=1, warn_on_overflow=False), + ) + + actor.start() + + except Exception as e: # pylint: disable=broad-except + _logger.error( + "Failed to start actor for dispatch type %r", + dispatch.type, + exc_info=e, + ) + self._actors[identity] = ActorDispatcher.ActorStatus( + failed_dispatch=dispatch + ) + else: + # No exception occurred, so we can add the actor to the list + self._actors[identity] = ActorDispatcher.ActorStatus( + actor_and_channel=ActorDispatcher.ActorAndChannel( + actor=actor, + channel=channel, + sender=channel.new_sender(), + current_dispatch=dispatch, ) + ) + + if predecessor_to_discard is not None: + discard_identity, discard_actor_and_channel = predecessor_to_discard + await self._discard_unresponsive_predecessor( + discard_identity, discard_actor_and_channel + ) async def _stop_actor( self, @@ -365,6 +848,16 @@ async def _stop_actor( _logger.info("Stopping actor for dispatch type %r", stopping_dispatch.type) await actor_and_channel.actor.stop(msg) await actor_and_channel.channel.close() + elif identity in self._recently_continued: + # A continuation handover already moved this identity's actor + # elsewhere (see `_continue_actor`); its own stop arriving here + # and finding nothing is expected, not a problem. + self._recently_continued.discard(identity) + _logger.debug( + "Actor for dispatch type %r was already handed over to a " + "continuation, ignoring its stop request", + stopping_dispatch.type, + ) else: _logger.warning( "Actor for dispatch type %r is not running, ignoring stop request", diff --git a/src/frequenz/dispatch/_bg_service.py b/src/frequenz/dispatch/_bg_service.py index dd7aaa2c..acc80753 100644 --- a/src/frequenz/dispatch/_bg_service.py +++ b/src/frequenz/dispatch/_bg_service.py @@ -14,6 +14,7 @@ from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from heapq import heapify, heappop, heappush +from types import MappingProxyType import grpc.aio from frequenz.channels import Broadcast, Receiver, select, selected_from @@ -157,6 +158,20 @@ async def wait_for_initialization(self) -> None: """Wait for the initial fetch to complete.""" await self._initial_fetch_event.wait() + def dispatches_snapshot(self) -> Mapping[DispatchId, Dispatch]: + """Return a read-only, live view of every dispatch currently known. + + Used by `ActorDispatcher`'s opt-in `dispatches_snapshot` parameter, + to confirm a unique continuation pair -- see + `ActorDispatcher.continuation_predicate`. + + Returns: + A live, read-only mapping (a `MappingProxyType` over the same + dict this scheduler mutates, so callers see updates but + cannot make any themselves). + """ + return MappingProxyType(self._dispatches) + # pylint: disable=redefined-builtin def new_lifecycle_events_receiver(self, type: str) -> Receiver[DispatchEvent]: """Create a new receiver for lifecycle events. diff --git a/src/frequenz/dispatch/_continuation.py b/src/frequenz/dispatch/_continuation.py new file mode 100644 index 00000000..3684657a --- /dev/null +++ b/src/frequenz/dispatch/_continuation.py @@ -0,0 +1,164 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Opt-in support for exactly-adjacent, compatible dispatch continuations. + +This module is deliberately separate from `_merge_strategies.py`: `MergeByType` +and `MergeByTypeTarget` merge dispatches that merely share (type[, target], +dry_run), with no regard for whether their time windows are adjacent or +overlapping. That is the wrong tool for "the next back-to-back dispatch window +is really a continuation of the previous one" -- a genuine, independent overlap +on the same target must NOT be treated as a continuation (see +`is_exact_continuation`). Nothing here changes `MergeByType`/`MergeByTypeTarget` +or `ActorDispatcher`'s default (per-dispatch-ID) behaviour; everything is opt-in. + +There is deliberately no scheduler-side filter/strategy in this module. Every +dispatch stop and start is always forwarded as-is; `ActorDispatcher` is the +only place that decides what to do with it, using `continuation_predicate`. +See `ActorDispatcher`'s "Continuation handovers" section for an overview +and a worked example. +""" + +from __future__ import annotations + +from frequenz.client.dispatch.types import ( + BatteryType, + EvChargerType, + InverterType, + TargetCategories, + TargetIds, +) + +from ._dispatch import Dispatch + + +def _canonical_target(target: object) -> frozenset[tuple[object, ...]]: + """Canonicalize a dispatch target into an order-independent, class-aware set. + + `TargetIds`/`TargetCategories` are already `frozenset`s, so their OWN + `==` is already order-independent -- but comparing them via + `tuple(target_a) == tuple(target_b)` throws that away and relies on two + separately-constructed frozensets happening to iterate in the same order, + which CPython does not guarantee for arbitrary construction paths. This + canonicalizes to a plain `frozenset` of hashable keys instead, so + comparison is unconditionally order-independent. + + For `TargetCategories`, each key is built from `TargetCategory.category2` + (the library's OWN normalization of a category/type element to a single + `ElectricalComponentCategory` value -- it deliberately treats the legacy + `ComponentCategory.BATTERY` and `ElectricalComponentCategory.BATTERY` as + the SAME real-world category, by value, and this canonicalization + respects that rather than fighting it), plus, when the element names a + specific sub-type (`BatteryType`/`EvChargerType`/`InverterType`), that + sub-type's own class AND value. A plain "any battery" target is therefore + NOT conflated with a specific "LI_ION battery" target (continuation + requires the same specificity, not just the same broad category) -- but + `ComponentCategory.BATTERY` and `ElectricalComponentCategory.BATTERY` on + their own ARE treated as the same target, matching the library's own + `category2` semantics. The sub-type is tagged with its own class name as + well as its value so that, were any of `BatteryType`/`EvChargerType`/ + `InverterType` to ever become an `IntEnum` (today none are plain `Enum`, + so this cannot yet happen), two different sub-types that happened to + share a raw integer value still could not be conflated. + + Args: + target: The dispatch target to canonicalize (a `TargetIds` or + `TargetCategories` instance). + + Raises: + TypeError: If `target` is neither a `TargetIds` nor a + `TargetCategories`. + + Returns: + An order-independent, class-aware, hashable representation of + `target`, safe to compare with `==` against another call's result. + """ + match target: + case TargetIds(): + return frozenset(("id", int(component_id)) for component_id in target) + case TargetCategories(): + keys: set[tuple[object, ...]] = set() + for category in target: + specific = ( + category.target + if isinstance( + category.target, (BatteryType, EvChargerType, InverterType) + ) + else None + ) + keys.add( + ( + "category", + category.category2, + type(specific).__qualname__ if specific is not None else None, + specific.value if specific is not None else None, + ) + ) + return frozenset(keys) + case _: + raise TypeError( + f"Unsupported target type for continuation comparison: {type(target)!r}" + ) + + +def is_exact_continuation(predecessor: Dispatch, successor: Dispatch) -> bool: + """Return whether `successor` exactly, compatibly continues `predecessor`. + + A successor continues a predecessor when, and only when: + + * they have the same dispatch `type`; + * they have the same `dry_run` mode; + * they resolve to the same `target` (compared order-independently); + * the successor's CURRENT occurrence starts exactly when the + predecessor's current occurrence ends -- a strict equality, not + `<=`. For a recurring successor, this is its current occurrence's + start, not its first one, so a daily pair of dispatches continues + on every day, not only the first. A successor that starts before + the predecessor ends is an OVERLAP, not a continuation, and must be + treated as a fully independent dispatch. + + Args: + predecessor: The dispatch that may be continued. + successor: The dispatch that may continue it. + + Returns: + True if `successor` is an exact, compatible continuation of `predecessor`. + """ + if predecessor.type != successor.type: + return False + if predecessor.dry_run != successor.dry_run: + return False + if _canonical_target(predecessor.target) != _canonical_target(successor.target): + return False + + if not predecessor.active: + # An explicit cancellation is authoritative and is never silently + # "continued through" by a later dispatch, even a coincidentally + # adjacent one -- see the module docstring and `until`'s own behaviour + # (it returns None once `active` is False). + return False + + if predecessor.duration is None: + # Runs indefinitely until explicitly stopped: there is no scheduled end + # for a successor to be adjacent to. NOTE: `Dispatch.until` raises + # ValueError for an active, duration-less dispatch rather than + # returning None -- this check exists specifically to avoid calling it + # in that case. + return False + + predecessor_until = predecessor.until + if predecessor_until is None: + # Should not happen given the two guards above, but avoid ever treating + # a missing boundary as a match. + return False + + # For a recurring successor, `start_time` is only the start of its FIRST + # occurrence. Use the start of its CURRENT occurrence instead, derived + # the same way `predecessor_until` above is: from `until` (the end of + # the occurrence running now) minus `duration`. A one-shot successor (or + # one not currently active) falls back to `start_time`, which is + # already its only/current occurrence. + successor_start = successor.start_time + if successor.duration is not None and (successor_until := successor.until): + successor_start = successor_until - successor.duration + return successor_start == predecessor_until diff --git a/src/frequenz/dispatch/_dispatcher.py b/src/frequenz/dispatch/_dispatcher.py index c49b843c..db5a9eee 100644 --- a/src/frequenz/dispatch/_dispatcher.py +++ b/src/frequenz/dispatch/_dispatcher.py @@ -314,7 +314,7 @@ def is_managed(self, dispatch_type: str) -> bool: """ return dispatch_type in self._actor_dispatchers - async def start_managing( + async def start_managing( # pylint: disable=too-many-arguments self, dispatch_type: str, *, @@ -322,6 +322,8 @@ async def start_managing( [DispatchInfo, Receiver[DispatchInfo]], Awaitable[Actor] ], merge_strategy: MergeStrategy | None = None, + continuation_predicate: Callable[[Dispatch, Dispatch], bool] | None = None, + continuation_accept_timeout: timedelta = timedelta(seconds=5), retry_interval: timedelta = timedelta(seconds=60), ) -> None: """Manage actors for a given dispatch type. @@ -348,10 +350,23 @@ async def start_managing( the same instance. * `None` — No merging, each dispatch maps to a separate instance. + `continuation_predicate` is a separate, opt-in mechanism, not a + `merge_strategy`, and can be combined with any of the above (or with + `None`). This is the only way to enable continuation handovers: it + wires the `ActorDispatcher` this method builds with both the + predicate and the live dispatches snapshot a handover needs. See + `ActorDispatcher`'s "Continuation handovers" section for what a + handover is and when it happens. + Args: dispatch_type: The type of the dispatch to manage. actor_factory: The factory to create actors. merge_strategy: The strategy to merge running intervals. + continuation_predicate: An opt-in predicate for continuation + handovers (normally `is_exact_continuation`). See + `ActorDispatcher`'s parameter of the same name. + continuation_accept_timeout: How long to wait for a candidate + actor to accept a continuation before giving up on it. retry_interval: The retry interval to use when actor creation fails. """ dispatcher = self._actor_dispatchers.get(dispatch_type) @@ -377,6 +392,13 @@ def id_identity(dispatch: Dispatch) -> DispatchActorId: id_identity if merge_strategy is None else merge_strategy.identity ), retry_interval=retry_interval, + continuation_predicate=continuation_predicate, + dispatches_snapshot=( + self._bg_service.dispatches_snapshot + if continuation_predicate is not None + else None + ), + continuation_accept_timeout=continuation_accept_timeout, ) if merge_strategy is not None: diff --git a/tests/test_continuation.py b/tests/test_continuation.py new file mode 100644 index 00000000..a25c73f7 --- /dev/null +++ b/tests/test_continuation.py @@ -0,0 +1,324 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Unit tests for `is_exact_continuation`'s target-equality semantics. + +These are pure, synchronous tests of `_canonical_target`/`is_exact_continuation` +-- no scheduler, no actors, no event loop. Synthetic IDs only. +""" + +from dataclasses import replace +from datetime import datetime, timedelta, timezone + +import pytest +import time_machine +from frequenz.client.common.microgrid.components import ComponentCategory +from frequenz.client.common.microgrid.electrical_components import ( + ElectricalComponentCategory, +) +from frequenz.client.dispatch.recurrence import Frequency, RecurrenceRule +from frequenz.client.dispatch.test.generator import DispatchGenerator +from frequenz.client.dispatch.types import ( + BatteryType, + DispatchId, + EvChargerType, + TargetCategories, + TargetIds, +) + +from frequenz.dispatch import Dispatch, is_exact_continuation +from frequenz.dispatch._continuation import _canonical_target + + +def _make_dispatch( + dispatch_id: int, + *, + start_time: datetime, + duration: timedelta | None, + target: TargetIds | TargetCategories, + active: bool = True, + dry_run: bool = False, + dispatch_type: str = "TEST", + recurrence: RecurrenceRule | None = None, +) -> Dispatch: + # pylint: disable=too-many-arguments + generator = DispatchGenerator() + spec = replace( + generator.generate_dispatch(), + id=DispatchId(dispatch_id), + type=dispatch_type, + start_time=start_time, + duration=duration, + target=target, + active=active, + dry_run=dry_run, + recurrence=recurrence if recurrence is not None else RecurrenceRule(), + ) + return Dispatch(spec) + + +UTC = timezone.utc + + +# --- _canonical_target: order independence --- + + +def test_reordered_target_ids_are_equal() -> None: + """Canonicalize reordered `TargetIds` equally.""" + assert _canonical_target(TargetIds(1, 2, 3)) == _canonical_target( + TargetIds(3, 1, 2) + ) + assert _canonical_target(TargetIds(5, 7)) == _canonical_target(TargetIds(7, 5)) + + +def test_reordered_target_categories_are_equal() -> None: + """Same for a multi-element `TargetCategories`.""" + a = TargetCategories( + ElectricalComponentCategory.BATTERY, ElectricalComponentCategory.INVERTER + ) + b = TargetCategories( + ElectricalComponentCategory.INVERTER, ElectricalComponentCategory.BATTERY + ) + assert _canonical_target(a) == _canonical_target(b) + + +# --- _canonical_target: class-aware, not bare-value, equality --- + + +def test_legacy_and_new_category_enum_for_the_same_category_are_equal() -> None: + """Canonicalize legacy and current spellings of a category equally.""" + legacy = TargetCategories(ComponentCategory.BATTERY) + current = TargetCategories(ElectricalComponentCategory.BATTERY) + assert _canonical_target(legacy) == _canonical_target(current) + + +def test_same_numeric_value_different_kind_is_not_equal() -> None: + """Keep equal numeric values of different target kinds distinct. + + A plain category target and a MORE SPECIFIC sub-type target must NOT be + conflated, even when the broad category matches. A `TargetIds` + whose id happens to numerically match a category's enum value must not be + conflated with that category either (different container kind entirely). + """ + plain_battery = TargetCategories(ElectricalComponentCategory.BATTERY) + specific_li_ion = TargetCategories(BatteryType.LI_ION) + assert _canonical_target(plain_battery) != _canonical_target( + specific_li_ion + ), "A plain 'any battery' target must not equal a specific battery sub-type target" + + battery_value = ElectricalComponentCategory.BATTERY.value + ids_with_matching_number = TargetIds(battery_value) + assert _canonical_target(ids_with_matching_number) != _canonical_target( + plain_battery + ), ( + "A TargetIds whose id numerically matches a category's enum value must " + "not be conflated with that category -- different container kind" + ) + + +def test_different_specific_subtypes_are_not_equal() -> None: + """Two different, equally-specific sub-types are not conflated with each other.""" + li_ion = TargetCategories(BatteryType.LI_ION) + assert _canonical_target(li_ion) != _canonical_target( + TargetCategories(EvChargerType.AC) + ) + + +# --- is_exact_continuation: end-to-end with the target comparison --- + + +def test_continuation_allowed_across_legacy_and_new_category_enum() -> None: + """Allow continuation across legacy and current category spellings.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=timedelta(minutes=10), + target=TargetCategories(ComponentCategory.BATTERY), + ) + successor = _make_dispatch( + 2, + start_time=boundary, + duration=None, + target=TargetCategories(ElectricalComponentCategory.BATTERY), + ) + assert is_exact_continuation(predecessor, successor) + + +def test_continuation_refused_for_differently_specific_targets() -> None: + """Refuse continuation between differently specific targets.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=timedelta(minutes=10), + target=TargetCategories(ElectricalComponentCategory.BATTERY), + ) + successor = _make_dispatch( + 2, + start_time=boundary, + duration=None, + target=TargetCategories(BatteryType.LI_ION), + ) + assert not is_exact_continuation(predecessor, successor) + + +def test_continuation_allowed_with_reordered_multi_id_target() -> None: + """Allow continuation with reordered component IDs.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=timedelta(minutes=10), + target=TargetIds(1, 2, 3), + ) + successor = _make_dispatch( + 2, + start_time=boundary, + duration=None, + target=TargetIds(3, 2, 1), + ) + assert is_exact_continuation(predecessor, successor) + + +# --- is_exact_continuation: recurring successor (regression) --- + + +@pytest.mark.parametrize("day", [0, 1, 2]) +def test_daily_pair_continues_on_every_occurrence(day: int) -> None: + """Continue between two daily dispatches on every day, not only the first.""" + first_day = datetime(2026, 1, 1, tzinfo=UTC) + daily = RecurrenceRule(frequency=Frequency.DAILY, interval=1) + predecessor = _make_dispatch( + 1, + start_time=first_day + timedelta(hours=9), + duration=timedelta(hours=1), + target=TargetIds(1), + recurrence=daily, + ) + successor = _make_dispatch( + 2, + start_time=first_day + timedelta(hours=10), + duration=timedelta(hours=1), + target=TargetIds(1), + recurrence=daily, + ) + + with time_machine.travel(first_day + timedelta(days=day, hours=10), tick=False): + assert is_exact_continuation(predecessor, successor) + + +# --- is_exact_continuation: rejection reasons --- + + +def test_continuation_refused_for_different_type() -> None: + """Refuse continuation between dispatches of a different type.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=timedelta(minutes=10), + target=TargetIds(1), + dispatch_type="TYPE_A", + ) + successor = _make_dispatch( + 2, + start_time=boundary, + duration=None, + target=TargetIds(1), + dispatch_type="TYPE_B", + ) + assert not is_exact_continuation(predecessor, successor) + + +def test_continuation_refused_for_different_dry_run() -> None: + """Refuse continuation between a dry-run and a non-dry-run dispatch.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=timedelta(minutes=10), + target=TargetIds(1), + dry_run=True, + ) + successor = _make_dispatch( + 2, + start_time=boundary, + duration=None, + target=TargetIds(1), + dry_run=False, + ) + assert not is_exact_continuation(predecessor, successor) + + +def test_continuation_refused_for_inactive_predecessor() -> None: + """Refuse continuation when the predecessor was explicitly cancelled.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=timedelta(minutes=10), + target=TargetIds(1), + active=False, + ) + successor = _make_dispatch( + 2, + start_time=boundary, + duration=None, + target=TargetIds(1), + ) + assert not is_exact_continuation(predecessor, successor) + + +def test_continuation_refused_for_predecessor_without_duration() -> None: + """Refuse continuation when the predecessor has no scheduled end.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=None, + target=TargetIds(1), + ) + successor = _make_dispatch( + 2, + start_time=boundary, + duration=None, + target=TargetIds(1), + ) + assert not is_exact_continuation(predecessor, successor) + + +def test_continuation_refused_for_a_gap() -> None: + """Refuse continuation when the successor starts after a gap.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=timedelta(minutes=10), + target=TargetIds(1), + ) + successor = _make_dispatch( + 2, + start_time=boundary + timedelta(seconds=1), + duration=None, + target=TargetIds(1), + ) + assert not is_exact_continuation(predecessor, successor) + + +def test_continuation_refused_for_an_overlap() -> None: + """Refuse continuation when the successor starts before the predecessor ends.""" + boundary = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + predecessor = _make_dispatch( + 1, + start_time=boundary - timedelta(minutes=10), + duration=timedelta(minutes=10), + target=TargetIds(1), + ) + successor = _make_dispatch( + 2, + start_time=boundary - timedelta(seconds=1), + duration=None, + target=TargetIds(1), + ) + assert not is_exact_continuation(predecessor, successor) diff --git a/tests/test_continuation_handover.py b/tests/test_continuation_handover.py new file mode 100644 index 00000000..77cbf464 --- /dev/null +++ b/tests/test_continuation_handover.py @@ -0,0 +1,382 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Deterministic unit tests for ActorDispatcher's continuation handovers. + +These drive `ActorDispatcher._handle_dispatch` directly (bypassing its +`running_status_receiver` channel and `_run()` loop), with a plain dict as +the `dispatches_snapshot` and a frozen clock (`fake_time`) so a dispatch's +boundary can be matched exactly without a real-time race. Each test runs in +milliseconds. See `test_continuation_realclock.py` for one end-to-end test +on top of the real `DispatchScheduler`. +""" + +import asyncio +import logging +from dataclasses import replace +from datetime import datetime, timedelta, timezone +from typing import Iterator, cast + +import pytest +import time_machine +from frequenz.channels import Broadcast, Receiver +from frequenz.client.dispatch.recurrence import RecurrenceRule +from frequenz.client.dispatch.test.generator import DispatchGenerator +from frequenz.client.dispatch.types import DispatchId, TargetIds +from frequenz.sdk.actor import Actor +from pytest import fixture + +from frequenz.dispatch import ( + ActorDispatcher, + Dispatch, + DispatchInfo, + is_exact_continuation, +) +from frequenz.dispatch._actor_dispatcher import DispatchActorId + + +@fixture +def generator() -> DispatchGenerator: + """Return a dispatch generator.""" + return DispatchGenerator() + + +@fixture +def fake_time() -> Iterator[time_machine.Traveller]: + """Replace real time with a time machine that doesn't automatically tick.""" + with time_machine.travel(destination=0, tick=False) as traveller: + yield traveller + + +def _now() -> datetime: + """Return the current (possibly frozen) time in UTC.""" + return datetime.now(tz=timezone.utc) + + +_HANDOVER_EVENTS: list[str] = [] + + +def _continuation_dispatch( + generator: DispatchGenerator, # pylint: disable=redefined-outer-name + *, + dispatch_id: int, + start: datetime, + duration: timedelta | None = timedelta(hours=1), + active: bool = True, +) -> Dispatch: + """Create a dispatch for continuation handover tests.""" + return Dispatch( + replace( + generator.generate_dispatch(), + id=DispatchId(dispatch_id), + type="CONTINUATION_TEST", + active=active, + dry_run=False, + start_time=start, + duration=duration, + target=TargetIds(1), + recurrence=RecurrenceRule(), + ) + ) + + +def _stopped( + generator: DispatchGenerator, dispatch: Dispatch +) -> Dispatch: # pylint: disable=redefined-outer-name + """Build a deactivated copy of `dispatch`, to send as its stop event. + + `Dispatch` has a custom `__init__` (it takes the whole client dispatch + as one positional argument), so plain `dataclasses.replace()` doesn't + work on it directly. + """ + return _continuation_dispatch( + generator, + dispatch_id=int(dispatch.id), + start=dispatch.start_time, + duration=dispatch.duration, + active=False, + ) + + +class _HandoverActor(Actor): + """Record start/stop order. Not `ContinuationCapable`.""" + + def __init__(self, info: DispatchInfo, receiver: Receiver[DispatchInfo]) -> None: + """Initialize the actor and record its start.""" + super().__init__(name=f"actor-{int(info.dispatch.id)}") + self.receiver = receiver + self.current_dispatch_id = info.dispatch.id + _HANDOVER_EVENTS.append(f"start {self.name}") + + async def _run(self) -> None: + async for _ in self.receiver: + pass + + async def stop(self, msg: str | None = None) -> None: + """Stop, recording that it happened.""" + _HANDOVER_EVENTS.append(f"stop {self.name}") + await super().stop(msg) + + @classmethod + async def create( + cls, info: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> "_HandoverActor": + """Create a new actor.""" + return cls(info, receiver) + + +class _RefusingHandoverActor(_HandoverActor): + """Explicitly refuses every continuation.""" + + async def accept_continuation(self, _update: DispatchInfo) -> bool: + """Refuse every continuation.""" + return False + + +class _AcceptingHandoverActor(_HandoverActor): + """Accepts a continuation that matches its current dispatch.""" + + def __init__(self, info: DispatchInfo, receiver: Receiver[DispatchInfo]) -> None: + """Initialize the actor and its acceptance counter.""" + super().__init__(info, receiver) + self.accept_continuation_calls = 0 + + async def accept_continuation(self, update: DispatchInfo) -> bool: + """Accept a continuation of our own current dispatch.""" + self.accept_continuation_calls += 1 + if update.continuation_of != self.current_dispatch_id: + return False + self.current_dispatch_id = update.dispatch.id + return True + + +class _TimingOutHandoverActor(_HandoverActor): + """Never responds to a continuation.""" + + async def accept_continuation(self, _update: DispatchInfo) -> bool: + """Hang well past any reasonable `continuation_accept_timeout`.""" + await asyncio.sleep(1_000_000) + return True # pragma: no cover -- never reached + + +class _RaisingHandoverActor(_HandoverActor): + """Raises instead of answering a continuation.""" + + async def accept_continuation(self, _update: DispatchInfo) -> bool: + """Raise instead of accepting or refusing.""" + raise RuntimeError("synthetic accept_continuation failure") + + +def _build_handover_dispatcher( + actor_class: type[_HandoverActor], + snapshot: dict[DispatchId, Dispatch], + *, + continuation_accept_timeout: timedelta = timedelta(seconds=5), +) -> ActorDispatcher: + """Create an `ActorDispatcher` wired for continuation handover tests.""" + + async def factory( + info: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> _HandoverActor: + return await actor_class.create(info, receiver) + + unused_channel = Broadcast[Dispatch](name="unused handover channel") + return ActorDispatcher( + actor_factory=factory, + running_status_receiver=unused_channel.new_receiver(), + continuation_predicate=is_exact_continuation, + dispatches_snapshot=lambda: snapshot, + continuation_accept_timeout=continuation_accept_timeout, + ) + + +@pytest.mark.parametrize("actor_class", [_HandoverActor, _RefusingHandoverActor]) +async def test_rejected_handover_keeps_start_before_stop( + generator: DispatchGenerator, + actor_class: type[_HandoverActor], + fake_time: time_machine.Traveller, +) -> None: + """A non-capable or refused handover must not stop the predecessor first.""" + _HANDOVER_EVENTS.clear() + start = _now() + boundary = start + timedelta(hours=1) + predecessor = _continuation_dispatch(generator, dispatch_id=1, start=start) + successor = _continuation_dispatch(generator, dispatch_id=2, start=boundary) + snapshot = {predecessor.id: predecessor, successor.id: successor} + dispatcher = _build_handover_dispatcher(actor_class, snapshot) + + # pylint: disable=protected-access + await dispatcher._handle_dispatch(predecessor) + await asyncio.sleep(0) + fake_time.move_to(boundary) + # Same order as DispatchScheduler: the successor's start is always + # processed before the predecessor's stop at the same instant. + await dispatcher._handle_dispatch(successor) + await asyncio.sleep(0) + await dispatcher._handle_dispatch(_stopped(generator, predecessor)) + await asyncio.sleep(0) + # pylint: enable=protected-access + + assert _HANDOVER_EVENTS[:3] == ["start actor-1", "start actor-2", "stop actor-1"] + + +@pytest.mark.parametrize( + "actor_class", [_TimingOutHandoverActor, _RaisingHandoverActor] +) +async def test_unresponsive_handover_stops_predecessor_after_starting_successor( + generator: DispatchGenerator, + actor_class: type[_HandoverActor], + fake_time: time_machine.Traveller, +) -> None: + """A timed-out or raising handover starts the successor before stopping.""" + _HANDOVER_EVENTS.clear() + start = _now() + boundary = start + timedelta(hours=1) + predecessor = _continuation_dispatch(generator, dispatch_id=1, start=start) + successor = _continuation_dispatch(generator, dispatch_id=2, start=boundary) + snapshot = {predecessor.id: predecessor, successor.id: successor} + dispatcher = _build_handover_dispatcher( + actor_class, snapshot, continuation_accept_timeout=timedelta(milliseconds=10) + ) + + # pylint: disable=protected-access + await dispatcher._handle_dispatch(predecessor) + await asyncio.sleep(0) + fake_time.move_to(boundary) + await dispatcher._handle_dispatch(successor) + # pylint: enable=protected-access + + assert _HANDOVER_EVENTS[:3] == ["start actor-1", "start actor-2", "stop actor-1"] + + +async def test_accepted_handover_reuses_actor_without_warning( + generator: DispatchGenerator, + caplog: pytest.LogCaptureFixture, + fake_time: time_machine.Traveller, +) -> None: + """A successful handover reuses the actor and logs no WARNING.""" + _HANDOVER_EVENTS.clear() + start = _now() + boundary = start + timedelta(hours=1) + predecessor = _continuation_dispatch(generator, dispatch_id=1, start=start) + successor = _continuation_dispatch(generator, dispatch_id=2, start=boundary) + snapshot = {predecessor.id: predecessor, successor.id: successor} + dispatcher = _build_handover_dispatcher(_AcceptingHandoverActor, snapshot) + + with caplog.at_level(logging.DEBUG, logger="frequenz.dispatch._actor_dispatcher"): + # pylint: disable=protected-access + await dispatcher._handle_dispatch(predecessor) + await asyncio.sleep(0) + fake_time.move_to(boundary) + await dispatcher._handle_dispatch(successor) + await asyncio.sleep(0) + await dispatcher._handle_dispatch(_stopped(generator, predecessor)) + await asyncio.sleep(0) + # pylint: enable=protected-access + + assert _HANDOVER_EVENTS == [ + "start actor-1" + ], "The actor must be reused, not restarted" + assert not any( + record.levelno >= logging.WARNING for record in caplog.records + ), "A successful handover's predecessor stop must not log a WARNING" + + +async def test_continuation_chain_reuses_the_same_actor_twice( + generator: DispatchGenerator, + fake_time: time_machine.Traveller, +) -> None: + """A chain of three back-to-back dispatches reuses the same actor twice.""" + _HANDOVER_EVENTS.clear() + start = _now() + boundary_1 = start + timedelta(hours=1) + boundary_2 = boundary_1 + timedelta(hours=1) + first = _continuation_dispatch(generator, dispatch_id=1, start=start) + second = _continuation_dispatch(generator, dispatch_id=2, start=boundary_1) + third = _continuation_dispatch(generator, dispatch_id=3, start=boundary_2) + snapshot = {d.id: d for d in (first, second, third)} + dispatcher = _build_handover_dispatcher(_AcceptingHandoverActor, snapshot) + + # pylint: disable=protected-access + await dispatcher._handle_dispatch(first) + await asyncio.sleep(0) + fake_time.move_to(boundary_1) + await dispatcher._handle_dispatch(second) + await asyncio.sleep(0) + fake_time.move_to(boundary_2) + await dispatcher._handle_dispatch(third) + await asyncio.sleep(0) + actor_status = dispatcher._actors[DispatchActorId(third.id)] + # pylint: enable=protected-access + + assert _HANDOVER_EVENTS == ["start actor-1"], "Only the first actor should start" + assert actor_status.actor_and_channel is not None + assert actor_status.actor_and_channel.current_dispatch.id == third.id + + +async def test_continuation_predicate_requires_matching_snapshot() -> None: + """Refuse a continuation opt-in that can never take effect.""" + channel = Broadcast[Dispatch](name="unused handover channel") + + async def factory( + info: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> _HandoverActor: + raise AssertionError("not called") + + with pytest.raises(ValueError): + ActorDispatcher( + actor_factory=factory, + running_status_receiver=channel.new_receiver(), + continuation_predicate=is_exact_continuation, + ) + + with pytest.raises(ValueError): + ActorDispatcher( + actor_factory=factory, + running_status_receiver=channel.new_receiver(), + dispatches_snapshot=lambda: {}, + ) + + +async def test_stop_before_start_race_falls_back_to_normal_stop_start( + generator: DispatchGenerator, + fake_time: time_machine.Traveller, +) -> None: + """A predecessor stop arriving before its successor's start is a plain stop. + + `DispatchScheduler` always sorts a start before a stop at the same + instant, so this reverse order is a rare race (e.g. an update to the + predecessor arriving right at its boundary). It must fall back to an + ordinary stop/start, exactly like any other race: no continuation + attempt, and no double payload delivery to either actor. + """ + _HANDOVER_EVENTS.clear() + start = _now() + boundary = start + timedelta(hours=1) + predecessor = _continuation_dispatch(generator, dispatch_id=1, start=start) + successor = _continuation_dispatch(generator, dispatch_id=2, start=boundary) + snapshot = {predecessor.id: predecessor, successor.id: successor} + dispatcher = _build_handover_dispatcher(_AcceptingHandoverActor, snapshot) + + # pylint: disable=protected-access + await dispatcher._handle_dispatch(predecessor) + await asyncio.sleep(0) + predecessor_status = dispatcher._actors[DispatchActorId(predecessor.id)] + assert predecessor_status.actor_and_channel is not None + predecessor_actor = cast( + _AcceptingHandoverActor, predecessor_status.actor_and_channel.actor + ) + fake_time.move_to(boundary) + # The predecessor's stop arrives BEFORE the successor's start -- the + # reverse of the scheduler's own ordering. The pair would otherwise be + # an exact match: this proves no continuation is attempted either way. + await dispatcher._handle_dispatch(_stopped(generator, predecessor)) + await asyncio.sleep(0) + await dispatcher._handle_dispatch(successor) + await asyncio.sleep(0) + # pylint: enable=protected-access + + assert _HANDOVER_EVENTS == ["start actor-1", "stop actor-1", "start actor-2"] + assert ( + predecessor_actor.accept_continuation_calls == 0 + ), "accept_continuation must never be called without a stop-first path" diff --git a/tests/test_continuation_realclock.py b/tests/test_continuation_realclock.py new file mode 100644 index 00000000..eceefb25 --- /dev/null +++ b/tests/test_continuation_realclock.py @@ -0,0 +1,606 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Real-clock, real-scheduler integration tests for continuation handovers. + +Deliberately NO `time_machine`, NO `async_solipsism`: this uses the DEFAULT +asyncio event loop and genuine `datetime.now()`, with SHORT real dispatch +durations (a few seconds), so the whole suite still runs in a few seconds +while every clock involved -- `asyncio`'s own loop time and +`DispatchScheduler`'s `Timer` -- is the SAME, single, real clock. This +exercises the real `Dispatcher.start_managing()`, the real +`DispatchScheduler`, and the official `FakeClient` test double, end-to-end. +See `test_continuation_handover.py` for the deterministic, millisecond-fast +unit tests of the fallback paths and edge cases. + +Assertions are event-based (`asyncio.wait_for` polling a condition), never a +fixed sleep-and-hope. + +Synthetic component ID 1 only. No network/API/host calls. +""" + +# pylint: disable=protected-access + +import asyncio +from collections.abc import Generator +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from typing import Any, cast +from unittest.mock import patch + +import pytest +from frequenz.channels import Receiver +from frequenz.client.common.microgrid import MicrogridId +from frequenz.client.dispatch.test.client import FakeClient +from frequenz.client.dispatch.types import TargetIds +from frequenz.sdk.actor import Actor + +from frequenz.dispatch import Dispatcher, DispatchInfo, is_exact_continuation +from frequenz.dispatch._actor_dispatcher import ActorDispatcher, DispatchActorId + +REAL_EVENT_LOOP_POLICY = asyncio.get_event_loop_policy() + + +@pytest.fixture +def event_loop_policy() -> Generator[asyncio.AbstractEventLoopPolicy, None, None]: + """Pin the real default asyncio event loop policy for this file. + + `test_frequenz_dispatch.py` defines an `event_loop_policy` fixture that + calls `asyncio.set_event_loop_policy(async_solipsism.EventLoopPolicy())` + -- a GLOBAL, process-wide mutation it never restores. pytest-asyncio's own + default `event_loop_policy` fixture just returns whatever the current + global policy is, so once that other file's tests have run in the same + process, every later file silently inherits a solipsism (manually-ticked, + never-really-advancing) loop -- exactly the shape of hang this file is + designed not to have. Defining this fixture here pins the real default + regardless of what ran before, independent of execution order. Restore + the previous global policy explicitly so this fixture cannot leak its own + process-wide mutation into tests that run after this file. + """ + previous_policy = asyncio.get_event_loop_policy() + asyncio.set_event_loop_policy(REAL_EVENT_LOOP_POLICY) + try: + yield REAL_EVENT_LOOP_POLICY + finally: + asyncio.set_event_loop_policy(previous_policy) + + +# The real dispatch API (via FakeClient, matching the real protobuf wire +# format) rounds `start_time` to the nearest second and `duration` with +# `round(seconds)` (confirmed empirically: a 400ms duration round-trips as +# exactly 0, a sub-second start_time has its microseconds truncated) -- so +# anything sub-second here is silently lossy. These are whole seconds, +# deliberately: short enough for a fast suite, long enough to round-trip +# exactly. +DURATION = timedelta(seconds=2) +STARTUP_MARGIN = timedelta(seconds=1) + + +def _now() -> datetime: + return datetime.now(tz=timezone.utc) + + +async def _wait_until( + predicate: Any, *, timeout: float = 3.0, interval: float = 0.01 +) -> None: + """Poll `predicate()` (real, short sleeps) until true, or raise.""" + + async def _poll() -> None: + while not predicate(): + await asyncio.sleep(interval) + + await asyncio.wait_for(_poll(), timeout=timeout) + + +def _running_actor(dispatcher: ActorDispatcher, identity: DispatchActorId) -> Actor: + """Return the actor currently running under `identity`. + + Fails loudly if `identity` has no actor (unregistered, or only a failed + dispatch) -- callers only use this once they've already waited for the + actor to be registered. + """ + actor_status = dispatcher._actors[identity] + assert actor_status.actor_and_channel is not None + return actor_status.actor_and_channel.actor + + +def _sole_running_actor(dispatcher: ActorDispatcher) -> Actor: + """Return the sole running actor-and-channel entry's actor. + + Fails loudly unless there is exactly one entry and it is running. + """ + (actor_status,) = dispatcher._actors.values() + assert actor_status.actor_and_channel is not None + return actor_status.actor_and_channel.actor + + +def _sole_current_dispatch_id(dispatcher: ActorDispatcher) -> Any: + """Return the sole entry's current dispatch id, or `None` if not running. + + Used from a `_wait_until` predicate, where an assert can't be used, so + this returns `None` instead of raising when there's no running actor yet. + """ + (actor_status,) = dispatcher._actors.values() + if actor_status.actor_and_channel is None: + return None + return actor_status.actor_and_channel.current_dispatch.id + + +class RecordingActor(Actor): + """Track the dispatch ID, received updates, and proposed power. + + The power is a `target_power_w` payload field stored directly. This actor + is NOT continuation-aware: it has no + `accept_continuation` method, so `isinstance(actor, ContinuationCapable)` + is `False`. + """ + + def __init__( + self, initial_dispatch: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> None: + """Initialize the recording actor.""" + super().__init__(name=f"actor-for-{initial_dispatch._src.id}") + self.current_dispatch_id = initial_dispatch._src.id + self.proposed_power_w: float | None = initial_dispatch.options.get( + "target_power_w" + ) + self.stop_called = False + self.receiver = receiver + + async def _run(self) -> None: + async for update in self.receiver: + if update._src.id == self.current_dispatch_id: + self.proposed_power_w = update.options.get("target_power_w") + + async def stop(self, msg: str | None = None) -> None: + """Stop, recording that it happened and withdrawing (like a real actor).""" + self.stop_called = True + self.proposed_power_w = None + await super().stop(msg) + + @classmethod + async def create( + cls, initial_dispatch: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> "RecordingActor": + """Create a new actor.""" + return cls(initial_dispatch, receiver) + + +class ContinuationAwareActor(RecordingActor): + """Implements `ContinuationCapable.accept_continuation`.""" + + async def accept_continuation(self, update: DispatchInfo) -> bool: + """Accept a continuation update, immediately applying its payload.""" + if update.continuation_of != self.current_dispatch_id: + return False + self.current_dispatch_id = update._src.id + self.proposed_power_w = update.options.get("target_power_w") + return True + + +@dataclass +class _Env: + dispatcher: Dispatcher + client: FakeClient + microgrid_id: MicrogridId + + +@pytest.fixture +async def env() -> _Env: + """Create a dispatcher on the real-time asyncio event loop. + + The dispatcher is backed by the official `FakeClient`, with no + time-machine or async-solipsism clock. + """ + + class _FakeClientWithSignature(FakeClient): + # 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: + super().__init__() + + # pylint: enable=too-many-arguments,unused-argument + + mid = MicrogridId(1) + with patch( + "frequenz.dispatch._dispatcher.DispatchApiClient", _FakeClientWithSignature + ): + dispatcher = Dispatcher( + microgrid_id=mid, server_url="grpc://test-url", key="test-key" + ) + dispatcher.start() + await asyncio.sleep(0.2) # let its background _run() task actually start + return _Env( + dispatcher=dispatcher, + client=cast(FakeClient, dispatcher.client), + microgrid_id=mid, + ) + + +def _actor_dispatcher_for( + dispatcher: Dispatcher, dispatch_type: str +) -> ActorDispatcher: + return dispatcher._actor_dispatchers[dispatch_type] + + +async def test_exact_adjacency_end_to_end_real_scheduler(env: _Env) -> None: + """Continue an exactly adjacent dispatch with the real scheduler. + + The predecessor naturally starts, and once the real scheduler's own + Timer fires the successor's own scheduled start, `ActorDispatcher` + resolves it into a continuation using the real `dispatches_snapshot`, + all without this test ever manually constructing or feeding any event. + """ + dispatch_type = "REALCLOCK_EXACT_ADJACENCY" + await env.dispatcher.start_managing( + dispatch_type=dispatch_type, + actor_factory=ContinuationAwareActor.create, + continuation_predicate=is_exact_continuation, + ) + actor_dispatcher = _actor_dispatcher_for(env.dispatcher, dispatch_type) + + start = _now() + STARTUP_MARGIN + boundary = start + DURATION + predecessor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=start, + duration=DURATION, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 1_200_000.0}, + ) + successor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=boundary, + duration=None, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 900_000.0}, # deliberately different + ) + + await _wait_until( + lambda: DispatchActorId(predecessor.id) in actor_dispatcher._actors + ) + actor = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, DispatchActorId(predecessor.id)), + ) + await _wait_until(lambda: actor.proposed_power_w == 1_200_000.0) + + # Real time passes naturally past `boundary` -- the real scheduler's own + # Timer (with the floor-fix) fires the real stop event for `predecessor`. + await _wait_until( + lambda: actor.current_dispatch_id == successor.id + and actor.proposed_power_w == 900_000.0, + timeout=5.0, + ) + + assert ( + not actor.stop_called + ), "Expected the actor to be reused via continuation, never stopped" + assert len(actor_dispatcher._actors) == 1, "Expected exactly one live actor, reused" + + +async def test_successor_deleted_after_continuation_real_scheduler(env: _Env) -> None: + """Stop the reused actor when its successor is deleted.""" + dispatch_type = "REALCLOCK_SUCCESSOR_DELETED" + await env.dispatcher.start_managing( + dispatch_type=dispatch_type, + actor_factory=ContinuationAwareActor.create, + continuation_predicate=is_exact_continuation, + ) + actor_dispatcher = _actor_dispatcher_for(env.dispatcher, dispatch_type) + + start = _now() + STARTUP_MARGIN + boundary = start + DURATION + predecessor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=start, + duration=DURATION, + target=TargetIds(1), + active=True, + dry_run=False, + payload={}, + ) + successor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=boundary, + duration=None, + target=TargetIds(1), + active=True, + dry_run=False, + payload={}, + ) + + await _wait_until( + lambda: DispatchActorId(predecessor.id) in actor_dispatcher._actors + ) + await _wait_until( + lambda: len(actor_dispatcher._actors) == 1 + and _sole_current_dispatch_id(actor_dispatcher) == successor.id, + timeout=5.0, + ) + reused_actor = cast(ContinuationAwareActor, _sole_running_actor(actor_dispatcher)) + + await env.client.delete(microgrid_id=env.microgrid_id, dispatch_id=successor.id) + + await _wait_until(lambda: reused_actor.stop_called, timeout=3.0) + await _wait_until(lambda: len(actor_dispatcher._actors) == 0, timeout=3.0) + + +async def test_ambiguous_successor_real_scheduler(env: _Env) -> None: + """Refuse two successors that both continue the same predecessor. + + The scheduler orders START before STOP at a shared instant. Pairwise + uniqueness therefore has to reject this ambiguity on the start side, + before either successor can arbitrarily claim the predecessor's actor. + Both successors must start independently and the predecessor must stop, + withdrawing its old proposal. + """ + dispatch_type = "REALCLOCK_AMBIGUOUS_SUCCESSOR" + await env.dispatcher.start_managing( + dispatch_type=dispatch_type, + actor_factory=ContinuationAwareActor.create, + continuation_predicate=is_exact_continuation, + ) + actor_dispatcher = _actor_dispatcher_for(env.dispatcher, dispatch_type) + + start = _now() + STARTUP_MARGIN + boundary = start + DURATION + predecessor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=start, + duration=DURATION, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 1_200_000.0}, + ) + successor_a = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=boundary, + duration=None, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 900_000.0}, + ) + successor_b = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=boundary, + duration=None, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 800_000.0}, + ) + + await _wait_until( + lambda: DispatchActorId(predecessor.id) in actor_dispatcher._actors + ) + predecessor_actor = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, DispatchActorId(predecessor.id)), + ) + + # Whichever race resolution occurs (see the docstring above), it must + # settle into EXACTLY two live actors/identities, one correctly + # representing each successor's own payload -- never fewer (an orphan) + # and never more (a double-claim), and never both successors pointing at + # the SAME actor (a corrupted shared re-key). + await _wait_until( + lambda: len(actor_dispatcher._actors) == 2 + and DispatchActorId(successor_a.id) in actor_dispatcher._actors + and DispatchActorId(successor_b.id) in actor_dispatcher._actors, + timeout=5.0, + ) + + actor_a = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, DispatchActorId(successor_a.id)), + ) + actor_b = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, DispatchActorId(successor_b.id)), + ) + assert ( + actor_a is not actor_b + ), "The two successors must never share the same re-keyed actor" + assert predecessor_actor is not actor_a + assert predecessor_actor is not actor_b + assert predecessor_actor.stop_called + assert predecessor_actor.proposed_power_w is None + assert actor_a.current_dispatch_id == successor_a.id + assert actor_b.current_dispatch_id == successor_b.id + assert actor_a.proposed_power_w == 900_000.0 + assert actor_b.proposed_power_w == 800_000.0 + + +async def test_ambiguous_predecessor_real_scheduler(env: _Env) -> None: + """Refuse two predecessors that both match one successor. + + The successor must start independently, then both predecessor actors must + stop and withdraw their own proposals. Stop-side processing must not + allow the second predecessor to claim the successor merely because the + first predecessor has already been stopped. + """ + dispatch_type = "REALCLOCK_AMBIGUOUS_PREDECESSOR" + await env.dispatcher.start_managing( + dispatch_type=dispatch_type, + actor_factory=ContinuationAwareActor.create, + continuation_predicate=is_exact_continuation, + ) + actor_dispatcher = _actor_dispatcher_for(env.dispatcher, dispatch_type) + + start = _now() + STARTUP_MARGIN + boundary = start + DURATION + predecessor_a = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=start, + duration=DURATION, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 1_200_000.0}, + ) + predecessor_b = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=start, + duration=DURATION, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 800_000.0}, + ) + successor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=boundary, + duration=None, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 900_000.0}, + ) + + await _wait_until( + lambda: DispatchActorId(predecessor_a.id) in actor_dispatcher._actors + and DispatchActorId(predecessor_b.id) in actor_dispatcher._actors + ) + actor_a = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, DispatchActorId(predecessor_a.id)), + ) + actor_b = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, DispatchActorId(predecessor_b.id)), + ) + + await _wait_until( + lambda: len(actor_dispatcher._actors) == 1 + and DispatchActorId(successor.id) in actor_dispatcher._actors, + timeout=5.0, + ) + successor_actor = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, DispatchActorId(successor.id)), + ) + + assert successor_actor is not actor_a + assert successor_actor is not actor_b + assert successor_actor.current_dispatch_id == successor.id + assert successor_actor.proposed_power_w == 900_000.0 + assert actor_a.stop_called and actor_a.proposed_power_w is None + assert actor_b.stop_called and actor_b.proposed_power_w is None + + +async def test_snapshot_predecessor_without_actor_still_makes_pair_ambiguous( + env: _Env, +) -> None: + """Count snapshot predecessors even when one actor failed to start. + + Start-side matching must not reuse the sole registered predecessor actor + when another known dispatch also matches the successor but has no actor. + """ + dispatch_type = "REALCLOCK_SNAPSHOT_ONLY_PREDECESSOR" + + async def selective_factory( + initial_dispatch: DispatchInfo, receiver: Receiver[DispatchInfo] + ) -> ContinuationAwareActor: + if initial_dispatch.options.get("fail_start"): + raise RuntimeError("synthetic actor start failure") + return cast( + ContinuationAwareActor, + await ContinuationAwareActor.create(initial_dispatch, receiver), + ) + + await env.dispatcher.start_managing( + dispatch_type=dispatch_type, + actor_factory=selective_factory, + continuation_predicate=is_exact_continuation, + ) + actor_dispatcher = _actor_dispatcher_for(env.dispatcher, dispatch_type) + + start = _now() + STARTUP_MARGIN + boundary = start + DURATION + registered_predecessor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=start, + duration=DURATION, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 1_200_000.0}, + ) + snapshot_only_predecessor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=start, + duration=DURATION, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 800_000.0, "fail_start": True}, + ) + successor = await env.client.create( + microgrid_id=env.microgrid_id, + type=dispatch_type, + start_time=boundary, + duration=None, + target=TargetIds(1), + active=True, + dry_run=False, + payload={"target_power_w": 900_000.0}, + ) + + registered_identity = DispatchActorId(registered_predecessor.id) + failed_identity = DispatchActorId(snapshot_only_predecessor.id) + await _wait_until( + lambda: ( + registered_identity in actor_dispatcher._actors + and actor_dispatcher._actors[registered_identity].actor_and_channel + is not None + and failed_identity in actor_dispatcher._actors + and actor_dispatcher._actors[failed_identity].failed_dispatch is not None + ) + ) + predecessor_actor = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, registered_identity), + ) + + await _wait_until( + lambda: len(actor_dispatcher._actors) == 1 + and DispatchActorId(successor.id) in actor_dispatcher._actors, + timeout=5.0, + ) + successor_actor = cast( + ContinuationAwareActor, + _running_actor(actor_dispatcher, DispatchActorId(successor.id)), + ) + + assert successor_actor is not predecessor_actor + assert successor_actor.current_dispatch_id == successor.id + assert successor_actor.proposed_power_w == 900_000.0 + assert predecessor_actor.stop_called + assert predecessor_actor.proposed_power_w is None From c381c5754f98873236eebe03c317fda0329d612c Mon Sep 17 00:00:00 2001 From: "Mathias L. Baumann" Date: Thu, 15 Oct 2026 18:39:35 +0200 Subject: [PATCH 3/3] Add release notes for dispatch handovers List the new public names from the continuation handover feature, the ActorAndChannel breaking change, and the scheduler timer fix. Signed-off-by: Mathias L. Baumann --- RELEASE_NOTES.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 4b13f7de..c47df5e1 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -8,11 +8,16 @@ +* `ActorDispatcher.ActorAndChannel` is no longer frozen and has a new required `current_dispatch` field. Code that builds it directly will break; use `ActorDispatcher` itself instead. + ## New Features +* Added opt-in support for reusing a continuation-capable actor across exactly adjacent, compatible dispatches, enabled only through `Dispatcher.start_managing(continuation_predicate=...)`. New public names: `ContinuationCapable`, `is_exact_continuation()`, `DispatchInfo.continuation_of` and `DispatchInfo.dispatch`. Ambiguous or unsupported handovers keep the normal stop/start behavior. + ## Bug Fixes * Docstrings now use absolute cross-references to public paths instead of relative ones. Relative cross-references are expanded from the module where an object is defined since mkdocstrings-python 2.0.9, which broke some links, and projects rendering docstrings inherited from this library needed `relative_crossrefs: true` for them to work at all. See [frequenz-repo-config-python#655](https://github.com/frequenz-floss/frequenz-repo-config-python/issues/655) for details. * Fixed actors being left running when an update changes a dispatch's merge identity. +* Fixed the scheduler's timer crashing when two scheduled events landed at the same instant, and stopped it from spinning at a microsecond interval once its event queue emptied afterward.