Skip to content

Commit

Permalink
Store a reference to the engine in receiver objects (#478)
Browse files Browse the repository at this point in the history
This PR fixes a bug which occurs when creating and using a higher order
formula engine, without holding a reference to it.
  • Loading branch information
shsms authored Jul 4, 2023
2 parents 89bde34 + d6ae901 commit 1b7053e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 2 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,5 @@ New `Quantity` types! These types can have units (power, current, voltage, etc.)
- Two bugs in the ring buffer which is used by the `MovingWindow` class were fixed:
- `len(buffer)` was not considering potentially existing gaps (areas without elements) in the buffer.
- A off-by-one error in the gap calculation logic was fixed that recorded a gap when there was none if an element with a future timestamp was added that would create a gap of exactly 1.

- A formula engine lifetime issue, when creating higher order formula receivers without holding on to a reference to the engine, was fixed.
14 changes: 13 additions & 1 deletion src/frequenz/sdk/timeseries/_formula_engine/_formula_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,19 @@ def new_receiver(
if self._task is None:
self._task = asyncio.create_task(self._run())

return self._channel.new_receiver(name, max_size)
recv = self._channel.new_receiver(name, max_size)

# This is a hack to ensure that the lifetime of the engine is tied to the
# lifetime of the receiver. This is necessary because the engine is a task that
# runs forever, and in cases where higher order built for example with the below
# idiom, the user would hold no references to the engine and it could get
# garbage collected before the receiver. This behaviour is explained in the
# `asyncio.create_task` docs here:
# https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
#
# formula = (grid_power_engine + bat_power_engine).build().new_receiver()
recv._engine_reference = self # type: ignore # pylint: disable=protected-access
return recv


class FormulaEngine3Phase(
Expand Down

0 comments on commit 1b7053e

Please sign in to comment.