Repository navigation
Add opt-in contiguous dispatch handovers - #311
Conversation
e1fc534 to
a75141d
Compare
llucax
left a comment
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
What about a configurable tolerance? 1us seems too small?
There was a problem hiding this comment.
🟡⬇️ 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
_bg_service.py:301-303: The loop that keeps waking up with nothing to do.RELEASE_NOTES.md:13: Describes the fix as preventing crashes for non-positive intervals.
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))
returnIt'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.
There was a problem hiding this comment.
🤖 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.)
There was a problem hiding this comment.
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.
| continuation_predicate: Callable[[Dispatch, Dispatch], bool] | None = None, | ||
| dispatches_snapshot: Callable[[], Mapping[DispatchId, Dispatch]] | None = None, | ||
| continuation_accept_timeout: timedelta = timedelta(seconds=5), |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🔵⬇️ 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_predicateargument (L317-L336) and inis_exact_continuation()(L112-L118) have no blank line before them, so they render as one paragraph with literal*characters. I checked it withmarkdown.markdown(). - The
_continuation.pymodule docstring (L15-L24) describes "an earlier version of this prototype" and points toActorDispatcher.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 privateupdate._srcattribute to get the new dispatch. A publicDispatchInfoproperty 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.
There was a problem hiding this comment.
🤖 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.
There was a problem hiding this comment.
🟡⬇️ 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
_dispatcher.py:353-359:start_managing()points users to "the module docstring offrequenz.dispatch._actor_dispatcher"._continuation.py:18-19: Points to the same private module docstring._actor_dispatcher.py:50-64: The example actor that ignores its receiver and stops right away.
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.
There was a problem hiding this comment.
🤖 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
left a comment
There was a problem hiding this comment.
🤖 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 withoutdispatches_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.
| # 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) |
There was a problem hiding this comment.
🟡⬇️ 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
_bg_service.py:301-303: The loop that keeps waking up with nothing to do.RELEASE_NOTES.md:13: Describes the fix as preventing crashes for non-positive intervals.
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))
returnIt'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.
| continuation_predicate: Callable[[Dispatch, Dispatch], bool] | None = None, | ||
| dispatches_snapshot: Callable[[], Mapping[DispatchId, Dispatch]] | None = None, | ||
| continuation_accept_timeout: timedelta = timedelta(seconds=5), |
There was a problem hiding this comment.
🔵⬇️ 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_predicateargument (L317-L336) and inis_exact_continuation()(L112-L118) have no blank line before them, so they render as one paragraph with literal*characters. I checked it withmarkdown.markdown(). - The
_continuation.pymodule docstring (L15-L24) describes "an earlier version of this prototype" and points toActorDispatcher.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 privateupdate._srcattribute to get the new dispatch. A publicDispatchInfoproperty 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.
214cfa3 to
9d88976
Compare
llucax
left a comment
There was a problem hiding this comment.
🤖 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_timeoutdocstring 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_ofdocstring still tells actors to use the private_src, although the new publicdispatchproperty 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 oftest_exact_adjacency_end_to_end_real_schedulerstill says the stop is resolved into a continuation, which can't happen now that the stop-first path is gone.
| continuation_predicate: Callable[[Dispatch, Dispatch], bool] | None = None, | ||
| dispatches_snapshot: Callable[[], Mapping[DispatchId, Dispatch]] | None = None, | ||
| continuation_accept_timeout: timedelta = timedelta(seconds=5), |
There was a problem hiding this comment.
🟡⬇️ 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
_dispatcher.py:353-359:start_managing()points users to "the module docstring offrequenz.dispatch._actor_dispatcher"._continuation.py:18-19: Points to the same private module docstring._actor_dispatcher.py:50-64: The example actor that ignores its receiver and stops right away.
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.
9d88976 to
ba8eced
Compare
|
🤖 Addressing the small leftovers from the follow-up review:
A reply on the 5b7adf2 commit message is coming separately. |
ba8eced to
a85526c
Compare
|
🤖 Dropped the 5b7adf2 commit entirely. After the stop-first path was removed, it only changed which dispatch's |
|
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>
a85526c to
c381c57
Compare
| @@ -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). | |||
| """ | |||
There was a problem hiding this comment.
This slipped, it was a breaking change. Addressing in #331.
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.