Skip to content

Keep send order in receivers with stream events - #301

Open
llucax wants to merge 2 commits into
frequenz-floss:v0.x.xfrom
llucax:preserve-mixed-receiver-order
Open

llucax wants to merge 2 commits into
frequenz-floss:v0.x.xfrom
llucax:preserve-mixed-receiver-order

Conversation

@llucax

@llucax llucax commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Receivers created with include_events=True merged a data receiver and an event receiver, so events could overtake data sent before them. In particular, StreamFatalError could arrive before the last data messages, and the documented pattern of stopping on that error lost them.

These receivers are now fed directly by the broadcaster. They keep one buffer per kind with sequence numbers, so they yield everything in send order while maxsize still applies to data and events separately. Data-only receivers are unchanged.

Changes users may need to act on, for receivers created with include_events=True:

  • They are no longer a frequenz.channels.Merger. Code that calls stop() on them should call close() instead.
  • Overflow is no longer logged as one warning per dropped message by the frequenz.channels._broadcast logger. The frequenz.client.base.streaming logger logs one warning when a buffer starts dropping messages and one info message afterwards. The info message is logged the next time a message of the same kind is queued after overflow_recovery_period without drops (a new new_receiver() argument, 5 minutes by default), or when the stream ends or the receiver is closed.

Other fixes in this PR:

  • A receiver created with include_events=True after the stream ended now stops at once, instead of waiting forever.
  • Closing such a receiver while a task waits in receive() raises ReceiverStoppedError in that task, not CancelledError.
  • new_receiver() raises ValueError if maxsize is less than 1.
  • If the retry strategy returns an interval that can't be converted to a timedelta, such as infinity or NaN, the stream ends as if the retry limit was reached, instead of the broadcaster failing and leaving receivers waiting.
  • The second commit validates the timing arguments of both retry strategies: LinearBackoff now rejects negative, infinite or NaN values, and ExponentialBackoff accepts max_interval=math.inf again, meaning no maximum.

Fixes #298

@llucax llucax added this to the v0.11.6 milestone Nov 30, 2026
@github-actions github-actions Bot added part:docs Affects the documentation part:tests Affects the unit, integration and performance (benchmarks) tests part:code Affects the code in general labels Nov 30, 2026
@llucax llucax self-assigned this Nov 30, 2026
@llucax
llucax force-pushed the preserve-mixed-receiver-order branch 5 times, most recently from 338fb08 to 045cd89 Compare December 1, 2026 09:48
@llucax
llucax marked this pull request as ready for review December 1, 2026 09:49
@llucax
llucax enabled auto-merge December 1, 2026 09:49

@daniel-zullo-frequenz daniel-zullo-frequenz 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.

The ordering tests pass. I found four edge cases around retry events, receiver shutdown, and buffer limits

Comment thread src/frequenz/client/base/streaming.py Resolved
Comment thread src/frequenz/client/base/streaming.py Resolved
Comment thread src/frequenz/client/base/streaming.py Resolved
Comment thread src/frequenz/client/base/streaming.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

The loop variable retains the last mixed receiver while waiting for more data, preventing abandoned subscribers from being disposed and allowing continued buffering and overflow warnings.

1 open issue
What changed in this PR

This PR addresses #298 by preserving send order between data and stream events in mixed receivers, preventing terminal errors from overtaking queued data.

Changes:

  • Replaces merged receivers with sequence-ordered buffers that retain separate data and event limits.
  • Adds overflow episode logging and a configurable recovery period while leaving data-only receivers unchanged.
  • Adds ordering, overflow, and lifecycle tests, and documents the behavior changes.
File Description
tests/​streaming/​test_grpc_stream_broadcaster.py Adds coverage for ordering, independent buffers, receiver lifecycle, and overflow logging.
src/​frequenz/​client/​base/​streaming.py Implements ordered mixed receivers and overflow recovery logging.
RELEASE_NOTES.md Documents ordering guarantees, receiver type changes, and overflow logging behavior.

Review effort: Balanced

Comment thread src/frequenz/client/base/streaming.py Resolved

@shsms shsms 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.

(Human: sorry some of these are long, I need to tell my AI to try to be more concise)

Thanks, this fixes a real problem, and the sequence-number approach keeps maxsize per kind as the issue wanted. I checked it against the base code: 9 of the new tests fail there, including test_terminal_error_after_queued_data (the fatal error arrives before the last three data messages). With the PR, all 175 tests pass with channels 1.12.0 and with 2.0.1. The claim that a message is queued for mixed receivers before the data channel's first suspension point also holds in channels 1.8, 1.12 and 2.0.1, so stop() can't deliver a message to only one kind of receiver.

Main points:

  • The for receiver in self._mixed_receivers loop in _run keeps the last mixed receiver alive, so a dropped receiver can keep buffering and log overflow warnings (inline comment).
  • The release notes put an API change and a new argument under Bug Fixes, and they leave out when the info message really comes (inline comment).

About the PR description: the same two points from the release-note comment apply. The info message is only checked when the next message of the same kind is queued. It is logged when the stream ends or the receiver is closed, not when the receiver is dropped. Also, the PR fixes two more things that the description doesn't mention (see the release-note comment).

Severity: medium

Comment thread src/frequenz/client/base/streaming.py Outdated
Comment on lines +519 to +520
for receiver in self._mixed_receivers:
receiver.enqueue_data(transformed)

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.

After this loop ends, receiver stays bound in _run's coroutine frame. So the last mixed receiver visited stays alive for as long as the stream runs, even after the caller drops it, and the WeakSet never forgets it.

I tried it with channels 1.12.0 and 2.0.1. A mixed receiver with maxsize=5 receives one data message, then I drop it and run gc.collect(). It stays alive, held only by the _run coroutine, and it keeps buffering. Then it logs Stream receiver [...] is full. Oldest data messages are being dropped. for a receiver nobody has, and a "recovered after dropping 34 data messages" info message when the stream ends.

It is released only when data is fanned out to another live mixed receiver. If it was the only one, that can be never, for example with retry_on_exhausted_stream=True. test_dropped_receiver_is_forgotten doesn't catch this because it drops the receiver before any data is sent.

Maybe move the loop into a helper, like _send_event, so the reference goes away when the helper returns:

Suggested change
for receiver in self._mixed_receivers:
receiver.enqueue_data(transformed)
self._send_data(transformed)

(The suggestion has to replace lines 519–520.)

    def _send_data(self, message: OutputT) -> None:
        """Send a data message to the receivers that include events."""
        for receiver in self._mixed_receivers:
            receiver.enqueue_data(message)

A bare del receiver after the loop is not enough: when there are no mixed receivers the name is never bound, and del raises UnboundLocalError and kills _run.

For the test: receive one data message, drop the receiver, and assert ref() is None while the stream is still running (before _finished()). After the stream ends the frame is gone, so the test would pass either way. With a small maxsize and more messages after the drop, it can also assert that no overflow warning is logged. Maybe the test could also get a name that doesn't use "dropped", which in this file mostly means dropped messages, e.g. test_unreferenced_receiver_is_released.

Severity: medium

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.

I used the _send_data() helper. The renamed test checks that the receiver is freed while the stream is still running and that later messages don’t trigger an overflow warning for it.

Comment thread RELEASE_NOTES.md Outdated

- `ExponentialBackoff` raises `ValueError` at construction if an interval, the multiplier, or jitter is negative or outside the finite floating-point range.
- `ExponentialBackoff` keeps retrying when the multiplier's power would overflow.
- Stream receivers created with `include_events=True` now yield data and events in the order they were sent. The returned receiver is no longer a `frequenz.channels.Merger`.

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 this is more than a bug fix for users:

  • "No longer a frequenz.channels.Merger" changes a released return value. Merger has a public async stop() (channels 1.12 and 2.0.1), so await rx.stop() now raises AttributeError, and isinstance(rx, Merger) no longer matches. Maybe this could go under ## Upgrading, with the migration step: use close() instead of stop().
  • The overflow log for these receivers moves from the frequenz.channels._broadcast logger to frequenz.client.base.streaming, and it changes level and frequency. Log filters or alerts on the old message stop matching. That could also go under ## Upgrading.
  • overflow_recovery_period is a new argument, so it could go under ## New Features, like warn_on_overflow did in v0.9.0.

The second bullet also says more than the code does:

  • "once no message was dropped for overflow_recovery_period": the clock is only checked when the next message of the same kind is queued (lines 129–133). For events that can be the next reconnect, hours later, or only when the stream ends. The docstrings say this; the release note doesn't.
  • "or when the receiver stops": the report is made when the stream ends (mark_stream_closed) or on close(). A receiver that is garbage-collected without close() never reports.
  • "mixed receiver" is not defined for a release-note reader. "A receiver created with include_events=True" is clearer.
  • The bullet is about 85 words. Maybe split it in two.

The tests also show two fixes the notes don't mention. On the base code:

  • A receiver with include_events=True that is created after the stream ended hangs forever, because the event channel is created then and never closed. test_first_receiver_after_stream_ended times out there.
  • close() while another task waits in receive() raises CancelledError in that task, from Merger.ready() reading a cancelled task. It should raise ReceiverStoppedError. test_close_receiver fails there.

Both could get a Bug Fixes line.

Severity: medium

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.

I moved the Merger and logging changes to Upgrading and the new argument to New Features. The release notes and PR description now explain when the overflow summary is logged. The notes also cover the two shutdown fixes you found.

Comment thread src/frequenz/client/base/streaming.py Outdated
Comment on lines +141 to +142
"Stream receiver [%s] recovered after dropping %d %s over %.1f seconds. "
"None were dropped in the last %.1f seconds.",

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.

report_drops() also runs from mark_stream_closed() and close(), and there the buffer may still be dropping messages. The log then says "recovered … None were dropped in the last 0.0 seconds", which is not true. test_data_overflow_keeps_events asserts this case: recovery(1) at line 630 is logged right after the last message was dropped, as "dropping 1 data messages".

Maybe a wording that is true on every path:

Suggested change
"Stream receiver [%s] recovered after dropping %d %s over %.1f seconds. "
"None were dropped in the last %.1f seconds.",
"Stream receiver [%s] dropped %d %s over %.1f seconds. "
"The last one was dropped %.1f seconds ago.",

(The suggestion has to replace lines 141–142.)

Or pass a reason in, and say "recovered" only from the check in append(). The docstring at line 137 ("since the warning") and the class docstring at lines 90–94 could then say "when the stream ends or the receiver is closed" instead of "when it stops". Also, "The first dropped message logs a warning" reads as "only once", but after a report the next drop warns again.

Severity: low

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 log now says “recovered” only after the recovery period has passed without drops. When the receiver closes or the stream ends, it just reports what was dropped.

assert await _drain(rx) == [_transformer(0), _transformer(1)]


async def test_close_receiver() -> None:

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.

Two things in close() are not covered by any test. I removed each one and all tests still pass:

  • The report_drops() calls in close() (lines 249–251). The release note and docstring promise the info message when the receiver stops, and close() is one way to stop it. A test could overflow a maxsize=1 receiver, call rx.close() while the stream still runs, and assert the info record right away. If it asserts only after the stream ends, mark_stream_closed() logs it and the test can't tell the two apart.
  • The if self._closed: return guard in _enqueue() (line 197). A closed receiver stays in the WeakSet while the caller still holds it. Without the guard it keeps buffering, and logs "is full" and then "recovered" for a receiver nobody reads. Here, maxsize=1 with more than one message sent after close(), and asserting no overflow log, would catch it.

Severity: low

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.

I added tests that check for the drop summary immediately on close() and verify that sending more messages after close() produces no overflow logs. The latter covers unregistering the receiver.

*,
maxsize: int = 50,
warn_on_overflow: bool = True,
overflow_recovery_period: timedelta = timedelta(minutes=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.

This is a public name, so it's worth one more look before it ships. "Recovery period" could be read as something that changes what the receiver does, like a retry or backoff. It only delays an info log, and only with warn_on_overflow=True and include_events=True. The docstring explains it, but at the call site the name alone doesn't. What do you think about a name that says it is about the log, like overflow_log_quiet_period? Keeping it is fine too if you prefer it.

Severity: question

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.

I’m keeping overflow_recovery_period. It describes how long a buffer has to go without drops before it counts as recovered. The docstring explains when that triggers a log and that it doesn’t change how messages are delivered.

Comment thread src/frequenz/client/base/streaming.py Outdated
"""Return the sequence number at the head of the nonempty buffer."""
return self._queue[0][0]

def append(self, sequence: int, message: _T, receiver: object) -> None:

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.

append() and report_drops() take the receiver on every call only to format the log label. The label doesn't change (__str__ uses _name and id(self)). Maybe _MessageBuffer.__init__ could take label: str once (str(self) from _MixedReceiver.__init__), and the per-call argument could go. A string also keeps the buffer from referencing its receiver.

Severity: nit

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.

Done. The buffer takes the label at construction, so append() and report_drops() no longer need the receiver.

Comment thread src/frequenz/client/base/streaming.py Outdated
StreamEvent: TypeAlias = StreamStarted | StreamRetrying | StreamFatalError
"""Type alias for the events that can be sent over the stream."""

_T = TypeVar("_T")

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 other TypeVars in the package have names that say what they are, and a docstring (InputT, OutputT, StubT, …). Maybe _MessageT = TypeVar("_MessageT") with """The type of the messages in a buffer.""".

Severity: nit

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.

Done. I renamed it to _MessageT and added a docstring.

A receiver created with `include_events=True` merged two broadcast
receivers, one for data and one for events. The merge yields whichever
message is ready first, so a `StreamFatalError` could arrive before data
sent earlier, and a consumer that stops on that error lost the data.

Feed these receivers directly from the broadcaster instead. Each one
keeps a buffer per kind, so `maxsize` still applies to data and events
separately and one kind never pushes out the other. Every message gets a
sequence number when it is queued, and the receiver always yields the
message with the lowest one, which is the send order. Messages are
queued synchronously before the data channel send, so stopping the
broadcaster can't deliver a message to one kind of receiver only.

A single shared channel for data and events would have been simpler,
but it would make `maxsize` a shared limit, so a burst of data could
push out events. That is a behavior change I don't want in a bug fix.

Overflow in these receivers is logged from this library's logger. A
buffer logs one warning when it starts dropping messages. Once it goes
`overflow_recovery_period` without dropping (a new `new_receiver()`
argument, 5 minutes by default), it logs one info message saying it
recovered, how many messages were dropped, over how long, and how long
ago the last one was dropped. An emptied buffer is not used as the
recovery signal, because a reader that empties its buffer between
bursts larger than `maxsize` would log a warning and an info message for
every burst. The period is checked only when a message is queued, so no
timer is needed. When the stream ends or the receiver is closed, pending
drops are reported in the same way, without claiming a recovery. Data
only receivers keep using the channel and its warnings unchanged.

Closing one of these receivers removes it from the broadcaster, so later
messages don't reach it. The broadcaster holds them in a `WeakSet` and
feeds data from a separate method, so no local variable in `_run()`
keeps an unreferenced receiver alive while the stream waits.

Building the `StreamRetrying` event converts the retry interval to a
`timedelta`, which fails for infinity, NaN and very large values. That
used to kill the broadcaster task without closing any receiver, and now
it happened even without receivers that include events. An interval
that can't be converted is now treated as an error from the retry
strategy: the stream ends as if the retry limit was reached, with its own
error message. Guessing a value instead would hide a broken strategy.

`new_receiver()` now rejects a `maxsize` below 1. A zero size never
worked: it made the broadcaster task fail on the first message, which
stopped the stream for every receiver.

Signed-off-by: Leandro Lucarella <luca-frequenz@llucax.com>
`LinearBackoff` accepted any interval and jitter. A negative,
infinite or NaN value makes no sense as a wait, and the broadcaster now
ends the stream when it gets an interval it can't convert to a
`timedelta`. It is better to reject these values when the strategy is
created, so `LinearBackoff` now raises `ValueError` for them, like
`ExponentialBackoff` does.

`ExponentialBackoff` rejected an infinite `max_interval` too, but that
is a reasonable way to say there is no maximum, and it worked before.
It is accepted again. The interval then keeps growing until it
overflows to infinity, which takes about a thousand retries with the
default multiplier, and the broadcaster then ends the stream.

The strategies don't check whether a value fits in a `timedelta`. That
depends on how the interval is used, so the broadcaster checks it.

Signed-off-by: Leandro Lucarella <luca-frequenz@llucax.com>
@llucax
llucax force-pushed the preserve-mixed-receiver-order branch from 045cd89 to 8249195 Compare December 1, 2026 15:03
@llucax

llucax commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Updated.

@daniel-zullo-frequenz daniel-zullo-frequenz 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'll wait for Sahas to check and resolve his comments to merge it

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

part:code Affects the code in general part:docs Affects the documentation part:tests Affects the unit, integration and performance (benchmarks) tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Preserve order in mixed stream receivers

4 participants