From 7a9421a6e38877bf0ed37571913e1d4548b4517e Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Mon, 16 Nov 2026 13:27:31 +0000 Subject: [PATCH 1/4] Add `TransientSenderError` `SenderError` doesn't tell a caller whether the sender can still be used. Code that keeps sending, like the new `Pipe` in the next commit, 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, no sender in this library raises it yet, but custom senders can, and the `Pipe` handles it. The class and its docstring are the ones that `v2.x.x` already has, so the next merge of `v1.x.x` into `v2.x.x` doesn't conflict on them. 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 c263124b..e357ab45 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -60,6 +60,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. + * [`ReceiverError`][frequenz.channels.ReceiverError]: Base class for all errors related to receivers. @@ -115,6 +118,7 @@ SenderClosedError, SenderError, SubscribableSender, + TransientSenderError, ) from ._with_previous import WithPrevious @@ -150,6 +154,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 8a5a4445..2a18ceea 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 SubscribableSender(Sender[SenderMessageT_contra], ABC): """A [`Sender`][frequenz.channels.Sender] that can be subscribed to.""" 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 226ffc2603c64d30702798b89df6b4a96f560d83 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Mon, 16 Nov 2026 13:29:03 +0000 Subject: [PATCH 2/4] Add the new `Pipe` to `frequenz.channels` `frequenz.channels.experimental.Pipe` leaves its sender and its receiver open when it stops by itself, and a failed send ends its task with an exception nobody reads. Changing that in place would silently change what existing users get, so the new behavior goes in a new top-level `Pipe`, and the experimental one stays as it is. The new `Pipe` closes its sender when its receiver stops. When sending fails with a `TransientSenderError`, the sender and its channel can still be used, so it logs a warning, drops the message and keeps forwarding. Any other `SenderError` is logged with its traceback, and the pipe closes both ends and stops, unless `close_pipe_on_send_error=False`, which drops the message and keeps going. Its docstring says who owns and closes each end. The class is the one already in `v2.x.x`, without its handling of `SenderHasNoReceiversError`, which only exists in v2, so the next merge of `v1.x.x` into `v2.x.x` conflicts as little as possible. The docstring explains what that means in v1: a send without receivers closes a `BroadcastChannel` and raises a `SenderError`, so the pipe stops and closes its ends by default, while a `Broadcast` with the default `auto_close=False` just drops the message and the pipe keeps going. The tests are the ones of `v2.x.x`, with new ones for the v1 cases above, and the class has a page in the user guide. Signed-off-by: Leandro Lucarella --- docs/user-guide/utilities/pipes.md | 10 + src/frequenz/channels/__init__.py | 5 + src/frequenz/channels/_pipe.py | 176 +++++++++++ tests/test_pipe.py | 461 +++++++++++++++++++++++++++++ 4 files changed, 652 insertions(+) create mode 100644 docs/user-guide/utilities/pipes.md create mode 100644 src/frequenz/channels/_pipe.py create mode 100644 tests/test_pipe.py diff --git a/docs/user-guide/utilities/pipes.md b/docs/user-guide/utilities/pipes.md new file mode 100644 index 00000000..2fedd24d --- /dev/null +++ b/docs/user-guide/utilities/pipes.md @@ -0,0 +1,10 @@ +# Pipes + +::: frequenz.channels._pipe.Pipe + options: + inherited_members: [] + members: [] + show_bases: false + show_root_heading: false + show_root_toc_entry: false + show_source: false diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index e357ab45..ed91aca5 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -43,6 +43,9 @@ * [`NopReceiver`][frequenz.channels.NopReceiver]: A place-holder receiver that never receives a message. +* [`Pipe`][frequenz.channels.Pipe]: Forwards all the messages from a receiver to + a sender. + * [`WithPrevious`][frequenz.channels.WithPrevious]: A composable predicate to filter messages based on the previous message received. @@ -103,6 +106,7 @@ from ._merge import Merger, merge from ._nop_receiver import NopReceiver from ._oneshot import OneshotChannel, OneshotReceiver, OneshotSender +from ._pipe import Pipe from ._receiver import Receiver, ReceiverError, ReceiverStoppedError from ._select import ( Selected, @@ -142,6 +146,7 @@ "OneshotChannel", "OneshotReceiver", "OneshotSender", + "Pipe", "Receiver", "ReceiverError", "ReceiverMessageT_co", diff --git a/src/frequenz/channels/_pipe.py b/src/frequenz/channels/_pipe.py new file mode 100644 index 00000000..fbe05022 --- /dev/null +++ b/src/frequenz/channels/_pipe.py @@ -0,0 +1,176 @@ +# License: MIT +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH + +"""Pipe between a receiver and a sender. + +The [`Pipe`][frequenz.channels.Pipe] class takes a receiver and a sender and creates a +pipe between them by forwarding all the messages received by the receiver to the +sender. +""" + +from __future__ import annotations + +import asyncio +import logging +import typing + +from ._generic import ChannelMessageT +from ._receiver import Receiver +from ._sender import Sender, SenderError, TransientSenderError + +_logger = logging.getLogger(__name__) + + +class Pipe(typing.Generic[ChannelMessageT]): + """A pipe between two channels. + + The [`Pipe`][frequenz.channels.Pipe] class takes a receiver and a 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 + [`TransientSenderError`][frequenz.channels.TransientSenderError], the pipe logs it + as a warning, drops the message and keeps sending the messages that follow, as the + sender and its channel can still be used. + + If sending fails with any other [`SenderError`][frequenz.channels.SenderError], the + pipe logs it with its traceback, 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. That option has no effect on a + [`TransientSenderError`][frequenz.channels.TransientSenderError], as the pipe never + stops for it. + + Note: + A [`BroadcastChannel`][frequenz.channels.BroadcastChannel] closes itself when a + message is sent to it while it has no receivers, and that send raises a + [`SenderError`][frequenz.channels.SenderError]. So when the pipe's sender + belongs to a [`BroadcastChannel`][frequenz.channels.BroadcastChannel] without + receivers, the pipe stops and, by default, closes both its ends. With + `close_pipe_on_send_error=False` the pipe keeps running, but it drops every + message, as the channel is closed for good. A + [`Broadcast`][frequenz.channels.Broadcast] created with the default + `auto_close=False` doesn't close itself: it drops the message and the pipe keeps + sending the messages that follow. + + [`stop()`][frequenz.channels.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. + + In any other case than the ones above where the pipe closes them, whoever created + the sender and the receiver is still responsible for closing them. 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 + from contextlib import closing, AsyncExitStack + + from frequenz.channels import BroadcastChannel, Pipe + + async def main() -> None: + # Senders, receivers and Pipe are in AsyncExitStack + # to close and stop them at the end. + async with AsyncExitStack() as stack: + source_sender, source_receiver = BroadcastChannel[int]( + name="source channel" + ) + stack.push_async_callback(source_sender.aclose) + stack.enter_context(closing(source_receiver)) + + forwarding_sender, receiver = BroadcastChannel[int]( + name="forwarding channel" + ) + stack.push_async_callback(forwarding_sender.aclose) + stack.enter_context(closing(receiver)) + + await stack.enter_async_context(Pipe(source_receiver, forwarding_sender)) + + await source_sender.send(10) + assert await receiver.receive() == 10 + + asyncio.run(main()) + ``` + """ + + def __init__( + 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`][frequenz.channels.SenderError] from sending that isn't + a [`TransientSenderError`][frequenz.channels.TransientSenderError] + 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]: + """Enter the runtime context.""" + await self.start() + return self + + async def __aexit__( + self, + _exc_type: typing.Type[BaseException] | None, + _exc: BaseException | None, + _tb: typing.Any, + ) -> None: + """Exit the runtime context.""" + await self.stop() + + async def start(self) -> None: + """Start this pipe if it is not already running.""" + if not self._task or self._task.done(): + self._task = asyncio.create_task(self._run()) + + async def stop(self) -> None: + """Stop this pipe.""" + if self._task and not self._task.done(): + self._task.cancel() + try: + await self._task + except asyncio.CancelledError: + pass + + async def _run(self) -> None: + outcome = "stopped" if self._close_pipe_on_send_error else "dropped a message" + async for value in self._receiver: + try: + await self._sender.send(value) + except TransientSenderError as error: + _logger.warning( + "Pipe from [%s] to [%s] dropped a message: %s", + self._receiver, + self._sender, + error, + ) + except SenderError: + _logger.exception( + "Pipe from [%s] to [%s] %s: sending failed", + self._receiver, + self._sender, + outcome, + ) + if not self._close_pipe_on_send_error: + continue + try: + await self._sender.aclose() + finally: + self._receiver.close() + return + await self._sender.aclose() diff --git a/tests/test_pipe.py b/tests/test_pipe.py new file mode 100644 index 00000000..6e04c0a0 --- /dev/null +++ b/tests/test_pipe.py @@ -0,0 +1,461 @@ +# License: MIT +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH + +"""Tests for the Pipe class.""" + +import asyncio +import logging +import typing +from contextlib import AsyncExitStack, closing + +import pytest +from frequenz.core.warnings import asserting_no_deprecations + +from frequenz.channels import ( + Broadcast, + BroadcastChannel, + BroadcastSender, + Pipe, + Receiver, + Sender, + SenderClosedError, + SenderError, + TransientSenderError, +) + +T = typing.TypeVar("T") + + +class Timeout: + """Sentinel for timeout.""" + + +async def receive_timeout(recv: Receiver[T], timeout: float = 0.1) -> T | type[Timeout]: + """Receive message from receiver with timeout.""" + try: + return await asyncio.wait_for(recv.receive(), timeout=timeout) + except asyncio.TimeoutError: + 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) + + +def receiver_count(sender: BroadcastSender[int]) -> int: + """Return how many open receivers the channel of a broadcast sender has.""" + return len(sender._channel._receivers) # pylint: disable=protected-access + + +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") + + +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 + + +class BusySender(Sender[int]): + """A sender that fails with a `TransientSenderError` for the first messages.""" + + def __init__(self, busy_messages: int) -> None: + """Initialize this sender. + + Args: + busy_messages: How many messages to reject. + """ + self.busy_messages = busy_messages + self.sent: list[int] = [] + self.closed = False + + async def send(self, message: int, /) -> None: + """Reject the first messages and keep the rest.""" + if self.busy_messages > 0: + self.busy_messages -= 1 + raise TransientSenderError("Busy", self) + self.sent.append(message) + + async def aclose(self) -> None: + """Remember that this sender was closed.""" + self.closed = True + + +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") + + +def test_pipe_does_not_warn() -> None: + """Ensure creating a pipe doesn't emit a deprecation warning.""" + _, source_receiver = BroadcastChannel[int](name="source") + sender, _ = BroadcastChannel[int](name="forwarding") + with asserting_no_deprecations(): + Pipe(source_receiver, sender) + + +async def test_pipe() -> None: + """Test pipe.""" + sender_chan1, receiver_chan1 = BroadcastChannel[int](name="channel1") + sender_chan2, receiver_chan2 = BroadcastChannel[int](name="channel2") + + async with Pipe(sender_chan2.subscribe(), sender_chan1.clone()): + await sender_chan2.send(42) + assert await receive_timeout(receiver_chan1) == 42 + assert await receive_timeout(receiver_chan2) == 42 + + await sender_chan2.send(-2) + assert await receive_timeout(receiver_chan1) == -2 + assert await receive_timeout(receiver_chan2) == -2 + + await sender_chan1.send(43) + assert await receive_timeout(receiver_chan1) == 43 + assert await receive_timeout(receiver_chan2) is Timeout + + await sender_chan2.send(5) + assert await receive_timeout(receiver_chan1) == 5 + assert await receive_timeout(receiver_chan2) == 5 + + await sender_chan2.send(5) + assert await receive_timeout(receiver_chan1) is Timeout + assert await receive_timeout(receiver_chan2) == 5 + + +async def test_pipe_with_async_exit_stack() -> None: + """Test how pipe should work with async exit stack.""" + # Senders, receivers and Pipe are in AsyncExitStack + # to close and stop them at the end. + async with AsyncExitStack() as stack: + source_sender, source_receiver = BroadcastChannel[int](name="source channel") + stack.push_async_callback(source_sender.aclose) + stack.enter_context(closing(source_receiver)) + + forwarding_sender, receiver = BroadcastChannel[int](name="forwarding channel") + stack.push_async_callback(forwarding_sender.aclose) + stack.enter_context(closing(receiver)) + + await stack.enter_async_context(Pipe(source_receiver, forwarding_sender)) + + await source_sender.send(10) + assert await receiver.receive() == 10 + + +async def test_pipe_stops_when_broadcast_channel_has_no_receivers( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure a pipe stops when sending closes a `BroadcastChannel` without receivers. + + In v1, a `BroadcastChannel` closes itself when a message is sent to it while it has + no receivers, and that send raises a `SenderError`, so the pipe closes its ends. + + Args: + caplog: The fixture to capture log records. + """ + 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 caplog.at_level(logging.WARNING, logger="frequenz.channels"): + await source_sender.send(1) + await wait_stopped(pipe) + + assert receiver_count(source_sender) == 0 + with pytest.raises(SenderClosedError): + await sender.send(2) + 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], SenderError) + assert not isinstance(exc_info[1], TransientSenderError) + + +async def test_pipe_drops_messages_when_broadcast_channel_has_no_receivers( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure a pipe that doesn't close on send errors drops every message. + + The `BroadcastChannel` is closed by the first send without receivers, so the pipe + can't deliver anything afterwards, even to receivers created later. + + Args: + caplog: The fixture to capture log records. + """ + 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.WARNING, logger="frequenz.channels"): + await source_sender.send(1) + await asyncio.sleep(0) + await source_sender.send(2) + await asyncio.sleep(0) + + assert receiver_count(source_sender) == 1 + assert [(r.levelno, r.exc_info is not None) for r in caplog.records] == [ + (logging.ERROR, True), + (logging.ERROR, True), + ] + assert "dropped a message" in caplog.records[0].getMessage() + with pytest.raises(SenderError): + sender.subscribe() + await pipe.stop() + + +@pytest.mark.filterwarnings("once::DeprecationWarning") +@pytest.mark.parametrize("close_pipe_on_send_error", [True, False]) +async def test_pipe_keeps_sending_with_broadcast_without_receivers( + close_pipe_on_send_error: bool, +) -> None: + """Ensure a pipe keeps going when a `Broadcast` without receivers drops a message. + + A `Broadcast` doesn't close itself by default, so sending without receivers drops + the message and doesn't fail. + + Args: + close_pipe_on_send_error: The pipe's `close_pipe_on_send_error` argument. + """ + source_sender, source_receiver = BroadcastChannel[int](name="source") + channel = Broadcast[int](name="forwarding") + + pipe = Pipe( + source_receiver, + channel.new_sender(), + close_pipe_on_send_error=close_pipe_on_send_error, + ) + await pipe.start() + await source_sender.send(1) + await asyncio.sleep(0) + + receiver = channel.new_receiver() + await source_sender.send(2) + assert await receive_timeout(receiver) == 2 + + assert receiver_count(source_sender) == 1 + await pipe.stop() + + +@pytest.mark.parametrize("close_pipe_on_send_error", [True, False]) +async def test_pipe_keeps_sending_after_transient_error( + close_pipe_on_send_error: bool, caplog: pytest.LogCaptureFixture +) -> None: + """Ensure a pipe drops the message that failed with a `TransientSenderError`. + + Args: + close_pipe_on_send_error: The pipe's `close_pipe_on_send_error` argument. + caplog: The fixture to capture log records. + """ + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender = BusySender(busy_messages=2) + + pipe = Pipe( + source_receiver, sender, close_pipe_on_send_error=close_pipe_on_send_error + ) + await pipe.start() + with caplog.at_level(logging.DEBUG, logger="frequenz.channels"): + for message in (1, 2, 3, 4): + await source_sender.send(message) + await asyncio.sleep(0) + + assert sender.sent == [3, 4] + assert not sender.closed + assert receiver_count(source_sender) == 1 + assert [(r.levelno, r.exc_info) for r in caplog.records] == [ + (logging.WARNING, None), + (logging.WARNING, None), + ] + assert "dropped a message" in caplog.records[0].getMessage() + assert "Busy" in caplog.records[0].getMessage() + await pipe.stop() + + +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() + await sender.aclose() + + pipe = Pipe(source_receiver, sender) + await pipe.start() + with caplog.at_level(logging.WARNING, logger="frequenz.channels"): + await source_sender.send(1) + await wait_stopped(pipe) + + assert receiver_count(source_sender) == 0 + with pytest.raises(SenderClosedError): + await sender.send(2) + 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) + + +@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. + + Args: + close_pipe_on_send_error: The pipe's `close_pipe_on_send_error` argument. + """ + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + 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 + + await source_sender.aclose() + await wait_stopped(pipe) + + with pytest.raises(SenderClosedError): + await sender.send(2) + assert sender.sender_count == 0 + + +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 receiver_count(source_sender) == 1 + await sender.send(2) + assert await receive_timeout(receiver) == 2 + + +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 receiver_count(source_sender) == 1 + assert not sender.closed + + +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"): + await source_sender.send(1) + await asyncio.sleep(0) + await source_sender.send(2) + await asyncio.sleep(0) + + assert receiver_count(source_sender) == 1 + assert [r.levelno for r in caplog.records] == [logging.ERROR, logging.ERROR] + assert "dropped a message" in caplog.records[0].getMessage() + await pipe.stop() + + +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() + await sender.aclose() + + 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) + + +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 receiver_count(source_sender) == 0 From 45eb5a9489d61109cb3e9d965c060e7b0e0f9dad Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Mon, 16 Nov 2026 13:44:06 +0000 Subject: [PATCH 3/4] Deprecate `experimental.Pipe` The new top-level `Pipe` replaces `frequenz.channels.experimental.Pipe`, so deprecate the experimental one in v1.13.0, and remove it in v3.0.0. It is not an alias of the new `Pipe`, as the two don't behave the same and an alias would change the behavior of existing code. The v1 implementation stays as it is, so code that still uses it keeps working, and code that has to support both v1 and v2 can use the new `Pipe`. The new `Pipe` closes its sender when its receiver stops, and both ends when sending fails, while the old one leaves them open. Users should check how they close their ends before they switch, so the warning says so, and not only which class to use. The notice has a short version, and the docstring body lists the differences, as the deprecations guide asks. The class, its warning and its docstring are the ones of `v2.x.x`, except for the version in the notice and the parts about `SenderHasNoReceiversError`, which doesn't exist in v1, so the next merge of `v1.x.x` into `v2.x.x` conflicts as little as possible. The tests check that the old `Pipe` keeps its behavior and warns. In v1 a send without receivers closes a `BroadcastChannel` and raises a plain `SenderError`, which still ends the task of the old `Pipe`. The tests and the docstring example use `BroadcastChannel` instead of the deprecated `Broadcast`. Signed-off-by: Leandro Lucarella --- src/frequenz/channels/experimental/_pipe.py | 59 +++++-- tests/experimental/test_pipe.py | 163 ++++++++++++++++---- 2 files changed, 183 insertions(+), 39 deletions(-) diff --git a/src/frequenz/channels/experimental/_pipe.py b/src/frequenz/channels/experimental/_pipe.py index 3c4ceea1..a13d7e4a 100644 --- a/src/frequenz/channels/experimental/_pipe.py +++ b/src/frequenz/channels/experimental/_pipe.py @@ -13,45 +13,78 @@ import asyncio import typing +from typing_extensions import deprecated + from .._generic import ChannelMessageT from .._receiver import Receiver from .._sender import Sender +@deprecated( + "frequenz.channels.experimental.Pipe is deprecated and will be removed in v3.0.0. " + "Use frequenz.channels.Pipe instead, but check how your code closes its sender and " + "receiver first: the new one closes its sender when its receiver stops, and both " + "ends when sending fails, while this one leaves them open." +) class Pipe(typing.Generic[ChannelMessageT]): """A pipe between two channels. + Deprecated: + Deprecated since v1.13.0, and will be removed in v3.0.0. Use + [`frequenz.channels.Pipe`][] instead, after checking how your code closes the + sender and the receiver: the new class closes them in cases where this one + leaves them open, and drops messages that fail with a + [`TransientSenderError`][frequenz.channels.TransientSenderError]. + The [`Pipe`][frequenz.channels.experimental.Pipe] class takes a receiver and a sender and creates a pipe between them by forwarding all the messages received by the receiver to the sender. + [`frequenz.channels.Pipe`][] is a separate implementation that treats its endpoints + differently, so moving to it can change how your code shuts down: + + * When its receiver stops, this pipe stops and leaves its sender open. + [`frequenz.channels.Pipe`][] closes its sender too. + * When sending fails with any [`SenderError`][frequenz.channels.SenderError], the + exception ends the task of this pipe and both ends stay open. + [`frequenz.channels.Pipe`][] logs the error and closes its sender and its + receiver by default, unless it is a + [`TransientSenderError`][frequenz.channels.TransientSenderError]: then it logs + it, drops the message and keeps forwarding. + * [`frequenz.channels.Pipe`][] also takes `close_pipe_on_send_error=False`, which + drops the message that failed with any other + [`SenderError`][frequenz.channels.SenderError] and keeps forwarding the next + ones. This doesn't bring back the behavior of this class, which stops on the + first send error. + * [`stop()`][frequenz.channels.experimental.Pipe.stop] leaves both ends open in + both. + 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/tests/experimental/test_pipe.py b/tests/experimental/test_pipe.py index 8d4fcea7..69248d49 100644 --- a/tests/experimental/test_pipe.py +++ b/tests/experimental/test_pipe.py @@ -1,21 +1,32 @@ # License: MIT # Copyright © 2024 Frequenz Energy-as-a-Service GmbH -"""Tests for the Pipe class.""" +"""Tests for the deprecated experimental Pipe class.""" import asyncio import typing -from contextlib import AsyncExitStack, aclosing, closing +from contextlib import AsyncExitStack, closing import pytest -from frequenz.channels import Broadcast, Receiver +from frequenz.channels import ( + BroadcastChannel, + Receiver, + Sender, + SenderError, +) from frequenz.channels.experimental import Pipe T = typing.TypeVar("T") -# These tests use the deprecated Broadcast on purpose. -pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") +DEPRECATION_MESSAGE = "frequenz.channels.experimental.Pipe is deprecated" +"""The start of the deprecation message, which the pytest filter matches.""" + + +def make_pipe(receiver: Receiver[T], sender: Sender[T]) -> Pipe[T]: + """Create a deprecated pipe, checking that it warns.""" + with pytest.deprecated_call(match=DEPRECATION_MESSAGE): + return Pipe(receiver, sender) class Timeout: @@ -30,17 +41,35 @@ 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_deprecation_message() -> None: + """Ensure the warning says what to use instead and what changes.""" + sender, receiver = BroadcastChannel[int](name="channel") + with pytest.deprecated_call() as record: + Pipe(receiver, sender) + + message = str(record[0].message) + assert message.startswith( + "frequenz.channels.experimental.Pipe is deprecated and will be removed in " + "v3.0.0. Use frequenz.channels.Pipe instead, " + ) + assert "closes its sender when its receiver stops" in message + assert "both ends when sending fails" in message + assert "this one leaves them open" in message + + async def test_pipe() -> None: """Test pipe.""" - channel1: Broadcast[int] = Broadcast(name="channel1") - channel2: Broadcast[int] = Broadcast(name="channel2") - - sender_chan1 = channel1.new_sender() - sender_chan2 = channel2.new_sender() - receiver_chan1 = channel1.new_receiver() - receiver_chan2 = channel2.new_receiver() + sender_chan1, receiver_chan1 = BroadcastChannel[int](name="channel1") + sender_chan2, receiver_chan2 = BroadcastChannel[int](name="channel2") - async with Pipe(channel2.new_receiver(), channel1.new_sender()): + async with make_pipe(sender_chan2.subscribe(), sender_chan1.clone()): await sender_chan2.send(42) assert await receive_timeout(receiver_chan1) == 42 assert await receive_timeout(receiver_chan2) == 42 @@ -64,23 +93,105 @@ async def test_pipe() -> None: async def test_pipe_with_async_exit_stack() -> None: """Test how pipe should work with async exit stack.""" - # 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_receiver = stack.enter_context(closing(source_channel.new_receiver())) + source_sender, source_receiver = BroadcastChannel[int](name="source channel") + 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(make_pipe(source_receiver, forwarding_sender)) - source_sender = source_channel.new_sender() await source_sender.send(10) assert await receiver.receive() == 10 + + +async def test_pipe_leaves_sender_open_when_receiver_stops() -> None: + """Ensure the deprecated pipe stops, but leaves its sender open.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + pipe = make_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) + + await sender.send(2) + assert await receive_timeout(receiver) == 2 + + +class FailingSender(Sender[int]): + """A sender whose sends fail with a `SenderError`.""" + + def __init__(self) -> None: + """Initialize this sender.""" + self.closed = False + + async def send(self, message: int, /) -> None: + """Fail to send.""" + raise SenderError("Sending failed", self) + + async def aclose(self) -> None: + """Remember that this sender was closed.""" + self.closed = True + + +async def test_pipe_leaves_both_ends_open_when_sending_fails() -> None: + """Ensure the deprecated pipe lets a send error end its task and closes nothing.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender = FailingSender() + + pipe = make_pipe(source_receiver, sender) + await pipe.start() + await source_sender.send(1) + with pytest.raises(SenderError, match="Sending failed"): + await wait_stopped(pipe) + + assert not sender.closed + # The receiver is still open: the source channel still accepts messages. + await source_sender.send(2) + assert await receive_timeout(source_receiver) == 2 + + +async def test_pipe_stops_when_sending_without_receivers() -> None: + """Ensure a send without receivers ends the task of the deprecated pipe. + + In v1, sending to a `BroadcastChannel` without receivers closes it and raises a + `SenderError`. The new `Pipe` closes its ends and stops instead. + """ + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + receiver.close() + + pipe = make_pipe(source_receiver, sender) + await pipe.start() + await source_sender.send(1) + with pytest.raises(SenderError): + await wait_stopped(pipe) + + # The pipe doesn't close its receiver: the source channel still accepts messages. + await source_sender.send(2) + assert await receive_timeout(source_receiver) == 2 + + +async def test_pipe_stop_leaves_both_ends_open() -> None: + """Ensure stopping the deprecated pipe leaves its sender and receiver open.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + pipe = make_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 From b78f947497f7c20739f0be61c757de48634a3291 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Mon, 16 Nov 2026 13:29:28 +0000 Subject: [PATCH 4/4] Update the release notes for the new `Pipe` Add a migration entry for the deprecation of `frequenz.channels.experimental.Pipe`, which says what to use instead and lists how the two pipes close their ends differently, with the wording of its deprecation warning. Add New Features entries for `Pipe` and `TransientSenderError`, which also say what a send without receivers does in v1 and in v2.0.0. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 0b99e77c..33157e83 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -24,6 +24,16 @@ This will probably be the last minor release of v1. It deprecates everything tha - `frequenz.channels.experimental.OptionalReceiver` will be removed in v2.0.0. Its deprecation warning now points at `frequenz.channels.NopReceiver`: use the receiver itself, or a `NopReceiver` when there is none. +- `frequenz.channels.experimental.Pipe` is deprecated and will be removed in v3.0.0. Its behavior is unchanged. Use the new `frequenz.channels.Pipe` instead, but check how your code closes the sender and the receiver of the pipe first, as the two behave differently: + + - When its receiver stops, the new `Pipe` closes its sender. The experimental one stops and leaves the sender open. + - When sending fails with a `SenderError` that isn't a `TransientSenderError`, the new `Pipe` logs the error and closes both its sender and its receiver by default. The experimental one lets the exception end its task and leaves both open. + - When sending fails with a `TransientSenderError`, the new `Pipe` logs a warning, drops the message and keeps forwarding. The experimental one lets the exception end its task. + - With `close_pipe_on_send_error=False`, the new `Pipe` also drops the message that failed with any other `SenderError` and keeps forwarding the next ones. This doesn't bring back the behavior of the experimental one. + - `stop()` leaves both ends open in both. + + The deprecation warning says so too: `frequenz.channels.experimental.Pipe is deprecated and will be removed in v3.0.0. Use frequenz.channels.Pipe instead, but check how your code closes its sender and receiver first: the new one closes its sender when its receiver stops, and both ends when sending fails, while this one leaves them open.` + - `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, as its deprecation warning says. 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. @@ -37,6 +47,12 @@ This will probably be the last minor release of v1. It deprecates everything tha - `NopReceiver` and `WithPrevious` are now stable, and available from `frequenz.channels`. +- `Pipe` is now available in `frequenz.channels`. It forwards all the messages from a receiver to a sender, like `frequenz.channels.experimental.Pipe`, but it also closes its ends: when its receiver stops it closes its sender, and when sending fails with a `SenderError` that isn't a `TransientSenderError` it closes its sender and its receiver, unless you pass `close_pipe_on_send_error=False`, in which case it drops the message and keeps going. When sending fails with a `TransientSenderError`, it logs a warning, drops the message and keeps forwarding, whatever `close_pipe_on_send_error` says. See the `Pipe` documentation for what the pipe leaves open and who has to close it. + + A send to a `BroadcastChannel` without receivers closes the channel and raises a plain `SenderError` in v1, so a `Pipe` sending to one stops and closes its ends by default. A `Broadcast` created with the default `auto_close=False` drops the message instead, and the pipe keeps going. In v2.0.0, a `BroadcastChannel` without receivers stays open, so the pipe keeps going too. + +- `TransientSenderError` is a new `SenderError` for errors after which the sender and its channel can still be used: only that message wasn't sent. No sender in this library raises it yet, but `Pipe` already handles it, and custom senders can raise it. + ## 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.