From da0ee39a1a1ef6dbb236f7847b75addcaa77a2f9 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 19 Oct 2026 15:04:20 +0000 Subject: [PATCH 01/35] Wake waiting broadcast receivers when they are closed `BroadcastReceiver.close()` is synchronous and couldn't notify the channel's condition variable, so a task waiting in `ready()` hung until the next message arrived or the channel was closed. Receivers now wait on an event that can be set from synchronous code. Waiters left on a closed event loop are skipped, so they don't make `close()` fail. For the same reason, `send()` and `aclose()` no longer raise `RuntimeError: Event loop is closed` because of them. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_broadcast.py | 48 ++++++++++++------- tests/test_broadcast.py | 72 +++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 16 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index a5f80621..f5834983 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -7,7 +7,7 @@ import logging import weakref -from asyncio import Condition +from asyncio import Event from collections import deque from typing import Generic, TypeVar @@ -216,8 +216,14 @@ def __init__( Only used for debugging purposes. """ - self._recv_cv: Condition = Condition() - """The condition to wait for data in the channel's buffer.""" + self._wakeup: Event = Event() + """The event receivers wait on for new messages or state changes. + + Each wake-up replaces it with a fresh event, then sets the old one, which wakes + up all receivers waiting on it. It can be set from synchronous code running on + the receivers' event loop, like + [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close]. + """ self._sender_count: int = 0 """The number of senders attached to this channel.""" @@ -280,8 +286,21 @@ async def aclose(self) -> None: """ self._latest = None self._closed = True - async with self._recv_cv: - self._recv_cv.notify_all() + self._wake_receivers() + + def _wake_receivers(self) -> None: + """Wake up all receivers waiting for new messages.""" + wakeup, self._wakeup = self._wakeup, Event() + try: + wakeup.set() + except RuntimeError: + # `set()` raises if the waiters' loop is closed, and they can't be woken + # anyway. All waiters of an event share one loop, so any other + # `RuntimeError`, like a call from another thread in debug mode, is + # re-raised. + loop = getattr(wakeup, "_loop", None) + if loop is None or not loop.is_closed(): + raise @deprecated("The close() method is deprecated, use aclose() instead") async def close(self) -> None: @@ -401,8 +420,7 @@ async def send(self, message: _T, /) -> None: self._channel ) self._channel._latest = message - async with self._channel._recv_cv: - self._channel._recv_cv.notify_all() + self._channel._wake_receivers() # pylint: enable=protected-access @override @@ -566,10 +584,8 @@ async def ready(self) -> bool: if self._q: return True - # Use a while loop here, to handle spurious wakeups of condition variables. - # - # The condition also makes sure that if there are already messages ready to be - # consumed, then we return immediately. + # Use a while loop here, because receivers are woken up on every channel + # state change, not only when a message for this receiver arrives. # pylint: disable=protected-access while len(self._q) == 0: if self._channel._closed or self._closed: @@ -577,8 +593,7 @@ async def ready(self) -> bool: if self._channel._auto_close_enabled and self._channel._sender_count == 0: await self._channel.aclose() return False - async with self._channel._recv_cv: - await self._channel._recv_cv.wait() + await self._channel._wakeup.wait() return True # pylint: enable=protected-access @@ -613,9 +628,10 @@ def close(self) -> None: [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. """ self._closed = True - self._channel._receivers.pop( # pylint: disable=protected-access - hash(self), None - ) + # pylint: disable=protected-access + self._channel._receivers.pop(hash(self), None) + self._channel._wake_receivers() + # pylint: enable=protected-access def __str__(self) -> str: """Return a string representation of this receiver.""" diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index 7035250b..bcc5dfbb 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -427,6 +427,78 @@ async def test_broadcast_close_receiver() -> None: _ = await receiver_2.receive() +async def test_broadcast_close_receiver_while_waiting() -> None: + """Ensure closing a receiver wakes up a task waiting on it.""" + chan = Broadcast[int](name="input-chan") + receiver = chan.new_receiver() + + waiter = asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + assert not waiter.done() + + receiver.close() + + assert await asyncio.wait_for(waiter, timeout=1.0) is False + + +def _leave_waiter_on_closed_loop(receiver: Receiver[int]) -> None: + """Leave a task waiting on the receiver in an event loop that is then closed.""" + + async def wait() -> None: + asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + + # The loop is closed without cancelling the waiting task. + loop = asyncio.new_event_loop() + try: + loop.run_until_complete(wait()) + finally: + loop.close() + + +def test_broadcast_wake_after_loop_closed() -> None: + """Ensure waking receivers works after a waiting receiver's loop closed.""" + chan = Broadcast[int](name="input-chan") + sender = chan.new_sender() + receiver = chan.new_receiver() + receiver_2 = chan.new_receiver() + + _leave_waiter_on_closed_loop(receiver) + receiver_2.close() + with pytest.raises(ReceiverStoppedError): + receiver_2.consume() + + _leave_waiter_on_closed_loop(receiver) + asyncio.run(sender.send(1)) + assert receiver.consume() == 1 + + _leave_waiter_on_closed_loop(receiver) + asyncio.run(chan.aclose()) + assert chan.is_closed + + +def test_broadcast_wake_from_other_thread_in_debug_mode() -> None: + """Ensure a wake-up from another thread still fails in debug mode.""" + + async def close_in_thread() -> None: + chan = Broadcast[int](name="input-chan") + receiver = chan.new_receiver() + receiver_2 = chan.new_receiver() + asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + with pytest.raises(RuntimeError, match="Non-thread-safe operation"): + await asyncio.to_thread(receiver_2.close) + + # The failed wake-up leaves the waiting task stuck, so this loop is closed + # without cancelling it. + loop = asyncio.new_event_loop() + loop.set_debug(True) + try: + loop.run_until_complete(close_in_thread()) + finally: + loop.close() + + async def test_broadcast_auto_close_1() -> None: """Ensure broadcast auto close works when all receivers are closed.""" sender, receiver = BroadcastChannel[int](name="auto-close-test") From 90fb133f285de9c97ec3098fa550b8e98937426a Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Wed, 21 Oct 2026 15:39:05 +0000 Subject: [PATCH 02/35] Stop reporting closed broadcast receivers as ready A closed receiver with messages left in its buffer kept returning True from `ready()`, while `consume()` raised `ReceiverStoppedError`. So `select()` yielded stopped selections for it forever, and a `filter()` on it made `select()` fail. Closing a receiver now drops its buffered messages, so it is never ready. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_broadcast.py | 5 ++-- tests/test_broadcast.py | 40 +++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index f5834983..c9031ce8 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -623,11 +623,12 @@ def consume(self) -> _T: def close(self) -> None: """Close the receiver. - After calling this method, new messages will not be received. Once the - receiver's buffer is drained, trying to receive a message will raise a + After calling this method, the messages left in the receiver's buffer are + dropped, and trying to receive a message raises a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. """ self._closed = True + self._q.clear() # pylint: disable=protected-access self._channel._receivers.pop(hash(self), None) self._channel._wake_receivers() diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index bcc5dfbb..85ea937f 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -17,6 +17,8 @@ ReceiverStoppedError, Sender, SenderError, + select, + selected_from, ) @@ -441,6 +443,44 @@ async def test_broadcast_close_receiver_while_waiting() -> None: assert await asyncio.wait_for(waiter, timeout=1.0) is False +async def test_broadcast_closed_receiver_drops_buffered_messages() -> None: + """Ensure closing a receiver drops its buffered messages and stops `select()`.""" + chan = Broadcast[int](name="input-chan") + sender = chan.new_sender() + receiver = chan.new_receiver() + filtered = chan.new_receiver().filter(lambda _: True) + await sender.send(1) + receiver.close() + filtered.close() + + assert len(receiver) == 0 + assert not await receiver.ready() + + async def stopped(recv: Receiver[int]) -> list[bool]: + return [ + selected.was_stopped + async for selected in select(recv) + if selected_from(selected, recv) + ] + + assert await asyncio.wait_for(stopped(receiver), timeout=1.0) == [True] + assert await asyncio.wait_for(stopped(filtered), timeout=1.0) == [True] + + +async def test_broadcast_receiver_closed_while_waking() -> None: + """Ensure a receiver closed while it wakes up isn't reported as ready.""" + chan = Broadcast[int](name="input-chan") + sender = chan.new_sender() + receiver = chan.new_receiver() + + waiter = asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + await sender.send(1) + receiver.close() + + assert await asyncio.wait_for(waiter, timeout=1.0) is False + + def _leave_waiter_on_closed_loop(receiver: Receiver[int]) -> None: """Leave a task waiting on the receiver in an event loop that is then closed.""" From 3b7e4da6ab9d905413e80469e12e492c81b44684 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Wed, 21 Oct 2026 15:08:04 +0000 Subject: [PATCH 03/35] Keep broadcast channels open when their receivers are gone Like tokio's broadcast channel, a send to an auto-closing broadcast channel without receivers still fails, but now leaves the channel open, so new receivers can still be subscribed. `send()` raises a `NoReceiversError` and drops the message, but with `resend_latest=True` it still keeps the message, so new receivers get the real latest one. Such a channel now closes itself only when it has no open senders. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/__init__.py | 6 ++ src/frequenz/channels/_broadcast.py | 68 ++++++++++-------- src/frequenz/channels/_sender.py | 21 ++++++ tests/test_broadcast.py | 108 ++++++++++++++++++++++++++-- 4 files changed, 167 insertions(+), 36 deletions(-) diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index b0657de5..e576ab27 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -54,6 +54,10 @@ * [`SenderError`][frequenz.channels.SenderError]: Base class for all errors related to senders. +* [`NoReceiversError`][frequenz.channels.NoReceiversError]: Error raised when sending + a message to a [`BroadcastChannel`][frequenz.channels.BroadcastChannel] that has no + receivers. + * [`ReceiverError`][frequenz.channels.ReceiverError]: Base class for all errors related to receivers. @@ -104,6 +108,7 @@ from ._sender import ( CloneableSender, CloneableSubscribableSender, + NoReceiversError, Sender, SenderClosedError, SenderError, @@ -126,6 +131,7 @@ "LatestValueCache", "MappedMessageT_co", "Merger", + "NoReceiversError", "OneshotChannel", "OneshotReceiver", "OneshotSender", diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index c9031ce8..4a1055ff 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -16,7 +16,12 @@ from ._exceptions import ChannelClosedError from ._generic import ChannelMessageT from ._receiver import Receiver, ReceiverStoppedError -from ._sender import CloneableSubscribableSender, SenderClosedError, SenderError +from ._sender import ( + CloneableSubscribableSender, + NoReceiversError, + SenderClosedError, + SenderError, +) _logger = logging.getLogger(__name__) @@ -201,14 +206,17 @@ def __init__( shown in the string representation of the channel. resend_latest: When True, every time a new receiver is created with [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver], the last - message seen by the channel will be sent to the new receiver - automatically. This allows new receivers on slow streams to get the - latest message as soon as they are created, without having to wait for - the next message on the channel to arrive. It is safe to be set in - data/reporting channels, but is not recommended for use in channels that - stream control instructions. - auto_close: If True, the channel will be closed when all senders or all - receivers are closed. + message sent to the channel will be sent to the new receiver + automatically, unless it was `None` or the channel was closed. A + message sent while the channel had no receivers counts too. This allows + new receivers on slow streams to get the latest message as soon as they + are created, without having to wait for the next message on the channel + to arrive. It is safe to be set in data/reporting channels, but is not + recommended for use in channels that stream control instructions. + auto_close: If True, the channel is closed when its last sender is + closed, or when a receiver waits for messages while the channel has + no senders. A `send()` while it has no receivers raises a + [`NoReceiversError`][frequenz.channels.NoReceiversError]. """ self._name: str = name """The name of the broadcast channel. @@ -240,19 +248,16 @@ def __init__( """The latest message sent to the channel.""" self._auto_close_enabled: bool = auto_close - """Whether to close the channel when all senders or all receivers are closed.""" + """Whether the channel closes itself when it has no senders left. + + If `True`, `send()` also raises while the channel has no receivers. See the + `auto_close` argument. + """ self.resend_latest: bool = resend_latest """Whether to resend the latest message to new receivers. - When `True`, every time a new receiver is created with - [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver], it will - automatically get sent the latest message on the channel. This allows new - receivers on slow streams to get the latest message as soon as they are created, - without having to wait for the next message on the channel to arrive. - - It is safe to be set in data/reporting channels, but is not recommended for use - in channels that stream control instructions. + See the `resend_latest` argument of the constructor. """ @property @@ -397,6 +402,10 @@ async def send(self, message: _T, /) -> None: A [`ChannelClosedError`][frequenz.channels.ChannelClosedError] is set as the cause. SenderClosedError: If this sender was closed. + NoReceiversError: If this sender and its channel are open, but the + channel has no receivers, and it is a + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or a + `Broadcast` created with `auto_close=True`. """ if self._closed: raise SenderClosedError(self) @@ -414,12 +423,9 @@ async def send(self, message: _T, /) -> None: recv._enqueue(message) for _hash in stale_refs: del self._channel._receivers[_hash] - if self._channel._auto_close_enabled and len(self._channel._receivers) == 0: - await self._channel.aclose() - raise SenderError("The channel was closed", self) from ChannelClosedError( - self._channel - ) self._channel._latest = message + if self._channel._auto_close_enabled and len(self._channel._receivers) == 0: + raise NoReceiversError(self) self._channel._wake_receivers() # pylint: enable=protected-access @@ -704,7 +710,10 @@ class BroadcastChannel( [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. When all senders of a channel are closed, all its receivers will be - automatically closed, and vice versa. + automatically closed. While all its receivers are closed, + [`send()`][frequenz.channels.BroadcastSender.send] drops the message and + raises a [`NoReceiversError`][frequenz.channels.NoReceiversError], but the + channel stays open. This channel is useful, for example, to implement a pub/sub pattern, where multiple consumers can subscribe to a channel to receive all messages. @@ -830,11 +839,12 @@ def __new__( shown in the string representation of the channel. resend_latest: When True, every time a new receiver is created with [`Broadcast.new_receiver()`][frequenz.channels.Broadcast.new_receiver], - the last message seen by the channel will be sent to the - new receiver automatically. This allows new receivers on slow streams to - get the latest message as soon as they are created, without having to - wait for the next message on the channel to arrive. It is safe to be - set in data/reporting channels, but is not recommended for use in + the last message sent to the channel will be sent to the new receiver + automatically, unless it was `None`. A message sent while the channel + had no receivers counts too. This allows new receivers on slow streams + to get the latest message as soon as they are created, without having + to wait for the next message on the channel to arrive. It is safe to + be set in data/reporting channels, but is not recommended for use in channels that stream control instructions. limit: Number of messages the receivers can hold in their buffers. warn_on_overflow: Whether to log a warning when a receiver's buffer is full diff --git a/src/frequenz/channels/_sender.py b/src/frequenz/channels/_sender.py index 8a5a4445..93b8b7ca 100644 --- a/src/frequenz/channels/_sender.py +++ b/src/frequenz/channels/_sender.py @@ -114,6 +114,27 @@ def __init__(self, sender: Sender[SenderMessageT_co]): super().__init__("Sender is closed", sender) +class NoReceiversError(SenderError[SenderMessageT_co]): + """An error indicating that a message was sent to a channel without receivers. + + It is raised by the senders of a + [`BroadcastChannel`][frequenz.channels.BroadcastChannel], and of a `Broadcast` + created with `auto_close=True`. The message is dropped. With + `resend_latest=True`, new receivers still get it if it is the last message sent and + it isn't `None`. The channel stays open, so sending works again once a new receiver + is attached. + """ + + def __init__(self, sender: Sender[SenderMessageT_co]): + """Initialize this error. + + Args: + sender: The [`Sender`][frequenz.channels.Sender] that tried to send the + message. + """ + super().__init__(f"Sender {sender} has no receivers", sender) + + class SubscribableSender(Sender[SenderMessageT_contra], ABC): """A [`Sender`][frequenz.channels.Sender] that can be subscribed to.""" diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index 85ea937f..032d8102 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -4,6 +4,8 @@ """Tests for the Broadcast implementation.""" import asyncio +import gc +import re from dataclasses import dataclass from typing import TypeGuard, assert_never @@ -13,6 +15,7 @@ Broadcast, BroadcastChannel, ChannelClosedError, + NoReceiversError, Receiver, ReceiverStoppedError, Sender, @@ -539,8 +542,8 @@ async def close_in_thread() -> None: loop.close() -async def test_broadcast_auto_close_1() -> None: - """Ensure broadcast auto close works when all receivers are closed.""" +async def test_broadcast_no_receivers_after_all_receivers_closed() -> None: + """Ensure sending fails once all receivers are closed.""" sender, receiver = BroadcastChannel[int](name="auto-close-test") receiver_2 = sender.subscribe() @@ -558,12 +561,16 @@ async def test_broadcast_auto_close_1() -> None: receiver_2.close() - with pytest.raises(SenderError) as excinfo: + with pytest.raises( + SenderError, + match=f"^Sender {re.escape(str(sender))} has no receivers$", + ) as excinfo: await sender.send(3) - assert isinstance(excinfo.value.__cause__, ChannelClosedError) + assert isinstance(excinfo.value, NoReceiversError) + assert excinfo.value.__cause__ is None -async def test_broadcast_auto_close_2() -> None: +async def test_broadcast_auto_close_on_all_senders_closed() -> None: """Ensure broadcast auto close works when all senders are closed.""" sender, receiver = BroadcastChannel[int](name="auto-close-test") @@ -586,12 +593,99 @@ async def test_broadcast_auto_close_2() -> None: assert isinstance(excinfo.value.__cause__, ChannelClosedError) -async def test_broadcast_closed_channels_remain_closed() -> None: - """Ensure that a closed channel can't be resurrected.""" +async def test_broadcast_subscribe_after_last_receiver_closed() -> None: + """Ensure a channel without receivers can get new ones after a failed send.""" + sender, receiver = BroadcastChannel[int](name="auto-close-test") + + receiver.close() + with pytest.raises(NoReceiversError): + await sender.send(0) + + receiver_2 = sender.subscribe() + await sender.send(1) + assert await receiver_2.receive() == 1 + + +async def test_broadcast_no_receivers_after_last_receiver_dropped() -> None: + """Ensure sending fails once the last receiver is garbage-collected.""" sender, receiver = BroadcastChannel[int](name="auto-close-test") + del receiver + gc.collect() + + with pytest.raises(NoReceiversError): + await sender.send(1) + + +async def test_broadcast_no_auto_close_send_without_receivers() -> None: + """Ensure a non-auto-closing `Broadcast` keeps a message sent without receivers. + + With `resend_latest=True`, a receiver created later gets it. + """ + chan = Broadcast[int](name="no-auto-close-test", resend_latest=True) + sender = chan.new_sender() + + await sender.send(1) + + receiver = chan.new_receiver() + assert await asyncio.wait_for(receiver.receive(), timeout=1.0) == 1 + + +async def test_broadcast_send_without_receivers_resent() -> None: + """Ensure a message sent without receivers is resent to new receivers.""" + sender, receiver = BroadcastChannel[int](name="resend-test", resend_latest=True) + await sender.send(1) receiver.close() + with pytest.raises(NoReceiversError): + await sender.send(2) + + receiver_2 = sender.subscribe() + assert await asyncio.wait_for(receiver_2.receive(), timeout=1.0) == 2 + + +async def test_broadcast_no_receivers_deprecated_auto_close() -> None: + """Ensure an auto-closing `Broadcast` stays open when sending without receivers.""" + chan = Broadcast[int](name="auto-close-test", auto_close=True) + sender = chan.new_sender() + + with pytest.raises(NoReceiversError): + await sender.send(1) + assert not chan.is_closed + + +async def test_broadcast_last_sender_aclose_wakes_receivers() -> None: + """Ensure closing the last sender wakes up a waiting receiver at once.""" + sender, receiver = BroadcastChannel[int](name="auto-close-test") + + waiter = asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + assert not waiter.done() + + await sender.aclose() + await asyncio.sleep(0) + + assert waiter.done() + assert waiter.result() is False + + +async def test_broadcast_auto_close_without_senders() -> None: + """Ensure an auto-closing `Broadcast` without senders closes when received from.""" + chan = Broadcast[int](name="auto-close-test", auto_close=True) + receiver = chan.new_receiver() + assert not chan.is_closed + + assert not await asyncio.wait_for(receiver.ready(), timeout=1.0) + assert chan.is_closed + + +async def test_broadcast_closed_channels_remain_closed() -> None: + """Ensure that a closed channel can't be resurrected.""" + chan = Broadcast[int](name="closed-test") + sender = chan.new_sender() + + await chan.aclose() + with pytest.raises(SenderError) as excinfo: await sender.send(1) assert isinstance(excinfo.value.__cause__, ChannelClosedError) From 4a16c77b34ecdc6651a78501156f90184ed3fb47 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 19 Oct 2026 15:07:32 +0000 Subject: [PATCH 04/35] Refuse to clone closed broadcast senders Unlike `send()` and `subscribe()`, `clone()` worked on a closed sender or channel. On a closed channel, it handed out senders that could never send. It now raises like `send()` and `subscribe()`, through a check that the three methods share. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_broadcast.py | 45 +++++++++++++++++++---------- tests/test_broadcast.py | 20 +++++++++++++ 2 files changed, 49 insertions(+), 16 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index 4a1055ff..b672840d 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -391,7 +391,7 @@ def sender_count(self) -> int: return self._channel._sender_count # pylint: disable=protected-access @override - async def send(self, message: _T, /) -> None: + async def send(self, message: _T, /) -> None: # noqa: DOC503 (raised indirectly) """Send a message to all broadcast receivers. Args: @@ -407,13 +407,8 @@ async def send(self, message: _T, /) -> None: [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or a `Broadcast` created with `auto_close=True`. """ - if self._closed: - raise SenderClosedError(self) + self._check_open() # pylint: disable=protected-access - if self._channel._closed: - raise SenderError("The channel was closed", self) from ChannelClosedError( - self._channel - ) stale_refs = [] for _hash, recv_ref in self._channel._receivers.items(): recv = recv_ref() @@ -448,13 +443,36 @@ async def aclose(self) -> None: ): await self._channel.aclose() + def _check_open(self) -> None: + """Check that this sender and its channel are open. + + Raises: + SenderError: If the underlying channel is closed. + SenderClosedError: If this sender is closed. + """ + if self._closed: + raise SenderClosedError(self) + if self._channel._closed: # pylint: disable=protected-access + raise SenderError("The channel was closed", self) from ChannelClosedError( + self._channel + ) + @override - def clone(self) -> BroadcastSender[_T]: - """Return a clone of this sender.""" + def clone(self) -> BroadcastSender[_T]: # noqa: DOC502 (raised indirectly) + """Return a clone of this sender. + + Returns: + A new sender attached to this sender's channel. + + Raises: + SenderError: If the underlying channel is closed. + SenderClosedError: If this sender is closed. + """ + self._check_open() return BroadcastSender(self._channel) @override - def subscribe( + def subscribe( # noqa: DOC502 (raised indirectly) self, name: str | None = None, limit: int = 50, @@ -475,12 +493,7 @@ def subscribe( SenderError: If the underlying channel is closed. SenderClosedError: If this sender is closed. """ - if self._closed: - raise SenderClosedError(self) - if self._channel._closed: # pylint: disable=protected-access - raise SenderError("The channel was closed", self) from ChannelClosedError( - self._channel - ) + self._check_open() return self._channel.new_receiver( name=name, limit=limit, warn_on_overflow=warn_on_overflow ) diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index 032d8102..84c2980f 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -19,6 +19,7 @@ Receiver, ReceiverStoppedError, Sender, + SenderClosedError, SenderError, select, selected_from, @@ -693,3 +694,22 @@ async def test_broadcast_closed_channels_remain_closed() -> None: with pytest.raises(SenderError) as excinfo: _ = sender.subscribe() assert isinstance(excinfo.value.__cause__, ChannelClosedError) + + with pytest.raises(SenderError) as excinfo: + _ = sender.clone() + assert isinstance(excinfo.value.__cause__, ChannelClosedError) + + +async def test_broadcast_closed_sender() -> None: + """Ensure a closed sender can't be used to send, clone or subscribe.""" + sender, _receiver = BroadcastChannel[int](name="closed-sender-test") + sender_2 = sender.clone() + await sender.aclose() + assert sender_2.sender_count == 1 + + with pytest.raises(SenderClosedError): + await sender.send(1) + with pytest.raises(SenderClosedError): + _ = sender.clone() + with pytest.raises(SenderClosedError): + _ = sender.subscribe() From 788a90c85096a7d32c8f0d70af26fddf93135fde Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 19 Oct 2026 15:08:01 +0000 Subject: [PATCH 05/35] Apply BroadcastChannel receiver options to subscribed receivers `limit` and `warn_on_overflow` were documented as applying to the channel's receivers, but only the initial receiver got them; `subscribe()` always fell back to 50 and `True`. They are now the defaults for `subscribe()`. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_broadcast.py | 53 +++++++++++++++++++---------- tests/test_broadcast.py | 38 +++++++++++++++++++++ 2 files changed, 73 insertions(+), 18 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index b672840d..619c6a44 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -254,6 +254,12 @@ def __init__( `auto_close` argument. """ + self._default_limit: int = 50 + """The default buffer size of receivers created with `BroadcastSender.subscribe()`.""" + + self._default_warn_on_overflow: bool = True + """The default overflow warning setting of subscribed receivers.""" + self.resend_latest: bool = resend_latest """Whether to resend the latest message to new receivers. @@ -475,16 +481,20 @@ def clone(self) -> BroadcastSender[_T]: # noqa: DOC502 (raised indirectly) def subscribe( # noqa: DOC502 (raised indirectly) self, name: str | None = None, - limit: int = 50, - warn_on_overflow: bool = True, + limit: int | None = None, + warn_on_overflow: bool | None = None, ) -> BroadcastReceiver[_T]: """Return a new receiver attached to this sender's channel. Args: name: A name to identify the receiver in the logs. - limit: Number of messages the receiver can hold in its buffer. + limit: Number of messages the receiver can hold in its buffer. If + `None`, the `limit` the `BroadcastChannel` was created with is used, + or `50` for a `Broadcast`. warn_on_overflow: Whether to log a warning when the receiver's buffer is - full and a message is dropped. + full and a message is dropped. If `None`, the `warn_on_overflow` + setting the `BroadcastChannel` was created with is used, or `True` + for a `Broadcast`. Returns: A new receiver attached to this sender's channel. @@ -494,9 +504,17 @@ def subscribe( # noqa: DOC502 (raised indirectly) SenderClosedError: If this sender is closed. """ self._check_open() + # pylint: disable=protected-access return self._channel.new_receiver( - name=name, limit=limit, warn_on_overflow=warn_on_overflow + name=name, + limit=self._channel._default_limit if limit is None else limit, + warn_on_overflow=( + self._channel._default_warn_on_overflow + if warn_on_overflow is None + else warn_on_overflow + ), ) + # pylint: enable=protected-access def __str__(self) -> str: """Return a string representation of this sender.""" @@ -859,9 +877,13 @@ def __new__( to wait for the next message on the channel to arrive. It is safe to be set in data/reporting channels, but is not recommended for use in channels that stream control instructions. - limit: Number of messages the receivers can hold in their buffers. + limit: Number of messages each receiver can hold in its buffer, for the + initial receiver and, by default, for receivers created with + [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]. warn_on_overflow: Whether to log a warning when a receiver's buffer is full - and a message is dropped. + and a message is dropped. Applies to the initial receiver and, by + default, to receivers created with + [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]. Returns: A new BroadcastChannel instance that can be destructured into an initial @@ -870,14 +892,9 @@ def __new__( channel = Broadcast[ChannelMessageT]( name=name, resend_latest=resend_latest, auto_close=True ) - return tuple.__new__( - cls, - ( - channel.new_sender(), - channel.new_receiver( - name=f"{name}_receiver", - limit=limit, - warn_on_overflow=warn_on_overflow, - ), - ), - ) + # pylint: disable=protected-access + channel._default_limit = limit + channel._default_warn_on_overflow = warn_on_overflow + # pylint: enable=protected-access + sender = channel.new_sender() + return tuple.__new__(cls, (sender, sender.subscribe(name=f"{name}_receiver"))) diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index 84c2980f..22262184 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -713,3 +713,41 @@ async def test_broadcast_closed_sender() -> None: _ = sender.clone() with pytest.raises(SenderClosedError): _ = sender.subscribe() + + +async def test_broadcast_subscribe_default_options( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure receivers subscribed to a `Broadcast` use the default options.""" + chan = Broadcast[int](name="subscribe-defaults-test") + sender = chan.new_sender() + receiver = sender.subscribe() + + with caplog.at_level("WARNING", logger="frequenz.channels._broadcast"): + for i in range(51): + await sender.send(i) + + assert len(receiver) == 50 + assert "is full. Oldest message was dropped." in caplog.text + + silent = sender.subscribe(warn_on_overflow=False) + assert not silent._warn_on_overflow # pylint: disable=protected-access + + +async def test_broadcast_subscribe_inherits_receiver_options() -> None: + """Ensure subscribed receivers default to the channel's receiver options.""" + sender, receiver = BroadcastChannel[int]( + name="options-test", limit=2, warn_on_overflow=False + ) + subscribed = sender.subscribe() + overridden = sender.subscribe(limit=3, warn_on_overflow=True) + + for i in range(4): + await sender.send(i) + + assert [len(receiver), len(subscribed), len(overridden)] == [2, 2, 3] + # pylint: disable=protected-access + assert not receiver._warn_on_overflow + assert not subscribed._warn_on_overflow + assert overridden._warn_on_overflow + # pylint: enable=protected-access From 6e7396674c34c54d54d3fbbfb46f74625d976a78 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 19 Oct 2026 15:08:29 +0000 Subject: [PATCH 06/35] Add has_receivers and has_senders to broadcast endpoints Lets producers stop when nobody is listening anymore, and consumers tell whether more messages can still arrive, without having to send or wait on the channel. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_broadcast.py | 35 ++++++++++++++ tests/test_broadcast.py | 72 +++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index 619c6a44..4df069da 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -396,6 +396,24 @@ def sender_count(self) -> int: """The number of open senders attached to this sender's channel.""" return self._channel._sender_count # pylint: disable=protected-access + @property + def has_receivers(self) -> bool: + """Whether this sender's channel is open and has any receivers. + + Producers can check this to stop producing messages that nobody would + receive. When this is `False` on an open + [`BroadcastChannel`][frequenz.channels.BroadcastChannel], + [`send()`][frequenz.channels.BroadcastSender.send] on an open sender raises a + [`NoReceiversError`][frequenz.channels.NoReceiversError] until a new receiver is + created with [`subscribe()`][frequenz.channels.BroadcastSender.subscribe]. + + This doesn't check whether this sender itself is closed. + """ + # pylint: disable=protected-access + return not self._channel._closed and any( + recv_ref() is not None for recv_ref in self._channel._receivers.values() + ) + @override async def send(self, message: _T, /) -> None: # noqa: DOC503 (raised indirectly) """Send a message to all broadcast receivers. @@ -595,6 +613,23 @@ def _enqueue(self, message: _T, /) -> None: ) self._q.append(message) + @property + def has_senders(self) -> bool: + """Whether this receiver's channel is open and has any senders. + + A [`BroadcastChannel`][frequenz.channels.BroadcastChannel] is closed as soon + as its last sender is closed. So once this is `False` on a + `BroadcastChannel`, it stays `False`, and no new messages will arrive. The + messages already in this receiver's buffer can still be received, unless this + receiver is closed. + + A sender that was garbage-collected without being closed still counts. + + This doesn't check whether this receiver itself is closed. + """ + # pylint: disable=protected-access + return not self._channel._closed and self._channel._sender_count > 0 + def __len__(self) -> int: """Return the number of unconsumed messages in the broadcast receiver. diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index 22262184..95392409 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -751,3 +751,75 @@ async def test_broadcast_subscribe_inherits_receiver_options() -> None: assert not subscribed._warn_on_overflow assert overridden._warn_on_overflow # pylint: enable=protected-access + + +async def test_broadcast_has_receivers() -> None: + """Ensure senders report whether their channel has receivers.""" + sender, receiver = BroadcastChannel[int](name="has-receivers-test") + receiver_2 = sender.subscribe() + assert sender.has_receivers + + receiver.close() + assert sender.has_receivers + + receiver_2.close() + assert not sender.has_receivers + + +async def test_broadcast_has_receivers_after_last_receiver_dropped() -> None: + """Ensure `has_receivers` doesn't count garbage-collected receivers.""" + sender, receiver = BroadcastChannel[int](name="has-receivers-test") + + del receiver + gc.collect() + + assert not sender.has_receivers + + +async def test_broadcast_has_senders() -> None: + """Ensure receivers report whether their channel has senders.""" + sender, receiver = BroadcastChannel[int](name="has-senders-test") + sender_2 = sender.clone() + assert receiver.has_senders + + await sender.aclose() + assert receiver.has_senders + + await sender_2.send(1) + await sender_2.aclose() + assert not receiver.has_senders + assert await receiver.receive() == 1 + + +async def test_broadcast_closed_endpoints_still_report_other_side() -> None: + """Ensure `has_receivers` and `has_senders` ignore the endpoint's own state.""" + sender, receiver = BroadcastChannel[int](name="has-closed-test") + sender_2 = sender.clone() + receiver_2 = sender.subscribe() + + await sender.aclose() + receiver.close() + + assert sender.has_receivers and sender_2.has_receivers + assert receiver.has_senders and receiver_2.has_senders + + +async def test_broadcast_has_receivers_and_senders_no_auto_close() -> None: + """Ensure non-auto-closing channels report their senders and receivers.""" + chan = Broadcast[int](name="input-chan") + sender = chan.new_sender() + assert not sender.has_receivers + + receiver = chan.new_receiver() + assert sender.has_receivers + assert receiver.has_senders + + await sender.aclose() + assert not receiver.has_senders + + sender_2 = chan.new_sender() + assert receiver.has_senders + + await chan.aclose() + assert not receiver.has_senders + assert not sender_2.has_receivers From 8d0b94e99d2a9079904f7f298167f611e64299bf Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 19 Oct 2026 15:11:08 +0000 Subject: [PATCH 07/35] Stop BroadcastChannel from emitting a deprecation warning `BroadcastChannel` was built on the deprecated `Broadcast` class, so creating one warned users to "use BroadcastChannel instead". The class is now private, and `Broadcast` is a deprecated alias of it, made with `deprecated_aliases()` from `frequenz-core`. Reaching the alias warns, creating a `BroadcastChannel` doesn't. Signed-off-by: Sahas Subramanian --- pyproject.toml | 3 ++- src/frequenz/channels/__init__.py | 20 +++++++++++++++- src/frequenz/channels/_broadcast.py | 17 +++++++------- tests/test_broadcast.py | 36 +++++++++++++++++++++++++++++ tests/test_merge_integration.py | 3 +-- 5 files changed, 66 insertions(+), 13 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index f8a14a06..faad5cbe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,7 +26,8 @@ classifiers = [ ] requires-python = ">= 3.11, < 4" dependencies = [ - "typing-extensions >= 4.12.0, < 5", + "frequenz-core >= 1.6.0, < 2", + "typing-extensions >= 4.13.0, < 5", "watchfiles >= 0.15.0, < 1.4.0", ] dynamic = ["version"] diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index e576ab27..c27885f2 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -83,8 +83,12 @@ given amount of time. """ +from typing import TYPE_CHECKING + +from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases + from ._anycast import Anycast -from ._broadcast import Broadcast, BroadcastChannel, BroadcastReceiver, BroadcastSender +from ._broadcast import BroadcastChannel, BroadcastReceiver, BroadcastSender from ._exceptions import ChannelClosedError, ChannelError, Error from ._generic import ( ChannelMessageT, @@ -115,6 +119,20 @@ SubscribableSender, ) +if TYPE_CHECKING: + from ._broadcast import _Broadcast as Broadcast +else: + __getattr__ = deprecated_aliases( + __name__, + DeprecatedAlias( + "Broadcast", + new_module="frequenz.channels._broadcast", + new_name="_Broadcast", + since="v1.12.0", + message="Please use BroadcastChannel instead.", + ), + ) + __all__ = [ "Anycast", "Broadcast", diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index 4df069da..47b3fc85 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -26,8 +26,7 @@ _logger = logging.getLogger(__name__) -@deprecated("Please use BroadcastChannel instead.") -class Broadcast( # pylint: disable=too-many-instance-attributes +class _Broadcast( # pylint: disable=too-many-instance-attributes Generic[ChannelMessageT] ): """A channel that delivers all messages to all receivers. @@ -353,12 +352,12 @@ def new_receiver( def __str__(self) -> str: """Return a string representation of this channel.""" - return f"{type(self).__name__}:{self._name}" + return f"{type(self).__name__.removeprefix('_')}:{self._name}" def __repr__(self) -> str: """Return a string representation of this channel.""" return ( - f"{type(self).__name__}(name={self._name!r}, " + f"{type(self).__name__.removeprefix('_')}(name={self._name!r}, " f"resend_latest={self.resend_latest!r}):<" f"latest={self._latest!r}, " f"receivers={len(self._receivers)!r}, " @@ -377,13 +376,13 @@ class BroadcastSender(CloneableSubscribableSender[_T]): method of an existing sender. """ - def __init__(self, channel: Broadcast[_T], /) -> None: + def __init__(self, channel: _Broadcast[_T], /) -> None: """Initialize this sender. Args: channel: A reference to the broadcast channel this sender belongs to. """ - self._channel: Broadcast[_T] = channel + self._channel: _Broadcast[_T] = channel """The broadcast channel this sender belongs to.""" self._closed: bool = False @@ -553,7 +552,7 @@ class BroadcastReceiver(Receiver[_T]): def __init__( self, - channel: Broadcast[_T], + channel: _Broadcast[_T], /, *, name: str | None, @@ -585,7 +584,7 @@ def __init__( Only used for debugging purposes. """ - self._channel: Broadcast[_T] = channel + self._channel: _Broadcast[_T] = channel """The broadcast channel that this receiver belongs to.""" self._q: deque[_T] = deque(maxlen=limit) @@ -924,7 +923,7 @@ def __new__( A new BroadcastChannel instance that can be destructured into an initial sender and receiver. """ - channel = Broadcast[ChannelMessageT]( + channel = _Broadcast[ChannelMessageT]( name=name, resend_latest=resend_latest, auto_close=True ) # pylint: disable=protected-access diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index 95392409..12d04ac9 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -6,11 +6,13 @@ import asyncio import gc import re +import warnings from dataclasses import dataclass from typing import TypeGuard, assert_never import pytest +from frequenz import channels from frequenz.channels import ( Broadcast, BroadcastChannel, @@ -823,3 +825,37 @@ async def test_broadcast_has_receivers_and_senders_no_auto_close() -> None: await chan.aclose() assert not receiver.has_senders assert not sender_2.has_receivers + + +async def test_broadcast_channel_str() -> None: + """Ensure BroadcastChannel endpoints are named like Broadcast ones.""" + sender, receiver = BroadcastChannel[int](name="str-test") + + assert str(sender) == "Broadcast:str-test:BroadcastSender" + assert str(receiver) == "Broadcast:str-test:BroadcastReceiver:str-test_receiver" + assert repr(sender).startswith("BroadcastSender(Broadcast(name='str-test'") + + +def test_broadcast_deprecated() -> None: + """Ensure reaching the `Broadcast` alias emits a deprecation warning.""" + with pytest.deprecated_call(match="Please use BroadcastChannel instead."): + _ = channels.Broadcast + + +async def test_broadcast_channel_closed_error_holds_broadcast() -> None: + """Ensure a closed `BroadcastChannel` reports a `Broadcast` in its error.""" + sender, receiver = BroadcastChannel[int](name="closed-error-test") + await sender.aclose() + + with pytest.raises(ReceiverStoppedError) as excinfo: + await receiver.receive() + + assert isinstance(excinfo.value.__cause__, ChannelClosedError) + assert isinstance(excinfo.value.__cause__.channel, Broadcast) + + +async def test_broadcast_channel_not_deprecated() -> None: + """Ensure creating a BroadcastChannel doesn't emit deprecation warnings.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + _ = BroadcastChannel[int](name="no-warnings-test") diff --git a/tests/test_merge_integration.py b/tests/test_merge_integration.py index 2854a20c..70b3d034 100644 --- a/tests/test_merge_integration.py +++ b/tests/test_merge_integration.py @@ -7,8 +7,7 @@ import pytest -from frequenz.channels import Anycast, Sender, merge -from frequenz.channels._broadcast import Broadcast +from frequenz.channels import Anycast, Broadcast, Sender, merge from frequenz.channels._receiver import ReceiverStoppedError From e59cc980b062c9ae4e196323f81d810a02583a07 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Sat, 31 Oct 2026 14:14:53 +0000 Subject: [PATCH 08/35] Point the Broadcast docs to BroadcastChannel `Broadcast` is deprecated, but its docstring still repeated the channel description and examples of `BroadcastChannel`. It now only says how to use the class. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_broadcast.py | 165 ++-------------------------- 1 file changed, 8 insertions(+), 157 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index 47b3fc85..794ed4ea 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -29,166 +29,17 @@ class _Broadcast( # pylint: disable=too-many-instance-attributes Generic[ChannelMessageT] ): - """A channel that delivers all messages to all receivers. - - # Description + """The implementation of broadcast channels. - [`Broadcast`][frequenz.channels.Broadcast] channels can have multiple - [senders][frequenz.channels.Sender] and multiple - [receivers][frequenz.channels.Receiver]. Each message sent through any of the - senders will be received by all receivers. - -
- ```bob - .---------. msg1 msg1,msg2 .-----------. - | Sender +------. .---------->| Receiver | - '---------' | .----------. | '-----------' - +----->| Channel +-----+ - .---------. | '----------' | .-----------. - | Sender +------' '----------->| Receiver | - '---------' msg2 msg1,msg2 '-----------' - ``` -
- - !!! Note inline end "Characteristics" + Please use [`BroadcastChannel`][frequenz.channels.BroadcastChannel] instead of + using this class directly through the deprecated + [`Broadcast`][frequenz.channels.Broadcast] alias. - * **Buffered:** Yes, with one buffer per receiver - * **Buffer full policy:** Drop oldest message - * **Multiple receivers:** Yes - * **Multiple senders:** Yes - * **Thread-safe:** No - - This channel is buffered, and when messages are not being consumed fast - enough and the buffer fills up, old messages will get dropped. - - Each receiver has its own buffer, so messages will only be dropped for - receivers that can't keep up with the senders, and not for the whole - channel. - - To create a new [senders][frequenz.channels.Sender] and - [receivers][frequenz.channels.Receiver] you can use the + Senders and receivers are created with [`.new_sender()`][frequenz.channels.Broadcast.new_sender] and - [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver] methods - respectively. - - When a channel is not needed anymore, it should be closed with - [`.aclose()`][frequenz.channels.Broadcast.aclose]. This will prevent further - attempts to [`send()`][frequenz.channels.Sender.send] data, and will allow - receivers to drain the pending items on their queues, but after that, - subsequent [`receive()`][frequenz.channels.Receiver.receive] calls will - raise a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. - - This channel is useful, for example, to implement a pub/sub pattern, where - multiple receivers can subscribe to a channel to receive all messages. - - In cases where each message needs to be delivered only to one receiver, an - [anycast][frequenz.channels.Anycast] channel may be used. - - # Examples - - Example: Send a few numbers to a receiver - This is a very simple example that sends a few numbers from a single sender to - a single receiver. - - ```python - import asyncio - - from frequenz.channels import Broadcast, Sender - - - async def send(sender: Sender[int]) -> None: - for message in range(3): - print(f"sending {message}") - await sender.send(message) - - - async def main() -> None: - channel = Broadcast[int](name="numbers") - - sender = channel.new_sender() - receiver = channel.new_receiver() - - async with asyncio.TaskGroup() as task_group: - task_group.create_task(send(sender)) - for _ in range(3): - message = await receiver.receive() - print(f"received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data - - - asyncio.run(main()) - ``` - - The output should look something like (although the sending and received might - appear more interleaved): - - ``` - sending 0 - sending 1 - sending 2 - received 0 - received 1 - received 2 - ``` - - Example: Send a few number from multiple senders to multiple receivers - This is a more complex example that sends a few numbers from multiple senders to - multiple receivers, using a small buffer to force the senders to block. - - ```python - import asyncio - - from frequenz.channels import Broadcast, Receiver, ReceiverStoppedError, Sender - - - async def send(name: str, sender: Sender[int], start: int, stop: int) -> None: - for message in range(start, stop): - print(f"{name} sending {message}") - await sender.send(message) - - - async def recv(name: str, receiver: Receiver[int]) -> None: - try: - async for message in receiver: - print(f"{name} received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data - except ReceiverStoppedError: - pass - - - async def main() -> None: - acast = Broadcast[int](name="numbers") - - async with asyncio.TaskGroup() as task_group: - task_group.create_task(send("sender_1", acast.new_sender(), 10, 13)) - task_group.create_task(send("sender_2", acast.new_sender(), 20, 22)) - task_group.create_task(recv("receiver_1", acast.new_receiver())) - task_group.create_task(recv("receiver_2", acast.new_receiver())) - - - asyncio.run(main()) - ``` - - The output should look something like this(although the sending and received - might appear interleaved in a different way): - - ``` - sender_1 sending 10 - sender_1 sending 11 - sender_1 sending 12 - sender_2 sending 20 - sender_2 sending 21 - receiver_1 received 10 - receiver_1 received 11 - receiver_1 received 12 - receiver_1 received 20 - receiver_1 received 21 - receiver_2 received 10 - receiver_2 received 11 - receiver_2 received 12 - receiver_2 received 20 - receiver_2 received 21 - ``` + [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver]. Unless it is + created with `auto_close=True`, the channel stays open until it is closed with + [`.aclose()`][frequenz.channels.Broadcast.aclose]. """ def __init__( From 3049de9c33f9d956154923d729e599eb1c7deb5b Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Sat, 31 Oct 2026 13:32:09 +0000 Subject: [PATCH 09/35] Document how BroadcastChannel closes itself About auto-closing, the docs only said that closing all senders closes all receivers, and what a send without receivers does. They now also cover what each side sees, that an unclosed sender keeps the channel open, and `has_receivers`/`has_senders`. The multi-sender example is fixed too: it claimed to use a small buffer to make the senders block, it caught a `ReceiverStoppedError` that `async for` never raises, and its receivers slept once after the loop instead of after each message. The first example now stops when its sender is closed. The `BroadcastSender` and `BroadcastReceiver` docs now point to `BroadcastChannel`, and the `resend_latest` docs point to `subscribe()`. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_broadcast.py | 159 ++++++++++++++++++++-------- tests/test_broadcast.py | 12 +++ 2 files changed, 127 insertions(+), 44 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index 794ed4ea..cc57226b 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -222,9 +222,9 @@ def __repr__(self) -> str: class BroadcastSender(CloneableSubscribableSender[_T]): """A sender to send messages to the broadcast channel. - Should not be created directly, but through the - [`.clone()`][frequenz.channels.BroadcastSender.clone] - method of an existing sender. + Should not be created directly, but through + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or the + [`.clone()`][frequenz.channels.BroadcastSender.clone] method of an existing sender. """ def __init__(self, channel: _Broadcast[_T], /) -> None: @@ -396,7 +396,8 @@ def __repr__(self) -> str: class BroadcastReceiver(Receiver[_T]): """A receiver to receive messages from the broadcast channel. - Should not be created directly, but through the + Should not be created directly, but through + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or the [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe] method of an existing sender. """ @@ -417,8 +418,7 @@ def __init__( get dropped just in this receiver. Args: - channel: A reference to the [`Broadcast`][frequenz.channels.Broadcast] - channel that this receiver belongs to. + channel: A reference to the broadcast channel this receiver belongs to. name: A name to identify the receiver in the logs. If `None` an `id(self)`-based name will be used. This is only for debugging purposes, it will be shown in the string representation of the @@ -609,27 +609,50 @@ class BroadcastChannel( receivers that can't keep up with the senders, and not for the whole channel. - Instantiating this class will create a new broadcast channel, and return an - initial sender and a receiver. Further senders and receivers can be created - with the [`BroadcastSender.clone()`][frequenz.channels.BroadcastSender.clone], + Instantiating this class creates a new broadcast channel, and returns an + initial sender and receiver. Further senders and receivers can be created + with the [`BroadcastSender.clone()`][frequenz.channels.BroadcastSender.clone] and [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe] methods respectively. When a sender or a receiver is not needed anymore, it should be closed with [`BroadcastSender.aclose()`][frequenz.channels.BroadcastSender.aclose] or - [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close]. This will prevent - further attempts to [`send()`][frequenz.channels.BroadcastSender.send] data, - and will allow receivers to drain the pending items on their queues, but - after that, subsequent [`receive()`][frequenz.channels.Receiver.receive] calls - will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. - - When all senders of a channel are closed, all its receivers will be - automatically closed. While all its receivers are closed, - [`send()`][frequenz.channels.BroadcastSender.send] drops the message and - raises a [`NoReceiversError`][frequenz.channels.NoReceiversError], but the - channel stays open. + [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close]. + + The channel closes itself when all its senders are closed. This is what each side + sees: + + * As soon as all senders are closed, the channel is closed. Receivers can still + drain the messages pending in their buffers, but after that, + [`receive()`][frequenz.channels.Receiver.receive] raises a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], and `async + for` loops over them end. + + * While all receivers are closed or garbage-collected, + [`send()`][frequenz.channels.BroadcastSender.send] drops the message and + raises a [`NoReceiversError`][frequenz.channels.NoReceiversError]. The + channel stays open, so once + [`subscribe()`][frequenz.channels.BroadcastSender.subscribe] creates a new + receiver, sending works again. With `resend_latest=True`, that receiver first + gets the last message sent, unless it was `None`, even if `send()` raised. + + Senders can check + [`has_receivers`][frequenz.channels.BroadcastSender.has_receivers] to stop + producing messages that nobody would receive, and receivers can check + [`has_senders`][frequenz.channels.BroadcastReceiver.has_senders] to find out + whether new messages can still arrive. + + Tip: + Close every sender, also when a task fails, for example with + `async with contextlib.aclosing(sender):`. A sender that is never closed keeps + the channel open, even if it was garbage-collected, and its receivers keep + waiting for messages. + + Close the initial receiver if it isn't needed, instead of binding it to `_`. + Until `_` is reassigned or goes out of scope, that receiver stays attached: + [`has_receivers`][frequenz.channels.BroadcastSender.has_receivers] stays + `True`, and the receiver's buffer fills up. This channel is useful, for example, to implement a pub/sub pattern, where multiple consumers can subscribe to a channel to receive all messages. @@ -638,12 +661,12 @@ class BroadcastChannel( Example: Send a few numbers to a receiver This is a very simple example that sends a few numbers from a single sender to - a single receiver. + a single receiver. The receiver stops when the sender is closed. ```python import asyncio - from frequenz.channels import BroadcastChannel, Sender + from frequenz.channels import BroadcastChannel, Receiver, Sender async def send(sender: Sender[int]) -> None: @@ -653,15 +676,18 @@ async def send(sender: Sender[int]) -> None: await sender.aclose() + async def receive(receiver: Receiver[int]) -> None: + async for message in receiver: + print(f"received {message}") + print("all senders are closed") + + async def main() -> None: sender, receiver = BroadcastChannel[int](name="numbers") async with asyncio.TaskGroup() as task_group: task_group.create_task(send(sender)) - for _ in range(3): - message = await receiver.receive() - print(f"received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data + task_group.create_task(receive(receiver)) asyncio.run(main()) @@ -677,16 +703,17 @@ async def main() -> None: received 0 received 1 received 2 + all senders are closed ``` - Example: Send a few number from multiple senders to multiple receivers + Example: Send a few numbers from multiple senders to multiple receivers This is a more complex example that sends a few numbers from multiple senders to - multiple receivers, using a small buffer to force the senders to block. + multiple receivers. The receivers stop when all senders are closed. ```python import asyncio - from frequenz.channels import BroadcastChannel, Receiver, ReceiverStoppedError, Sender + from frequenz.channels import BroadcastChannel, Receiver, Sender async def send(name: str, sender: Sender[int], start: int, stop: int) -> None: @@ -696,30 +723,28 @@ async def send(name: str, sender: Sender[int], start: int, stop: int) -> None: await sender.aclose() - async def recv(name: str, receiver: Receiver[int]) -> None: - try: - async for message in receiver: - print(f"{name} received {message}") + async def receive(name: str, receiver: Receiver[int]) -> None: + async for message in receiver: + print(f"{name} received {message}") await asyncio.sleep(0.1) # sleep (or work) with the data - except ReceiverStoppedError: - pass async def main() -> None: sender_1, receiver_1 = BroadcastChannel[int](name="numbers") sender_2 = sender_1.clone() receiver_2 = sender_1.subscribe() + async with asyncio.TaskGroup() as task_group: task_group.create_task(send("sender_1", sender_1, 10, 13)) task_group.create_task(send("sender_2", sender_2, 20, 22)) - task_group.create_task(recv("receiver_1", receiver_1)) - task_group.create_task(recv("receiver_2", receiver_2)) + task_group.create_task(receive("receiver_1", receiver_1)) + task_group.create_task(receive("receiver_2", receiver_2)) asyncio.run(main()) ``` - The output should look something like this(although the sending and received + The output should look something like this (although the sending and received might appear interleaved in a different way): ``` @@ -729,16 +754,62 @@ async def main() -> None: sender_2 sending 20 sender_2 sending 21 receiver_1 received 10 - receiver_1 received 11 - receiver_1 received 12 - receiver_1 received 20 - receiver_1 received 21 receiver_2 received 10 + receiver_1 received 11 receiver_2 received 11 + receiver_1 received 12 receiver_2 received 12 + receiver_1 received 20 receiver_2 received 20 + receiver_1 received 21 receiver_2 received 21 ``` + + Example: Stop producing messages when nobody is listening + This example produces messages only for as long as there are receivers to + receive them. + + ```python + import asyncio + + from frequenz.channels import BroadcastChannel, BroadcastSender, Receiver + + + async def produce(sender: BroadcastSender[int]) -> None: + counter = 0 + while sender.has_receivers: + await sender.send(counter) + counter += 1 + await asyncio.sleep(0.1) # wait for (or compute) the next message + print(f"no receivers left, stopping after {counter} messages") + await sender.aclose() + + + async def consume(receiver: Receiver[int]) -> None: + for _ in range(3): + print(f"received {await receiver.receive()}") + receiver.close() + + + async def main() -> None: + sender, receiver = BroadcastChannel[int](name="numbers") + + async with asyncio.TaskGroup() as task_group: + task_group.create_task(produce(sender)) + task_group.create_task(consume(receiver)) + + + asyncio.run(main()) + ``` + + The output should be: + + ``` + received 0 + received 1 + received 2 + no receivers left, stopping after 3 messages + ``` """ def __new__( @@ -754,7 +825,7 @@ def __new__( name: The name of the channel. This is for logging purposes, and it will be shown in the string representation of the channel. resend_latest: When True, every time a new receiver is created with - [`Broadcast.new_receiver()`][frequenz.channels.Broadcast.new_receiver], + [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe], the last message sent to the channel will be sent to the new receiver automatically, unless it was `None`. A message sent while the channel had no receivers counts too. This allows new receivers on slow streams diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index 12d04ac9..3701653b 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -672,6 +672,18 @@ async def test_broadcast_last_sender_aclose_wakes_receivers() -> None: assert waiter.result() is False +async def test_broadcast_unclosed_sender_keeps_channel_open() -> None: + """Ensure a garbage-collected sender that wasn't closed keeps the channel open.""" + sender, receiver = BroadcastChannel[int](name="auto-close-test") + sender_2 = sender.clone() + + del sender + gc.collect() + await sender_2.aclose() + + assert receiver.has_senders + + async def test_broadcast_auto_close_without_senders() -> None: """Ensure an auto-closing `Broadcast` without senders closes when received from.""" chan = Broadcast[int](name="auto-close-test", auto_close=True) From 28fcb62aab796aa0cb6b500528e22cd11e1d7d69 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Sat, 31 Oct 2026 13:32:21 +0000 Subject: [PATCH 10/35] Correct the broadcast docs on closing The `aclose()` docs said that receiving after the buffer is drained returns `None`; they now say a `ReceiverStoppedError` is raised. The receiver guide, `Receiver.close()` and the `map()` and `filter()` receivers said every closed receiver drains its buffer first; they now say this depends on the receiver. `BroadcastReceiver.close()` doesn't reliably wake up tasks when called from another thread, so its docs now say where to call it. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_anycast.py | 4 ++-- src/frequenz/channels/_broadcast.py | 9 +++++++-- src/frequenz/channels/_receiver.py | 31 ++++++++++++++++++----------- 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/src/frequenz/channels/_anycast.py b/src/frequenz/channels/_anycast.py index 75cfa72d..63912806 100644 --- a/src/frequenz/channels/_anycast.py +++ b/src/frequenz/channels/_anycast.py @@ -280,8 +280,8 @@ async def aclose(self) -> None: Receivers will still be able to drain the pending messages on the channel, but after that, subsequent - [`receive()`][frequenz.channels.Receiver.receive] calls will return `None` - immediately. + [`receive()`][frequenz.channels.Receiver.receive] calls will raise a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. """ self._closed = True async with self._send_cv: diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index cc57226b..ae42419e 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -142,8 +142,8 @@ async def aclose(self) -> None: Receivers will still be able to drain the pending items on their queues, but after that, subsequent - [`receive()`][frequenz.channels.Receiver.receive] calls will return `None` - immediately. + [`receive()`][frequenz.channels.Receiver.receive] calls will raise a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. """ self._latest = None self._closed = True @@ -548,6 +548,11 @@ def close(self) -> None: After calling this method, the messages left in the receiver's buffer are dropped, and trying to receive a message raises a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. + + Call this only from the thread that runs the event loop of the channel's + receivers. From another thread, tasks waiting on any receiver of the channel + might not wake up. If asyncio debug mode is on and a task is waiting, this also + raises a `RuntimeError`, and the waiting tasks stay stuck. """ self._closed = True self._q.clear() diff --git a/src/frequenz/channels/_receiver.py b/src/frequenz/channels/_receiver.py index f1ce77ac..436fc3b5 100644 --- a/src/frequenz/channels/_receiver.py +++ b/src/frequenz/channels/_receiver.py @@ -131,10 +131,11 @@ [`Receiver.close()`][frequenz.channels.Receiver.close] method can be used for this purpose. -After [`Receiver.close()`][frequenz.channels.Receiver.close] is called, we can still -receive messages that are in the receiver's buffer, but as soon as the receiver's buffer -has been drained, trying to receive further messages from a *closed* receiver will raise -a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. +After [`Receiver.close()`][frequenz.channels.Receiver.close] is called, some receivers +still deliver the messages in their buffer, and raise a +[`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError] once it is drained. +Others, like [`BroadcastReceiver`][frequenz.channels.BroadcastReceiver], raise it at +once. # Advanced Usage @@ -237,8 +238,10 @@ def close(self) -> None: """Close the receiver. After calling this method, new messages will not be available from the receiver. - Once the receiver's buffer is drained, trying to receive a message will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. + Trying to receive a message raises a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], either at once + or once the messages already in the receiver's buffer are received, depending on + the receiver. """ raise NotImplementedError("close() must be implemented by subclasses") @@ -498,9 +501,11 @@ def consume(self) -> MappedMessageT_co: # noqa: DOC502 def close(self) -> None: """Close the receiver. - After calling this method, new messages will not be received. Once the - receiver's buffer is drained, trying to receive a message will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. + After calling this method, new messages will not be received. Trying to + receive a message then raises a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], either at once + or once the messages already in the buffer are received, depending on the + input receiver. """ self._receiver.close() @@ -602,9 +607,11 @@ def consume(self) -> ReceiverMessageT_co: def close(self) -> None: """Close the receiver. - After calling this method, new messages will not be received. Once the - receiver's buffer is drained, trying to receive a message will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. + After calling this method, new messages will not be received. Trying to + receive a message then raises a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], either at once + or once the messages already in the buffer are received, depending on the + input receiver. """ self._receiver.close() From c109906060b62d1fc1c4b07ec7eb9f77bca7aea9 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 19 Oct 2026 15:40:23 +0000 Subject: [PATCH 11/35] Show BroadcastChannel in the user guide and README The user guide, package overview and README still presented the deprecated `Broadcast` and `Anycast` classes. They now show `BroadcastChannel`, the overview marks `Anycast` as deprecated, and the user guide drops its `Anycast` page. A new page covers `OneshotChannel`. The README showcase now closes its data senders, and its receiver stops when the data channels close. Signed-off-by: Sahas Subramanian --- README.md | 53 ++++++++----------- docs/user-guide/channels/broadcast.md | 2 +- docs/user-guide/channels/index.md | 2 +- .../channels/{anycast.md => oneshot.md} | 4 +- .../receiving/synchronization/index.md | 10 ++-- src/frequenz/channels/__init__.py | 22 ++++++-- 6 files changed, 49 insertions(+), 44 deletions(-) rename docs/user-guide/channels/{anycast.md => oneshot.md} (76%) diff --git a/README.md b/README.md index a08ffd64..10ee1cc7 100644 --- a/README.md +++ b/README.md @@ -67,13 +67,11 @@ python3 -m pip install frequenz-channels ```python import asyncio -from frequenz.channels import Anycast +from frequenz.channels import BroadcastChannel async def main() -> None: - hello_channel = Anycast[str](name="hello-world-channel") - sender = hello_channel.new_sender() - receiver = hello_channel.new_receiver() + sender, receiver = BroadcastChannel[str](name="hello-world-channel") await sender.send("Hello World!") message = await receiver.receive() @@ -100,8 +98,7 @@ from enum import Enum, auto from typing import assert_never from frequenz.channels import ( - Anycast, - Broadcast, + BroadcastChannel, Receiver, Sender, merge, @@ -151,6 +148,7 @@ async def send( await control_reply.send(Reply(ReplyCommand.PONG, str(sender))) case _ as unknown: assert_never(unknown) + await sender.aclose() print(f"{sender}: Finished") @@ -159,13 +157,16 @@ async def receive( control_command: Receiver[Command], control_reply: Sender[Reply], ) -> None: - """Receive data from multiple channels, until no more data is received for 2 seconds.""" + """Receive data from multiple channels, until they're closed or idle for 2 seconds.""" print("receive: Starting") timer = Timer(timedelta(seconds=2.0), SkipMissedAndDrift()) print(f"{timer=}") merged = merge(*receivers) async for selected in select(merged, timer, control_command): if selected_from(selected, merged): + if selected.was_stopped: + print("receive: All data channels were closed") + break message = selected.message print(f"receive: Received {message=}") timer.reset() @@ -191,51 +192,41 @@ async def receive( async def main() -> None: - data_channel_1 = Anycast[str](name="data-channel-1") - data_channel_2 = Anycast[str](name="data-channel-2") - command_channel = Broadcast[Command](name="control-channel") # (1)! - reply_channel = Anycast[Reply](name="reply-channel") + data_sender_1, data_receiver_1 = BroadcastChannel[str](name="data-channel-1") + data_sender_2, data_receiver_2 = BroadcastChannel[str](name="data-channel-2") + command_sender, command_receiver = BroadcastChannel[Command]( + name="control-channel" + ) + reply_sender, reply_receiver = BroadcastChannel[Reply](name="reply-channel") async with asyncio.TaskGroup() as tasks: tasks.create_task( - send( - data_channel_1.new_sender(), - command_channel.new_receiver(), - reply_channel.new_sender(), - ), + send(data_sender_1, command_receiver, reply_sender.clone()), name="send-channel-1", ) tasks.create_task( - send( - data_channel_2.new_sender(), - command_channel.new_receiver(), - reply_channel.new_sender(), - ), + send(data_sender_2, command_sender.subscribe(), reply_sender.clone()), name="send-channel-2", ) tasks.create_task( receive( - [data_channel_1.new_receiver(), data_channel_2.new_receiver()], - command_channel.new_receiver(), - reply_channel.new_sender(), + [data_receiver_1, data_receiver_2], + command_sender.subscribe(), + reply_sender, ), name="receive", ) - control_sender = command_channel.new_sender() - reply_receiver = reply_channel.new_receiver() - # Send a ping command to all tasks and wait for the replies - await control_sender.send(Command.PING) + await command_sender.send(Command.PING) print(f"main: {await reply_receiver.receive()}") print(f"main: {await reply_receiver.receive()}") print(f"main: {await reply_receiver.receive()}") await asyncio.sleep(5.0) - # Stop senders, after 2 seconds not receiving any data, - # the receiver will stop too - await control_sender.send(Command.STOP_SENDER) + # Stop the senders. This closes the data channels, so the receiver stops too. + await command_sender.send(Command.STOP_SENDER) asyncio.run(main()) diff --git a/docs/user-guide/channels/broadcast.md b/docs/user-guide/channels/broadcast.md index f759bce3..ba8ebe2e 100644 --- a/docs/user-guide/channels/broadcast.md +++ b/docs/user-guide/channels/broadcast.md @@ -1,6 +1,6 @@ # Broadcast -::: frequenz.channels._broadcast.Broadcast +::: frequenz.channels._broadcast.BroadcastChannel options: inherited_members: [] members: [] diff --git a/docs/user-guide/channels/index.md b/docs/user-guide/channels/index.md index c6f2df64..55bd172c 100644 --- a/docs/user-guide/channels/index.md +++ b/docs/user-guide/channels/index.md @@ -35,7 +35,7 @@ various factors: Because these questions can have many answers, there are different types of channels. Frequenz Channels offers a few of them: -* [Anycast](anycast.md) * [Broadcast](broadcast.md) +* [Oneshot](oneshot.md) More might be added in the future, and you can also create your own. diff --git a/docs/user-guide/channels/anycast.md b/docs/user-guide/channels/oneshot.md similarity index 76% rename from docs/user-guide/channels/anycast.md rename to docs/user-guide/channels/oneshot.md index eca01889..9405ca72 100644 --- a/docs/user-guide/channels/anycast.md +++ b/docs/user-guide/channels/oneshot.md @@ -1,6 +1,6 @@ -# Anycast +# Oneshot -::: frequenz.channels._anycast.Anycast +::: frequenz.channels._oneshot.OneshotChannel options: inherited_members: [] members: [] diff --git a/docs/user-guide/receiving/synchronization/index.md b/docs/user-guide/receiving/synchronization/index.md index 60d70d86..050847fb 100644 --- a/docs/user-guide/receiving/synchronization/index.md +++ b/docs/user-guide/receiving/synchronization/index.md @@ -6,8 +6,8 @@ as soon as it is available in one single task. A naive approach like this will not work: ```python show_lines="4:" -receiver1: Receiver[int] = channel1.new_receiver() -receiver2: Receiver[int] = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[int](name="channel2") message = await receiver1.receive() print(f"Received from channel1: {message}") @@ -16,9 +16,9 @@ message = await receiver2.receive() print(f"Received from channel2: {message}") ``` -The problem is that if the first message is not available in `channel1` but in -`channel2`, the program will be blocked until a message is available in -`channel1`, but you probably want to receive the first message from `channel2` +The problem is that if the first message is not available in `receiver1` but in +`receiver2`, the program will be blocked until a message is available in +`receiver1`, but you probably want to receive the first message from `receiver2` as soon as it is available. Frequenz Channels provides two tools to solve this issue: diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index c27885f2..881f1a7e 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -17,15 +17,29 @@ * [`Sender`][frequenz.channels.Sender]: An object that can send messages to a channel. +* [`CloneableSender`][frequenz.channels.CloneableSender], + [`SubscribableSender`][frequenz.channels.SubscribableSender] and + [`CloneableSubscribableSender`][frequenz.channels.CloneableSubscribableSender]: + Senders that can create more senders, or receivers, attached to the same channel. + Channels: -* [`Anycast`][frequenz.channels.Anycast]: A channel that supports multiple +* [`BroadcastChannel`][frequenz.channels.BroadcastChannel]: A channel to broadcast + messages from multiple senders to multiple receivers. Each message sent through any + of the senders is received by all of the receivers. The channel closes itself when + all its senders are closed. A `send()` while it has no receivers raises a + [`NoReceiversError`][frequenz.channels.NoReceiversError]. + +* [`OneshotChannel`][frequenz.channels.OneshotChannel]: A channel that can send a + single message from one sender to one receiver. + +* [`Anycast`][frequenz.channels.Anycast] (deprecated): A channel that supports multiple senders and multiple receivers. A message sent through a sender will be received by exactly one receiver. -* [`Broadcast`][frequenz.channels.Broadcast]: A channel to broadcast messages - from multiple senders to multiple receivers. Each message sent through any of - the senders is received by all of the receivers. +* [`Broadcast`][frequenz.channels.Broadcast] (deprecated): The predecessor of + [`BroadcastChannel`][frequenz.channels.BroadcastChannel]. Unless it is created with + `auto_close=True`, it must be closed with `aclose()`. Utilities to work with channels: From 81897bd1e8cff0a69adf5d3aa68e09d8429d1380 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 19 Oct 2026 15:15:59 +0000 Subject: [PATCH 12/35] Use BroadcastChannel in docstring examples The examples used the deprecated `Anycast` and `Broadcast` classes. Also fix some examples with missing imports, and the latest value cache examples, which checked the cache before its task could run. The `Anycast` docs now point to `BroadcastChannel`. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/_anycast.py | 2 +- src/frequenz/channels/_exceptions.py | 14 +++--- src/frequenz/channels/_latest_value_cache.py | 10 ++-- src/frequenz/channels/_merge.py | 24 ++++----- src/frequenz/channels/_receiver.py | 49 +++++++++---------- src/frequenz/channels/_select.py | 40 ++++++--------- src/frequenz/channels/_sender.py | 22 ++++----- src/frequenz/channels/event.py | 6 +-- .../_grouping_latest_value_cache.py | 10 ++-- src/frequenz/channels/experimental/_pipe.py | 25 +++++----- .../channels/experimental/_relay_sender.py | 11 ++--- .../channels/experimental/_with_previous.py | 32 ++++++------ src/frequenz/channels/timer.py | 9 ++-- 13 files changed, 115 insertions(+), 139 deletions(-) diff --git a/src/frequenz/channels/_anycast.py b/src/frequenz/channels/_anycast.py index 63912806..57e52852 100644 --- a/src/frequenz/channels/_anycast.py +++ b/src/frequenz/channels/_anycast.py @@ -93,7 +93,7 @@ class Anycast(Generic[ChannelMessageT]): This channel is useful, for example, to distribute work across multiple workers. In cases where each message needs to be received by every receiver, a - [broadcast][frequenz.channels.Broadcast] channel may be used. + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] may be used. # Examples diff --git a/src/frequenz/channels/_exceptions.py b/src/frequenz/channels/_exceptions.py index 191d83cc..9412fe1e 100644 --- a/src/frequenz/channels/_exceptions.py +++ b/src/frequenz/channels/_exceptions.py @@ -19,11 +19,10 @@ was closed while sending or receiving a message, the original exception will be available as the cause of the exception: -```python show_lines="6:" -from frequenz.channels import Anycast, ChannelClosedError, SenderError +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, ChannelClosedError, SenderError -channel = Anycast[int](name="test-channel") -sender = channel.new_sender() +sender, receiver = BroadcastChannel[int](name="test-channel") try: await sender.send(42) @@ -44,11 +43,10 @@ explicitly calling [`receive()`][frequenz.channels.Receiver.receive] on the receiver after the iteration is done: - ```python show_lines="6:" - from frequenz.channels import Anycast, ChannelClosedError, ReceiverStoppedError + ```python show_lines="5:" + from frequenz.channels import BroadcastChannel, ChannelClosedError, ReceiverStoppedError - channel = Anycast[int](name="test-channel") - receiver = channel.new_receiver() + sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver: print(message) diff --git a/src/frequenz/channels/_latest_value_cache.py b/src/frequenz/channels/_latest_value_cache.py index 1e85786f..71774bdc 100644 --- a/src/frequenz/channels/_latest_value_cache.py +++ b/src/frequenz/channels/_latest_value_cache.py @@ -16,16 +16,18 @@ Example: ```python - from frequenz.channels import Broadcast, LatestValueCache + import asyncio - channel = Broadcast[int](name="lvc_test") + from frequenz.channels import BroadcastChannel, LatestValueCache - cache = LatestValueCache(channel.new_receiver()) - sender = channel.new_sender() + sender, receiver = BroadcastChannel[int](name="lvc_test") + + cache = LatestValueCache(receiver) assert not cache.has_value() await sender.send(5) + await asyncio.sleep(0) # Let the cache process the message assert cache.has_value() assert cache.get() == 5 diff --git a/src/frequenz/channels/_merge.py b/src/frequenz/channels/_merge.py index 68c1d134..ac5000a4 100644 --- a/src/frequenz/channels/_merge.py +++ b/src/frequenz/channels/_merge.py @@ -9,21 +9,19 @@ stream, you can use [`merge()`][frequenz.channels.merge] to create a new receiver that will receive messages from all the given receivers: -```python show_lines="8:" -from frequenz.channels import Anycast, Receiver, merge +```python show_lines="6:" +from frequenz.channels import BroadcastChannel, Receiver, merge -channel1: Anycast[int] = Anycast(name="channel1") -channel2: Anycast[int] = Anycast(name="channel2") -receiver1 = channel1.new_receiver() -receiver2 = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[int](name="channel2") async for message in merge(receiver1, receiver2): print(message) ``` -If the first message comes from `channel2` and the second message from `channel1`, the -first message will be received immediately, and the second message will be received as -soon as it is available. +If the first message comes from `receiver2` and the second message from `receiver1`, +the first message will be received immediately, and the second message will be +received as soon as it is available. This can be helpful when you just need to receive messages and don't care about where are they coming from specifically. If you need to know where the message came @@ -69,12 +67,10 @@ def merge(*receivers: Receiver[ReceiverMessageT_co]) -> Merger[ReceiverMessageT_ stream like this: ```python - from frequenz.channels import Broadcast + from frequenz.channels import BroadcastChannel, merge - channel1 = Broadcast[int](name="input-channel-1") - channel2 = Broadcast[int](name="input-channel-2") - receiver1 = channel1.new_receiver() - receiver2 = channel2.new_receiver() + sender1, receiver1 = BroadcastChannel[int](name="input-channel-1") + sender2, receiver2 = BroadcastChannel[int](name="input-channel-2") async for message in merge(receiver1, receiver2): print(f"received {message}") diff --git a/src/frequenz/channels/_receiver.py b/src/frequenz/channels/_receiver.py index 436fc3b5..1d81af10 100644 --- a/src/frequenz/channels/_receiver.py +++ b/src/frequenz/channels/_receiver.py @@ -7,15 +7,15 @@ Messages are received from [channels](/user-guide/channels/index.md) through [`Receiver`][frequenz.channels.Receiver] objects. -[`Receiver`][frequenz.channels.Receiver]s are usually created by calling -`channel.new_receiver()` and are [async iterators][typing.AsyncIterator], so the easiest -way to receive messages from them as a stream is to use `async for`: +[`Receiver`][frequenz.channels.Receiver]s usually come from creating a channel, like a +[`BroadcastChannel`][frequenz.channels.BroadcastChannel], or from calling +`sender.subscribe()`. They are [async iterators][typing.AsyncIterator], so the +easiest way to receive messages from them as a stream is to use `async for`: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver: print(message) @@ -24,11 +24,10 @@ If you need to receive messages in different places or expecting a particular sequence, you can use the [`receive()`][frequenz.channels.Receiver.receive] method: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") first_message = await receiver.receive() print(f"First message: {first_message}") @@ -42,11 +41,10 @@ If you need to transform the received messages, receivers provide a [`map()`][frequenz.channels.Receiver.map] method to easily do so: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver.map(lambda x: x + 1): print(message) @@ -60,11 +58,10 @@ If you need to filter the received messages, receivers provide a [`filter()`][frequenz.channels.Receiver.filter] method to easily do so: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver.filter(lambda x: x % 2 == 0): print(message) # Only even numbers will be printed @@ -90,11 +87,10 @@ closed), a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError] exception is raised by [`receive()`][frequenz.channels.Receiver.receive] method. -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, ReceiverError, ReceiverStoppedError -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") try: await receiver.receive() @@ -107,11 +103,10 @@ When used as an async iterator, the iteration will just stop without raising an exception: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, ReceiverError, ReceiverStoppedError -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") try: async for message in receiver: diff --git a/src/frequenz/channels/_select.py b/src/frequenz/channels/_select.py index 079d54b0..19f47851 100644 --- a/src/frequenz/channels/_select.py +++ b/src/frequenz/channels/_select.py @@ -18,13 +18,11 @@ function to check the source of the message, and the [`message`][frequenz.channels.Selected.message] attribute to access the message: -```python show_lines="8:" -from frequenz.channels import Anycast, ReceiverStoppedError, select, selected_from +```python show_lines="6:" +from frequenz.channels import BroadcastChannel, ReceiverStoppedError, select, selected_from -channel1: Anycast[int] = Anycast(name="channel1") -channel2: Anycast[str] = Anycast(name="channel2") -receiver1 = channel1.new_receiver() -receiver2 = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[str](name="channel2") async for selected in select(receiver1, receiver2): if selected_from(selected, receiver1): @@ -46,13 +44,11 @@ If for some reason you want to ignore a received message, just add the receiver to the if-chain and do nothing with the message: - ```python show_lines="8:" - from frequenz.channels import Anycast, select, selected_from + ```python show_lines="6:" + from frequenz.channels import BroadcastChannel, select, selected_from - channel1: Anycast[int] = Anycast(name="channel1") - channel2: Anycast[str] = Anycast(name="channel2") - receiver1 = channel1.new_receiver() - receiver2 = channel2.new_receiver() + sender1, receiver1 = BroadcastChannel[int](name="channel1") + sender2, receiver2 = BroadcastChannel[str](name="channel2") async for selected in select(receiver1, receiver2): if selected_from(selected, receiver1): @@ -72,13 +68,11 @@ [`was_stopped`][frequenz.channels.Selected.was_stopped] method to check if the selected [`Receiver`][frequenz.channels.Receiver] was stopped: -```python show_lines="8:" -from frequenz.channels import Anycast, select, selected_from +```python show_lines="6:" +from frequenz.channels import BroadcastChannel, select, selected_from -channel1: Anycast[int] = Anycast(name="channel1") -channel2: Anycast[str] = Anycast(name="channel2") -receiver1 = channel1.new_receiver() -receiver2 = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[str](name="channel2") async for selected in select(receiver1, receiver2): if selected_from(selected, receiver1): @@ -107,13 +101,11 @@ You can use a try-except block to handle exceptions as usual: -```python show_lines="8:" -from frequenz.channels import Anycast, ReceiverStoppedError, select, selected_from +```python show_lines="6:" +from frequenz.channels import BroadcastChannel, ReceiverStoppedError, select, selected_from -channel1: Anycast[int] = Anycast(name="channel1") -channel2: Anycast[str] = Anycast(name="channel2") -receiver1 = channel1.new_receiver() -receiver2 = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[str](name="channel2") async for selected in select(receiver1, receiver2): if selected_from(selected, receiver1): diff --git a/src/frequenz/channels/_sender.py b/src/frequenz/channels/_sender.py index 93b8b7ca..d190ed37 100644 --- a/src/frequenz/channels/_sender.py +++ b/src/frequenz/channels/_sender.py @@ -6,15 +6,16 @@ # Senders Messages are sent to a [channel](/user-guide/channels) through -[`Sender`][frequenz.channels.Sender] objects. [`Sender`][frequenz.channels.Sender]s are -usually created by calling `channel.new_sender()`, and are a very simple abstraction -that only provides a single [`send()`][frequenz.channels.Sender.send] method: +[`Sender`][frequenz.channels.Sender] objects. [`Sender`][frequenz.channels.Sender]s +usually come from creating a channel, like a +[`BroadcastChannel`][frequenz.channels.BroadcastChannel], or from calling +`sender.clone()`. They are a very simple abstraction that mainly provides a +[`send()`][frequenz.channels.Sender.send] method: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -sender = channel.new_sender() +sender, receiver = BroadcastChannel[str](name="test-channel") await sender.send("Hello, world!") ``` @@ -36,11 +37,10 @@ If there is any failure sending a message, a [`SenderError`][frequenz.channels.SenderError] exception is raised. -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, SenderError -channel = Anycast[int](name="test-channel") -sender = channel.new_sender() +sender, receiver = BroadcastChannel[str](name="test-channel") try: await sender.send("Hello, world!") diff --git a/src/frequenz/channels/event.py b/src/frequenz/channels/event.py index 87c58af5..6915435d 100644 --- a/src/frequenz/channels/event.py +++ b/src/frequenz/channels/event.py @@ -46,12 +46,10 @@ class Event(Receiver[None]): ```python import asyncio - from frequenz.channels import Anycast, select, selected_from + from frequenz.channels import BroadcastChannel, select, selected_from from frequenz.channels.event import Event - channel: Anycast[int] = Anycast(name="channel") - receiver = channel.new_receiver() - sender = channel.new_sender() + sender, receiver = BroadcastChannel[int](name="channel") stop_event = Event(name="stop") diff --git a/src/frequenz/channels/experimental/_grouping_latest_value_cache.py b/src/frequenz/channels/experimental/_grouping_latest_value_cache.py index 0e31ab45..4d320645 100644 --- a/src/frequenz/channels/experimental/_grouping_latest_value_cache.py +++ b/src/frequenz/channels/experimental/_grouping_latest_value_cache.py @@ -68,18 +68,20 @@ class GroupingLatestValueCache(Mapping[HashableT, ValueT_co]): Example: ```python - from frequenz.channels import Broadcast + import asyncio + + from frequenz.channels import BroadcastChannel from frequenz.channels.experimental import GroupingLatestValueCache - channel = Broadcast[tuple[int, str]](name="lvc_test") + sender, receiver = BroadcastChannel[tuple[int, str]](name="lvc_test") - cache = GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x[0]) - sender = channel.new_sender() + cache = GroupingLatestValueCache(receiver, key=lambda x: x[0]) assert cache.get(6) is None assert 6 not in cache await sender.send((6, "twenty-six")) + await asyncio.sleep(0) # Let the cache process the message assert 6 in cache assert cache.get(6) == (6, "twenty-six") diff --git a/src/frequenz/channels/experimental/_pipe.py b/src/frequenz/channels/experimental/_pipe.py index 3c4ceea1..9726c228 100644 --- a/src/frequenz/channels/experimental/_pipe.py +++ b/src/frequenz/channels/experimental/_pipe.py @@ -28,30 +28,29 @@ class Pipe(typing.Generic[ChannelMessageT]): Example: ```python import asyncio - from contextlib import closing, aclosing, AsyncExitStack + from contextlib import closing, AsyncExitStack - from frequenz.channels import Broadcast + from frequenz.channels import BroadcastChannel from frequenz.channels.experimental import Pipe async def main() -> None: - # Channels, receivers and Pipe are in AsyncExitStack + # Senders, receivers and Pipe are in AsyncExitStack # to close and stop them at the end. async with AsyncExitStack() as stack: - source_channel = await stack.enter_async_context( - aclosing(Broadcast[int](name="source channel")) + source_sender, source_receiver = BroadcastChannel[int]( + name="source channel" ) - source_receiver = stack.enter_context(closing(source_channel.new_receiver())) + stack.push_async_callback(source_sender.aclose) + stack.enter_context(closing(source_receiver)) - forwarding_channel = await stack.enter_async_context( - aclosing(Broadcast[int](name="forwarding channel")) - ) - await stack.enter_async_context( - Pipe(source_receiver, forwarding_channel.new_sender()) + forwarding_sender, receiver = BroadcastChannel[int]( + name="forwarding channel" ) + stack.push_async_callback(forwarding_sender.aclose) + stack.enter_context(closing(receiver)) - receiver = stack.enter_context(closing(forwarding_channel.new_receiver())) + await stack.enter_async_context(Pipe(source_receiver, forwarding_sender)) - source_sender = source_channel.new_sender() await source_sender.send(10) assert await receiver.receive() == 10 diff --git a/src/frequenz/channels/experimental/_relay_sender.py b/src/frequenz/channels/experimental/_relay_sender.py index b1d223c0..0016f541 100644 --- a/src/frequenz/channels/experimental/_relay_sender.py +++ b/src/frequenz/channels/experimental/_relay_sender.py @@ -24,16 +24,13 @@ class RelaySender(Sender[SenderMessageT_contra]): Example: ```python - from frequenz.channels import Broadcast + from frequenz.channels import BroadcastChannel from frequenz.channels.experimental import RelaySender - channel1: Broadcast[int] = Broadcast(name="channel1") - channel2: Broadcast[int] = Broadcast(name="channel2") + sender1, receiver1 = BroadcastChannel[int](name="channel1") + sender2, receiver2 = BroadcastChannel[int](name="channel2") - receiver1 = channel1.new_receiver() - receiver2 = channel2.new_receiver() - - tee_sender = RelaySender(channel1.new_sender(), channel2.new_sender()) + tee_sender = RelaySender(sender1, sender2) await tee_sender.send(5) assert await receiver1.receive() == 5 diff --git a/src/frequenz/channels/experimental/_with_previous.py b/src/frequenz/channels/experimental/_with_previous.py index 9d7420f0..9710d415 100644 --- a/src/frequenz/channels/experimental/_with_previous.py +++ b/src/frequenz/channels/experimental/_with_previous.py @@ -30,44 +30,42 @@ class WithPrevious(Generic[ChannelMessageT]): Example: Receiving only messages that are different from the previous one. ```python - from frequenz.channels import Broadcast + from frequenz.channels import BroadcastChannel from frequenz.channels.experimental import WithPrevious - channel = Broadcast[int](name="example") - receiver = channel.new_receiver().filter(WithPrevious(lambda old, new: old != new)) - sender = channel.new_sender() + sender, receiver = BroadcastChannel[int](name="example") + filtered = receiver.filter(WithPrevious(lambda old, new: old != new)) # This message will be received as it is the first message. await sender.send(1) - assert await receiver.receive() == 1 + assert await filtered.receive() == 1 - # This message will be skipped as it equals to the previous one. + # This message will be skipped as it equals the previous one. await sender.send(1) - # This message will be received as it is a different from the previous one. + # This message will be received as it is different from the previous one. await sender.send(0) - assert await receiver.receive() == 0 + assert await filtered.receive() == 0 ``` Example: Receiving only messages if they are bigger than the previous one. ```python - from frequenz.channels import Broadcast + from frequenz.channels import BroadcastChannel from frequenz.channels.experimental import WithPrevious - channel = Broadcast[int](name="example") - receiver = channel.new_receiver().filter( + sender, receiver = BroadcastChannel[int](name="example") + filtered = receiver.filter( WithPrevious(lambda old, new: new > old, first_is_true=False) ) - sender = channel.new_sender() - # This message will skipped as first_is_true is False. + # This message will be skipped as first_is_true is False. await sender.send(1) # This message will be received as it is bigger than the previous one (1). await sender.send(2) - assert await receiver.receive() == 2 + assert await filtered.receive() == 2 - # This message will be skipped as it is smaller than the previous one (1). + # This message will be skipped as it is smaller than the previous one (2). await sender.send(0) # This message will be skipped as it is not bigger than the previous one (0). @@ -75,11 +73,11 @@ class WithPrevious(Generic[ChannelMessageT]): # This message will be received as it is bigger than the previous one (0). await sender.send(1) - assert await receiver.receive() == 1 + assert await filtered.receive() == 1 # This message will be received as it is bigger than the previous one (1). await sender.send(2) - assert await receiver.receive() == 2 + assert await filtered.receive() == 2 ``` """ diff --git a/src/frequenz/channels/timer.py b/src/frequenz/channels/timer.py index 3b4cf7a4..dc402832 100644 --- a/src/frequenz/channels/timer.py +++ b/src/frequenz/channels/timer.py @@ -21,7 +21,7 @@ import asyncio from datetime import datetime, timedelta - from frequenz.channels.timer import Timer + from frequenz.channels.timer import Timer, TriggerAllMissed async def main() -> None: @@ -46,13 +46,12 @@ async def main() -> None: import asyncio from datetime import timedelta - from frequenz.channels import Anycast, select, selected_from - from frequenz.channels.timer import Timer + from frequenz.channels import BroadcastChannel, select, selected_from + from frequenz.channels.timer import SkipMissedAndDrift, Timer async def main() -> None: - channel = Anycast[int](name="data-channel") - data_receiver = channel.new_receiver() + sender, data_receiver = BroadcastChannel[int](name="data-channel") timer = Timer(timedelta(seconds=1.0), SkipMissedAndDrift()) From 93e5bff1d701010750638fae22129652c80bc3a8 Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Wed, 21 Oct 2026 14:43:30 +0000 Subject: [PATCH 13/35] Close a pipe's ends when it stops on its own A `Pipe` whose receiver stopped, or whose send failed with a `SenderError`, ended but kept its sender open, so the receivers of the sender's channel could wait forever. Since a broadcast channel now stays open without receivers, receivers subscribed after a failed send waited forever too. And the pipe's receiver stayed attached to its source channel, so `has_receivers` stayed `True` there. Close the sender in both cases, and the receiver too when the send failed. `stop()` still leaves both open. After a send fails with a `SenderError`, the pipe now logs the error itself: a `NoReceiversError` as a warning, and any other error with its traceback. Its task then ends normally, so asyncio logs nothing. If closing one of the pipe's ends fails, the task ends with that error. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/experimental/_pipe.py | 45 ++++- tests/experimental/test_pipe.py | 213 +++++++++++++++++++- 2 files changed, 255 insertions(+), 3 deletions(-) diff --git a/src/frequenz/channels/experimental/_pipe.py b/src/frequenz/channels/experimental/_pipe.py index 9726c228..84aec295 100644 --- a/src/frequenz/channels/experimental/_pipe.py +++ b/src/frequenz/channels/experimental/_pipe.py @@ -11,11 +11,14 @@ from __future__ import annotations import asyncio +import logging import typing from .._generic import ChannelMessageT from .._receiver import Receiver -from .._sender import Sender +from .._sender import NoReceiversError, Sender, SenderError + +_logger = logging.getLogger(__name__) class Pipe(typing.Generic[ChannelMessageT]): @@ -25,6 +28,22 @@ class Pipe(typing.Generic[ChannelMessageT]): sender and creates a pipe between them by forwarding all the messages received by the receiver to the sender. + When its receiver stops, the pipe closes its sender and stops. If sending fails + with a [`SenderError`][frequenz.channels.SenderError], for example because the + sender's channel has no receivers, the pipe closes both its sender and its + receiver, and stops. It logs the error: a + [`NoReceiversError`][frequenz.channels.NoReceiversError] as a warning, and any + other error with its traceback. + + [`stop()`][frequenz.channels.experimental.Pipe.stop] leaves its sender and its + receiver open. So does any exception while receiving, other than the receiver + stopping, and any exception from sending that isn't a + [`SenderError`][frequenz.channels.SenderError]. Such an exception ends the pipe's + task, and a later `stop()` doesn't raise it. + + Give the pipe a clone of the sender if you still need to send after the pipe stops + on its own. + Example: ```python import asyncio @@ -101,4 +120,26 @@ async def stop(self) -> None: async def _run(self) -> None: async for value in self._receiver: - await self._sender.send(value) + try: + await self._sender.send(value) + except NoReceiversError as error: + _logger.warning( + "Pipe from [%s] to [%s] stopped: %s", + self._receiver, + self._sender, + error, + ) + except SenderError: + _logger.exception( + "Pipe from [%s] to [%s] stopped: sending failed", + self._receiver, + self._sender, + ) + else: + continue + try: + await self._sender.aclose() + finally: + self._receiver.close() + return + await self._sender.aclose() diff --git a/tests/experimental/test_pipe.py b/tests/experimental/test_pipe.py index f0158e14..098b2f75 100644 --- a/tests/experimental/test_pipe.py +++ b/tests/experimental/test_pipe.py @@ -4,10 +4,21 @@ """Tests for the Pipe class.""" import asyncio +import logging import typing from contextlib import AsyncExitStack, aclosing, closing -from frequenz.channels import Broadcast, Receiver +import pytest + +from frequenz.channels import ( + Broadcast, + BroadcastChannel, + NoReceiversError, + Receiver, + Sender, + SenderClosedError, + SenderError, +) from frequenz.channels.experimental import Pipe T = typing.TypeVar("T") @@ -25,6 +36,13 @@ async def receive_timeout(recv: Receiver[T], timeout: float = 0.1) -> T | type[T return Timeout +async def wait_stopped(pipe: Pipe[int]) -> None: + """Wait until the task of a started pipe ends.""" + task = pipe._task # pylint: disable=protected-access + assert task is not None + await asyncio.wait_for(task, timeout=1.0) + + async def test_pipe() -> None: """Test pipe.""" channel1: Broadcast[int] = Broadcast(name="channel1") @@ -79,3 +97,196 @@ async def test_pipe_with_async_exit_stack() -> None: source_sender = source_channel.new_sender() await source_sender.send(10) assert await receiver.receive() == 10 + + +async def test_pipe_closes_both_ends_when_sending_fails( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure a pipe closes its sender and receiver when it can't send.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + receiver.close() + + pipe = Pipe(source_receiver, sender) + await pipe.start() + with pytest.raises(NoReceiversError): + await sender.send(0) + + with caplog.at_level(logging.WARNING, logger="frequenz.channels.experimental"): + await source_sender.send(1) + await wait_stopped(pipe) + + assert not source_sender.has_receivers + with pytest.raises(SenderClosedError): + await sender.send(2) + assert [(r.levelno, r.exc_info) for r in caplog.records] == [ + (logging.WARNING, None) + ] + assert "stopped" in caplog.records[0].getMessage() + assert "has no receivers" in caplog.records[0].getMessage() + + +async def test_pipe_logs_send_failure(caplog: pytest.LogCaptureFixture) -> None: + """Ensure a pipe logs a failed send with its traceback.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + + sender, receiver = BroadcastChannel[int](name="forwarding") + receiver.close() + await sender.aclose() + + pipe = Pipe(source_receiver, sender) + await pipe.start() + with caplog.at_level(logging.WARNING, logger="frequenz.channels.experimental"): + await source_sender.send(1) + await wait_stopped(pipe) + + assert [r.levelno for r in caplog.records] == [logging.ERROR] + assert "stopped" in caplog.records[0].getMessage() + exc_info = caplog.records[0].exc_info + assert exc_info is not None and isinstance(exc_info[1], SenderClosedError) + assert not source_sender.has_receivers + + +async def test_pipe_closes_sender_when_receiver_stops() -> None: + """Ensure a pipe closes its sender when its receiver stops.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + pipe = Pipe(source_receiver, sender) + await pipe.start() + await source_sender.send(1) + assert await receive_timeout(receiver) == 1 + + await source_sender.aclose() + await wait_stopped(pipe) + + with pytest.raises(SenderClosedError): + await sender.send(2) + assert not receiver.has_senders + + +async def test_pipe_stop_leaves_both_ends_open() -> None: + """Ensure stopping a pipe leaves its sender and receiver open.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + pipe = Pipe(source_receiver, sender) + await pipe.start() + await asyncio.sleep(0) + await pipe.stop() + + await sender.send(1) + assert await receive_timeout(receiver) == 1 + await source_sender.send(2) + assert await receive_timeout(source_receiver) == 2 + + +async def test_pipe_leaves_both_ends_open_on_receive_exception() -> None: + """Ensure an exception while receiving leaves a pipe's ends open.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + def fail(_: int) -> int: + raise ValueError("Mapping failed") + + pipe = Pipe(source_receiver.map(fail), sender) + await pipe.start() + await source_sender.send(1) + with pytest.raises(ValueError, match="Mapping failed"): + await wait_stopped(pipe) + + assert source_sender.has_receivers + await sender.send(2) + assert await receive_timeout(receiver) == 2 + + +class ValueErrorSender(Sender[int]): + """A sender whose sends raise an error that isn't a `SenderError`.""" + + def __init__(self) -> None: + """Initialize this sender.""" + self.closed = False + + async def send(self, message: int, /) -> None: + """Fail to send.""" + raise ValueError("Sending failed") + + async def aclose(self) -> None: + """Remember that this sender was closed.""" + self.closed = True + + +async def test_pipe_leaves_both_ends_open_on_send_exception() -> None: + """Ensure an exception from sending that isn't a `SenderError` leaves both open.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender = ValueErrorSender() + + pipe = Pipe(source_receiver, sender) + await pipe.start() + await source_sender.send(1) + with pytest.raises(ValueError, match="Sending failed"): + await wait_stopped(pipe) + + assert source_sender.has_receivers + assert not sender.closed + + +class UncloseableReceiver(Receiver[int]): + """A receiver whose `close()` fails.""" + + def __init__(self, receiver: Receiver[int]) -> None: + """Wrap the given receiver.""" + self._receiver = receiver + + async def ready(self) -> bool: + """Wait until the wrapped receiver is ready.""" + return await self._receiver.ready() + + def consume(self) -> int: + """Return the wrapped receiver's message.""" + return self._receiver.consume() + + def close(self) -> None: + """Fail to close.""" + raise NotImplementedError("close() is not supported") + + +async def test_pipe_closes_sender_when_receiver_cannot_close() -> None: + """Ensure a failed send closes the sender even if the receiver can't close.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + receiver.close() + + pipe = Pipe(UncloseableReceiver(source_receiver), sender) + await pipe.start() + await source_sender.send(1) + with pytest.raises(NotImplementedError): + await wait_stopped(pipe) + + with pytest.raises(SenderClosedError): + await sender.send(2) + + +class FailingSender(Sender[int]): + """A sender whose sends and `aclose()` fail.""" + + async def send(self, message: int, /) -> None: + """Fail to send.""" + raise SenderError("Sending failed", self) + + async def aclose(self) -> None: + """Fail to close.""" + raise RuntimeError("Closing failed") + + +async def test_pipe_closes_receiver_when_sender_cannot_close() -> None: + """Ensure a failed send closes the receiver even if the sender can't close.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + + pipe = Pipe(source_receiver, FailingSender()) + await pipe.start() + await source_sender.send(1) + with pytest.raises(RuntimeError, match="Closing failed"): + await wait_stopped(pipe) + + assert not source_sender.has_receivers From d8f894aefd84168fde35c2516ccca9d7eb5b77ab Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 2 Nov 2026 13:57:46 +0000 Subject: [PATCH 14/35] Let a pipe keep sending after a failed send A failed send stops a `Pipe`, which is wrong when no receivers is a normal state of the sender's channel. With `close_pipe_on_send_error=False`, the pipe drops the message and keeps sending the messages that follow. A stopped receiver still closes the sender and stops the pipe. With that option, a missing receiver is expected, so it is logged at debug level, not as a warning for each message. Signed-off-by: Sahas Subramanian --- src/frequenz/channels/experimental/_pipe.py | 43 +++++++++++++---- tests/experimental/test_pipe.py | 53 ++++++++++++++++++++- 2 files changed, 84 insertions(+), 12 deletions(-) diff --git a/src/frequenz/channels/experimental/_pipe.py b/src/frequenz/channels/experimental/_pipe.py index 84aec295..d5c36f69 100644 --- a/src/frequenz/channels/experimental/_pipe.py +++ b/src/frequenz/channels/experimental/_pipe.py @@ -28,12 +28,17 @@ class Pipe(typing.Generic[ChannelMessageT]): sender and creates a pipe between them by forwarding all the messages received by the receiver to the sender. - When its receiver stops, the pipe closes its sender and stops. If sending fails - with a [`SenderError`][frequenz.channels.SenderError], for example because the - sender's channel has no receivers, the pipe closes both its sender and its - receiver, and stops. It logs the error: a - [`NoReceiversError`][frequenz.channels.NoReceiversError] as a warning, and any - other error with its traceback. + When its receiver stops, the pipe closes its sender and stops. + + If sending fails with a [`SenderError`][frequenz.channels.SenderError], for example + because the sender's channel has no receivers, the pipe closes both its sender and + its receiver, and stops. With `close_pipe_on_send_error=False`, it drops the + message instead, and keeps sending the messages that follow. + + The pipe logs a failed send: a + [`NoReceiversError`][frequenz.channels.NoReceiversError] as a warning, or at debug + level with `close_pipe_on_send_error=False`, and any other error with its + traceback. [`stop()`][frequenz.channels.experimental.Pipe.stop] leaves its sender and its receiver open. So does any exception while receiving, other than the receiver @@ -78,16 +83,25 @@ async def main() -> None: """ def __init__( - self, receiver: Receiver[ChannelMessageT], sender: Sender[ChannelMessageT] + self, + receiver: Receiver[ChannelMessageT], + sender: Sender[ChannelMessageT], + *, + close_pipe_on_send_error: bool = True, ) -> None: """Create a new pipe between two channels. Args: receiver: The receiver channel. sender: The sender channel. + close_pipe_on_send_error: Whether a `SenderError` from sending closes the + sender and the receiver and stops the pipe. If `False`, the pipe drops + the message and keeps sending the messages that follow, even if the + sender is closed and every send fails. """ self._sender = sender self._receiver = receiver + self._close_pipe_on_send_error = close_pipe_on_send_error self._task: asyncio.Task[None] | None = None async def __aenter__(self) -> Pipe[ChannelMessageT]: @@ -119,24 +133,33 @@ async def stop(self) -> None: pass async def _run(self) -> None: + if self._close_pipe_on_send_error: + no_receivers_level, outcome = logging.WARNING, "stopped" + else: + no_receivers_level, outcome = logging.DEBUG, "dropped a message" async for value in self._receiver: try: await self._sender.send(value) except NoReceiversError as error: - _logger.warning( - "Pipe from [%s] to [%s] stopped: %s", + _logger.log( + no_receivers_level, + "Pipe from [%s] to [%s] %s: %s", self._receiver, self._sender, + outcome, error, ) except SenderError: _logger.exception( - "Pipe from [%s] to [%s] stopped: sending failed", + "Pipe from [%s] to [%s] %s: sending failed", self._receiver, self._sender, + outcome, ) else: continue + if not self._close_pipe_on_send_error: + continue try: await self._sender.aclose() finally: diff --git a/tests/experimental/test_pipe.py b/tests/experimental/test_pipe.py index 098b2f75..732573d0 100644 --- a/tests/experimental/test_pipe.py +++ b/tests/experimental/test_pipe.py @@ -147,12 +147,17 @@ async def test_pipe_logs_send_failure(caplog: pytest.LogCaptureFixture) -> None: assert not source_sender.has_receivers -async def test_pipe_closes_sender_when_receiver_stops() -> None: +@pytest.mark.parametrize("close_pipe_on_send_error", [True, False]) +async def test_pipe_closes_sender_when_receiver_stops( + close_pipe_on_send_error: bool, +) -> None: """Ensure a pipe closes its sender when its receiver stops.""" source_sender, source_receiver = BroadcastChannel[int](name="source") sender, receiver = BroadcastChannel[int](name="forwarding") - pipe = Pipe(source_receiver, sender) + pipe = Pipe( + source_receiver, sender, close_pipe_on_send_error=close_pipe_on_send_error + ) await pipe.start() await source_sender.send(1) assert await receive_timeout(receiver) == 1 @@ -231,6 +236,50 @@ async def test_pipe_leaves_both_ends_open_on_send_exception() -> None: assert not sender.closed +async def test_pipe_keeps_sending_after_no_receivers( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure a pipe that doesn't close on send errors outlives missing receivers.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + receiver.close() + + pipe = Pipe(source_receiver, sender, close_pipe_on_send_error=False) + await pipe.start() + with caplog.at_level(logging.DEBUG, logger="frequenz.channels.experimental"): + await source_sender.send(1) + await asyncio.sleep(0) + + new_receiver = sender.subscribe() + await source_sender.send(2) + assert await receive_timeout(new_receiver) == 2 + + assert source_sender.has_receivers + assert [r.levelno for r in caplog.records] == [logging.DEBUG] + assert "dropped a message" in caplog.records[0].getMessage() + await pipe.stop() + + +async def test_pipe_keeps_sending_after_send_failure( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure a pipe that doesn't close on send errors logs each failed send.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + + pipe = Pipe(source_receiver, FailingSender(), close_pipe_on_send_error=False) + await pipe.start() + with caplog.at_level(logging.WARNING, logger="frequenz.channels.experimental"): + await source_sender.send(1) + await asyncio.sleep(0) + await source_sender.send(2) + await asyncio.sleep(0) + + assert source_sender.has_receivers + assert [r.levelno for r in caplog.records] == [logging.ERROR, logging.ERROR] + assert "dropped a message" in caplog.records[0].getMessage() + await pipe.stop() + + class UncloseableReceiver(Receiver[int]): """A receiver whose `close()` fails.""" From 42053e0f97e841afcd35169b5163ac84e0cca7ae Mon Sep 17 00:00:00 2001 From: Sahas Subramanian Date: Mon, 19 Oct 2026 15:13:09 +0000 Subject: [PATCH 15/35] Update release notes Signed-off-by: Sahas Subramanian --- RELEASE_NOTES.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index fbd4aa0a..f06eca10 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -8,12 +8,48 @@ +- A `BroadcastChannel`, or a `Broadcast` created with `auto_close=True`, no longer closes when a message is sent while it has no receivers. `send()` now drops the message and raises a `NoReceiversError`, a `SenderError` without a cause. The channel stays open: `subscribe()` keeps working, and sending works again once a new receiver is attached. + +- Code that waited for such a channel to close after a send without receivers, for example by checking for a `ChannelClosedError` cause or for `is_closed`, should catch `NoReceiversError` instead. It can then stop sending, or close all of the channel's senders to close the channel. + +- An experimental `Pipe` now closes its sender when its receiver stops. Before, it left the sender open. + +- When sending fails with a `SenderError`, for example because the sender's `BroadcastChannel` has no receivers, a `Pipe` now closes both its sender and its receiver, and logs the error: a `NoReceiversError` as a warning, and any other error with its traceback. Before, the pipe stopped but left both open. + +- `Pipe.stop()` still leaves a pipe's sender and receiver open. So does any exception while receiving, other than the receiver stopping, and any exception from sending that isn't a `SenderError`. + +- To keep a `Pipe` running after a `SenderError`, pass `close_pipe_on_send_error=False`. It then drops the message, keeps sending the messages that follow, and logs a `NoReceiversError` at debug level. + +- Give a `Pipe` a clone of its sender if you still need to send after the pipe stops on its own. + +- `BroadcastSender.clone()` now raises a `SenderClosedError` if the sender is closed, and a `SenderError` if the channel is closed, like `send()` and `subscribe()` do. Clone a sender before closing it, or catch `SenderError`. + +- `BroadcastSender.subscribe()` now uses the `limit` and `warn_on_overflow` values the `BroadcastChannel` was created with as defaults, instead of `50` and `True`. Pass `limit=50, warn_on_overflow=True` to keep the old values. + +- Call `BroadcastReceiver.close()` from the thread that runs the event loop of the channel's receivers. From another thread, tasks waiting on any receiver of the channel might not wake up. If asyncio debug mode is on and a task is waiting, `close()` also raises a `RuntimeError`, and the waiting tasks stay stuck. Use `loop.call_soon_threadsafe(receiver.close)` instead. + +- `Broadcast` is now a deprecated alias of the class behind `BroadcastChannel`. The `DeprecationWarning` is now emitted when `Broadcast` is imported or accessed from `frequenz.channels`, including by `from frequenz.channels import *`, instead of each time a channel is created, and type checkers no longer report it as deprecated. Please use `BroadcastChannel` instead. + +- This package now depends on `frequenz-core >= 1.6.0, < 2`, and needs `typing-extensions >= 4.13.0`. + ## New Features +- `NoReceiversError` is a new `SenderError`. An open sender of a `BroadcastChannel`, or of a `Broadcast` created with `auto_close=True`, raises it from `send()` while the channel is open but has no receivers. The message is dropped, but with `resend_latest=True`, new receivers still get it if it is the last message sent and it isn't `None`. + +- `BroadcastSender.has_receivers` and `BroadcastReceiver.has_senders` tell whether the other side of a broadcast channel is still there, so producers can stop producing messages that nobody would receive. A sender that was garbage-collected without being closed still counts. + ## 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. + +- Closing a broadcast receiver now wakes up tasks waiting for messages on it, instead of leaving them blocked until the next message arrived or the channel was closed. + +- Closing a broadcast receiver now drops the messages left in its buffer, so it is no longer reported as ready. So `select()` no longer reports it as stopped over and over, and no longer fails with a `SelectError` for a `filter()` on it. + +- Sending to or closing a broadcast channel no longer raises `RuntimeError: Event loop is closed` when a receiver was left waiting on an event loop that has since been closed. + +- Creating a `BroadcastChannel` no longer emits a deprecation warning telling users to use `BroadcastChannel` instead. From 64f5d463283b466dc1cb453a1d606197e0d865a3 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 13:39:41 +0000 Subject: [PATCH 16/35] Use `buffer_size` in the tests of the subscribed receiver options The deprecations pytest filter turns this library's own deprecation warnings into errors. After merging v1.x.x, `limit` is deprecated in `BroadcastChannel()` and `BroadcastSender.subscribe()`, so the test that checks how subscribed receivers inherit the channel's options failed. It now uses `buffer_size`. The tests that use `Broadcast` don't need any change: its warning doesn't match the filter, so it is only reported once. Reworking it is for the `Broadcast` deprecation task. Signed-off-by: Leandro Lucarella --- tests/test_broadcast.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index bc9939e2..ae692f59 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -758,10 +758,10 @@ async def test_broadcast_subscribe_default_options( async def test_broadcast_subscribe_inherits_receiver_options() -> None: """Ensure subscribed receivers default to the channel's receiver options.""" sender, receiver = BroadcastChannel[int]( - name="options-test", limit=2, warn_on_overflow=False + name="options-test", buffer_size=2, warn_on_overflow=False ) subscribed = sender.subscribe() - overridden = sender.subscribe(limit=3, warn_on_overflow=True) + overridden = sender.subscribe(buffer_size=3, warn_on_overflow=True) for i in range(4): await sender.send(i) From f9559f6de39f089d7ad3ca980b78a929a35d26c7 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 13:42:01 +0000 Subject: [PATCH 17/35] Make the broadcast channel options keyword-only `BroadcastChannel()` and `BroadcastSender.subscribe()` now take everything but the name by keyword: `resend_latest`, `buffer_size`, `warn_on_overflow`, and the deprecated `limit`. v2.0.0 is the place to make this change, and a positional call fails with a `TypeError` instead of silently changing its meaning: `limit` used to be the third positional argument, so it can't stay positional once `resend_latest` becomes keyword-only. `buffer_size` is the documented name in both functions. `subscribe()` keeps its `None` defaults for `buffer_size` and `warn_on_overflow`, which mean "use the channel's value", so the tests that pass them by position or rely on the positional `limit` are updated. `limit` keeps working with its deprecation warning until it is removed. Signed-off-by: Leandro Lucarella --- src/frequenz/channels/_broadcast.py | 31 +++++++++--------- tests/test_broadcast_buffer_size.py | 51 +++++++++++++---------------- 2 files changed, 37 insertions(+), 45 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index be608d1f..9b4df85c 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -418,6 +418,7 @@ def subscribe( def subscribe( self, name: str | None = None, + *, limit: int | None = None, warn_on_overflow: bool | None = None, ) -> BroadcastReceiver[_T]: ... @@ -426,10 +427,10 @@ def subscribe( def subscribe( # noqa: DOC502 (raised indirectly) self, name: str | None = None, - limit: int | None | _NOT_GIVEN = _NOT_GIVEN, - warn_on_overflow: bool | None = None, *, + limit: int | None | _NOT_GIVEN = _NOT_GIVEN, buffer_size: int | None | _NOT_GIVEN = _NOT_GIVEN, + warn_on_overflow: bool | None = None, ) -> BroadcastReceiver[_T]: """Return a new receiver attached to this sender's channel. @@ -441,15 +442,14 @@ def subscribe( # noqa: DOC502 (raised indirectly) name: A name to identify the receiver in the logs. limit: Deprecated, use `buffer_size` instead. Passing both `limit` and `buffer_size` raises a `TypeError`. - warn_on_overflow: Whether to log a warning when the receiver's buffer is - full and a message is dropped. If `None`, the `warn_on_overflow` - setting the `BroadcastChannel` was created with is used, or `True` - for a `Broadcast`. Pass it by keyword: passing it by position - requires passing the deprecated `limit` too. buffer_size: Number of messages the receiver can hold in its buffer. If `None` or not given, the buffer size the `BroadcastChannel` was created with is used, or `50` for a `Broadcast`. It must be at least 1. + warn_on_overflow: Whether to log a warning when the receiver's buffer is + full and a message is dropped. If `None`, the `warn_on_overflow` + setting the `BroadcastChannel` was created with is used, or `True` + for a `Broadcast`. Returns: A new receiver attached to this sender's channel. @@ -915,8 +915,8 @@ async def main() -> None: def __new__( cls, name: str, - resend_latest: bool = False, *, + resend_latest: bool = False, buffer_size: int = 50, warn_on_overflow: bool = True, ) -> BroadcastChannel[ChannelMessageT]: ... @@ -929,6 +929,7 @@ def __new__( def __new__( cls, name: str, + *, resend_latest: bool = False, limit: int = 50, warn_on_overflow: bool = True, @@ -937,11 +938,11 @@ def __new__( def __new__( # noqa: DOC502 (raised indirectly), pylint: disable=too-many-arguments cls, name: str, + *, resend_latest: bool = False, limit: int | _NOT_GIVEN = _NOT_GIVEN, - warn_on_overflow: bool = True, - *, buffer_size: int | _NOT_GIVEN = _NOT_GIVEN, + warn_on_overflow: bool = True, ) -> BroadcastChannel[ChannelMessageT]: """Create a new BroadcastChannel instance. @@ -963,16 +964,14 @@ def __new__( # noqa: DOC502 (raised indirectly), pylint: disable=too-many-argum channels that stream control instructions. limit: Deprecated, use `buffer_size` instead. Passing both `limit` and `buffer_size` raises a `TypeError`. - warn_on_overflow: Whether to log a warning when a receiver's buffer is full - and a message is dropped. Applies to the initial receiver and, by - default, to receivers created with - [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]. - Pass it by keyword: passing it by position requires passing the - deprecated `limit` too. buffer_size: Number of messages each receiver can hold in its buffer, for the initial receiver and, by default, for receivers created with [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe] (50 if neither this nor `limit` is given). It must be at least 1. + warn_on_overflow: Whether to log a warning when a receiver's buffer is full + and a message is dropped. Applies to the initial receiver and, by + default, to receivers created with + [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]. Returns: A new BroadcastChannel instance that can be destructured into an initial diff --git a/tests/test_broadcast_buffer_size.py b/tests/test_broadcast_buffer_size.py index d79e0972..844c306b 100644 --- a/tests/test_broadcast_buffer_size.py +++ b/tests/test_broadcast_buffer_size.py @@ -54,17 +54,34 @@ async def test_default_buffer_size() -> None: assert _drain(receiver_2) == list(range(10, 60)) -async def test_buffer_size_is_keyword_only() -> None: - """Ensure `buffer_size` can't be passed by position.""" +async def test_options_are_keyword_only() -> None: + """Ensure every option but the name has to be passed by keyword.""" sender, _receiver = BroadcastChannel[int](name="test") with pytest.raises(TypeError): # We want to test the runtime error. # pylint: disable-next=too-many-function-args - BroadcastChannel[int]("test", False, 5, True, 7) # type: ignore[call-overload] + BroadcastChannel[int]("test", False) # type: ignore[call-overload] with pytest.raises(TypeError): # We want to test the runtime error. - sender.subscribe("test", 5, True, 7) # type: ignore[call-overload] + sender.subscribe("test", 5) # type: ignore[call-overload] + with pytest.raises(TypeError): + # We want to test the runtime error. + sender.subscribe("test", None, True) # type: ignore[call-overload] + + +async def test_subscribe_none_uses_the_channel_options() -> None: + """Ensure passing `None` to `subscribe()` is the same as not passing it.""" + sender, _receiver = BroadcastChannel[int]( + name="test", buffer_size=2, warn_on_overflow=False + ) + receiver = sender.subscribe(buffer_size=None, warn_on_overflow=None) + + for message in range(5): + await sender.send(message) + + assert _drain(receiver) == [3, 4] + assert not receiver._warn_on_overflow # pylint: disable=protected-access @pytest.mark.parametrize("buffer_size", [0, -1]) @@ -116,30 +133,6 @@ async def test_limit_keyword_is_deprecated() -> None: assert _drain(receiver_2) == [2, 3, 4] -async def test_limit_position_is_deprecated() -> None: - """Ensure passing `limit` by position warns, but still sets the buffer size.""" - with pytest.deprecated_call( - match=r"^The argument limit in frequenz\.channels\.BroadcastChannel is deprecated\b" - ) as warnings_record: - sender, receiver_1 = BroadcastChannel[int]("test", False, 2, False) - assert warnings_record[0].filename == __file__ - - with pytest.deprecated_call( - match=( - r"^The argument limit in frequenz\.channels\.BroadcastSender\.subscribe " - r"is deprecated\b" - ) - ) as warnings_record: - receiver_2 = sender.subscribe("test", 3, False) - assert warnings_record[0].filename == __file__ - - for message in range(5): - await sender.send(message) - - assert _drain(receiver_1) == [3, 4] - assert _drain(receiver_2) == [2, 3, 4] - - @pytest.mark.parametrize("limit", [0, -1]) async def test_limit_must_be_positive(limit: int) -> None: """Ensure the error of a deprecated `limit` smaller than 1 names `limit`.""" @@ -162,7 +155,7 @@ async def test_buffer_size_is_not_deprecated() -> None: _ = sender.subscribe(buffer_size=2, warn_on_overflow=False) _ = sender.subscribe() _ = sender.subscribe("name") - _ = BroadcastChannel[int]("name", True) + _ = BroadcastChannel[int]("name", resend_latest=True) async def test_limit_and_buffer_size_conflict_does_not_warn() -> None: From 0f0ec60243b597bc546d9a6bbdeff56aca508658 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 13:44:42 +0000 Subject: [PATCH 18/35] Store the loop of waiting receivers instead of reading `Event._loop` `_wake_receivers()` read the private `Event._loop` attribute to tell whether `set()` failed because the loop of the waiting receivers was closed. Store the running loop when the first receiver starts waiting, next to the event, and skip `set()` when that loop is closed. No private attribute is needed and any other error from `set()`, like a call from another thread in debug mode, still raises. Signed-off-by: Leandro Lucarella --- src/frequenz/channels/_broadcast.py | 23 ++++++++++++----------- tests/test_broadcast.py | 2 ++ 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index 9b4df85c..d129204b 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -8,7 +8,7 @@ import logging import warnings import weakref -from asyncio import Event +from asyncio import AbstractEventLoop, Event, get_running_loop from collections import deque from typing import Generic, TypeVar, overload @@ -139,6 +139,9 @@ def __init__( [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close]. """ + self._wakeup_loop: AbstractEventLoop | None = None + """The loop of the receivers waiting on `_wakeup`, cleared on each wake-up.""" + self._sender_count: int = 0 """The number of senders attached to this channel.""" @@ -208,16 +211,12 @@ async def aclose(self) -> None: def _wake_receivers(self) -> None: """Wake up all receivers waiting for new messages.""" wakeup, self._wakeup = self._wakeup, Event() - try: - wakeup.set() - except RuntimeError: - # `set()` raises if the waiters' loop is closed, and they can't be woken - # anyway. All waiters of an event share one loop, so any other - # `RuntimeError`, like a call from another thread in debug mode, is - # re-raised. - loop = getattr(wakeup, "_loop", None) - if loop is None or not loop.is_closed(): - raise + loop, self._wakeup_loop = self._wakeup_loop, None + # Receivers can't be woken up once their loop is closed, and `set()` would + # raise. Any other error from `set()` is raised. + if loop is not None and loop.is_closed(): + return + wakeup.set() @deprecated("The close() method is deprecated, use aclose() instead") async def close(self) -> None: @@ -609,6 +608,8 @@ async def ready(self) -> bool: if self._channel._auto_close_enabled and self._channel._sender_count == 0: await self._channel.aclose() return False + if self._channel._wakeup_loop is None: + self._channel._wakeup_loop = get_running_loop() await self._channel._wakeup.wait() return True # pylint: enable=protected-access diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index ae692f59..09bdfe30 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -522,6 +522,8 @@ def test_broadcast_wake_after_loop_closed() -> None: _leave_waiter_on_closed_loop(receiver) asyncio.run(chan.aclose()) assert chan.is_closed + # pylint: disable-next=protected-access + assert chan._wakeup_loop is None def test_broadcast_wake_from_other_thread_in_debug_mode() -> None: From af81c74b785c54e727ad325bc950240014bab3b9 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 13:46:24 +0000 Subject: [PATCH 19/35] Rename the internal `limit` of broadcast receivers to `buffer_size` The receiver's constructor argument, the channel's default and what `repr()` shows still said `limit`, while the public arguments are `buffer_size` now. `Broadcast.new_receiver()` keeps its `limit` argument, as it belongs to the deprecated `Broadcast` class. Signed-off-by: Leandro Lucarella --- src/frequenz/channels/_broadcast.py | 22 ++++++++++++---------- tests/test_broadcast_buffer_size.py | 8 ++++++++ 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index d129204b..d16428be 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -163,7 +163,7 @@ def __init__( `auto_close` argument. """ - self._default_limit: int = 50 + self._default_buffer_size: int = 50 """The default buffer size of receivers created with `BroadcastSender.subscribe()`.""" self._default_warn_on_overflow: bool = True @@ -249,7 +249,7 @@ def new_receiver( A new receiver attached to this channel. """ recv: BroadcastReceiver[ChannelMessageT] = BroadcastReceiver( - self, name=name, limit=limit, warn_on_overflow=warn_on_overflow + self, name=name, buffer_size=limit, warn_on_overflow=warn_on_overflow ) self._receivers[hash(recv)] = weakref.ref(recv) if self.resend_latest and self._latest is not None: @@ -467,7 +467,9 @@ def subscribe( # noqa: DOC502 (raised indirectly) return self._channel.new_receiver( name=name, limit=( - self._channel._default_limit if resolved_size is None else resolved_size + self._channel._default_buffer_size + if resolved_size is None + else resolved_size ), warn_on_overflow=( self._channel._default_warn_on_overflow @@ -501,7 +503,7 @@ def __init__( /, *, name: str | None, - limit: int, + buffer_size: int, warn_on_overflow: bool, ) -> None: """Initialize this receiver. @@ -516,7 +518,7 @@ def __init__( `id(self)`-based name will be used. This is only for debugging purposes, it will be shown in the string representation of the receiver. - limit: Number of messages the receiver can hold in its buffer. + buffer_size: Number of messages the receiver can hold in its buffer. warn_on_overflow: Whether to log a warning when the receiver's buffer is full and a message is dropped. """ @@ -531,7 +533,7 @@ def __init__( self._channel: _Broadcast[_T] = channel """The broadcast channel that this receiver belongs to.""" - self._q: deque[_T] = deque(maxlen=limit) + self._q: deque[_T] = deque(maxlen=buffer_size) """The receiver's internal message queue.""" self._closed: bool = False @@ -662,10 +664,10 @@ def __str__(self) -> str: def __repr__(self) -> str: """Return a string representation of this receiver.""" - limit = self._q.maxlen - assert limit is not None + buffer_size = self._q.maxlen + assert buffer_size is not None return ( - f"{type(self).__name__}(name={self._name!r}, limit={limit!r}, " + f"{type(self).__name__}(name={self._name!r}, buffer_size={buffer_size!r}, " f"{self._channel!r}):" ) @@ -989,7 +991,7 @@ def __new__( # noqa: DOC502 (raised indirectly), pylint: disable=too-many-argum name=name, resend_latest=resend_latest, auto_close=True ) # pylint: disable=protected-access - channel._default_limit = ( + channel._default_buffer_size = ( _DEFAULT_BUFFER_SIZE if resolved_size is None else resolved_size ) channel._default_warn_on_overflow = warn_on_overflow diff --git a/tests/test_broadcast_buffer_size.py b/tests/test_broadcast_buffer_size.py index 844c306b..dcd7487e 100644 --- a/tests/test_broadcast_buffer_size.py +++ b/tests/test_broadcast_buffer_size.py @@ -84,6 +84,14 @@ async def test_subscribe_none_uses_the_channel_options() -> None: assert not receiver._warn_on_overflow # pylint: disable=protected-access +async def test_receiver_repr_shows_buffer_size() -> None: + """Ensure the receiver's `repr()` shows its buffer size as `buffer_size`.""" + _sender, receiver = BroadcastChannel[int](name="test", buffer_size=2) + + assert "buffer_size=2" in repr(receiver) + assert "limit" not in repr(receiver) + + @pytest.mark.parametrize("buffer_size", [0, -1]) async def test_buffer_size_must_be_positive(buffer_size: int) -> None: """Ensure the error of a buffer smaller than 1 names `buffer_size`.""" From f2eaab1ae236ce8e75c71cc78f6cfa4441ddf2a6 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 13:46:53 +0000 Subject: [PATCH 20/35] Update the release notes for the merge of v1.x.x The merge brought in everything that is part of the upcoming v1.13.0, and its release notes describe the changes of the v1 side. Remove them from the v2 notes, together with the entries of this branch that are part of v1.13.0 too: the `frequenz-core` and `typing-extensions` requirements, the docstring cross-references fix and the fix for the `BroadcastChannel()` warning. Keep the entries about the broadcast changes that are only in v2, update the one about the `subscribe()` defaults to say `buffer_size`, and add the entries for the options that are keyword-only now and for the new `repr()` of `BroadcastReceiver`. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 36 +++++++----------------------------- 1 file changed, 7 insertions(+), 29 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 7b1f8b31..b8f113ca 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,27 +2,15 @@ ## Summary -This will probably be the last minor release of v1. It deprecates everything that will be removed in v2.0.0. + ## Upgrading -- `frequenz-core >= 1.6.0, < 2` is now a runtime dependency. It provides the utilities this project uses to deprecate symbols following the Frequenz deprecations guide. + -- The minimum `typing-extensions` version is now 4.16.0. `frequenz-core` requires 4.13.0, and the new `buffer_size` argument needs the `sentinel` type added in 4.16.0. +- `BroadcastChannel()` and `BroadcastSender.subscribe()` now take everything but the name by keyword: `resend_latest`, `buffer_size` and `warn_on_overflow`. The deprecated `limit` is keyword-only too, so a call that passed `limit` or any other option by position fails with a `TypeError`. Pass them by keyword, as v1.13.0 recommends. -- `frequenz.channels.Anycast`, deprecated since v1.12.0, will be removed in a future version, not necessarily the next major one. Its deprecation warning now recommends copying its code into your project if you need it, or [opening an issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if you think it should stay in the library. - -- `watchfiles` versions up to 1.3 are now allowed. - -- `frequenz.channels.experimental.GroupingLatestValueCache` and its type variables `DefaultT`, `HashableT` and `ValueT_co`, and `frequenz.channels.experimental.RelaySender` are deprecated and will be removed in v2.0.0. There is no replacement in this library: copy their code into your project if you need them, or [open an issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if you think they should stay. - -- `frequenz.channels.experimental.NopReceiver` and `frequenz.channels.experimental.WithPrevious` are deprecated. Import them from `frequenz.channels` instead; they are the same objects, so only the import changes. The old names will be removed in v2.0.0. - -- The deprecation warning of `frequenz.channels.experimental.OptionalReceiver` now points at `frequenz.channels.NopReceiver`. Use the receiver itself, or a `NopReceiver` when there is none. - -- `frequenz.channels.timer.Timer` was renamed to `MonotonicTimer`, to make clear it uses the event loop's monotonic clock and to free the name `Timer` for a wall clock timer in a later version. `Timer` still works as a deprecated alias and will be removed in v2.0.0. The change is mechanical: replace `Timer` with `MonotonicTimer` in imports and uses. - -- The `limit` argument of `BroadcastChannel()` and `BroadcastSender.subscribe()` is deprecated and will be removed in v2.0.0. Use the new `buffer_size` argument instead. It does the same, but its name says what is limited: the number of messages each receiver can hold. `buffer_size` is keyword-only. A call that passes both `limit` and `buffer_size` raises a `TypeError`. Passing `warn_on_overflow` by position is deprecated too, because the new form only accepts it by keyword: pass it by keyword. v2.0.0 will also make `resend_latest` keyword-only, so pass it by keyword too. `Broadcast` and `Anycast` are not changed. +- The `repr()` of a `BroadcastReceiver` shows its `buffer_size` instead of `limit`. - A `BroadcastChannel`, or a `Broadcast` created with `auto_close=True`, no longer closes when a message is sent while it has no receivers. `send()` now drops the message and raises a `NoReceiversError`, a `SenderError` without a cause. The channel stays open: `subscribe()` keeps working, and sending works again once a new receiver is attached. @@ -40,17 +28,15 @@ This will probably be the last minor release of v1. It deprecates everything tha - `BroadcastSender.clone()` now raises a `SenderClosedError` if the sender is closed, and a `SenderError` if the channel is closed, like `send()` and `subscribe()` do. Clone a sender before closing it, or catch `SenderError`. -- `BroadcastSender.subscribe()` now uses the `limit` and `warn_on_overflow` values the `BroadcastChannel` was created with as defaults, instead of `50` and `True`. Pass `limit=50, warn_on_overflow=True` to keep the old values. +- `BroadcastSender.subscribe()` now uses the `buffer_size` and `warn_on_overflow` values the `BroadcastChannel` was created with as defaults, instead of `50` and `True`. Pass `buffer_size=50, warn_on_overflow=True` to keep the old values. - Call `BroadcastReceiver.close()` from the thread that runs the event loop of the channel's receivers. From another thread, tasks waiting on any receiver of the channel might not wake up. If asyncio debug mode is on and a task is waiting, `close()` also raises a `RuntimeError`, and the waiting tasks stay stuck. Use `loop.call_soon_threadsafe(receiver.close)` instead. - `Broadcast` is now a deprecated alias of the class behind `BroadcastChannel`. The `DeprecationWarning` is now emitted when `Broadcast` is imported or accessed from `frequenz.channels`, including by `from frequenz.channels import *`, instead of each time a channel is created, and type checkers no longer report it as deprecated. Please use `BroadcastChannel` instead. -- This package now depends on `frequenz-core >= 1.6.0, < 2`, and needs `typing-extensions >= 4.13.0`. - ## New Features -- `NopReceiver` and `WithPrevious` are now stable, and available from `frequenz.channels`. + - `NoReceiversError` is a new `SenderError`. An open sender of a `BroadcastChannel`, or of a `Broadcast` created with `auto_close=True`, raises it from `send()` while the channel is open but has no receivers. The message is dropped, but with `resend_latest=True`, new receivers still get it if it is the last message sent and it isn't `None`. @@ -58,18 +44,10 @@ This will probably be the last minor release of v1. It deprecates everything tha ## Bug Fixes -- `BroadcastChannel()` no longer emits the deprecation warning of `Broadcast`, which it uses internally. You were getting a warning about a class you never used. - -- `OneshotReceiver.close()` no longer raises `NotImplementedError`. It now works like in the other receivers: a message sent before closing can still be received, and after that receiving raises `ReceiverStoppedError`. The sender can still send, but its message is discarded. - -- Creating a broadcast receiver with a `buffer_size` (or `limit`) of 0 now raises a `ValueError`, from `BroadcastChannel()` and `BroadcastSender.subscribe()`. Before, the first message sent to it raised an `IndexError`, after other receivers might have got the message already. - -- 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. + - Closing a broadcast receiver now wakes up tasks waiting for messages on it, instead of leaving them blocked until the next message arrived or the channel was closed. - Closing a broadcast receiver now drops the messages left in its buffer, so it is no longer reported as ready. So `select()` no longer reports it as stopped over and over, and no longer fails with a `SelectError` for a `filter()` on it. - Sending to or closing a broadcast channel no longer raises `RuntimeError: Event loop is closed` when a receiver was left waiting on an event loop that has since been closed. - -- Creating a `BroadcastChannel` no longer emits a deprecation warning telling users to use `BroadcastChannel` instead. From 68a0f0f2245bc9146dcf113ab7e5862354bac369 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:16:19 +0000 Subject: [PATCH 21/35] Remove the deprecated `limit` argument of broadcast channels `BroadcastChannel()` and `BroadcastSender.subscribe()` deprecated `limit` in favor of `buffer_size` in v1.13.0, and said it would go in v2.0.0. Remove the `@deprecated` overloads, the `_NOT_GIVEN` marker that told "not passed" from 50, and the `limit` branches of the buffer size check. The check is now a plain validation of `buffer_size`, still raising a `ValueError` below 1. `Broadcast.new_receiver()` keeps its `limit` argument, as `Broadcast` stays in v2. Remove the tests for the deprecation too. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 4 +- src/frequenz/channels/_broadcast.py | 140 ++++------------------------ tests/test_broadcast_buffer_size.py | 88 +---------------- 3 files changed, 25 insertions(+), 207 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index b8f113ca..5db53e6f 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -8,7 +8,9 @@ -- `BroadcastChannel()` and `BroadcastSender.subscribe()` now take everything but the name by keyword: `resend_latest`, `buffer_size` and `warn_on_overflow`. The deprecated `limit` is keyword-only too, so a call that passed `limit` or any other option by position fails with a `TypeError`. Pass them by keyword, as v1.13.0 recommends. +- `BroadcastChannel()` and `BroadcastSender.subscribe()` now take everything but the name by keyword: `resend_latest`, `buffer_size` and `warn_on_overflow`. A call that passed any of them by position fails with a `TypeError`. Pass them by keyword, as v1.13.0 recommends. + +- The deprecated `limit` argument of `BroadcastChannel()` and `BroadcastSender.subscribe()` is removed. Use `buffer_size` instead, which exists since v1.13.0, so you can migrate before upgrading. `Broadcast.new_receiver()` still takes `limit`. - The `repr()` of a `BroadcastReceiver` shows its `buffer_size` instead of `limit`. diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index d16428be..cd768d8e 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -6,13 +6,12 @@ from __future__ import annotations import logging -import warnings import weakref from asyncio import AbstractEventLoop, Event, get_running_loop from collections import deque -from typing import Generic, TypeVar, overload +from typing import Generic, TypeVar -from typing_extensions import deprecated, override, sentinel +from typing_extensions import deprecated, override from ._exceptions import ChannelClosedError from ._generic import ChannelMessageT @@ -26,60 +25,27 @@ _logger = logging.getLogger(__name__) -_NOT_GIVEN = sentinel("_NOT_GIVEN") -"""A marker for the arguments of the broadcast channel that were not passed.""" - _DEFAULT_BUFFER_SIZE = 50 """The default buffer size of broadcast receivers.""" -_LIMIT_DEPRECATION = ( - "The argument limit in {function} is deprecated and will be removed in " - "v2.0.0. Use buffer_size instead." -) -"""The warning of the deprecated `limit` argument, for a function's full name.""" - -def _resolve_buffer_size( - function: str, - *, - limit: int | None | _NOT_GIVEN, - buffer_size: int | None | _NOT_GIVEN, -) -> int | None: - """Return the buffer size to use out of `limit` and `buffer_size`. +def _check_buffer_size(buffer_size: int) -> int: + """Return the buffer size, after checking that it is valid. Args: - function: The name of the function that got the arguments, for the error - messages. - limit: The `limit` argument the function got, or `_NOT_GIVEN`. - buffer_size: The `buffer_size` argument the function got, or `_NOT_GIVEN`. + buffer_size: The buffer size to check. Returns: - The buffer size to use, or `None` if it should be the channel's default. + The buffer size. Raises: - TypeError: If both `limit` and `buffer_size` were given. ValueError: If the buffer size is smaller than 1. """ - buffer_size_given = buffer_size is not _NOT_GIVEN and buffer_size is not None - if limit is not _NOT_GIVEN and buffer_size_given: - raise TypeError( - f"{function}() got both `limit` and `buffer_size`, " - "pass only `buffer_size`" - ) - if limit is not _NOT_GIVEN: - warnings.warn( - _LIMIT_DEPRECATION.format(function=f"frequenz.channels.{function}"), - category=DeprecationWarning, - # The caller of the function that got the argument - stacklevel=3, + if buffer_size < 1: + raise ValueError( + f"The receiver's buffer_size must be at least 1, not {buffer_size}" ) - argument = "limit" if limit is not _NOT_GIVEN else "buffer_size" - size = limit if limit is not _NOT_GIVEN else buffer_size - if size is _NOT_GIVEN or size is None: - return None - if size < 1: - raise ValueError(f"The receiver's {argument} must be at least 1, not {size}") - return size + return buffer_size class _Broadcast( # pylint: disable=too-many-instance-attributes @@ -163,7 +129,7 @@ def __init__( `auto_close` argument. """ - self._default_buffer_size: int = 50 + self._default_buffer_size: int = _DEFAULT_BUFFER_SIZE """The default buffer size of receivers created with `BroadcastSender.subscribe()`.""" self._default_warn_on_overflow: bool = True @@ -400,47 +366,18 @@ def clone(self) -> BroadcastSender[_T]: # noqa: DOC502 (raised indirectly) self._check_open() return BroadcastSender(self._channel) - @overload - def subscribe( - self, - name: str | None = None, - *, - buffer_size: int | None = None, - warn_on_overflow: bool | None = None, - ) -> BroadcastReceiver[_T]: ... - - @overload - @deprecated( - "The argument limit in frequenz.channels.BroadcastSender.subscribe is " - "deprecated and will be removed in v2.0.0. Use buffer_size instead." - ) - def subscribe( - self, - name: str | None = None, - *, - limit: int | None = None, - warn_on_overflow: bool | None = None, - ) -> BroadcastReceiver[_T]: ... - @override def subscribe( # noqa: DOC502 (raised indirectly) self, name: str | None = None, *, - limit: int | None | _NOT_GIVEN = _NOT_GIVEN, - buffer_size: int | None | _NOT_GIVEN = _NOT_GIVEN, + buffer_size: int | None = None, warn_on_overflow: bool | None = None, ) -> BroadcastReceiver[_T]: """Return a new receiver attached to this sender's channel. - Deprecated: - The `limit` argument is deprecated since v1.13.0. Use `buffer_size` - instead. - Args: name: A name to identify the receiver in the logs. - limit: Deprecated, use `buffer_size` instead. Passing both `limit` - and `buffer_size` raises a `TypeError`. buffer_size: Number of messages the receiver can hold in its buffer. If `None` or not given, the buffer size the `BroadcastChannel` was created with is used, or `50` for a `Broadcast`. It must be at @@ -456,20 +393,16 @@ def subscribe( # noqa: DOC502 (raised indirectly) Raises: SenderError: If the underlying channel is closed. SenderClosedError: If this sender is closed. - TypeError: If both `limit` and `buffer_size` are given. ValueError: If the buffer size is smaller than 1. """ self._check_open() - resolved_size = _resolve_buffer_size( - "BroadcastSender.subscribe", limit=limit, buffer_size=buffer_size - ) # pylint: disable=protected-access return self._channel.new_receiver( name=name, limit=( self._channel._default_buffer_size - if resolved_size is None - else resolved_size + if buffer_size is None + else _check_buffer_size(buffer_size) ), warn_on_overflow=( self._channel._default_warn_on_overflow @@ -914,45 +847,16 @@ async def main() -> None: ``` """ - @overload - def __new__( + def __new__( # noqa: DOC502 (raised indirectly) cls, name: str, *, resend_latest: bool = False, buffer_size: int = 50, warn_on_overflow: bool = True, - ) -> BroadcastChannel[ChannelMessageT]: ... - - @overload - @deprecated( - "The argument limit in frequenz.channels.BroadcastChannel is deprecated and " - "will be removed in v2.0.0. Use buffer_size instead." - ) - def __new__( - cls, - name: str, - *, - resend_latest: bool = False, - limit: int = 50, - warn_on_overflow: bool = True, - ) -> BroadcastChannel[ChannelMessageT]: ... - - def __new__( # noqa: DOC502 (raised indirectly), pylint: disable=too-many-arguments - cls, - name: str, - *, - resend_latest: bool = False, - limit: int | _NOT_GIVEN = _NOT_GIVEN, - buffer_size: int | _NOT_GIVEN = _NOT_GIVEN, - warn_on_overflow: bool = True, ) -> BroadcastChannel[ChannelMessageT]: """Create a new BroadcastChannel instance. - Deprecated: - The `limit` argument is deprecated since v1.13.0. Use `buffer_size` - instead. - Args: name: The name of the channel. This is for logging purposes, and it will be shown in the string representation of the channel. @@ -965,12 +869,10 @@ def __new__( # noqa: DOC502 (raised indirectly), pylint: disable=too-many-argum to wait for the next message on the channel to arrive. It is safe to be set in data/reporting channels, but is not recommended for use in channels that stream control instructions. - limit: Deprecated, use `buffer_size` instead. Passing both `limit` - and `buffer_size` raises a `TypeError`. buffer_size: Number of messages each receiver can hold in its buffer, for the initial receiver and, by default, for receivers created with - [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe] - (50 if neither this nor `limit` is given). It must be at least 1. + [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]. + It must be at least 1. warn_on_overflow: Whether to log a warning when a receiver's buffer is full and a message is dropped. Applies to the initial receiver and, by default, to receivers created with @@ -981,19 +883,13 @@ def __new__( # noqa: DOC502 (raised indirectly), pylint: disable=too-many-argum sender and receiver. Raises: - TypeError: If both `limit` and `buffer_size` are given. ValueError: If the buffer size is smaller than 1. """ - resolved_size = _resolve_buffer_size( - "BroadcastChannel", limit=limit, buffer_size=buffer_size - ) channel = _Broadcast[ChannelMessageT]( name=name, resend_latest=resend_latest, auto_close=True ) # pylint: disable=protected-access - channel._default_buffer_size = ( - _DEFAULT_BUFFER_SIZE if resolved_size is None else resolved_size - ) + channel._default_buffer_size = _check_buffer_size(buffer_size) channel._default_warn_on_overflow = warn_on_overflow # pylint: enable=protected-access sender = channel.new_sender() diff --git a/tests/test_broadcast_buffer_size.py b/tests/test_broadcast_buffer_size.py index dcd7487e..65e7f9b0 100644 --- a/tests/test_broadcast_buffer_size.py +++ b/tests/test_broadcast_buffer_size.py @@ -3,12 +3,10 @@ """Tests for the `buffer_size` argument of broadcast channels.""" -from typing import get_overloads - import pytest from frequenz.core.warnings import asserting_no_deprecations -from frequenz.channels import BroadcastChannel, BroadcastReceiver, BroadcastSender +from frequenz.channels import BroadcastChannel, BroadcastReceiver def _drain(receiver: BroadcastReceiver[int]) -> list[int]: @@ -61,13 +59,13 @@ async def test_options_are_keyword_only() -> None: with pytest.raises(TypeError): # We want to test the runtime error. # pylint: disable-next=too-many-function-args - BroadcastChannel[int]("test", False) # type: ignore[call-overload] + BroadcastChannel[int]("test", False) # type: ignore[call-arg] with pytest.raises(TypeError): # We want to test the runtime error. - sender.subscribe("test", 5) # type: ignore[call-overload] + sender.subscribe("test", 5) # type: ignore[call-arg] with pytest.raises(TypeError): # We want to test the runtime error. - sender.subscribe("test", None, True) # type: ignore[call-overload] + sender.subscribe("test", None, True) # type: ignore[call-arg] async def test_subscribe_none_uses_the_channel_options() -> None: @@ -103,57 +101,6 @@ async def test_buffer_size_must_be_positive(buffer_size: int) -> None: _ = sender.subscribe(buffer_size=buffer_size) -async def test_limit_and_buffer_size_conflict() -> None: - """Ensure passing both `limit` and `buffer_size` raises a `TypeError`.""" - with pytest.raises(TypeError, match="both `limit` and `buffer_size`"): - # We want to test the runtime error. - BroadcastChannel[int](name="test", limit=2, buffer_size=2) # type: ignore[call-overload] - - sender, _receiver = BroadcastChannel[int](name="test") - with pytest.raises(TypeError, match="both `limit` and `buffer_size`"): - # We want to test the runtime error. - sender.subscribe(limit=2, buffer_size=2) # type: ignore[call-overload] - - -async def test_limit_keyword_is_deprecated() -> None: - """Ensure passing `limit` by keyword warns, but still sets the buffer size.""" - with pytest.deprecated_call( - match=r"^The argument limit in frequenz\.channels\.BroadcastChannel is deprecated\b" - ) as warnings_record: - sender, receiver_1 = BroadcastChannel[int]( - name="test", limit=2, warn_on_overflow=False - ) - assert warnings_record[0].filename == __file__ - - with pytest.deprecated_call( - match=( - r"^The argument limit in frequenz\.channels\.BroadcastSender\.subscribe " - r"is deprecated\b" - ) - ) as warnings_record: - receiver_2 = sender.subscribe(limit=3, warn_on_overflow=False) - assert warnings_record[0].filename == __file__ - - for message in range(5): - await sender.send(message) - - assert _drain(receiver_1) == [3, 4] - assert _drain(receiver_2) == [2, 3, 4] - - -@pytest.mark.parametrize("limit", [0, -1]) -async def test_limit_must_be_positive(limit: int) -> None: - """Ensure the error of a deprecated `limit` smaller than 1 names `limit`.""" - with pytest.deprecated_call(): - with pytest.raises(ValueError, match="limit must be at least 1"): - _ = BroadcastChannel[int](name="test", limit=limit) - - sender, _receiver = BroadcastChannel[int](name="test") - with pytest.deprecated_call(): - with pytest.raises(ValueError, match="limit must be at least 1"): - _ = sender.subscribe(limit=limit) - - async def test_buffer_size_is_not_deprecated() -> None: """Ensure the new argument and the defaults don't warn.""" with asserting_no_deprecations(): @@ -164,30 +111,3 @@ async def test_buffer_size_is_not_deprecated() -> None: _ = sender.subscribe() _ = sender.subscribe("name") _ = BroadcastChannel[int]("name", resend_latest=True) - - -async def test_limit_and_buffer_size_conflict_does_not_warn() -> None: - """Ensure the error for passing both arguments comes without a warning.""" - with asserting_no_deprecations(): - with pytest.raises(TypeError): - # We want to test the runtime error. - BroadcastChannel[int]( # type: ignore[call-overload] - name="test", limit=2, buffer_size=2 - ) - - -def test_deprecated_overloads_have_the_runtime_message() -> None: - """Ensure `mypy` and the runtime report the same message for `limit`.""" - for function, name in ( - (BroadcastChannel.__new__, "BroadcastChannel"), - (BroadcastSender.subscribe, "BroadcastSender.subscribe"), - ): - deprecated_overloads = [ - message - for overload in get_overloads(function) - if (message := getattr(overload, "__deprecated__", None)) is not None - ] - assert deprecated_overloads == [ - f"The argument limit in frequenz.channels.{name} is deprecated and will " - "be removed in v2.0.0. Use buffer_size instead." - ] From 126cd22969a112161dc13e5c57789aa387fe8037 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:16:36 +0000 Subject: [PATCH 22/35] Remove the deprecated `Timer` alias `Timer` was a deprecated alias of `MonotonicTimer` since v1.13.0. Removing it in v2.0.0, and only adding a wall clock `Timer` in a later version, means no code silently changes clock when upgrading. Remove the alias, its `deprecated_aliases()` lookup and the tests of the warning. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 2 ++ src/frequenz/channels/timer.py | 28 ---------------------------- tests/test_timer.py | 26 -------------------------- 3 files changed, 2 insertions(+), 54 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 5db53e6f..41af530c 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -12,6 +12,8 @@ - The deprecated `limit` argument of `BroadcastChannel()` and `BroadcastSender.subscribe()` is removed. Use `buffer_size` instead, which exists since v1.13.0, so you can migrate before upgrading. `Broadcast.new_receiver()` still takes `limit`. +- The deprecated `frequenz.channels.timer.Timer` is removed. Use `MonotonicTimer` instead, which exists since v1.13.0, so you can migrate before upgrading. The name `Timer` will be used for a wall clock timer in a later version. + - The `repr()` of a `BroadcastReceiver` shows its `buffer_size` instead of `limit`. - A `BroadcastChannel`, or a `Broadcast` created with `auto_close=True`, no longer closes when a message is sent while it has no receivers. `send()` now drops the message and raises a `NoReceiversError`, a `SenderError` without a cause. The channel stays open: `subscribe()` keeps working, and sending works again once a new receiver is attached. diff --git a/src/frequenz/channels/timer.py b/src/frequenz/channels/timer.py index 6c57cccb..0a55ce8a 100644 --- a/src/frequenz/channels/timer.py +++ b/src/frequenz/channels/timer.py @@ -100,9 +100,7 @@ async def main() -> None: import abc import asyncio from datetime import timedelta -from typing import TYPE_CHECKING, TypeAlias -from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases from typing_extensions import override from ._receiver import Receiver, ReceiverStoppedError @@ -112,7 +110,6 @@ async def main() -> None: "MonotonicTimer", "SkipMissedAndDrift", "SkipMissedAndResync", - "Timer", "TriggerAllMissed", ] @@ -813,28 +810,3 @@ def __repr__(self) -> str: f"{type(self).__name__}<{self.interval=}, {self.missed_tick_policy=}, " f"{self.loop=}, {self.is_running=}>" ) - - -if TYPE_CHECKING: - Timer: TypeAlias = MonotonicTimer - """A receiver that sends a message regularly. - - Deprecated: - Deprecated since v1.13.0. Use - [`MonotonicTimer`][frequenz.channels.timer.MonotonicTimer] instead. - - The name `Timer` will be used for a wall clock timer in a later version. - """ -else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias( - "Timer", - new_name="MonotonicTimer", - since="v1.13.0", - message=( - "{old} is deprecated. Use {new} instead. The name Timer will be " - "used for a wall clock timer in a later version." - ), - ), - ) diff --git a/tests/test_timer.py b/tests/test_timer.py index 197e0a80..b618f861 100644 --- a/tests/test_timer.py +++ b/tests/test_timer.py @@ -767,34 +767,8 @@ async def receive_timer3() -> None: assert timer_trigger_order == [2, 1, 3] -def test_timer_is_deprecated_alias() -> None: - """Test that `Timer` warns and is the same class as `MonotonicTimer`.""" - with pytest.deprecated_call( - match=r"^frequenz\.channels\.timer\.Timer is deprecated\. " - r"Use frequenz\.channels\.timer\.MonotonicTimer instead\. " - r"The name Timer will be used for a wall clock timer in a later version\.$" - ): - from frequenz.channels.timer import ( # pylint: disable=import-outside-toplevel - Timer, - ) - - assert Timer is MonotonicTimer - - async def test_monotonic_timer_is_not_deprecated() -> None: """Test that creating a `MonotonicTimer` doesn't emit deprecation warnings.""" with asserting_no_deprecations(): timer = MonotonicTimer(timedelta(seconds=1.0), TriggerAllMissed()) timer.stop() - - -def test_timer_star_import_warns() -> None: - """Test that `from frequenz.channels.timer import *` still provides `Timer`.""" - namespace: dict[str, Any] = {} - with pytest.deprecated_call( - match=r"^frequenz\.channels\.timer\.Timer is deprecated\. " - ): - # pylint: disable-next=exec-used - exec("from frequenz.channels.timer import *", namespace) - assert namespace["Timer"] is MonotonicTimer - assert namespace["MonotonicTimer"] is MonotonicTimer From baadabab9eddb8ae58882a30690d5f42039548a0 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:17:12 +0000 Subject: [PATCH 23/35] Remove the deprecated symbols of `experimental` v1.13.0 deprecated these and said they would go in v2.0.0: * `GroupingLatestValueCache` and its type variables `DefaultT`, `HashableT` and `ValueT_co`. * `RelaySender`. * `OptionalReceiver`. * The `experimental` names of `WithPrevious` and `NopReceiver`, which moved to the top-level `frequenz.channels`. Remove their modules, the aliases and the tests that checked the warnings. `Pipe` stays in `experimental`. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 8 + .../channels/experimental/__init__.py | 111 ------ .../_grouping_latest_value_cache.py | 331 ------------------ .../experimental/_optional_receiver.py | 94 ----- .../channels/experimental/_relay_sender.py | 74 ---- tests/experimental/test_deprecated_aliases.py | 30 -- tests/experimental/test_optional_receiver.py | 80 ----- tests/experimental/test_relay_sender.py | 49 --- ...grouping_latest_value_cache_integration.py | 156 --------- 9 files changed, 8 insertions(+), 925 deletions(-) delete mode 100644 src/frequenz/channels/experimental/_grouping_latest_value_cache.py delete mode 100644 src/frequenz/channels/experimental/_optional_receiver.py delete mode 100644 src/frequenz/channels/experimental/_relay_sender.py delete mode 100644 tests/experimental/test_deprecated_aliases.py delete mode 100644 tests/experimental/test_optional_receiver.py delete mode 100644 tests/experimental/test_relay_sender.py delete mode 100644 tests/test_grouping_latest_value_cache_integration.py diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 41af530c..41c897ba 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -14,6 +14,14 @@ - The deprecated `frequenz.channels.timer.Timer` is removed. Use `MonotonicTimer` instead, which exists since v1.13.0, so you can migrate before upgrading. The name `Timer` will be used for a wall clock timer in a later version. +- `frequenz.channels.experimental.GroupingLatestValueCache` is removed, together with its type variables `DefaultT`, `HashableT` and `ValueT_co`. Copy its code into your project if you still need it, or open an issue if you think it should stay in the library. + +- `frequenz.channels.experimental.RelaySender` is removed. Copy its code into your project if you still need it, or open an issue if you think it should stay in the library. + +- `frequenz.channels.experimental.OptionalReceiver` is removed. Use the receiver itself, or `frequenz.channels.NopReceiver` when there is none. `NopReceiver` exists since v1.13.0, so you can migrate before upgrading. + +- `WithPrevious` and `NopReceiver` are no longer available from `frequenz.channels.experimental`. Import them from `frequenz.channels`, where they are available since v1.13.0, so you can migrate before upgrading. + - The `repr()` of a `BroadcastReceiver` shows its `buffer_size` instead of `limit`. - A `BroadcastChannel`, or a `Broadcast` created with `auto_close=True`, no longer closes when a message is sent while it has no receivers. `send()` now drops the message and raises a `NoReceiversError`, a `SenderError` without a cause. The channel stays open: `subscribe()` keeps working, and sending works again once a new receiver is attached. diff --git a/src/frequenz/channels/experimental/__init__.py b/src/frequenz/channels/experimental/__init__.py index 210cd02f..479ea50f 100644 --- a/src/frequenz/channels/experimental/__init__.py +++ b/src/frequenz/channels/experimental/__init__.py @@ -10,119 +10,8 @@ guidelines](https://github.com/frequenz-floss/docs/blob/v0.x.x/python/experimental-packages.md). """ -from typing import TYPE_CHECKING, TypeAlias, TypeVar - -from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases - -from ._grouping_latest_value_cache import GroupingLatestValueCache -from ._optional_receiver import OptionalReceiver from ._pipe import Pipe -from ._relay_sender import RelaySender __all__ = [ - "DefaultT", - "GroupingLatestValueCache", - "HashableT", - "NopReceiver", - "OptionalReceiver", "Pipe", - "RelaySender", - "ValueT_co", - "WithPrevious", ] - -# The type variables of `GroupingLatestValueCache` use a workaround: `@deprecated` -# only works on classes and functions, so it can't mark them. `deprecated_aliases()` -# is meant for symbols that moved or were renamed, but its `__getattr__` is the only -# way to warn when they are reached from here, so their aliases point at the private -# module that defines them, which is not a move. That's also why they need a custom -# `message` and hand-written notices: the generated ones would point at the private -# module. See https://github.com/frequenz-floss/frequenz-core-python/issues/222. -if TYPE_CHECKING: - from collections.abc import Hashable - - from .._nop_receiver import NopReceiver as _NopReceiver - from .._with_previous import WithPrevious as _WithPrevious - - NopReceiver: TypeAlias = _NopReceiver - """A place-holder receiver that will never receive a message. - - Deprecated: - Deprecated since v1.13.0. Use - [`frequenz.channels.NopReceiver`][frequenz.channels.NopReceiver] instead. - """ - - WithPrevious: TypeAlias = _WithPrevious - """A composable predicate to build predicates that can also use the previous message. - - Deprecated: - Deprecated since v1.13.0. Use - [`frequenz.channels.WithPrevious`][frequenz.channels.WithPrevious] instead. - """ - - # Type variables can't be aliased, so type checkers get new ones, equivalent to - # the ones in `_grouping_latest_value_cache`. - DefaultT = TypeVar("DefaultT") - """Type variable for the default value returned by - [`GroupingLatestValueCache.get`][frequenz.channels.experimental.GroupingLatestValueCache.get]. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0 together with - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - """ - - HashableT = TypeVar("HashableT", bound=Hashable) - """Type variable for the keys used to group values in the - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0 together with - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - """ - - ValueT_co = TypeVar("ValueT_co", covariant=True) - """Covariant type variable for the values cached by the - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0 together with - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - """ -else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias( - "NopReceiver", - new_module="frequenz.channels", - since="v1.13.0", - ), - DeprecatedAlias( - "WithPrevious", - new_module="frequenz.channels", - since="v1.13.0", - ), - DeprecatedAlias( - "DefaultT", - new_module="frequenz.channels.experimental._grouping_latest_value_cache", - since="v1.13.0", - message="{old} is deprecated and will be removed in v2.0.0, together with " - "frequenz.channels.experimental.GroupingLatestValueCache. Copy it into " - "your project if you need it.", - ), - DeprecatedAlias( - "HashableT", - new_module="frequenz.channels.experimental._grouping_latest_value_cache", - since="v1.13.0", - message="{old} is deprecated and will be removed in v2.0.0, together with " - "frequenz.channels.experimental.GroupingLatestValueCache. Copy it into " - "your project if you need it.", - ), - DeprecatedAlias( - "ValueT_co", - new_module="frequenz.channels.experimental._grouping_latest_value_cache", - since="v1.13.0", - message="{old} is deprecated and will be removed in v2.0.0, together with " - "frequenz.channels.experimental.GroupingLatestValueCache. Copy it into " - "your project if you need it.", - ), - ) diff --git a/src/frequenz/channels/experimental/_grouping_latest_value_cache.py b/src/frequenz/channels/experimental/_grouping_latest_value_cache.py deleted file mode 100644 index 71ff41d5..00000000 --- a/src/frequenz/channels/experimental/_grouping_latest_value_cache.py +++ /dev/null @@ -1,331 +0,0 @@ -# License: MIT -# Copyright © 2025 Frequenz Energy-as-a-Service GmbH - -"""Caches the latest values in a receiver, grouped by key.""" - -import asyncio -from collections.abc import ( - Callable, - Hashable, - ItemsView, - Iterator, - KeysView, - Mapping, - ValuesView, -) -from typing import TypeVar, overload - -from typing_extensions import deprecated, override - -from .._receiver import Receiver - -ValueT_co = TypeVar("ValueT_co", covariant=True) -"""Covariant type variable for the values cached by the -[`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. -""" - -DefaultT = TypeVar("DefaultT") -"""Type variable for the default value returned by -[`GroupingLatestValueCache.get`][frequenz.channels.experimental.GroupingLatestValueCache.get]. -""" - -HashableT = TypeVar("HashableT", bound=Hashable) -"""Type variable for the keys used to group values in the -[`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. -""" - - -class _NotSpecified: - """A sentinel value to indicate that no default value was provided.""" - - def __repr__(self) -> str: - """Return a string representation of this sentinel.""" - return "<_NotSpecified>" - - -@deprecated( - "frequenz.channels.experimental.GroupingLatestValueCache is deprecated and will " - "be removed in v2.0.0. Copy its code into your project if you need it, or open " - "an issue at https://github.com/frequenz-floss/frequenz-channels-python/issues " - "if you think it should stay in frequenz-channels." -) -class GroupingLatestValueCache(Mapping[HashableT, ValueT_co]): - """A cache that stores the latest value in a receiver, grouped by key. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0. Copy its code into - your project if you need it, or [open an - issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if - you think it should stay in this library. - - It provides a way to look up on demand, the latest value in a stream for any key, as - long as there has been at least one value received for that key. - - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache] - takes a [`Receiver`][frequenz.channels.Receiver] and a `key` function as arguments - and stores the latest value received by that receiver for each key separately. - - The - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache] - implements the [`Mapping`][collections.abc.Mapping] interface, so it can be used - like a dictionary. Additionally other methods from - [`MutableMapping`][collections.abc.MutableMapping] are implemented, but only methods - removing items from the cache are allowed, such as - [`pop()`][frequenz.channels.experimental.GroupingLatestValueCache.pop], - [`popitem()`][frequenz.channels.experimental.GroupingLatestValueCache.popitem], - [`clear()`][frequenz.channels.experimental.GroupingLatestValueCache.clear], and - [`__delitem__()`][frequenz.channels.experimental.GroupingLatestValueCache.__delitem__]. - Other update methods are not provided because the user should not update the cache - values directly. - - Example: - ```python - import asyncio - - from frequenz.channels import BroadcastChannel - from frequenz.channels.experimental import GroupingLatestValueCache - - sender, receiver = BroadcastChannel[tuple[int, str]](name="lvc_test") - - cache = GroupingLatestValueCache(receiver, key=lambda x: x[0]) - - assert cache.get(6) is None - assert 6 not in cache - - await sender.send((6, "twenty-six")) - await asyncio.sleep(0) # Let the cache process the message - - assert 6 in cache - assert cache.get(6) == (6, "twenty-six") - - del cache[6] - - assert cache.get(6) is None - assert 6 not in cache - - await cache.stop() - ``` - """ - - def __init__( - self, - receiver: Receiver[ValueT_co], - *, - key: Callable[[ValueT_co], HashableT], - unique_id: str | None = None, - ) -> None: - """Create a new cache. - - Args: - receiver: The receiver to cache values from. - key: A function that takes a value and returns a key to group the values - by. - unique_id: A string to help uniquely identify this instance. If not - provided, a unique identifier will be generated from the object's - [`id()`][id]. It is used mostly for debugging purposes. - """ - self._receiver: Receiver[ValueT_co] = receiver - self._key: Callable[[ValueT_co], HashableT] = key - self._unique_id: str = hex(id(self)) if unique_id is None else unique_id - self._latest_value_by_key: dict[HashableT, ValueT_co] = {} - self._task: asyncio.Task[None] = asyncio.create_task( - self._run(), name=f"LatestValueCache«{self._unique_id}»" - ) - - @property - def unique_id(self) -> str: - """The unique identifier of this instance.""" - return self._unique_id - - @override - def keys(self) -> KeysView[HashableT]: - """Return the keys for which values have been received.""" - return self._latest_value_by_key.keys() - - @override - def items(self) -> ItemsView[HashableT, ValueT_co]: - """Return an iterator over the key-value pairs of the latest values received.""" - return self._latest_value_by_key.items() - - @override - def values(self) -> ValuesView[ValueT_co]: - """Return an iterator over the latest values received.""" - return self._latest_value_by_key.values() - - @overload - def get(self, key: HashableT, default: None = None) -> ValueT_co | None: - """Return the latest value that has been received for a specific key.""" - - # MyPy passes this overload as a valid signature, but pylint does not like it. - @overload - def get( # pylint: disable=signature-differs - self, key: HashableT, default: DefaultT - ) -> ValueT_co | DefaultT: - """Return the latest value that has been received for a specific key.""" - - @override - def get( - self, key: HashableT, default: DefaultT | None = None - ) -> ValueT_co | DefaultT | None: - """Return the latest value that has been received. - - Args: - key: The key to retrieve the latest value for. - default: The default value to return if no value has been received yet for - the specified key. If not provided, it defaults to `None`. - - Returns: - The latest value that has been received. - """ - return self._latest_value_by_key.get(key, default) - - @override - def __iter__(self) -> Iterator[HashableT]: - """Return an iterator over the keys for which values have been received.""" - return iter(self._latest_value_by_key) - - @override - def __len__(self) -> int: - """Return the number of keys for which values have been received.""" - return len(self._latest_value_by_key) - - @override - def __getitem__(self, key: HashableT) -> ValueT_co: # noqa: DOC502 - """Return the latest value that has been received for a specific key. - - Args: - key: The key to retrieve the latest value for. - - Returns: - The latest value that has been received for that key. - - Raises: - KeyError: If no value has been received for `key` yet. - """ - return self._latest_value_by_key[key] - - @override - def __contains__(self, key: object, /) -> bool: - """Return whether a value has been received for a specific key. - - Args: - key: The key to check for. - - Returns: - `True` if a value has been received for that key, `False` otherwise. - """ - return key in self._latest_value_by_key - - @override - def __eq__(self, other: object, /) -> bool: - """Return whether this cache is equal to another object. - - Two caches are considered equal if they have the same keys and values. - - Args: - other: The object to compare with. - - Returns: - `True` if the caches are equal, `False` otherwise. - """ - match other: - case GroupingLatestValueCache(): - return self._latest_value_by_key == other._latest_value_by_key - case Mapping(): - return self._latest_value_by_key == other - case _: - return NotImplemented - - @override - def __ne__(self, value: object, /) -> bool: - """Return whether this cache is not equal to another object. - - Args: - value: The object to compare with. - - Returns: - `True` if the caches are not equal, `False` otherwise. - """ - return not self.__eq__(value) - - def __delitem__(self, key: HashableT) -> None: # noqa: DOC502 - """Clear the latest value for a specific key. - - Args: - key: The key for which to clear the latest value. - - Raises: - KeyError: If no value has been received for `key` yet. - """ - del self._latest_value_by_key[key] - - @overload - def pop(self, key: HashableT, /) -> ValueT_co | None: - """Remove the latest value for a specific key and return it.""" - - @overload - def pop(self, key: HashableT, /, default: DefaultT) -> ValueT_co | DefaultT: - """Remove the latest value for a specific key and return it.""" - - def pop( # noqa: DOC502 - self, key: HashableT, /, default: DefaultT | _NotSpecified = _NotSpecified() - ) -> ValueT_co | DefaultT | None: - """Remove the latest value for a specific key and return it. - - If no value has been received yet for that key, it returns the default value or - raises a [`KeyError`][] if no default value is provided. - - Args: - key: The key for which to remove the latest value. - default: The default value to return if no value has been received yet for - the specified key. - - Returns: - The latest value that has been received for that key, or the default value if - no value has been received yet and a default value is provided. - - Raises: - KeyError: If no value has been received for `key` and no `default` was provided. - """ - if isinstance(default, _NotSpecified): - return self._latest_value_by_key.pop(key) - return self._latest_value_by_key.pop(key, default) - - def popitem(self) -> tuple[HashableT, ValueT_co]: # noqa: DOC502 - """Remove and return a (key, value) pair from the cache. - - Pairs are returned in LIFO (last-in, first-out) order. - - Returns: - A tuple containing the key and the latest value that has been received for - that key. - - Raises: - KeyError: If the cache is empty. - """ - return self._latest_value_by_key.popitem() - - def clear(self) -> None: - """Clear all entries from the cache.""" - self._latest_value_by_key.clear() - - async def stop(self) -> None: - """Stop the cache.""" - if not self._task.done(): - self._task.cancel() - try: - await self._task - except asyncio.CancelledError: - pass - - def __repr__(self) -> str: - """Return a string representation of this cache.""" - return ( - f"" - ) - - async def _run(self) -> None: - async for value in self._receiver: - key = self._key(value) - self._latest_value_by_key[key] = value diff --git a/src/frequenz/channels/experimental/_optional_receiver.py b/src/frequenz/channels/experimental/_optional_receiver.py deleted file mode 100644 index c878b641..00000000 --- a/src/frequenz/channels/experimental/_optional_receiver.py +++ /dev/null @@ -1,94 +0,0 @@ -# License: MIT -# Copyright © 2025 Frequenz Energy-as-a-Service GmbH - -"""A receiver that will wait indefinitely if there is no underlying receiver. - -The [`OptionalReceiver`][frequenz.channels.experimental.OptionalReceiver] is useful when -the underlying receiver is not set initially. Instead of making `if-else` branches to -check if the receiver is set, you can use this receiver to wait indefinitely if it is -not set. -""" - -import asyncio - -from typing_extensions import deprecated, override - -from frequenz.channels import Receiver, ReceiverError, ReceiverMessageT_co - - -@deprecated( - "frequenz.channels.experimental.OptionalReceiver is deprecated. " - "Use the receiver itself, or frequenz.channels.NopReceiver when there is none." -) -class OptionalReceiver(Receiver[ReceiverMessageT_co]): - """A receiver that will wait indefinitely if there is no underlying receiver. - - Deprecated: - Deprecated since v1.9.0. Use the receiver itself, or a - [`frequenz.channels.NopReceiver`][frequenz.channels.NopReceiver] when there - is none. - - This receiver is useful when the underlying receiver is not set initially. - Instead of making `if-else` branches to check if the receiver is set, you can use - this receiver to wait indefinitely if it is not set. - """ - - def __init__(self, receiver: Receiver[ReceiverMessageT_co] | None): - """Initialize this instance. - - Args: - receiver: The underlying receiver, or `None` if there is no receiver. - """ - self._receiver: Receiver[ReceiverMessageT_co] | None = receiver - - @override - async def ready(self) -> bool: - """Wait until the receiver is ready with a message or an error. - - Once a call to - [`ready()`][frequenz.channels.experimental.OptionalReceiver.ready] has finished, - the message should be read with a call to - [`consume()`][frequenz.channels.experimental.OptionalReceiver.consume] - ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The - receiver will remain ready (this method will return immediately) until it is - consumed. - - Returns: - Whether the receiver is still active. - """ - if self._receiver is not None: - return await self._receiver.ready() - - # If there's no receiver, wait forever - await asyncio.Event().wait() - return False - - @override - def consume(self) -> ReceiverMessageT_co: # noqa: DOC503 (raised indirectly) - """Return the latest message once the receiver is ready. - - [`ready()`][frequenz.channels.experimental.OptionalReceiver.ready] must be - called before each call to - [`consume()`][frequenz.channels.experimental.OptionalReceiver.consume]. - - Returns: - The next message received. - - Raises: - ReceiverStoppedError: If the receiver stopped producing messages. - ReceiverError: If there is some problem with the underlying receiver. - """ - if self._receiver is None: - raise ReceiverError( - "`consume()` must be preceded by a call to `ready()`", self - ) - return self._receiver.consume() - - def is_set(self) -> bool: - """Return whether the receiver is set.""" - return self._receiver is not None - - def close(self) -> None: - """Stop the receiver.""" - if self._receiver is not None: - self._receiver.close() diff --git a/src/frequenz/channels/experimental/_relay_sender.py b/src/frequenz/channels/experimental/_relay_sender.py deleted file mode 100644 index 3ac6402d..00000000 --- a/src/frequenz/channels/experimental/_relay_sender.py +++ /dev/null @@ -1,74 +0,0 @@ -# License: MIT -# Copyright © 2024 Frequenz Energy-as-a-Service GmbH - -"""A Sender for sending messages to multiple senders. - -The [`RelaySender`][frequenz.channels.experimental.RelaySender] class takes multiple -senders and forwards all the messages sent to it, to the senders it was created with. -""" - -import asyncio - -from typing_extensions import deprecated, override - -from .._generic import SenderMessageT_contra -from .._sender import Sender - - -@deprecated( - "frequenz.channels.experimental.RelaySender is deprecated and will be removed in " - "v2.0.0. Copy its code into your project if you need it, or open an issue at " - "https://github.com/frequenz-floss/frequenz-channels-python/issues if you think " - "it should stay in frequenz-channels." -) -class RelaySender(Sender[SenderMessageT_contra]): - """A [`Sender`][frequenz.channels.Sender] for sending messages to multiple senders. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0. Copy its code into - your project if you need it, or [open an - issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if - you think it should stay in this library. - - The [`RelaySender`][frequenz.channels.experimental.RelaySender] class takes multiple - senders and forwards all the messages sent to it, to the senders it was created - with. - - Example: - ```python - from frequenz.channels import BroadcastChannel - from frequenz.channels.experimental import RelaySender - - sender1, receiver1 = BroadcastChannel[int](name="channel1") - sender2, receiver2 = BroadcastChannel[int](name="channel2") - - tee_sender = RelaySender(sender1, sender2) - - await tee_sender.send(5) - assert await receiver1.receive() == 5 - assert await receiver2.receive() == 5 - ``` - """ - - def __init__(self, *senders: Sender[SenderMessageT_contra]) -> None: - """Create a new [`RelaySender`][frequenz.channels.experimental.RelaySender]. - - Args: - *senders: The senders to send messages to. - """ - self._senders = senders - - @override - async def send(self, message: SenderMessageT_contra, /) -> None: - """Send a message. - - Args: - message: The message to be sent. - """ - for sender in self._senders: - await sender.send(message) - - @override - async def aclose(self) -> None: - """Close this sender.""" - await asyncio.gather(*(sender.aclose() for sender in self._senders)) diff --git a/tests/experimental/test_deprecated_aliases.py b/tests/experimental/test_deprecated_aliases.py deleted file mode 100644 index 077e51cd..00000000 --- a/tests/experimental/test_deprecated_aliases.py +++ /dev/null @@ -1,30 +0,0 @@ -# License: MIT -# Copyright © 2026 Frequenz Energy-as-a-Service GmbH - -"""Tests for the deprecated aliases of symbols promoted out of `experimental`.""" - -import pytest -from frequenz.core.warnings import asserting_no_deprecations - -import frequenz.channels -from frequenz.channels import experimental - -_PROMOTED = ["NopReceiver", "WithPrevious"] - - -@pytest.mark.parametrize("name", _PROMOTED) -def test_old_name_warns(name: str) -> None: - """Ensure the old `experimental` name warns and is the very same object.""" - with pytest.deprecated_call( - match=rf"^frequenz\.channels\.experimental\.{name} is deprecated\. " - rf"Use frequenz\.channels\.{name} instead\.$" - ): - old = getattr(experimental, name) - assert old is getattr(frequenz.channels, name) - - -@pytest.mark.parametrize("name", _PROMOTED) -def test_new_name_does_not_warn(name: str) -> None: - """Ensure the new top-level name doesn't warn.""" - with asserting_no_deprecations(): - _ = getattr(frequenz.channels, name) diff --git a/tests/experimental/test_optional_receiver.py b/tests/experimental/test_optional_receiver.py deleted file mode 100644 index 82f1e967..00000000 --- a/tests/experimental/test_optional_receiver.py +++ /dev/null @@ -1,80 +0,0 @@ -# License: MIT -# Copyright © 2025 Frequenz Energy-as-a-Service GmbH - -"""Tests for the OptionalReceiver class.""" - -import asyncio -from contextlib import aclosing, closing - -import pytest - -from frequenz.channels import Broadcast, ReceiverError, ReceiverStoppedError -from frequenz.channels.experimental import OptionalReceiver - -# Every test here uses the deprecated OptionalReceiver on purpose. -pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") - - -async def test_receiver_with_none_does_not_end() -> None: - """Test that the receiver with None does not end.""" - with closing(OptionalReceiver[int](None)) as receiver: - assert not receiver.is_set() - - with pytest.raises(TimeoutError): - await asyncio.wait_for(receiver.ready(), timeout=0.3) - - -async def test_receiver_with_none_raises_error_when_consuming() -> None: - """Test that the receiver with None raises an error when consuming.""" - with closing(OptionalReceiver[int](None)) as receiver: - assert not receiver.is_set() - - with pytest.raises(ReceiverError): - receiver.consume() - - -async def test_receiver_with_underlying_receiver_forwards_messages() -> None: - """Test that the receiver forwards messages.""" - async with aclosing(Broadcast[int](name="test")) as channel: - with closing(OptionalReceiver[int](channel.new_receiver())) as receiver: - assert receiver.is_set() - - sender = channel.new_sender() - - await sender.send(5) - value = await asyncio.wait_for(receiver.receive(), timeout=0.1) - assert value == 5 - - await sender.send(100) - value = await asyncio.wait_for(receiver.receive(), timeout=0.1) - assert value == 100 - - -async def test_receiver_ends_when_underlying_receiver_ends() -> None: - """Test that the receiver ends when the underlying receiver ends.""" - async with aclosing(Broadcast[int](name="test")) as channel: - with ( - closing(channel.new_receiver()) as receiver, - closing(OptionalReceiver[int](receiver)) as optional_receiver, - ): - assert optional_receiver.is_set() - - receiver.close() - # First check if ready method returns False - is_active = await optional_receiver.ready() - assert is_active is False - - # Then check if `receive` method raises ReceiverStoppedError - with pytest.raises(ReceiverStoppedError): - await optional_receiver.receive() - - -def test_deprecation_warning() -> None: - """Test that the receiver warns it is deprecated.""" - with pytest.deprecated_call( - match=r"^frequenz\.channels\.experimental\.OptionalReceiver is deprecated\. " - r"Use the receiver itself, or frequenz\.channels\.NopReceiver when there is " - r"none\.$" - ): - receiver = OptionalReceiver[int](None) - receiver.close() diff --git a/tests/experimental/test_relay_sender.py b/tests/experimental/test_relay_sender.py deleted file mode 100644 index fa008966..00000000 --- a/tests/experimental/test_relay_sender.py +++ /dev/null @@ -1,49 +0,0 @@ -# License: MIT -# Copyright © 2024 Frequenz Energy-as-a-Service GmbH - -"""Tests for the RelaySender class.""" - -import pytest - -from frequenz.channels import Broadcast -from frequenz.channels.experimental import RelaySender - - -async def test_tee_sender() -> None: - """Test tee sender.""" - channel1: Broadcast[int] = Broadcast(name="channel1") - channel2: Broadcast[int] = Broadcast(name="channel2") - channel3: Broadcast[int] = Broadcast(name="channel3") - - with pytest.deprecated_call(): - sender = RelaySender( - channel1.new_sender(), channel2.new_sender(), channel3.new_sender() - ) - receiver1 = channel1.new_receiver() - receiver2 = channel2.new_receiver() - receiver3 = channel3.new_receiver() - - await sender.send(42) - assert ( - await receiver1.receive() - == await receiver2.receive() - == await receiver3.receive() - == 42 - ) - - await sender.send(-2) - assert ( - await receiver1.receive() - == await receiver2.receive() - == await receiver3.receive() - == -2 - ) - - -def test_relay_sender_is_deprecated() -> None: - """Test that creating a RelaySender warns.""" - with pytest.deprecated_call( - match=r"^frequenz\.channels\.experimental\.RelaySender is deprecated and " - r"will be removed in v2\.0\.0\. Copy its code into your project" - ): - RelaySender() diff --git a/tests/test_grouping_latest_value_cache_integration.py b/tests/test_grouping_latest_value_cache_integration.py deleted file mode 100644 index 10d44fa3..00000000 --- a/tests/test_grouping_latest_value_cache_integration.py +++ /dev/null @@ -1,156 +0,0 @@ -# License: MIT -# Copyright © 2024 Frequenz Energy-as-a-Service GmbH - -"""Tests for the LatestValueCache implementation.""" - -import asyncio -import importlib - -import pytest - -from frequenz.channels import Broadcast -from frequenz.channels.experimental import GroupingLatestValueCache - - -@pytest.mark.integration -async def test_latest_value_cache_key() -> None: # pylint: disable=too-many-statements - """Ensure LatestValueCache works with keys.""" - channel = Broadcast[tuple[int, str]](name="lvc_test") - - with pytest.deprecated_call(): - cache: GroupingLatestValueCache[int, tuple[int, str]] = ( - GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x[0]) - ) - sender = channel.new_sender() - - assert 5 not in cache - assert cache.get(0) is None - - assert cache.keys() == set() - - await sender.send((5, "a")) - await sender.send((6, "b")) - await sender.send((5, "c")) - await asyncio.sleep(0) - - assert 5 in cache - assert 6 in cache - assert 7 not in cache - - assert cache.get(5) == (5, "c") - assert cache[5] == (5, "c") - assert cache.get(6) == (6, "b") - assert cache[6] == (6, "b") - - assert cache.keys() == {5, 6} - - assert cache.get(7, default=(7, "default")) == (7, "default") - - await sender.send((12, "d")) - await asyncio.sleep(0) - - assert cache.get(12) == (12, "d") - assert cache.get(12) == (12, "d") - assert cache.get(5) == (5, "c") - assert cache.get(6) == (6, "b") - - await sender.send((6, "e")) - await sender.send((6, "f")) - await sender.send((6, "g")) - await asyncio.sleep(0) - - assert cache.get(6) == (6, "g") - - assert cache.keys() == {5, 6, 12} - - del cache[5] - assert 5 not in cache - assert 6 in cache - - assert cache.get(5) is None - assert cache.keys() == {6, 12} - - assert cache.pop(6) == (6, "g") - assert 6 not in cache - assert cache.keys() == {12} - - assert cache.pop(8, default=True) is True - with pytest.raises(KeyError): - cache.pop(8) - - assert cache.popitem() == (12, (12, "d")) - assert 12 not in cache - assert not cache - - await sender.send((1, "h")) - await sender.send((2, "i")) - await asyncio.sleep(0) - - expected = {1: (1, "h"), 2: (2, "i")} - assert cache.keys() == expected.keys() - assert list(cache.values()) == list(expected.values()) - assert list(cache.items()) == list(expected.items()) - assert cache == expected - assert list(cache) == list(expected) - - cache.clear() - assert not cache - assert cache.keys() == set() - - await cache.stop() - - -@pytest.mark.integration -async def test_equality() -> None: - """Test that two caches with the same content are equal.""" - channel = Broadcast[tuple[int, str]](name="lvc_test") - - with pytest.deprecated_call(): - cache1: GroupingLatestValueCache[int, tuple[int, str]] = ( - GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x[0]) - ) - with pytest.deprecated_call(): - cache2: GroupingLatestValueCache[int, tuple[int, str]] = ( - GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x[0]) - ) - - sender = channel.new_sender() - await sender.send((1, "one")) - await sender.send((2, "two")) - await asyncio.sleep(0) - - assert cache1 == cache2 - - del cache1[1] - assert cache1 != cache2 - - await cache1.stop() - await cache2.stop() - - -@pytest.mark.integration -async def test_grouping_latest_value_cache_is_deprecated() -> None: - """Test that creating a GroupingLatestValueCache warns.""" - channel = Broadcast[int](name="lvc_test") - with pytest.deprecated_call( - match=r"^frequenz\.channels\.experimental\.GroupingLatestValueCache is " - r"deprecated and will be removed in v2\.0\.0\. Copy its code into your project" - ): - cache = GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x) - await cache.stop() - - -@pytest.mark.parametrize("name", ["DefaultT", "HashableT", "ValueT_co"]) -def test_type_variables_are_deprecated(name: str) -> None: - """Test that reaching the type variables of GroupingLatestValueCache warns.""" - experimental = importlib.import_module("frequenz.channels.experimental") - private = importlib.import_module( - "frequenz.channels.experimental._grouping_latest_value_cache" - ) - with pytest.deprecated_call( - match=rf"^frequenz\.channels\.experimental\.{name} is deprecated and will be " - r"removed in v2\.0\.0, together with " - r"frequenz\.channels\.experimental\.GroupingLatestValueCache\." - ): - value = getattr(experimental, name) - assert value is getattr(private, name) From 0672ebefa5f2b7bcaabfd72787b3b6f2fde1a95e Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:18:04 +0000 Subject: [PATCH 24/35] Remove the deprecated `close()` of channels `Anycast` and `Broadcast` kept an `async close()` method, a deprecated alias of `aclose()`. It was deprecated since v1.8.0, when `aclose()` was added to follow what `contextlib.aclosing()` expects. Remove it from both. `Anycast` stays in v2, deprecated, and the class behind `Broadcast` stays too, so the removal doesn't depend on those. `BroadcastChannel` never had the method, and the receivers' `close()` is not affected. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 2 ++ src/frequenz/channels/_anycast.py | 8 -------- src/frequenz/channels/_broadcast.py | 10 +--------- 3 files changed, 3 insertions(+), 17 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 41c897ba..fdd41345 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -22,6 +22,8 @@ - `WithPrevious` and `NopReceiver` are no longer available from `frequenz.channels.experimental`. Import them from `frequenz.channels`, where they are available since v1.13.0, so you can migrate before upgrading. +- The deprecated `async close()` method of `Anycast` and `Broadcast` is removed. Use `aclose()` instead, which exists since v1.8.0, so you can migrate before upgrading. It also works with `contextlib.aclosing()`. + - The `repr()` of a `BroadcastReceiver` shows its `buffer_size` instead of `limit`. - A `BroadcastChannel`, or a `Broadcast` created with `auto_close=True`, no longer closes when a message is sent while it has no receivers. `send()` now drops the message and raises a `NoReceiversError`, a `SenderError` without a cause. The channel stays open: `subscribe()` keeps working, and sending works again once a new receiver is attached. diff --git a/src/frequenz/channels/_anycast.py b/src/frequenz/channels/_anycast.py index cc6ebdbf..5140eb7f 100644 --- a/src/frequenz/channels/_anycast.py +++ b/src/frequenz/channels/_anycast.py @@ -295,14 +295,6 @@ async def aclose(self) -> None: async with self._recv_cv: self._recv_cv.notify_all() - @deprecated("The close() method is deprecated, use aclose() instead") - async def close(self) -> None: - """Close the channel. - - Deprecated alias for [`.aclose()`][frequenz.channels.Anycast.aclose]. - """ - return await self.aclose() - def new_sender(self) -> Sender[ChannelMessageT]: """Return a new sender attached to this channel.""" return _Sender(self) diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index cd768d8e..485aec04 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -11,7 +11,7 @@ from collections import deque from typing import Generic, TypeVar -from typing_extensions import deprecated, override +from typing_extensions import override from ._exceptions import ChannelClosedError from ._generic import ChannelMessageT @@ -184,14 +184,6 @@ def _wake_receivers(self) -> None: return wakeup.set() - @deprecated("The close() method is deprecated, use aclose() instead") - async def close(self) -> None: - """Close the channel. - - Deprecated alias for [`.aclose()`][frequenz.channels.Broadcast.aclose]. - """ - return await self.aclose() - def new_sender(self) -> BroadcastSender[ChannelMessageT]: """Return a new sender attached to this channel.""" return BroadcastSender(self) From b059ac2433468e777e30265d4353006beea8acdc Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:36:27 +0000 Subject: [PATCH 25/35] Make `Receiver.close()` abstract `Receiver.close()` was added in v1.6.0 without being abstract, because that would have been a breaking change, so the base class raised a `NotImplementedError`. A receiver without its own `close()` only failed when something called it, for example a `map()` or `filter()` wrapper. Making it abstract in v2.0.0 reports the missing method when the class is instantiated, and `mypy` reports it too. Every receiver in this library implements `close()` already, and so do the subclasses we found in our own projects. An implementation works on v1 too, so projects can still support both major versions. Add a test that a subclass without `close()` can't be instantiated, and document the requirement in the release notes. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 2 ++ src/frequenz/channels/_receiver.py | 2 +- tests/test_receiver.py | 26 ++++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 tests/test_receiver.py diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index b8f113ca..6de635d0 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -34,6 +34,8 @@ - `Broadcast` is now a deprecated alias of the class behind `BroadcastChannel`. The `DeprecationWarning` is now emitted when `Broadcast` is imported or accessed from `frequenz.channels`, including by `from frequenz.channels import *`, instead of each time a channel is created, and type checkers no longer report it as deprecated. Please use `BroadcastChannel` instead. +- `Receiver.close()` is now an abstract method, so a custom `Receiver` subclass that doesn't implement it can't be instantiated anymore. Before, calling it raised a `NotImplementedError`. All the receivers in this library implement it already. Add a `close()` method to your own receivers; the same implementation works on v1, so your code can support both major versions. + ## New Features diff --git a/src/frequenz/channels/_receiver.py b/src/frequenz/channels/_receiver.py index b7c53025..be1c6b8a 100644 --- a/src/frequenz/channels/_receiver.py +++ b/src/frequenz/channels/_receiver.py @@ -260,6 +260,7 @@ def consume(self) -> ReceiverMessageT_co: ReceiverError: If there is some problem with the receiver. """ + @abstractmethod def close(self) -> None: """Close the receiver. @@ -269,7 +270,6 @@ def close(self) -> None: or once the messages already in the receiver's buffer are received, depending on the receiver. """ - raise NotImplementedError("close() must be implemented by subclasses") def __aiter__(self) -> Self: """Get an async iterator over the received messages. diff --git a/tests/test_receiver.py b/tests/test_receiver.py new file mode 100644 index 00000000..42b869cc --- /dev/null +++ b/tests/test_receiver.py @@ -0,0 +1,26 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for the Receiver base class.""" + +import pytest + +from frequenz.channels import Receiver + + +def test_receiver_without_close_cannot_be_instantiated() -> None: + """Test that a receiver subclass has to implement `close()`.""" + + class NoCloseReceiver(Receiver[int]): + """A receiver that doesn't implement `close()`.""" + + async def ready(self) -> bool: + """Return that the receiver is not ready.""" + return False + + def consume(self) -> int: + """Return a message.""" + return 0 + + with pytest.raises(TypeError, match=r"abstract method.*close"): + NoCloseReceiver() # type: ignore[abstract] # pylint: disable=abstract-class-instantiated From 1774ed67d07146d30ee1f008dc772320070bc0cd Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:15:35 +0000 Subject: [PATCH 26/35] Add `TransientSenderError` `SenderError` doesn't tell a caller whether the sender can still be used. Code that keeps sending, like the new `Pipe` planned for v2, has to tell the errors that only drop one message apart from the ones that make the sender or its channel unusable. `TransientSenderError` is a new `SenderError` for the first kind: the message wasn't sent, but the sender and its channel can still be used. It is a base class only; nothing raises it yet. The next commit makes `NoReceiversError` derive from it. The class and its docstring are the ones PR 591 added to v1, which was reverted before v1.13.0. Signed-off-by: Leandro Lucarella --- src/frequenz/channels/__init__.py | 5 +++++ src/frequenz/channels/_sender.py | 30 ++++++++++++++++++++++++++++++ tests/test_sender.py | 22 ++++++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 tests/test_sender.py diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index 0c714646..fd887759 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -74,6 +74,9 @@ * [`SenderError`][frequenz.channels.SenderError]: Base class for all errors related to senders. +* [`TransientSenderError`][frequenz.channels.TransientSenderError]: Base class for + sender errors after which the sender can still be used. + * [`NoReceiversError`][frequenz.channels.NoReceiversError]: Error raised when sending a message to a [`BroadcastChannel`][frequenz.channels.BroadcastChannel] that has no receivers. @@ -138,6 +141,7 @@ SenderClosedError, SenderError, SubscribableSender, + TransientSenderError, ) from ._with_previous import WithPrevious @@ -188,6 +192,7 @@ "SenderMessageT_co", "SenderMessageT_contra", "SubscribableSender", + "TransientSenderError", "UnhandledSelectedError", "WithPrevious", "merge", diff --git a/src/frequenz/channels/_sender.py b/src/frequenz/channels/_sender.py index d190ed37..ad211764 100644 --- a/src/frequenz/channels/_sender.py +++ b/src/frequenz/channels/_sender.py @@ -47,6 +47,10 @@ except SenderError as error: print(f"Error sending message: {error}") ``` + +Most errors mean that the sender, or its channel, can't be used anymore. A +[`TransientSenderError`][frequenz.channels.TransientSenderError] means that only +this message wasn't sent, and sending again later can work. """ from __future__ import annotations @@ -114,6 +118,32 @@ def __init__(self, sender: Sender[SenderMessageT_co]): super().__init__("Sender is closed", sender) +class TransientSenderError(SenderError[SenderMessageT_co]): + """An error indicating that a message wasn't sent, but sending can still work. + + The sender and its channel can still be used, so sending again later can + succeed. Any other [`SenderError`][frequenz.channels.SenderError] means the + sender or its channel can't be used anymore, so catch this error first to tell + them apart: + + Example: + ```python + from frequenz.channels import Sender, SenderError, TransientSenderError + + + async def try_send(sender: Sender[int], message: int) -> bool: + try: + await sender.send(message) + except TransientSenderError: + return False # Not sent this time, but the sender still works. + except SenderError: + await sender.aclose() # The sender can't be used anymore. + raise + return True + ``` + """ + + class NoReceiversError(SenderError[SenderMessageT_co]): """An error indicating that a message was sent to a channel without receivers. diff --git a/tests/test_sender.py b/tests/test_sender.py new file mode 100644 index 00000000..8c39e64c --- /dev/null +++ b/tests/test_sender.py @@ -0,0 +1,22 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for the sender errors.""" + +from frequenz.channels import ( + BroadcastChannel, + SenderClosedError, + SenderError, + TransientSenderError, +) + + +def test_transient_sender_error() -> None: + """Ensure transient errors are sender errors, and closed senders aren't transient.""" + sender, _receiver = BroadcastChannel[int](name="test") + error = TransientSenderError("Not sent", sender) + + assert isinstance(error, SenderError) + assert error.sender is sender + assert str(error) == "Not sent" + assert not issubclass(SenderClosedError, TransientSenderError) From b0820309d5aa252670cdf0a4fdd046e25b484510 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:16:34 +0000 Subject: [PATCH 27/35] Rename `NoReceiversError` to `SenderHasNoReceiversError` `NoReceiversError` says what is missing, but not who is affected, and reads like an error of the channel. The new name says that the sender has nobody to send to, like the other sender errors. The error was added by PR 565 for v2.0.0 and never released, so the old name has no alias or deprecation. The error is now a `TransientSenderError`. Sending to a channel without receivers drops the message, but the sender and the channel stay open, and sending works again once a receiver subscribes, which is what that class is for. It is still a `SenderError`, so code that catches `SenderError` keeps working. Everything that mentioned the old name uses the new one: the code, the docstrings and user guide pages built from them, the handling and the docs of the experimental `Pipe`, and the tests. The `Pipe`'s log messages don't contain the class name, so they stay the same. Signed-off-by: Leandro Lucarella --- src/frequenz/channels/__init__.py | 12 ++++++------ src/frequenz/channels/_broadcast.py | 20 ++++++++++---------- src/frequenz/channels/_sender.py | 9 ++++++--- src/frequenz/channels/experimental/_pipe.py | 10 +++++----- tests/experimental/test_pipe.py | 4 ++-- tests/test_broadcast.py | 14 ++++++++------ tests/test_sender.py | 12 ++++++++++++ 7 files changed, 49 insertions(+), 32 deletions(-) diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index fd887759..73d2bd23 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -28,7 +28,7 @@ messages from multiple senders to multiple receivers. Each message sent through any of the senders is received by all of the receivers. The channel closes itself when all its senders are closed. A `send()` while it has no receivers raises a - [`NoReceiversError`][frequenz.channels.NoReceiversError]. + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]. * [`OneshotChannel`][frequenz.channels.OneshotChannel]: A channel that can send a single message from one sender to one receiver. @@ -77,9 +77,9 @@ * [`TransientSenderError`][frequenz.channels.TransientSenderError]: Base class for sender errors after which the sender can still be used. -* [`NoReceiversError`][frequenz.channels.NoReceiversError]: Error raised when sending - a message to a [`BroadcastChannel`][frequenz.channels.BroadcastChannel] that has no - receivers. +* [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]: Error + raised when sending a message to a + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] that has no receivers. * [`ReceiverError`][frequenz.channels.ReceiverError]: Base class for all errors related to receivers. @@ -136,10 +136,10 @@ from ._sender import ( CloneableSender, CloneableSubscribableSender, - NoReceiversError, Sender, SenderClosedError, SenderError, + SenderHasNoReceiversError, SubscribableSender, TransientSenderError, ) @@ -175,7 +175,7 @@ "LatestValueCache", "MappedMessageT_co", "Merger", - "NoReceiversError", + "SenderHasNoReceiversError", "NopReceiver", "OneshotChannel", "OneshotReceiver", diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index 485aec04..f5ab70d7 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -18,9 +18,9 @@ from ._receiver import Receiver, ReceiverStoppedError from ._sender import ( CloneableSubscribableSender, - NoReceiversError, SenderClosedError, SenderError, + SenderHasNoReceiversError, ) _logger = logging.getLogger(__name__) @@ -88,7 +88,7 @@ def __init__( auto_close: If True, the channel is closed when its last sender is closed, or when a receiver waits for messages while the channel has no senders. A `send()` while it has no receivers raises a - [`NoReceiversError`][frequenz.channels.NoReceiversError]. + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]. """ self._name: str = name """The name of the broadcast channel. @@ -264,10 +264,10 @@ def has_receivers(self) -> bool: """Whether this sender's channel is open and has any receivers. Producers can check this to stop producing messages that nobody would - receive. When this is `False` on an open - [`BroadcastChannel`][frequenz.channels.BroadcastChannel], - [`send()`][frequenz.channels.BroadcastSender.send] on an open sender raises a - [`NoReceiversError`][frequenz.channels.NoReceiversError] until a new receiver is + receive. While this is `False`, an open sender of an open + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] raises a + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError] + from [`send()`][frequenz.channels.BroadcastSender.send] until a new receiver is created with [`subscribe()`][frequenz.channels.BroadcastSender.subscribe]. This doesn't check whether this sender itself is closed. @@ -289,7 +289,7 @@ async def send(self, message: _T, /) -> None: # noqa: DOC503 (raised indirectly A [`ChannelClosedError`][frequenz.channels.ChannelClosedError] is set as the cause. SenderClosedError: If this sender was closed. - NoReceiversError: If this sender and its channel are open, but the + SenderHasNoReceiversError: If this sender and its channel are open, but the channel has no receivers, and it is a [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or a `Broadcast` created with `auto_close=True`. @@ -307,7 +307,7 @@ async def send(self, message: _T, /) -> None: # noqa: DOC503 (raised indirectly del self._channel._receivers[_hash] self._channel._latest = message if self._channel._auto_close_enabled and len(self._channel._receivers) == 0: - raise NoReceiversError(self) + raise SenderHasNoReceiversError(self) self._channel._wake_receivers() # pylint: enable=protected-access @@ -657,8 +657,8 @@ class BroadcastChannel( for` loops over them end. * While all receivers are closed or garbage-collected, - [`send()`][frequenz.channels.BroadcastSender.send] drops the message and - raises a [`NoReceiversError`][frequenz.channels.NoReceiversError]. The + [`send()`][frequenz.channels.BroadcastSender.send] drops the message and raises a + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]. The channel stays open, so once [`subscribe()`][frequenz.channels.BroadcastSender.subscribe] creates a new receiver, sending works again. With `resend_latest=True`, that receiver first diff --git a/src/frequenz/channels/_sender.py b/src/frequenz/channels/_sender.py index ad211764..4acf74a9 100644 --- a/src/frequenz/channels/_sender.py +++ b/src/frequenz/channels/_sender.py @@ -144,15 +144,18 @@ async def try_send(sender: Sender[int], message: int) -> bool: """ -class NoReceiversError(SenderError[SenderMessageT_co]): +class SenderHasNoReceiversError(TransientSenderError[SenderMessageT_co]): """An error indicating that a message was sent to a channel without receivers. It is raised by the senders of a [`BroadcastChannel`][frequenz.channels.BroadcastChannel], and of a `Broadcast` created with `auto_close=True`. The message is dropped. With `resend_latest=True`, new receivers still get it if it is the last message sent and - it isn't `None`. The channel stays open, so sending works again once a new receiver - is attached. + it isn't `None`. + + It is a [`TransientSenderError`][frequenz.channels.TransientSenderError]: the + sender and its channel stay open, so sending works again once a new receiver + subscribes. """ def __init__(self, sender: Sender[SenderMessageT_co]): diff --git a/src/frequenz/channels/experimental/_pipe.py b/src/frequenz/channels/experimental/_pipe.py index d5c36f69..331c0fbf 100644 --- a/src/frequenz/channels/experimental/_pipe.py +++ b/src/frequenz/channels/experimental/_pipe.py @@ -16,7 +16,7 @@ from .._generic import ChannelMessageT from .._receiver import Receiver -from .._sender import NoReceiversError, Sender, SenderError +from .._sender import Sender, SenderError, SenderHasNoReceiversError _logger = logging.getLogger(__name__) @@ -36,9 +36,9 @@ class Pipe(typing.Generic[ChannelMessageT]): message instead, and keeps sending the messages that follow. The pipe logs a failed send: a - [`NoReceiversError`][frequenz.channels.NoReceiversError] as a warning, or at debug - level with `close_pipe_on_send_error=False`, and any other error with its - traceback. + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError] as a + warning, or at debug level with `close_pipe_on_send_error=False`, and any other + error with its traceback. [`stop()`][frequenz.channels.experimental.Pipe.stop] leaves its sender and its receiver open. So does any exception while receiving, other than the receiver @@ -140,7 +140,7 @@ async def _run(self) -> None: async for value in self._receiver: try: await self._sender.send(value) - except NoReceiversError as error: + except SenderHasNoReceiversError as error: _logger.log( no_receivers_level, "Pipe from [%s] to [%s] %s: %s", diff --git a/tests/experimental/test_pipe.py b/tests/experimental/test_pipe.py index 732573d0..0dab6a9e 100644 --- a/tests/experimental/test_pipe.py +++ b/tests/experimental/test_pipe.py @@ -13,11 +13,11 @@ from frequenz.channels import ( Broadcast, BroadcastChannel, - NoReceiversError, Receiver, Sender, SenderClosedError, SenderError, + SenderHasNoReceiversError, ) from frequenz.channels.experimental import Pipe @@ -109,7 +109,7 @@ async def test_pipe_closes_both_ends_when_sending_fails( pipe = Pipe(source_receiver, sender) await pipe.start() - with pytest.raises(NoReceiversError): + with pytest.raises(SenderHasNoReceiversError): await sender.send(0) with caplog.at_level(logging.WARNING, logger="frequenz.channels.experimental"): diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index 09bdfe30..d1bba559 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -18,12 +18,13 @@ Broadcast, BroadcastChannel, ChannelClosedError, - NoReceiversError, Receiver, ReceiverStoppedError, Sender, SenderClosedError, SenderError, + SenderHasNoReceiversError, + TransientSenderError, select, selected_from, ) @@ -578,7 +579,8 @@ async def test_broadcast_no_receivers_after_all_receivers_closed() -> None: match=f"^Sender {re.escape(str(sender))} has no receivers$", ) as excinfo: await sender.send(3) - assert isinstance(excinfo.value, NoReceiversError) + assert isinstance(excinfo.value, SenderHasNoReceiversError) + assert isinstance(excinfo.value, TransientSenderError) assert excinfo.value.__cause__ is None @@ -610,7 +612,7 @@ async def test_broadcast_subscribe_after_last_receiver_closed() -> None: sender, receiver = BroadcastChannel[int](name="auto-close-test") receiver.close() - with pytest.raises(NoReceiversError): + with pytest.raises(SenderHasNoReceiversError): await sender.send(0) receiver_2 = sender.subscribe() @@ -625,7 +627,7 @@ async def test_broadcast_no_receivers_after_last_receiver_dropped() -> None: del receiver gc.collect() - with pytest.raises(NoReceiversError): + with pytest.raises(SenderHasNoReceiversError): await sender.send(1) @@ -649,7 +651,7 @@ async def test_broadcast_send_without_receivers_resent() -> None: await sender.send(1) receiver.close() - with pytest.raises(NoReceiversError): + with pytest.raises(SenderHasNoReceiversError): await sender.send(2) receiver_2 = sender.subscribe() @@ -661,7 +663,7 @@ async def test_broadcast_no_receivers_deprecated_auto_close() -> None: chan = Broadcast[int](name="auto-close-test", auto_close=True) sender = chan.new_sender() - with pytest.raises(NoReceiversError): + with pytest.raises(SenderHasNoReceiversError): await sender.send(1) assert not chan.is_closed diff --git a/tests/test_sender.py b/tests/test_sender.py index 8c39e64c..7c5b635f 100644 --- a/tests/test_sender.py +++ b/tests/test_sender.py @@ -7,6 +7,7 @@ BroadcastChannel, SenderClosedError, SenderError, + SenderHasNoReceiversError, TransientSenderError, ) @@ -20,3 +21,14 @@ def test_transient_sender_error() -> None: assert error.sender is sender assert str(error) == "Not sent" assert not issubclass(SenderClosedError, TransientSenderError) + + +def test_sender_has_no_receivers_error() -> None: + """Ensure having no receivers is a transient sender error.""" + sender, _receiver = BroadcastChannel[int](name="test") + error = SenderHasNoReceiversError(sender) + + assert isinstance(error, TransientSenderError) + assert isinstance(error, SenderError) + assert error.sender is sender + assert str(error) == f"Sender {sender} has no receivers" From 446a1ee19716d83c3f125dca79899d5e626e5bdd Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:16:43 +0000 Subject: [PATCH 28/35] Update the release notes for the new sender errors PR 565's entries still used the old `NoReceiversError` name. Use `SenderHasNoReceiversError` in all of them, and add an entry for the new `TransientSenderError`, which the renamed error derives from. The entry for the renamed error says that sending works again once a receiver subscribes. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 5d44b251..8c0d7b13 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -26,17 +26,17 @@ - The `repr()` of a `BroadcastReceiver` shows its `buffer_size` instead of `limit`. -- A `BroadcastChannel`, or a `Broadcast` created with `auto_close=True`, no longer closes when a message is sent while it has no receivers. `send()` now drops the message and raises a `NoReceiversError`, a `SenderError` without a cause. The channel stays open: `subscribe()` keeps working, and sending works again once a new receiver is attached. +- A `BroadcastChannel`, or a `Broadcast` created with `auto_close=True`, no longer closes when a message is sent while it has no receivers. `send()` now drops the message and raises a `SenderHasNoReceiversError`, a `SenderError` without a cause. The channel stays open: `subscribe()` keeps working, and sending works again once a new receiver is attached. -- Code that waited for such a channel to close after a send without receivers, for example by checking for a `ChannelClosedError` cause or for `is_closed`, should catch `NoReceiversError` instead. It can then stop sending, or close all of the channel's senders to close the channel. +- Code that waited for such a channel to close after a send without receivers, for example by checking for a `ChannelClosedError` cause or for `is_closed`, should catch `SenderHasNoReceiversError` instead. It can then stop sending, or close all of the channel's senders to close the channel. - An experimental `Pipe` now closes its sender when its receiver stops. Before, it left the sender open. -- When sending fails with a `SenderError`, for example because the sender's `BroadcastChannel` has no receivers, a `Pipe` now closes both its sender and its receiver, and logs the error: a `NoReceiversError` as a warning, and any other error with its traceback. Before, the pipe stopped but left both open. +- When sending fails with a `SenderError`, for example because the sender's `BroadcastChannel` has no receivers, a `Pipe` now closes both its sender and its receiver, and logs the error: a `SenderHasNoReceiversError` as a warning, and any other error with its traceback. Before, the pipe stopped but left both open. - `Pipe.stop()` still leaves a pipe's sender and receiver open. So does any exception while receiving, other than the receiver stopping, and any exception from sending that isn't a `SenderError`. -- To keep a `Pipe` running after a `SenderError`, pass `close_pipe_on_send_error=False`. It then drops the message, keeps sending the messages that follow, and logs a `NoReceiversError` at debug level. +- To keep a `Pipe` running after a `SenderError`, pass `close_pipe_on_send_error=False`. It then drops the message, keeps sending the messages that follow, and logs a `SenderHasNoReceiversError` at debug level. - Give a `Pipe` a clone of its sender if you still need to send after the pipe stops on its own. @@ -54,7 +54,9 @@ -- `NoReceiversError` is a new `SenderError`. An open sender of a `BroadcastChannel`, or of a `Broadcast` created with `auto_close=True`, raises it from `send()` while the channel is open but has no receivers. The message is dropped, but with `resend_latest=True`, new receivers still get it if it is the last message sent and it isn't `None`. +- `TransientSenderError` is a new `SenderError` for errors after which the sender and its channel can still be used: only the message that failed wasn't sent. Catch it before `SenderError` to tell it apart from the errors that make a sender unusable. + +- `SenderHasNoReceiversError` is a new `TransientSenderError`. An open sender of a `BroadcastChannel`, or of a `Broadcast` created with `auto_close=True`, raises it from `send()` while the channel is open but has no receivers. The message is dropped, but with `resend_latest=True`, new receivers still get it if it is the last message sent and it isn't `None`. The channel stays open, so sending works again once a receiver subscribes. - `BroadcastSender.has_receivers` and `BroadcastReceiver.has_senders` tell whether the other side of a broadcast channel is still there, so producers can stop producing messages that nobody would receive. A sender that was garbage-collected without being closed still counts. From 11e2720f4e9afffe1bc344264a61adb088437e9a Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 20 Nov 2026 08:44:48 +0000 Subject: [PATCH 29/35] Use `BroadcastChannel` where `Anycast` was only an example The `Receiver` module docstring built its `WithPrevious` filter example on an `Anycast`, and `test_merge()` used `Anycast` to feed `merge()`. Both only needed some channel, so they shouldn't depend on a class that is about to be removed. Use a `BroadcastChannel` in both, as the other examples in the docstring do. This also drops the `filterwarnings` mark `test_merge()` needed to use a deprecated class. Signed-off-by: Leandro Lucarella --- src/frequenz/channels/_receiver.py | 7 +++---- tests/test_merge_integration.py | 16 +++++++--------- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/frequenz/channels/_receiver.py b/src/frequenz/channels/_receiver.py index be1c6b8a..ee06460a 100644 --- a/src/frequenz/channels/_receiver.py +++ b/src/frequenz/channels/_receiver.py @@ -74,11 +74,10 @@ To filter messages based on the previous one, for example to skip repeated messages, use [`WithPrevious`][frequenz.channels.WithPrevious] to build the filter function: -```python show_lines="6:" -from frequenz.channels import Anycast, WithPrevious +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, WithPrevious -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver.filter(WithPrevious(lambda old, new: old != new)): print(message) # Only messages different from the previous one will be printed diff --git a/tests/test_merge_integration.py b/tests/test_merge_integration.py index ec7c2231..c7967832 100644 --- a/tests/test_merge_integration.py +++ b/tests/test_merge_integration.py @@ -7,30 +7,28 @@ import pytest -from frequenz.channels import Anycast, Broadcast, Sender, merge +from frequenz.channels import Broadcast, BroadcastChannel, Sender, merge from frequenz.channels._receiver import ReceiverStoppedError @pytest.mark.integration -# This test uses the deprecated Anycast on purpose. -@pytest.mark.filterwarnings("once::DeprecationWarning") async def test_merge() -> None: """Ensure merge() receives messages in order.""" - chan1 = Anycast[int](name="chan1") - chan2 = Anycast[int](name="chan2") + sender1, receiver1 = BroadcastChannel[int](name="chan1") + sender2, receiver2 = BroadcastChannel[int](name="chan2") async def send(ch1: Sender[int], ch2: Sender[int]) -> None: for ctr in range(5): await ch1.send(ctr + 1) await ch2.send(ctr + 101) - await chan1.aclose() + await ch1.aclose() await ch2.send(1000) - await chan2.aclose() + await ch2.aclose() - senders = asyncio.create_task(send(chan1.new_sender(), chan2.new_sender())) + senders = asyncio.create_task(send(sender1, sender2)) results: list[int] = [] - async for item in merge(chan1.new_receiver(), chan2.new_receiver()): + async for item in merge(receiver1, receiver2): results.append(item) await senders for ctr in range(5): From bbd0be0311c3d02ee68d5c18e9f81fc97d535e5d Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 20 Nov 2026 08:47:53 +0000 Subject: [PATCH 30/35] Remove `Anycast` `Anycast` was deprecated since v1.12.0. It is removed in v2.0.0 with no replacement, so there is nothing to migrate to and users who still need it have to copy its code into their projects. Remove the class, its export and documentation in the package docstring, its tests and its benchmark. Also drop it from the `part:channels` labeler rule and from the bug report template. The release notes entry about the removed `async close()` now only mentions `Broadcast`, as `Anycast` doesn't exist anymore, and a new upgrading entry tells to copy the code if it is still needed. Signed-off-by: Leandro Lucarella --- .github/ISSUE_TEMPLATE/bug.yml | 2 +- .github/labeler.yml | 1 - RELEASE_NOTES.md | 4 +- benchmarks/benchmark_anycast.py | 127 -------- src/frequenz/channels/__init__.py | 6 - src/frequenz/channels/_anycast.py | 505 ------------------------------ tests/test_anycast.py | 259 --------------- 7 files changed, 4 insertions(+), 900 deletions(-) delete mode 100644 benchmarks/benchmark_anycast.py delete mode 100644 src/frequenz/channels/_anycast.py delete mode 100644 tests/test_anycast.py diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index 0f440753..d1eae7f2 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -50,7 +50,7 @@ body: - Documentation (part:docs) - Unit, integration and performance tests (part:tests) - Build script, CI, dependencies, etc. (part:tooling) - - Channels, `Broadcast`, `Anycast`, etc. (part:channels) + - Channels, `BroadcastChannel`, etc. (part:channels) - Core types (`Sender`, `Receiver`, exceptions, etc.) (part:core) - Experimental features (the `experimental` package) (part:experimental) - Utilities (`Event`, `FileWatcher`, `Timer`, etc.) (part:utilities) diff --git a/.github/labeler.yml b/.github/labeler.yml index b50ec0e3..313d999b 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -39,7 +39,6 @@ "part:channels": - changed-files: - any-glob-to-any-file: - - "src/frequenz/channels/_anycast.py" - "src/frequenz/channels/_broadcast.py" "part:core": diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 8c0d7b13..104245e9 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -14,6 +14,8 @@ - The deprecated `frequenz.channels.timer.Timer` is removed. Use `MonotonicTimer` instead, which exists since v1.13.0, so you can migrate before upgrading. The name `Timer` will be used for a wall clock timer in a later version. +- `Anycast` is removed. There is no replacement: copy its code into your project if you still need it. + - `frequenz.channels.experimental.GroupingLatestValueCache` is removed, together with its type variables `DefaultT`, `HashableT` and `ValueT_co`. Copy its code into your project if you still need it, or open an issue if you think it should stay in the library. - `frequenz.channels.experimental.RelaySender` is removed. Copy its code into your project if you still need it, or open an issue if you think it should stay in the library. @@ -22,7 +24,7 @@ - `WithPrevious` and `NopReceiver` are no longer available from `frequenz.channels.experimental`. Import them from `frequenz.channels`, where they are available since v1.13.0, so you can migrate before upgrading. -- The deprecated `async close()` method of `Anycast` and `Broadcast` is removed. Use `aclose()` instead, which exists since v1.8.0, so you can migrate before upgrading. It also works with `contextlib.aclosing()`. +- The deprecated `async close()` method of `Broadcast` is removed. Use `aclose()` instead, which exists since v1.8.0, so you can migrate before upgrading. It also works with `contextlib.aclosing()`. - The `repr()` of a `BroadcastReceiver` shows its `buffer_size` instead of `limit`. diff --git a/benchmarks/benchmark_anycast.py b/benchmarks/benchmark_anycast.py deleted file mode 100644 index 68e4ae3b..00000000 --- a/benchmarks/benchmark_anycast.py +++ /dev/null @@ -1,127 +0,0 @@ -# License: MIT -# Copyright © 2022 Frequenz Energy-as-a-Service GmbH - -"""Benchmark for Anycast channels.""" - -import asyncio -import csv -import timeit -from collections.abc import Coroutine -from typing import Any - -from frequenz.channels import Anycast, Receiver, Sender - - -async def send_msg(num_messages: int, chan: Sender[int]) -> None: - """Send messages to the channel continuously. - - Args: - num_messages: Number of messages to send. - chan: Channel sender to send the messages to. - """ - # send one message for each receiver - for ctr in range(num_messages): - await chan.send(ctr + 1) - - -async def benchmark_anycast( - num_channels: int, - num_messages: int, - num_receivers: int, - buffer_size: int, -) -> int: - """Ensure sent messages are received by one receiver. - - Args: - num_channels: Number of channels to create. - num_messages: Number of messages to send per channel. - num_receivers: Number of broadcast receivers per channel. - buffer_size: Buffer size of each channel. - - Returns: - Total number of messages received by all channels. - """ - channels: list[Anycast[int]] = [ - Anycast(name="test", limit=buffer_size) for _ in range(num_channels) - ] - senders = [ - asyncio.create_task(send_msg(num_messages, bcast.new_sender())) - for bcast in channels - ] - - # Even though we want just a single int, use a list, so that it can be - # updated from other methods. - recv_trackers = [0] - - async def update_tracker_on_receive(chan: Receiver[int]) -> None: - async for _ in chan: - recv_trackers[0] += 1 - - receivers = [] - for acast in channels: - for _ in range(num_receivers): - receivers.append(update_tracker_on_receive(acast.new_receiver())) - - receivers_runs = asyncio.gather(*receivers) - - await asyncio.gather(*senders) - for bcast in channels: - await bcast.aclose() - await receivers_runs - return recv_trackers[0] - - -def time_async_task(task: Coroutine[Any, Any, int]) -> tuple[float, Any]: - """Run a task and return the time taken and the result. - - Args: - task: Task to run. - - Returns: - Run time in fractional seconds, task return value. - """ - start = timeit.default_timer() - ret = asyncio.run(task) - return timeit.default_timer() - start, ret - - -def run_one( - num_channels: int, - num_messages: int, - num_receivers: int, - buffer_size: int, -) -> dict[str, Any]: - """Run a single benchmark.""" - runtime, total_msgs = time_async_task( - benchmark_anycast(num_channels, num_messages, num_receivers, buffer_size) - ) - ret = { - "channels": num_channels, - "messages_per_channel": num_messages, - "receivers": num_receivers, - "buffer_size": buffer_size, - "total_messages": total_msgs, - "runtime": f"{runtime:.3f}", - } - - return ret - - -def run() -> None: - """Run all benchmarks.""" - with open("/dev/stdout", "w", encoding="utf-8") as csvfile: - fields = run_one(1, 0, 1, 1) - out = csv.DictWriter(csvfile, fields.keys()) - out.writeheader() - out.writerow(run_one(1, 1000000, 1, 100)) - out.writerow(run_one(1, 1000000, 1, 1000)) - out.writerow(run_one(1, 1000000, 10, 100)) - out.writerow(run_one(1, 1000000, 10, 1000)) - out.writerow(run_one(1000, 1000, 1, 100)) - out.writerow(run_one(1000, 1000, 1, 1000)) - out.writerow(run_one(1000, 1000, 10, 100)) - out.writerow(run_one(1000, 1000, 10, 1000)) - - -if __name__ == "__main__": - run() diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index 73d2bd23..b8018723 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -33,10 +33,6 @@ * [`OneshotChannel`][frequenz.channels.OneshotChannel]: A channel that can send a single message from one sender to one receiver. -* [`Anycast`][frequenz.channels.Anycast] (deprecated): A channel that supports multiple - senders and multiple receivers. A message sent through a sender will be - received by exactly one receiver. - * [`Broadcast`][frequenz.channels.Broadcast] (deprecated): The predecessor of [`BroadcastChannel`][frequenz.channels.BroadcastChannel]. Unless it is created with `auto_close=True`, it must be closed with `aclose()`. @@ -110,7 +106,6 @@ from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases -from ._anycast import Anycast from ._broadcast import BroadcastChannel, BroadcastReceiver, BroadcastSender from ._exceptions import ChannelClosedError, ChannelError, Error from ._generic import ( @@ -160,7 +155,6 @@ ) __all__ = [ - "Anycast", "Broadcast", "BroadcastChannel", "BroadcastReceiver", diff --git a/src/frequenz/channels/_anycast.py b/src/frequenz/channels/_anycast.py deleted file mode 100644 index 5140eb7f..00000000 --- a/src/frequenz/channels/_anycast.py +++ /dev/null @@ -1,505 +0,0 @@ -# License: MIT -# Copyright © 2022 Frequenz Energy-as-a-Service GmbH - -"""A channel for sending data across async tasks.""" - -from __future__ import annotations - -import logging -from asyncio import Condition -from collections import deque -from typing import Generic, TypeVar - -from typing_extensions import deprecated, override - -from ._exceptions import ChannelClosedError -from ._generic import ChannelMessageT -from ._receiver import Receiver, ReceiverStoppedError -from ._sender import Sender, SenderClosedError, SenderError - -_logger = logging.getLogger(__name__) - - -@deprecated( - "frequenz.channels.Anycast is deprecated and will be removed in a future " - "version. Copy its code into your project if you need it, or open an issue at " - "https://github.com/frequenz-floss/frequenz-channels-python/issues if you think " - "it should stay in frequenz-channels." -) -class Anycast(Generic[ChannelMessageT]): - """A channel that delivers each message to exactly one receiver. - - Deprecated: - Deprecated since v1.12.0, and will be removed in a future version. Copy its - code into your project if you need it, or [open an - issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if - you think it should stay in this library. - - # Description - - !!! Tip inline end - - [`Anycast`][frequenz.channels.Anycast] channels behave like the - [Golang](https://golang.org/) [channels](https://go.dev/ref/spec#Channel_types). - - [`Anycast`][frequenz.channels.Anycast] channels support multiple - [senders][frequenz.channels.Sender] and multiple - [receivers][frequenz.channels.Receiver]. Each message sent through any of the - senders will be received by exactly one receiver (but **any** receiver). - -
- ```bob - .---------. msg1 msg1 .-----------. - | Sender +------. .------>| Receiver | - '---------' | .----------. | '-----------' - +----->| Channel +-----+ - .---------. | '----------' | .-----------. - | Sender +------' '------>| Receiver | - '---------' msg2 msg2 '-----------' - ``` -
- - !!! Note inline end "Characteristics" - - * **Buffered:** Yes, with a global channel buffer - * **Buffer full policy:** Block senders - * **Multiple receivers:** Yes - * **Multiple senders:** Yes - * **Thread-safe:** No - - This channel is buffered, and if the senders are faster than the receivers, then the - channel's buffer will fill up. In that case, the senders will block at the - [`send()`][frequenz.channels.Sender.send] method until the receivers consume the - messages in the channel's buffer. The channel's buffer size can be configured at - creation time via the `limit` argument. - - The first receiver that is awaited will get the next message. When multiple - receivers are waiting, the [asyncio][] loop scheduler picks a receiver for each next - message. - - This means that, in practice, there might be only one receiver receiving all the - messages, depending on how tasks are scheduled. - - If you need to ensure some delivery policy (like round-robin or uniformly random), - then you will have to implement it yourself. - - To create a new [senders][frequenz.channels.Sender] and - [receivers][frequenz.channels.Receiver] you can use the - [`.new_sender()`][frequenz.channels.Anycast.new_sender] and - [`.new_receiver()`][frequenz.channels.Anycast.new_receiver] methods - respectively. - - When the channel is not needed anymore, it should be closed with the - [`.aclose()`][frequenz.channels.Anycast.aclose] method. This will prevent further - attempts to [`send()`][frequenz.channels.Sender.send] data. Receivers will still be - able to drain the pending messages on the channel, but after that, subsequent - [`receive()`][frequenz.channels.Receiver.receive] calls will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError] exception. - - This channel is useful, for example, to distribute work across multiple workers. - - In cases where each message needs to be received by every receiver, a - [`BroadcastChannel`][frequenz.channels.BroadcastChannel] may be used. - - # Examples - - Example: Send a few numbers to a receiver - This is a very simple example that sends a few numbers from a single sender to - a single receiver. - - ```python - import asyncio - - from frequenz.channels import Anycast, Sender - - - async def send(sender: Sender[int]) -> None: - for message in range(3): - print(f"sending {message}") - await sender.send(message) - - - async def main() -> None: - channel = Anycast[int](name="numbers") - - sender = channel.new_sender() - receiver = channel.new_receiver() - - async with asyncio.TaskGroup() as task_group: - task_group.create_task(send(sender)) - for _ in range(3): - message = await receiver.receive() - print(f"received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data - - - asyncio.run(main()) - ``` - - The output should look something like (although the sending and received might - appear more interleaved): - - ``` - sending 0 - sending 1 - sending 2 - received 0 - received 1 - received 2 - ``` - - Example: Send a few number from multiple senders to multiple receivers - This is a more complex example that sends a few numbers from multiple senders to - multiple receivers, using a small buffer to force the senders to block. - - ```python - import asyncio - - from frequenz.channels import Anycast, Receiver, ReceiverStoppedError, Sender - - - async def send(name: str, sender: Sender[int], start: int, stop: int) -> None: - for message in range(start, stop): - print(f"{name} sending {message}") - await sender.send(message) - - - async def recv(name: str, receiver: Receiver[int]) -> None: - try: - async for message in receiver: - print(f"{name} received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data - except ReceiverStoppedError: - pass - - - async def main() -> None: - acast = Anycast[int](name="numbers", limit=2) - - async with asyncio.TaskGroup() as task_group: - task_group.create_task(send("sender_1", acast.new_sender(), 10, 13)) - task_group.create_task(send("sender_2", acast.new_sender(), 20, 22)) - task_group.create_task(recv("receiver_1", acast.new_receiver())) - task_group.create_task(recv("receiver_2", acast.new_receiver())) - - - asyncio.run(main()) - ``` - - The output should look something like this(although the sending and received - might appear interleaved in a different way): - - ``` - sender_1 sending 10 - sender_1 sending 11 - sender_1 sending 12 - Anycast channel [Anycast:numbers:_Sender] is full, blocking sender until a receiver - consumes a message - sender_2 sending 20 - Anycast channel [Anycast:numbers:_Sender] is full, blocking sender until a receiver - consumes a message - receiver_1 received 10 - receiver_1 received 11 - sender_2 sending 21 - Anycast channel [Anycast:numbers:_Sender] is full, blocking sender until a receiver - consumes a message - receiver_1 received 12 - receiver_1 received 20 - receiver_1 received 21 - ``` - """ - - def __init__(self, *, name: str, limit: int = 10) -> None: - """Initialize this channel. - - Args: - name: The name of the channel. This is for logging purposes, and it will be - shown in the string representation of the channel. - limit: The size of the internal buffer in number of messages. If the buffer - is full, then the senders will block until the receivers consume the - messages in the buffer. - """ - self._name: str = name - """The name of the channel. - - This is for logging purposes, and it will be shown in the string representation - of the channel. - """ - - self._deque: deque[ChannelMessageT] = deque(maxlen=limit) - """The channel's buffer.""" - - self._send_cv: Condition = Condition() - """The condition to wait for free space in the channel's buffer. - - If the channel's buffer is full, then the sender waits for messages to - get consumed using this condition until there's some free space - available in the channel's buffer. - """ - - self._recv_cv: Condition = Condition() - """The condition to wait for messages in the channel's buffer. - - If the channel's buffer is empty, then the receiver waits for messages - using this condition until there's a message available in the channel's - buffer. - """ - - self._closed: bool = False - """Whether the channel is closed.""" - - @property - def name(self) -> str: - """The name of this channel. - - This is for debugging purposes, it will be shown in the string representation - of this channel. - """ - return self._name - - @property - def is_closed(self) -> bool: - """Whether this channel is closed. - - Any further attempts to use this channel after it is closed will result in an - exception. - """ - return self._closed - - @property - def limit(self) -> int: - """The maximum number of messages that can be stored in the channel's buffer. - - If the length of channel's buffer reaches the limit, then the sender - blocks at the [`send()`][frequenz.channels.Sender.send] method until - a message is consumed. - """ - maxlen = self._deque.maxlen - assert maxlen is not None - return maxlen - - async def aclose(self) -> None: - """Close the channel. - - Any further attempts to [`send()`][frequenz.channels.Sender.send] data - will raise a [`SenderError`][frequenz.channels.SenderError]. - - Receivers will still be able to drain the pending messages on the channel, - but after that, subsequent - [`receive()`][frequenz.channels.Receiver.receive] calls will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. - """ - self._closed = True - async with self._send_cv: - self._send_cv.notify_all() - async with self._recv_cv: - self._recv_cv.notify_all() - - def new_sender(self) -> Sender[ChannelMessageT]: - """Return a new sender attached to this channel.""" - return _Sender(self) - - def new_receiver(self) -> Receiver[ChannelMessageT]: - """Return a new receiver attached to this channel.""" - return _Receiver(self) - - def __str__(self) -> str: - """Return a string representation of this channel.""" - return f"{type(self).__name__}:{self._name}" - - def __repr__(self) -> str: - """Return a string representation of this channel.""" - return ( - f"{type(self).__name__}(name={self._name!r}, limit={self.limit!r}):<" - f"current={len(self._deque)!r}, closed={self._closed!r}>" - ) - - -_T = TypeVar("_T") - - -class _Sender(Sender[_T]): - """A sender to send messages to an Anycast channel. - - Should not be created directly, but through the - [`Anycast.new_sender()`][frequenz.channels.Anycast.new_sender] - method. - """ - - def __init__(self, channel: Anycast[_T], /) -> None: - """Initialize this sender. - - Args: - channel: A reference to the channel that this sender belongs to. - """ - self._channel: Anycast[_T] = channel - """The channel that this sender belongs to.""" - - self._closed: bool = False - """Whether the sender is closed.""" - - @override - async def send(self, message: _T, /) -> None: - """Send a message across the channel. - - To send, this method inserts the message into the Anycast channel's - buffer. If the channel's buffer is full, waits for messages to get - consumed, until there's some free space available in the buffer. Each - message will be received by exactly one receiver. - - Args: - message: The message to be sent. - - Raises: - SenderError: If the underlying channel was closed. - A [`ChannelClosedError`][frequenz.channels.ChannelClosedError] is - set as the cause. - SenderClosedError: If this sender was closed. - """ - if self._closed: - raise SenderClosedError(self) - - # pylint: disable=protected-access - if self._channel._closed: - raise SenderError("The channel was closed", self) from ChannelClosedError( - self._channel - ) - if len(self._channel._deque) == self._channel._deque.maxlen: - _logger.warning( - "Anycast channel [%s] is full, blocking sender until a receiver " - "consumes a message", - self, - ) - while len(self._channel._deque) == self._channel._deque.maxlen: - async with self._channel._send_cv: - await self._channel._send_cv.wait() - _logger.info( - "Anycast channel [%s] has space again, resuming the blocked sender", - self, - ) - self._channel._deque.append(message) - async with self._channel._recv_cv: - self._channel._recv_cv.notify(1) - # pylint: enable=protected-access - - @override - async def aclose(self) -> None: - """Close this sender. - - After closing, the sender will not be able to send any more messages. Any - attempt to send a message through a closed sender will raise a - [`SenderError`][frequenz.channels.SenderError]. - """ - self._closed = True - - def __str__(self) -> str: - """Return a string representation of this sender.""" - return f"{self._channel}:{type(self).__name__}" - - def __repr__(self) -> str: - """Return a string representation of this sender.""" - return f"{type(self).__name__}({self._channel!r})" - - -class _Empty: - """A sentinel to indicate that a message has not been set.""" - - -class _Receiver(Receiver[_T]): - """A receiver to receive messages from an Anycast channel. - - Should not be created directly, but through the - [`Anycast.new_receiver()`][frequenz.channels.Anycast.new_receiver] - method. - """ - - def __init__(self, channel: Anycast[_T], /) -> None: - """Initialize this receiver. - - Args: - channel: A reference to the channel that this receiver belongs to. - """ - self._channel: Anycast[_T] = channel - """The channel that this receiver belongs to.""" - - self._closed: bool = False - """Whether the receiver is closed.""" - - self._next: _T | type[_Empty] = _Empty - - @override - async def ready(self) -> bool: - """Wait until the receiver is ready with a message or an error. - - Once a call to [`.ready()`][frequenz.channels.Receiver.ready] has finished, the - message should be read with a call to - [`.consume()`][frequenz.channels.Receiver.consume] - ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The - receiver will remain ready (this method will return immediately) until it is - consumed. - - Returns: - Whether the receiver is still active. - """ - # if a message is already ready, then return immediately. - if self._next is not _Empty: - return True - - if self._closed: - return False - - # pylint: disable=protected-access - while len(self._channel._deque) == 0: - if self._channel._closed: - return False - async with self._channel._recv_cv: - await self._channel._recv_cv.wait() - self._next = self._channel._deque.popleft() - async with self._channel._send_cv: - self._channel._send_cv.notify(1) - # pylint: enable=protected-access - return True - - @override - def consume(self) -> _T: - """Return the latest message once [`ready()`][frequenz.channels.Receiver.ready] is complete. - - Returns: - The next message that was received. - - Raises: - ReceiverStoppedError: If the receiver stopped producing messages. - """ - if ( # pylint: disable=protected-access - self._next is _Empty and self._channel._closed - ): - raise ReceiverStoppedError(self) from ChannelClosedError(self._channel) - - if self._next is _Empty and self._closed: - raise ReceiverStoppedError(self) - - assert ( - self._next is not _Empty - ), "`consume()` must be preceded by a call to `ready()`" - # mypy doesn't understand that the assert above ensures that self._next is not - # _Sentinel. So we have to use a type ignore here. - next_val: _T = self._next # type: ignore[assignment] - self._next = _Empty - - return next_val - - @override - def close(self) -> None: - """Close this receiver. - - After closing, the receiver will not be able to receive any more messages. - """ - self._closed = True - - def __str__(self) -> str: - """Return a string representation of this receiver.""" - return f"{self._channel}:{type(self).__name__}" - - def __repr__(self) -> str: - """Return a string representation of this receiver.""" - return f"{type(self).__name__}({self._channel!r})" diff --git a/tests/test_anycast.py b/tests/test_anycast.py deleted file mode 100644 index 10f758bf..00000000 --- a/tests/test_anycast.py +++ /dev/null @@ -1,259 +0,0 @@ -# License: MIT -# Copyright © 2022 Frequenz Energy-as-a-Service GmbH - -"""Tests for the Channel implementation.""" - -import asyncio - -import pytest - -from frequenz.channels import ( - Anycast, - ChannelClosedError, - Receiver, - ReceiverStoppedError, - Sender, - SenderError, -) - -# Every test here uses the deprecated Anycast on purpose. -pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") - - -def test_deprecation_warning() -> None: - """Test that Anycast warns it is deprecated.""" - with pytest.deprecated_call( - match=r"^frequenz\.channels\.Anycast is deprecated and will be removed in a " - r"future version\. Copy its code into your project if you need it, or open an " - r"issue at https://github\.com/frequenz-floss/frequenz-channels-python/issues " - r"if you think it should stay in frequenz-channels\.$" - ): - _ = Anycast[int](name="test") - - -async def test_anycast() -> None: - """Ensure sent messages are received by one receiver.""" - acast: Anycast[int] = Anycast(name="test") - - num_receivers = 5 - num_senders = 5 - expected_sum = num_senders * num_receivers * (num_receivers + 1) / 2 - - # a list of `num_receivers` elements, where each element with get - # incremented by values the corresponding receiver receives. Once the run - # finishes, we will check if their sum equals `expected_sum`. - recv_trackers = [0] * num_receivers - - async def send_msg(chan: Sender[int]) -> None: - # send one message for each receiver - for ctr in range(num_receivers): - await chan.send(ctr + 1) - - async def update_tracker_on_receive(receiver_id: int, recv: Receiver[int]) -> None: - while True: - try: - msg = await recv.receive() - except ReceiverStoppedError as err: - assert err.receiver is recv - assert isinstance(err.__cause__, ChannelClosedError) - return - recv_trackers[receiver_id] += msg - # without the sleep, decommissioning receivers temporarily, all - # messages go to the first receiver. - await asyncio.sleep(0) - - receivers = [] - for ctr in range(num_receivers): - receivers.append(update_tracker_on_receive(ctr, acast.new_receiver())) - - # get one more sender and receiver to test channel operations after the - # channel is closed. - after_close_receiver = acast.new_receiver() - after_close_sender = acast.new_sender() - - receivers_runs = asyncio.gather(*receivers) - senders = [] - for ctr in range(num_senders): - senders.append(send_msg(acast.new_sender())) - - await asyncio.gather(*senders) - await acast.aclose() - await receivers_runs - - with pytest.raises(SenderError): - await after_close_sender.send(5) - with pytest.raises(ReceiverStoppedError) as excinfo: - await after_close_receiver.receive() - assert excinfo.value.receiver is after_close_receiver - assert isinstance(excinfo.value.__cause__, ChannelClosedError) - assert excinfo.value.__cause__.channel is acast - - actual_sum = 0 - for ctr in recv_trackers: - # ensure all receivers have got messages - assert ctr > 0 - actual_sum += ctr - assert actual_sum == expected_sum - - -async def test_anycast_after_close() -> None: - """Ensure closed channels can't get new messages.""" - acast: Anycast[int] = Anycast(name="test") - - receiver = acast.new_receiver() - sender = acast.new_sender() - - await sender.send(2) - - await acast.aclose() - - with pytest.raises(SenderError): - await sender.send(5) - - assert await receiver.receive() == 2 - with pytest.raises(ReceiverStoppedError): - await receiver.receive() - - -async def test_anycast_full() -> None: - """Ensure send calls to a full channel are blocked.""" - buffer_size = 10 - timeout = 0.2 - acast: Anycast[int] = Anycast(name="test", limit=buffer_size) - - receiver = acast.new_receiver() - sender = acast.new_sender() - - timeout_at = 0 - for ctr in range(buffer_size + 1): - try: - await asyncio.wait_for(sender.send(ctr), timeout) - except asyncio.TimeoutError: - # expect timeout once the buffer is full - timeout_at = ctr - - assert timeout_at == buffer_size - - timeout_at = 0 - for ctr in range(buffer_size + 1): - try: - msg = await asyncio.wait_for(receiver.receive(), timeout) - assert ctr == msg - except asyncio.TimeoutError: - # expect timeout once the buffer is empty - timeout_at = ctr - - assert timeout_at == buffer_size - - try: - await asyncio.wait_for(sender.send(100), timeout) - except asyncio.TimeoutError: - # should not timeout now, because we've just drained the channel - assert False - - try: - msg = await asyncio.wait_for(receiver.receive(), timeout) - assert msg == 100 - except asyncio.TimeoutError: - # should not timeout now, because we've just sent a message to the - # channel. - assert False - - -async def test_anycast_none_messages() -> None: - """Ensure None messages can be sent and received.""" - acast: Anycast[int | None] = Anycast(name="test") - - sender = acast.new_sender() - receiver = acast.new_receiver() - - await sender.send(5) - assert await receiver.receive() == 5 - - await sender.send(None) - assert await receiver.receive() is None - - await sender.send(10) - assert await receiver.receive() == 10 - - -async def test_anycast_async_iterator() -> None: - """Check that the anycast receiver works as an async iterator.""" - acast: Anycast[str] = Anycast(name="test") - - sender = acast.new_sender() - receiver = acast.new_receiver() - - async def send_messages() -> None: - for val in ["one", "two", "three", "four", "five"]: - await sender.send(val) - await acast.aclose() - - sender_task = asyncio.create_task(send_messages()) - - received = [] - async for recv in receiver: - received.append(recv) - - assert received == ["one", "two", "three", "four", "five"] - - await sender_task - - -async def test_anycast_map() -> None: - """Ensure map runs on all incoming messages.""" - chan: Anycast[int] = Anycast(name="test") - sender = chan.new_sender() - - # transform int receiver into bool receiver. - receiver: Receiver[bool] = chan.new_receiver().map(lambda num: num > 10) - - await sender.send(8) - await sender.send(12) - - assert (await receiver.receive()) is False - assert (await receiver.receive()) is True - - -async def test_anycast_filter() -> None: - """Ensure filter keeps only the messages that pass the filter.""" - chan = Anycast[int](name="input-chan") - sender = chan.new_sender() - - # filter out all numbers less than 10. - receiver: Receiver[int] = chan.new_receiver().filter(lambda num: num > 10) - - await sender.send(8) - await sender.send(12) - await sender.send(5) - await sender.send(15) - - assert (await receiver.receive()) == 12 - assert (await receiver.receive()) == 15 - - -async def test_anycast_close_receiver() -> None: - """Ensure closing a receiver stops the receiver.""" - chan = Anycast[int](name="input-chan") - sender = chan.new_sender() - - receiver_1 = chan.new_receiver() - receiver_2 = chan.new_receiver() - - await sender.send(1) - - assert (await receiver_1.receive()) == 1 - - receiver_1.close() - - await sender.send(2) - - with pytest.raises(ReceiverStoppedError): - _ = await receiver_1.receive() - - assert (await receiver_2.receive()) == 2 - - receiver_2.close() - - with pytest.raises(ReceiverStoppedError): - _ = await receiver_2.receive() From 2e53357b4fa3252f2b784190c79dcd60125f12ae Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:42:24 +0000 Subject: [PATCH 31/35] Deprecate `Broadcast` with `@deprecated`, not an alias `Broadcast` was a `deprecated_aliases()` alias of the private `_Broadcast`. The generated docs showed the private class, and the deprecation said "Please use BroadcastChannel instead", which doesn't follow the deprecations guide and doesn't match the pytest filter for the project's own deprecations. Make `Broadcast` a public class again, as in v1.13.0: rename `_Broadcast` back, decorate it with `@deprecated` and give it the guide's warning and a `Deprecated:` notice. `BroadcastChannel()` still doesn't warn, as it creates the channel inside `ignoring_deprecations()`. I tried a public subclass of `_Broadcast` with only the decorator, which leaves the implementation private. But then the channel inside a `BroadcastChannel` is not a `Broadcast`, so `isinstance()` and `ChannelClosedError[Broadcast[...]]` fail for it, unlike in v1. The renamed class keeps both working and matches v1, so the next forward merge has nothing to reconcile. The warning moves back from the import of `Broadcast` to its instantiation. The tests that use `Broadcast` on purpose ignore the warning with a module-level mark, and a new test checks its message. Signed-off-by: Leandro Lucarella --- src/frequenz/channels/__init__.py | 20 +---------- src/frequenz/channels/_broadcast.py | 38 ++++++++++++-------- tests/experimental/test_pipe.py | 3 ++ tests/test_broadcast.py | 19 ++++++---- tests/test_latest_value_cache_integration.py | 3 ++ tests/test_merge_integration.py | 3 ++ 6 files changed, 45 insertions(+), 41 deletions(-) diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index b8018723..09075fa0 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -102,11 +102,7 @@ generates a message after a given amount of time. """ -from typing import TYPE_CHECKING - -from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases - -from ._broadcast import BroadcastChannel, BroadcastReceiver, BroadcastSender +from ._broadcast import Broadcast, BroadcastChannel, BroadcastReceiver, BroadcastSender from ._exceptions import ChannelClosedError, ChannelError, Error from ._generic import ( ChannelMessageT, @@ -140,20 +136,6 @@ ) from ._with_previous import WithPrevious -if TYPE_CHECKING: - from ._broadcast import _Broadcast as Broadcast -else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias( - "Broadcast", - new_module="frequenz.channels._broadcast", - new_name="_Broadcast", - since="v1.12.0", - message="Please use BroadcastChannel instead.", - ), - ) - __all__ = [ "Broadcast", "BroadcastChannel", diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index f5ab70d7..fe3116b6 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -11,7 +11,8 @@ from collections import deque from typing import Generic, TypeVar -from typing_extensions import override +from frequenz.core.warnings import ignoring_deprecations +from typing_extensions import deprecated, override from ._exceptions import ChannelClosedError from ._generic import ChannelMessageT @@ -48,14 +49,18 @@ def _check_buffer_size(buffer_size: int) -> int: return buffer_size -class _Broadcast( # pylint: disable=too-many-instance-attributes +@deprecated( + "frequenz.channels.Broadcast is deprecated. " + "Use frequenz.channels.BroadcastChannel instead." +) +class Broadcast( # pylint: disable=too-many-instance-attributes Generic[ChannelMessageT] ): - """The implementation of broadcast channels. + """A channel that delivers all messages to all receivers. - Please use [`BroadcastChannel`][frequenz.channels.BroadcastChannel] instead of - using this class directly through the deprecated - [`Broadcast`][frequenz.channels.Broadcast] alias. + Deprecated: + Deprecated since v1.12.0. Use + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] instead. Senders and receivers are created with [`.new_sender()`][frequenz.channels.Broadcast.new_sender] and @@ -216,12 +221,12 @@ def new_receiver( def __str__(self) -> str: """Return a string representation of this channel.""" - return f"{type(self).__name__.removeprefix('_')}:{self._name}" + return f"{type(self).__name__}:{self._name}" def __repr__(self) -> str: """Return a string representation of this channel.""" return ( - f"{type(self).__name__.removeprefix('_')}(name={self._name!r}, " + f"{type(self).__name__}(name={self._name!r}, " f"resend_latest={self.resend_latest!r}):<" f"latest={self._latest!r}, " f"receivers={len(self._receivers)!r}, " @@ -240,13 +245,13 @@ class BroadcastSender(CloneableSubscribableSender[_T]): [`.clone()`][frequenz.channels.BroadcastSender.clone] method of an existing sender. """ - def __init__(self, channel: _Broadcast[_T], /) -> None: + def __init__(self, channel: Broadcast[_T], /) -> None: """Initialize this sender. Args: channel: A reference to the broadcast channel this sender belongs to. """ - self._channel: _Broadcast[_T] = channel + self._channel: Broadcast[_T] = channel """The broadcast channel this sender belongs to.""" self._closed: bool = False @@ -424,7 +429,7 @@ class BroadcastReceiver(Receiver[_T]): def __init__( self, - channel: _Broadcast[_T], + channel: Broadcast[_T], /, *, name: str | None, @@ -455,7 +460,7 @@ def __init__( Only used for debugging purposes. """ - self._channel: _Broadcast[_T] = channel + self._channel: Broadcast[_T] = channel """The broadcast channel that this receiver belongs to.""" self._q: deque[_T] = deque(maxlen=buffer_size) @@ -877,9 +882,12 @@ def __new__( # noqa: DOC502 (raised indirectly) Raises: ValueError: If the buffer size is smaller than 1. """ - channel = _Broadcast[ChannelMessageT]( - name=name, resend_latest=resend_latest, auto_close=True - ) + # Broadcast is deprecated, but it is an implementation detail of this + # class, so users shouldn't be warned about it. + with ignoring_deprecations(): + channel = Broadcast[ChannelMessageT]( + name=name, resend_latest=resend_latest, auto_close=True + ) # pylint: disable=protected-access channel._default_buffer_size = _check_buffer_size(buffer_size) channel._default_warn_on_overflow = warn_on_overflow diff --git a/tests/experimental/test_pipe.py b/tests/experimental/test_pipe.py index 0dab6a9e..494c1ff7 100644 --- a/tests/experimental/test_pipe.py +++ b/tests/experimental/test_pipe.py @@ -23,6 +23,9 @@ T = typing.TypeVar("T") +# These tests use the deprecated Broadcast on purpose. +pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") + class Timeout: """Sentinel for timeout.""" diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index d1bba559..adf58975 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -13,7 +13,6 @@ import pytest from frequenz.core.warnings import asserting_no_deprecations -from frequenz import channels from frequenz.channels import ( Broadcast, BroadcastChannel, @@ -29,6 +28,18 @@ selected_from, ) +# These tests use the deprecated Broadcast on purpose. +pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") + + +def test_broadcast_is_deprecated() -> None: + """Ensure `Broadcast` warns it is deprecated, and what to use instead.""" + with pytest.deprecated_call( + match=r"^frequenz\.channels\.Broadcast is deprecated\. " + r"Use frequenz\.channels\.BroadcastChannel instead\.$" + ): + _ = Broadcast[int](name="deprecation-test") + async def test_broadcast() -> None: """Ensure sent messages are received by all receivers.""" @@ -859,12 +870,6 @@ async def test_broadcast_channel_str() -> None: assert repr(sender).startswith("BroadcastSender(Broadcast(name='str-test'") -def test_broadcast_deprecated() -> None: - """Ensure reaching the `Broadcast` alias emits a deprecation warning.""" - with pytest.deprecated_call(match="Please use BroadcastChannel instead."): - _ = channels.Broadcast - - async def test_broadcast_channel_closed_error_holds_broadcast() -> None: """Ensure a closed `BroadcastChannel` reports a `Broadcast` in its error.""" sender, receiver = BroadcastChannel[int](name="closed-error-test") diff --git a/tests/test_latest_value_cache_integration.py b/tests/test_latest_value_cache_integration.py index 0c39b21e..28aa4cd5 100644 --- a/tests/test_latest_value_cache_integration.py +++ b/tests/test_latest_value_cache_integration.py @@ -9,6 +9,9 @@ from frequenz.channels import Broadcast, LatestValueCache +# These tests use the deprecated Broadcast on purpose. +pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") + @pytest.mark.integration async def test_latest_value_cache() -> None: diff --git a/tests/test_merge_integration.py b/tests/test_merge_integration.py index c7967832..7ed2a1c3 100644 --- a/tests/test_merge_integration.py +++ b/tests/test_merge_integration.py @@ -10,6 +10,9 @@ from frequenz.channels import Broadcast, BroadcastChannel, Sender, merge from frequenz.channels._receiver import ReceiverStoppedError +# These tests use the deprecated Broadcast on purpose. +pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") + @pytest.mark.integration async def test_merge() -> None: From 07d9f575e0c08aa2cb8c97cdb19e5b039cd9e7f9 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 13 Nov 2026 14:42:27 +0000 Subject: [PATCH 32/35] Drop the release notes entry about `Broadcast` The entry said `Broadcast` became an alias that warns on import. It is a deprecated class again and warns when a channel is created, exactly as in v1, so there is nothing to tell users about it. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 104245e9..80f627bb 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -48,8 +48,6 @@ - Call `BroadcastReceiver.close()` from the thread that runs the event loop of the channel's receivers. From another thread, tasks waiting on any receiver of the channel might not wake up. If asyncio debug mode is on and a task is waiting, `close()` also raises a `RuntimeError`, and the waiting tasks stay stuck. Use `loop.call_soon_threadsafe(receiver.close)` instead. -- `Broadcast` is now a deprecated alias of the class behind `BroadcastChannel`. The `DeprecationWarning` is now emitted when `Broadcast` is imported or accessed from `frequenz.channels`, including by `from frequenz.channels import *`, instead of each time a channel is created, and type checkers no longer report it as deprecated. Please use `BroadcastChannel` instead. - - `Receiver.close()` is now an abstract method, so a custom `Receiver` subclass that doesn't implement it can't be instantiated anymore. Before, calling it raised a `NotImplementedError`. All the receivers in this library implement it already. Add a `close()` method to your own receivers; the same implementation works on v1, so your code can support both major versions. ## New Features From 12ab64678f09b33413af772522619f813a7c1d9f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:47:57 +0000 Subject: [PATCH 33/35] build(deps-dev): Bump the minor group across 1 directory with 10 updates Bumps the minor group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [flake8](https://github.com/pycqa/flake8) | `7.4.1` | `7.5.0` | | [mkdocs-material](https://github.com/squidfunk/mkdocs-material) | `9.7.7` | `9.8.1` | | [griffe](https://github.com/mkdocstrings/griffe) | `2.3.0` | `2.4.1` | | [types-markdown](https://github.com/python/typeshed) | `3.10.2.20260712` | `3.11.3.20261108` | | [nox](https://github.com/wntrblm/nox) | `2026.8.17` | `2026.10.20` | | [pylint](https://github.com/pylint-dev/pylint) | `4.0.9` | `4.1.4` | | [hypothesis](https://github.com/HypothesisWorks/hypothesis) | `6.168.3` | `6.170.15` | | [pytest](https://github.com/pytest-dev/pytest) | `9.1.1` | `9.2.0` | | [pytest-mock](https://github.com/pytest-dev/pytest-mock) | `3.16.0` | `3.17.0` | | [setuptools](https://github.com/pypa/setuptools) | `84.1.0` | `84.2.1` | Updates `flake8` from 7.4.1 to 7.5.0 - [Commits](https://github.com/pycqa/flake8/compare/7.4.1...7.5.0) Updates `mkdocs-material` from 9.7.7 to 9.8.1 - [Release notes](https://github.com/squidfunk/mkdocs-material/releases) - [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG) - [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.7.7...9.8.1) Updates `griffe` from 2.3.0 to 2.4.1 - [Release notes](https://github.com/mkdocstrings/griffe/releases) - [Changelog](https://github.com/mkdocstrings/griffe/blob/main/CHANGELOG.md) - [Commits](https://github.com/mkdocstrings/griffe/compare/2.3.0...2.4.1) Updates `types-markdown` from 3.10.2.20260712 to 3.11.3.20261108 - [Commits](https://github.com/python/typeshed/commits) Updates `nox` from 2026.8.17 to 2026.10.20 - [Release notes](https://github.com/wntrblm/nox/releases) - [Changelog](https://github.com/wntrblm/nox/blob/main/CHANGELOG.md) - [Commits](https://github.com/wntrblm/nox/compare/2026.08.17...2026.10.20) Updates `pylint` from 4.0.9 to 4.1.4 - [Release notes](https://github.com/pylint-dev/pylint/releases) - [Commits](https://github.com/pylint-dev/pylint/compare/v4.0.9...v4.1.4) Updates `hypothesis` from 6.168.3 to 6.170.15 - [Release notes](https://github.com/HypothesisWorks/hypothesis/releases) - [Commits](https://github.com/HypothesisWorks/hypothesis/compare/v6.168.3...v6.170.15) Updates `pytest` from 9.1.1 to 9.2.0 - [Release notes](https://github.com/pytest-dev/pytest/releases) - [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/pytest/compare/9.1.1...9.2.0) Updates `pytest-mock` from 3.16.0 to 3.17.0 - [Release notes](https://github.com/pytest-dev/pytest-mock/releases) - [Changelog](https://github.com/pytest-dev/pytest-mock/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/pytest-mock/compare/v3.16.0...v3.17.0) Updates `setuptools` from 84.1.0 to 84.2.1 - [Release notes](https://github.com/pypa/setuptools/releases) - [Changelog](https://github.com/pypa/setuptools/blob/main/NEWS.rst) - [Commits](https://github.com/pypa/setuptools/compare/v84.1.0...v84.2.1) --- updated-dependencies: - dependency-name: flake8 dependency-version: 7.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: griffe dependency-version: 2.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: hypothesis dependency-version: 6.170.15 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: mkdocs-material dependency-version: 9.8.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: nox dependency-version: 2026.10.20 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: pylint dependency-version: 4.1.3 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: pytest dependency-version: 9.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: pytest-mock dependency-version: 3.17.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: setuptools dependency-version: 84.2.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor - dependency-name: types-markdown dependency-version: 3.11.3.20261108 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: minor ... Signed-off-by: dependabot[bot] --- pyproject.toml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index b44eac0a..4fd8ba8c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ [build-system] requires = [ - "setuptools == 84.1.0", + "setuptools == 84.2.1", "setuptools_scm[toml] == 10.3.4", "frequenz-repo-config[lib] == 0.19.0", ] @@ -38,7 +38,7 @@ email = "floss@frequenz.com" [project.optional-dependencies] dev-flake8 = [ - "flake8 == 7.4.1", + "flake8 == 7.5.0", "flake8-datetimez == 26.8.1", "flake8-docstrings == 1.7.0", "flake8-pyproject == 1.2.4", # For reading the flake8 config from pyproject.toml @@ -57,31 +57,31 @@ dev-mkdocs = [ "mkdocs-include-markdown-plugin == 7.3.0", "mkdocs-literate-nav == 0.6.3", "mkdocs-macros-plugin == 1.5.0", - "mkdocs-material == 9.7.7", + "mkdocs-material == 9.8.1", "mkdocstrings[python] == 1.0.8", "mkdocstrings-python == 2.0.10", "pymdownx-superfence-filter-lines == 0.1.0", - "griffe==2.3.0", + "griffe==2.4.1", ] dev-mypy = [ # For checking the noxfile, docs/ script, and tests "frequenz-channels[dev-mkdocs,dev-noxfile,dev-pytest]", "mypy == 2.4.1", - "types-Markdown == 3.10.2.20260712", + "types-Markdown == 3.11.3.20261108", ] -dev-noxfile = ["nox == 2026.8.17", "frequenz-repo-config[lib] == 0.19.0"] +dev-noxfile = ["nox == 2026.10.20", "frequenz-repo-config[lib] == 0.19.0"] dev-pylint = [ # For checking the noxfile, docs/ script, and tests "frequenz-channels[dev-mkdocs,dev-noxfile,dev-pytest]", - "pylint == 4.0.9", + "pylint == 4.1.4", ] dev-pytest = [ "async-solipsism == 0.10", "frequenz-repo-config[extra-lint-examples] == 0.19.0", - "hypothesis == 6.168.3", - "pytest == 9.1.1", + "hypothesis == 6.170.15", + "pytest == 9.2.0", "pytest-asyncio == 1.4.1", - "pytest-mock == 3.16.0", + "pytest-mock == 3.17.0", ] dev = [ "frequenz-channels[dev-mkdocs,dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]", From 40324b5310a6e5f40763b12aa94a3424846131df Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 20 Nov 2026 18:21:44 +0000 Subject: [PATCH 34/35] Bump pymdownx-superfence-filter-lines to 1.0.0 mkdocs-material 9.8.1 needs `pymdown-extensions >= 11.0.1`, but `pymdownx-superfence-filter-lines` 0.1.0 requires `< 11`, so the dependencies can't be resolved and both the docs build and nox fail. Version 1.0.0 supports `pymdown-extensions` 11 to 13, and its code hasn't changed since 0.1.0. Dependabot doesn't update it in the minor group, so it has to be bumped here. Signed-off-by: Leandro Lucarella --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 4fd8ba8c..c1a1c365 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,7 +60,7 @@ dev-mkdocs = [ "mkdocs-material == 9.8.1", "mkdocstrings[python] == 1.0.8", "mkdocstrings-python == 2.0.10", - "pymdownx-superfence-filter-lines == 0.1.0", + "pymdownx-superfence-filter-lines == 1.0.0", "griffe==2.4.1", ] dev-mypy = [ From 4a78e933add55f1bfaa3a952aa1df00f40d99e73 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 20 Nov 2026 18:28:04 +0000 Subject: [PATCH 35/35] Silence pylint's abstract-method warning in a receiver test pylint 4.1 reports W0223 (`abstract-method`) for `NoCloseReceiver`, because it doesn't implement the abstract `close()`. The test leaves it out on purpose, to check that such a receiver can't be instantiated, so disable the warning for that class. Signed-off-by: Leandro Lucarella --- tests/test_receiver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_receiver.py b/tests/test_receiver.py index 42b869cc..f224033b 100644 --- a/tests/test_receiver.py +++ b/tests/test_receiver.py @@ -11,7 +11,7 @@ def test_receiver_without_close_cannot_be_instantiated() -> None: """Test that a receiver subclass has to implement `close()`.""" - class NoCloseReceiver(Receiver[int]): + class NoCloseReceiver(Receiver[int]): # pylint: disable=abstract-method """A receiver that doesn't implement `close()`.""" async def ready(self) -> bool: