Skip to content

Add opt-in contiguous dispatch handovers - #311

Merged
Marenz merged 3 commits into
frequenz-floss:v1.x.xfrom
Marenz:contiguous-handover-gap
Nov 16, 2026
Merged

Marenz merged 3 commits into
frequenz-floss:v1.x.xfrom
Marenz:contiguous-handover-gap

Conversation

@Marenz

@Marenz Marenz commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

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.

Caller wiring and actor support are still required before this changes application behavior.

@github-actions github-actions Bot added part:tests Affects the unit, integration and performance (benchmarks) tests part:dispatcher Affects the high-level dispatcher interface part:docs Affects the documentation part:tooling Affects the development tooling (CI, deployment, dependency management, etc.) labels Oct 15, 2026
@Marenz
Marenz force-pushed the contiguous-handover-gap branch from e1fc534 to a75141d Compare November 13, 2026 11:42
@Marenz
Marenz marked this pull request as ready for review November 13, 2026 11:43
@Marenz
Marenz requested a review from a team as a code owner November 13, 2026 11:43
@Marenz
Marenz requested review from stefan-brus-frequenz and removed request for a team November 13, 2026 11:43

@llucax llucax left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't get "Support contiguous dispatch scheduling", it adds dispatches_snapshot() but it doesn't use it.

I feel the commit messages and the PR are lacking some more context. The logic looks... complex, so it would be nice to make sure it is justified.

AI review coming up.

Comment thread src/frequenz/dispatch/_bg_service.py Resolved
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about a configurable tolerance? 1us seems too small?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡⬇️ The 1 µs floor leaves the timer in a busy loop once the queue is empty

The floor fixes the ZeroDivisionError, but the timer keeps ticking every microsecond after the last of a pair of coincident events empties _scheduled_events. Timer is periodic. _update_timer() only resets it when something is queued, so after the last event the timer keeps the 1 µs interval. _run() then wakes up on every tick and takes the if not self._scheduled_events: continue branch until a new dispatch event arrives, which can be hours later.

A handover to an open-ended successor ends up exactly like this. The successor's start is processed first (see QueueItem.priority). _schedule_stop() queues no stop for the successor, because the successor has no duration. Then the predecessor's stop is popped, and the queue is empty.

I measured it with the real DispatchScheduler, a FakeClient and a Timer subclass that counts ready() calls. With a 1 s predecessor followed by a successor with duration=None, the timer woke up about 48,000 times in the second after the handover. Two one-shot dispatches that stop at the same time give about 57,000 wake-ups per second. Before this PR, the same situation produced a negative interval, which also spins (about 54,000 wake-ups per second on v1.x.x). So the busy loop isn't new, but the floor doesn't fix it either. The new release note says the change "prevented scheduler crashes when coincident events produced a non-positive timer interval", but only a zero interval crashed; negative intervals spun instead.

About your tolerance question: the 1 µs isn't a tolerance. It's only the smallest interval Timer accepts. Adjacency is checked with strict equality in is_exact_continuation().

Impact

The scheduler burns CPU on the edge device until the next dispatch event. This is in DispatchScheduler, so it affects every user, not only the ones that enable continuations.

Related locations

Suggested fix (⬇️ effort)

Give the timer a long interval when nothing is queued, for example in _update_timer():

if not self._scheduled_events:
    timer.reset(interval=timedelta(days=1))
    return

It's probably also worth reporting upstream that Timer.reset() doesn't validate interval the way Timer.__init__() does.

Suggested tests

Call _update_timer() with an empty queue and check that the timer isn't left with a tiny interval.

Suggested new tests
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)

🟡 Medium Severity: Probably best to fix before merging, OK to skip if there is a good reason.
⬇️ Low Effort: Low hanging fruit, easy fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Fixed: _update_timer() now parks the timer at a 1-hour interval when the event queue is empty, instead of leaving it at the microsecond floor. Added test_update_timer_parks_timer_when_queue_is_empty. (Used an hour rather than a day: timedelta(days=1) equals asyncio's own MAXIMUM_SELECT_TIMEOUT, and some test event loops treat that as sleep-forever and raise.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 1 µs isn't a tolerance between dispatch times. It's only the smallest interval Timer.reset() accepts, used when an event is already due. Adjacency is checked with exact equality (successor.start == predecessor.start + duration), both computed exactly, so there is nothing a tolerance could loosen.

Comment on lines +299 to +301
continuation_predicate: Callable[[Dispatch, Dispatch], bool] | None = None,
dispatches_snapshot: Callable[[], Mapping[DispatchId, Dispatch]] | None = None,
continuation_accept_timeout: timedelta = timedelta(seconds=5),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel all this continuation logic is very complex, and should be explained somewhere else, ideally with examples, not just in the arguments docs. It is really hard to see as a whole and the interactions there.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵⬇️ Some of the new docs render badly, describe old prototypes or depend on private names

Besides the missing user guide, the new docstrings have a few concrete problems:

  • mkdocs uses Python-Markdown, which doesn't let a list interrupt a paragraph. The bullet lists in the continuation_predicate argument (L317-L336) and in is_exact_continuation() (L112-L118) have no blank line before them, so they render as one paragraph with literal * characters. I checked it with markdown.markdown().
  • The _continuation.py module docstring (L15-L24) describes "an earlier version of this prototype" and points to ActorDispatcher.dispatches_snapshot, which isn't an attribute. The history belongs in the commit message, if anywhere.
  • ContinuationCapable.accept_continuation() (L43-L53) talks about a "proposal pool", "physical power" and "downstream aggregation". Those belong to specific power actors, not to this library, which doesn't know what an actor does. The docstring also tells the actor to read the private update._src attribute to get the new dispatch. A public DispatchInfo property for the dispatch (or at least its ID) would make the contract usable without private access.
  • The docstrings use a lot of all-caps words and long explanations of why something is safe. A short statement of the contract in the docstrings would be much easier to follow. The details and an example can go in the user guide suggested above.

Impact

The API docs for the new feature are hard to read and partly wrong, and the actor contract depends on a private attribute.

Suggested fix (⬇️ effort)

Add a blank line before each list, remove the history and the reference to the missing attribute, keep the protocol docs generic, and add a public accessor to DispatchInfo for the source dispatch.


🔵 Low Severity: Addressing it is optional (low impact or nice to have).
⬇️ Low Effort: Low hanging fruit, easy fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Fixed: added a blank line before each bullet list so they render correctly, removed the _continuation.py history and the reference to a nonexistent ActorDispatcher.dispatches_snapshot attribute, and rewrote ContinuationCapable.accept_continuation()'s docstring to drop actor-specific wording (proposal pool, physical power, downstream aggregation). Added a public DispatchInfo.dispatch property so an actor never has to read the private _src. Also added a module-level explanation of continuation handovers, with a short example, in _actor_dispatcher.py.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡⬇️ The new handover guide isn't in the published docs

The new explanation and example went into the module docstring of _actor_dispatcher.py (L4-L73). The API docs generator skips every module whose name starts with _ (see _is_internal()), so this docstring is never rendered. Users only see the docstrings of the public names exported by frequenz.dispatch.

The example is also only a skeleton. new_with_dispatch() throws away the update receiver, so the actor never gets normal dispatch updates. _run() is just pass, so the actor finishes as soon as it starts.

Impact

The guide you asked for exists in the code, but users reading the docs can't find it. Two docstrings send them to the private module instead.

Related locations

Suggested fix (⬇️ effort)

Move the guide somewhere that gets rendered, for example the ContinuationCapable class docstring, the frequenz.dispatch package docstring in __init__.py, or a page under docs/. Point start_managing() there with a cross-reference. Make the example a working actor that keeps the receiver and handles normal updates in _run(), like the ActorDispatcher example does.


🟡 Medium Severity: Probably best to fix before merging, OK to skip if there is a good reason.
⬇️ Low Effort: Low hanging fruit, easy fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Fixed: moved the explanation and example into ActorDispatcher's own docstring, under a new "Continuation handovers" section, since frequenz.dispatch._actor_dispatcher is skipped by the docs generator but ActorDispatcher (exported from frequenz.dispatch) is not. Updated the cross-references in start_managing() and _continuation.py to point there instead. Rewrote the example into a complete, working actor: it keeps the receiver, adopts the initial dispatch's target_power_w in new_with_dispatch(), applies updates in _run(), and adopts a continuation's new target_power_w in accept_continuation(). Verified with mkdocs build --strict: the "Continuation handovers" section and example render under ActorDispatcher in reference/frequenz/dispatch/index.html.

@llucax llucax left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 rAIview (AI review here!)

The handover works in the main scenario. However, the fallback paths don't behave as described, and some important cases aren't covered. The review focused on the event ordering between the scheduler and ActorDispatcher, on the fallback paths, and on the new public API.

The most important findings:

  • The 1 µs timer floor fixes the ZeroDivisionError, but once the queue is empty the scheduler keeps waking up about 50,000 times per second until the next dispatch event. A handover to an open-ended successor ends up exactly in this state. The busy loop already existed with negative intervals, but this fix doesn't address it.
  • When a handover is rejected (actor not ContinuationCapable, refusal, exception or timeout), the predecessor's actor is stopped before the successor's actor is started. Without the predicate the order is the opposite, so "unsupported handovers keep the normal stop/start behavior" isn't true.
  • is_exact_continuation() compares against the successor's first occurrence, so recurring successors only hand over on their first occurrence.
  • ActorDispatcher(continuation_predicate=...) silently does nothing without dispatches_snapshot, and users have no public way to get a snapshot.
  • None of the fallback paths, the stop-first order or the chained handovers have tests.

There are also some less important findings about warning noise on every handover, the stop-first path only covering rare races, the docs rendering and wording, the release notes, and unrelated changes in one commit.

Comment thread src/frequenz/dispatch/_continuation.py Resolved
Comment thread tests/test_continuation_realclock.py Resolved
Comment thread RELEASE_NOTES.md Resolved
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡⬇️ The 1 µs floor leaves the timer in a busy loop once the queue is empty

The floor fixes the ZeroDivisionError, but the timer keeps ticking every microsecond after the last of a pair of coincident events empties _scheduled_events. Timer is periodic. _update_timer() only resets it when something is queued, so after the last event the timer keeps the 1 µs interval. _run() then wakes up on every tick and takes the if not self._scheduled_events: continue branch until a new dispatch event arrives, which can be hours later.

A handover to an open-ended successor ends up exactly like this. The successor's start is processed first (see QueueItem.priority). _schedule_stop() queues no stop for the successor, because the successor has no duration. Then the predecessor's stop is popped, and the queue is empty.

I measured it with the real DispatchScheduler, a FakeClient and a Timer subclass that counts ready() calls. With a 1 s predecessor followed by a successor with duration=None, the timer woke up about 48,000 times in the second after the handover. Two one-shot dispatches that stop at the same time give about 57,000 wake-ups per second. Before this PR, the same situation produced a negative interval, which also spins (about 54,000 wake-ups per second on v1.x.x). So the busy loop isn't new, but the floor doesn't fix it either. The new release note says the change "prevented scheduler crashes when coincident events produced a non-positive timer interval", but only a zero interval crashed; negative intervals spun instead.

About your tolerance question: the 1 µs isn't a tolerance. It's only the smallest interval Timer accepts. Adjacency is checked with strict equality in is_exact_continuation().

Impact

The scheduler burns CPU on the edge device until the next dispatch event. This is in DispatchScheduler, so it affects every user, not only the ones that enable continuations.

Related locations

Suggested fix (⬇️ effort)

Give the timer a long interval when nothing is queued, for example in _update_timer():

if not self._scheduled_events:
    timer.reset(interval=timedelta(days=1))
    return

It's probably also worth reporting upstream that Timer.reset() doesn't validate interval the way Timer.__init__() does.

Suggested tests

Call _update_timer() with an empty queue and check that the timer isn't left with a tiny interval.

Suggested new tests
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)

🟡 Medium Severity: Probably best to fix before merging, OK to skip if there is a good reason.
⬇️ Low Effort: Low hanging fruit, easy fix.

Comment on lines +299 to +301
continuation_predicate: Callable[[Dispatch, Dispatch], bool] | None = None,
dispatches_snapshot: Callable[[], Mapping[DispatchId, Dispatch]] | None = None,
continuation_accept_timeout: timedelta = timedelta(seconds=5),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵⬇️ Some of the new docs render badly, describe old prototypes or depend on private names

Besides the missing user guide, the new docstrings have a few concrete problems:

  • mkdocs uses Python-Markdown, which doesn't let a list interrupt a paragraph. The bullet lists in the continuation_predicate argument (L317-L336) and in is_exact_continuation() (L112-L118) have no blank line before them, so they render as one paragraph with literal * characters. I checked it with markdown.markdown().
  • The _continuation.py module docstring (L15-L24) describes "an earlier version of this prototype" and points to ActorDispatcher.dispatches_snapshot, which isn't an attribute. The history belongs in the commit message, if anywhere.
  • ContinuationCapable.accept_continuation() (L43-L53) talks about a "proposal pool", "physical power" and "downstream aggregation". Those belong to specific power actors, not to this library, which doesn't know what an actor does. The docstring also tells the actor to read the private update._src attribute to get the new dispatch. A public DispatchInfo property for the dispatch (or at least its ID) would make the contract usable without private access.
  • The docstrings use a lot of all-caps words and long explanations of why something is safe. A short statement of the contract in the docstrings would be much easier to follow. The details and an example can go in the user guide suggested above.

Impact

The API docs for the new feature are hard to read and partly wrong, and the actor contract depends on a private attribute.

Suggested fix (⬇️ effort)

Add a blank line before each list, remove the history and the reference to the missing attribute, keep the protocol docs generic, and add a public accessor to DispatchInfo for the source dispatch.


🔵 Low Severity: Addressing it is optional (low impact or nice to have).
⬇️ Low Effort: Low hanging fruit, easy fix.

@llucax llucax added part:actor Affects the dispatching actor and removed part:tooling Affects the development tooling (CI, deployment, dependency management, etc.) labels Nov 13, 2026
@Marenz
Marenz force-pushed the contiguous-handover-gap branch 2 times, most recently from 214cfa3 to 9d88976 Compare November 13, 2026 16:46

@llucax llucax left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 rAIview (AI review here!)

Follow-up review after the update. All the earlier findings were addressed, and I checked the main fixes again: the timer no longer spins once its queue is empty, a rejected handover now starts the successor before stopping the predecessor, and recurring successors hand over on every occurrence. The new deterministic tests cover the fallback paths well.

The only important point left is that the new handover guide lives in a private module docstring, which the docs generator doesn't render (inline comment in the docs thread).

There are also a few small leftovers:

  • The message of 5b7adf2 says a later commit makes _stop_actor() look up a unique successor. That lookup was removed together with the stop-first path, so now the change only affects a log message. The message should say so, or the commit can be dropped.
  • The continuation_accept_timeout docstring says a timeout counts as a refusal. A refused actor is left running, but a timed-out one is now stopped after the successor's actor starts.
  • The DispatchInfo.continuation_of docstring still tells actors to use the private _src, although the new public dispatch property exists.
  • The comment about parking the timer says _schedule_start()/_schedule_stop() reset the timer. Their callers do, through _update_timer().
  • In test_continuation_realclock.py, the module docstring still mentions "the continuation prototype" and dispatches of "a few hundred milliseconds", but they last 2 s. The docstring of test_exact_adjacency_end_to_end_real_scheduler still says the stop is resolved into a continuation, which can't happen now that the stop-first path is gone.

Comment on lines +299 to +301
continuation_predicate: Callable[[Dispatch, Dispatch], bool] | None = None,
dispatches_snapshot: Callable[[], Mapping[DispatchId, Dispatch]] | None = None,
continuation_accept_timeout: timedelta = timedelta(seconds=5),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡⬇️ The new handover guide isn't in the published docs

The new explanation and example went into the module docstring of _actor_dispatcher.py (L4-L73). The API docs generator skips every module whose name starts with _ (see _is_internal()), so this docstring is never rendered. Users only see the docstrings of the public names exported by frequenz.dispatch.

The example is also only a skeleton. new_with_dispatch() throws away the update receiver, so the actor never gets normal dispatch updates. _run() is just pass, so the actor finishes as soon as it starts.

Impact

The guide you asked for exists in the code, but users reading the docs can't find it. Two docstrings send them to the private module instead.

Related locations

Suggested fix (⬇️ effort)

Move the guide somewhere that gets rendered, for example the ContinuationCapable class docstring, the frequenz.dispatch package docstring in __init__.py, or a page under docs/. Point start_managing() there with a cross-reference. Make the example a working actor that keeps the receiver and handles normal updates in _run(), like the ActorDispatcher example does.


🟡 Medium Severity: Probably best to fix before merging, OK to skip if there is a good reason.
⬇️ Low Effort: Low hanging fruit, easy fix.

@Marenz
Marenz force-pushed the contiguous-handover-gap branch from 9d88976 to ba8eced Compare November 16, 2026 09:22
@Marenz

Marenz commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

🤖 Addressing the small leftovers from the follow-up review:

  • The continuation_accept_timeout docstring: fixed. It now says a timeout is not the same as a refusal — a refused actor keeps running as before, a timed-out one is stopped, and only after the successor's actor has already started.
  • DispatchInfo.continuation_of's docstring: fixed, now points to the public dispatch property instead of the private _src.
  • The timer-parking comment: fixed, now says _update_timer() (called by whichever caller schedules something new) resets it, not _schedule_start()/_schedule_stop() directly.
  • test_continuation_realclock.py: fixed the module docstring (no more "prototype", corrected the duration to a few seconds) and test_exact_adjacency_end_to_end_real_scheduler's docstring, which now describes the successor's start resolving the continuation, not a stop (that can't happen anymore).

A reply on the 5b7adf2 commit message is coming separately.

@Marenz
Marenz force-pushed the contiguous-handover-gap branch from ba8eced to a85526c Compare November 16, 2026 09:28
@Marenz

Marenz commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

🤖 Dropped the 5b7adf2 commit entirely. After the stop-first path was removed, it only changed which dispatch's .type went into a log line, which is identical in every real case, so there was nothing left to keep it for.

@llucax

llucax commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

I forgot to mention, I got a bit annoyed by the Claude-like language in the commit messages, it is impossible to follow for me, but I guess this is a lost battle right now (did I mentioned I hate how Claude writes?).

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 <mathias.baumann@frequenz.com>
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 <mathias.baumann@frequenz.com>
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 <mathias.baumann@frequenz.com>
@Marenz
Marenz force-pushed the contiguous-handover-gap branch from a85526c to c381c57 Compare November 16, 2026 10:42
@Marenz
Marenz added this pull request to the merge queue Nov 16, 2026
Merged via the queue into frequenz-floss:v1.x.x with commit 566bba2 Nov 16, 2026
9 checks passed
@Marenz
Marenz deleted the contiguous-handover-gap branch November 16, 2026 10:51
Comment on lines 208 to +397
@@ -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).
"""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This slipped, it was a breaking change. Addressing in #331.

@llucax llucax added the scope:breaking-change Breaking change, users will need to update their code label Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

part:actor Affects the dispatching actor part:dispatcher Affects the high-level dispatcher interface part:docs Affects the documentation part:tests Affects the unit, integration and performance (benchmarks) tests scope:breaking-change Breaking change, users will need to update their code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants