Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

## Upgrading

<!-- Here goes notes on how to upgrade from previous versions, including deprecations and what they should be replaced with -->
- `LatestValueCache` now closes the receiver when it is stopped.
- Fetching values from stopped `LatestValueCache` instances is now disallowed.

## New Features

Expand Down
14 changes: 11 additions & 3 deletions src/frequenz/channels/_latest_value_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ class LatestValueCache(typing.Generic[T_co]):

It provides a way to look up the latest value in a stream without any delay,
as long as there has been one value received.

Takes ownership of the receiver. When the cache is stopped, the receiver
will be closed.
Comment on lines +56 to +58
Copy link

Copilot AI Feb 16, 2026

Choose a reason for hiding this comment

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

Since this is a behavior/ownership change, consider also updating the module/package-level documentation for LatestValueCache (e.g., the module docstring and/or the entry in frequenz.channels.__init__ docs) so users reading the top-level docs learn that stop() closes the receiver.

Copilot uses AI. Check for mistakes.
"""

def __init__(
Expand All @@ -66,12 +69,13 @@ def __init__(
provided, a unique identifier will be generated from the object's
[`id()`][id]. It is used mostly for debugging purposes.
"""
self._receiver = receiver
self._receiver: Receiver[T_co] = receiver
self._unique_id: str = hex(id(self)) if unique_id is None else unique_id
self._latest_value: T_co | _Sentinel = _Sentinel()
self._task = asyncio.create_task(
self._task: asyncio.Task[None] = asyncio.create_task(
self._run(), name=f"LatestValueCache«{self._unique_id}»"
)
self._stopped: bool = False

@property
def unique_id(self) -> str:
Expand All @@ -93,6 +97,8 @@ def get(self) -> T_co:
"""
if isinstance(self._latest_value, _Sentinel):
raise ValueError("No value has been received yet.")
if self._stopped:
raise ValueError("Cache has been stopped.")
return self._latest_value

def has_value(self) -> bool:
Expand All @@ -108,7 +114,9 @@ async def _run(self) -> None:
self._latest_value = value

async def stop(self) -> None:
"""Stop the cache."""
"""Stop the cache and close the owned receiver."""
self._receiver.close()
self._stopped = True
if not self._task.done():
self._task.cancel()
try:
Expand Down
Loading