diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 6315f985b..3e439dddc 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -14,6 +14,8 @@ - `SourceProperties` has a new `dropped_samples` field, with the number of samples the resampler dropped because its buffer was full. +- `SourceProperties` has new `total_windows_without_samples` and `current_windows_without_samples` fields, with the number of resampling windows without relevant samples in total and in the current gap in the data. They tell how healthy a timeseries is, and whether it is in a gap right now. The windows before the first sample was received are counted too. + ## Bug Fixes @@ -23,3 +25,5 @@ - `initial_buffer_len` is the number of samples to receive before estimating the input sampling period. - `warn_buffer_len` logs a warning, once per timeseries, when a buffer holds more samples than this after removing old ones. - `max_buffer_len` logs an error, once per timeseries, when samples needed to resample may have been dropped because the buffer was full. + +- The resampler no longer logs a warning at every resampling while a timeseries has no relevant samples. It logs it once when the samples stop, and logs when they are back, with the number of windows without them. diff --git a/src/frequenz/sdk/timeseries/_resampling/_base_types.py b/src/frequenz/sdk/timeseries/_resampling/_base_types.py index 46f02e181..decc4e4a1 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_base_types.py +++ b/src/frequenz/sdk/timeseries/_resampling/_base_types.py @@ -63,3 +63,21 @@ class SourceProperties: It is updated when resampling, so it doesn't include the samples dropped since the last resampling. """ + + total_windows_without_samples: int = 0 + """The number of resampling windows that had no relevant samples. + + The resampled value of these windows is `None`. The windows before the first + sample was received are counted too. It is updated when resampling. + """ + + current_windows_without_samples: int = 0 + """The number of resampling windows without relevant samples in the current gap. + + It is `0` when the last resampled window had relevant samples, so it tells + whether the timeseries currently has a gap in its data, and for how long. It + is updated when resampling. + + Resampling functions are only called for windows with relevant samples, so + they always see `0` here. + """ diff --git a/src/frequenz/sdk/timeseries/_resampling/_buffer.py b/src/frequenz/sdk/timeseries/_resampling/_buffer.py new file mode 100644 index 000000000..f75a4071e --- /dev/null +++ b/src/frequenz/sdk/timeseries/_resampling/_buffer.py @@ -0,0 +1,214 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""The buffer holding the samples of a timeseries until they are resampled.""" + +import itertools +import logging +from bisect import bisect, bisect_left +from collections import deque +from datetime import datetime +from typing import assert_never + +from ._base_types import SourceProperties +from ._config import WindowSide + +_logger = logging.getLogger(__name__) + + +class _ResamplingBuffer: + """The buffer holding the samples of a timeseries until they are resampled. + + The buffer can't hold more than `max_len` samples: when it is full, the oldest + sample is dropped when a new one is added. Otherwise, old samples are only + removed when asked to, while advancing to the next resampling window. + + It keeps the number of received and dropped samples, the windows without + relevant samples, and the time of the first sample, up to date in the + source properties. It logs when relevant samples may have been dropped or + when it holds more than `warn_len` samples, and when it has no relevant + samples, once per gap in the data. + """ + + def __init__( + self, + name: str, + *, + max_len: int, + warn_len: int, + source_properties: SourceProperties, + ) -> None: + """Initialize an instance. + + Args: + name: The name of the timeseries (for logging purposes). + max_len: The maximum number of samples the buffer can hold. + warn_len: The number of samples above which a warning is logged. + source_properties: The properties of the timeseries to keep up to date. + """ + self._name = name + self._samples: deque[tuple[datetime, float]] = deque(maxlen=max_len) + self._warn_len = warn_len + self._source_properties = source_properties + self._removed_samples = 0 + """The number of samples removed because they were too old.""" + self._logged_dropped = False + """Whether dropping relevant samples was already logged.""" + self._logged_too_big = False + """Whether the buffer holding more than `warn_len` was already logged.""" + + def __len__(self) -> int: + """Return the number of samples in the buffer. + + Returns: + The number of samples in the buffer. + """ + return len(self._samples) + + def add(self, sample: tuple[datetime, float]) -> None: + """Add a new sample to the buffer. + + Args: + sample: The sample to add. + """ + self._samples.append(sample) + if self._source_properties.sampling_start is None: + self._source_properties.sampling_start = sample[0] + self._source_properties.received_samples += 1 + + def advance_window( + self, + start: datetime, + end: datetime, + closed: WindowSide, + *, + remove_older: bool, + ) -> list[tuple[datetime, float]]: + """Advance to the next resampling window and return its relevant samples. + + It must be called once for each resampled window, as it also updates the + dropped samples and the windows without relevant samples in the source + properties, logs the problems it finds, and removes the samples before + the relevant ones when asked to. + + Args: + start: The start of the period of the relevant samples. + end: The end of the period of the relevant samples. + closed: Which side of the period between `start` and `end` includes + the samples exactly at its edge. + remove_older: Whether to remove the samples before the relevant ones + from the buffer. + + Returns: + The relevant samples, oldest first. + """ + match closed: + case WindowSide.LEFT: + bisect_func = bisect_left + case WindowSide.RIGHT: + bisect_func = bisect + case unexpected: + assert_never(unexpected) + + min_index = bisect_func(self._samples, start, key=lambda s: s[0]) + max_index = bisect_func(self._samples, end, key=lambda s: s[0]) + + # Dropped samples are counted here, as counting them when adding samples + # would slow down adding samples, which must be as fast as possible. + self._update_dropped_samples(min_index) + + # Using itertools for slicing doesn't look very efficient, but + # experiments with a custom (ring) buffer that can slice showed that + # it is not that bad. See: + # https://github.com/frequenz-floss/frequenz-sdk-python/pull/130 + # So if we need more performance beyond this point, we probably need to + # resort to some C (or similar) implementation. + relevant_samples = list(itertools.islice(self._samples, min_index, max_index)) + # Missing samples are logged once per gap in the data, not for each window. + props = self._source_properties + if not relevant_samples: + props.total_windows_without_samples += 1 + props.current_windows_without_samples += 1 + if props.current_windows_without_samples == 1: + self._log_no_relevant_samples(start, end) + elif props.current_windows_without_samples: + _logger.info( + "Relevant samples found for timeseries %s after %s windows " + "without them", + self._name, + props.current_windows_without_samples, + ) + props.current_windows_without_samples = 0 + + if remove_older: + for _ in range(min_index): + self._samples.popleft() + self._removed_samples += min_index + self._log_too_big() + + return relevant_samples + + def _update_dropped_samples(self, min_index: int) -> None: + """Update the number of dropped samples, logging once if needed ones may be. + + Args: + min_index: The index of the oldest relevant sample in the buffer. + """ + props = self._source_properties + dropped = props.received_samples - self._removed_samples - len(self._samples) + new_drops = dropped > props.dropped_samples + props.dropped_samples = dropped + # Dropped samples are older than the oldest one in the buffer, so they can + # only be needed if the oldest one in the buffer is not older than the + # relevant ones. Their timestamps are not kept, so they may also be older + # than the relevant ones. + if self._logged_dropped or not new_drops or min_index > 0: + return + self._logged_dropped = True + _logger.error( + "The buffer for timeseries %s is full (max_buffer_len=%s), so samples " + "needed for resampling may have been dropped. Use a bigger " + "max_buffer_len.", + self._name, + self._samples.maxlen, + ) + + def _log_too_big(self) -> None: + """Log, once, if the buffer holds more than `warn_len` samples.""" + if self._logged_too_big or len(self._samples) <= self._warn_len: + return + self._logged_too_big = True + _logger.warning( + "The buffer for timeseries %s holds %s samples, more than " + "warn_buffer_len (%s)", + self._name, + len(self._samples), + self._warn_len, + ) + + def _log_no_relevant_samples(self, start: datetime, end: datetime) -> None: + """Log that no relevant samples were found. + + Args: + start: The start of the period of the relevant samples. + end: The end of the period of the relevant samples. + """ + if not _logger.isEnabledFor(logging.WARNING): + return + + if self._samples: + buffer_info = ( + f"{self._samples[0][0]} to {self._samples[-1][0]}, " + f"{len(self._samples)} samples" + ) + else: + buffer_info = "empty" + + _logger.warning( + "No relevant samples found for timeseries %s between %s and %s " + "(buffer: %s)", + self._name, + start, + end, + buffer_info, + ) diff --git a/src/frequenz/sdk/timeseries/_resampling/_resampler.py b/src/frequenz/sdk/timeseries/_resampling/_resampler.py index 17f0f0dd2..b21ad3a58 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_resampler.py +++ b/src/frequenz/sdk/timeseries/_resampling/_resampler.py @@ -6,10 +6,8 @@ from __future__ import annotations import asyncio -import itertools import logging -from bisect import bisect, bisect_left -from collections import deque +from collections.abc import Callable from datetime import datetime, timedelta, timezone from typing import assert_never @@ -19,6 +17,7 @@ from ..._internal._asyncio import cancel_and_await from .._base_types import Sample from ._base_types import Sink, Source, SourceProperties +from ._buffer import _ResamplingBuffer from ._config import ResamplerConfig, ResamplerConfig2, WindowSide from ._exceptions import ResamplingError, SourceStoppedError from ._wall_clock_timer import TickInfo, WallClockTimer @@ -276,9 +275,7 @@ class _ResamplingHelper: Once the input period is known, older samples are removed from the buffer when resampling, as they won't be relevant for any later window either. Before that, the look-back can still grow when the input period is - estimated, so samples are kept. In any case, the buffer can't hold more than - `max_buffer_len` samples: when it is full, the oldest sample is dropped when - a new one is added. + estimated, so samples are kept. """ def __init__(self, name: str, config: ResamplerConfig) -> None: @@ -290,16 +287,17 @@ def __init__(self, name: str, config: ResamplerConfig) -> None: """ self._name = name self._config = config - self._buffer: deque[tuple[datetime, float]] = deque( - maxlen=config.max_buffer_len - ) self._source_properties: SourceProperties = SourceProperties() - self._removed_samples = 0 - """The number of samples removed because they were too old.""" - self._logged_dropped = False - """Whether dropping relevant samples was already logged.""" - self._logged_too_big = False - """Whether the buffer holding more than `warn_buffer_len` was already logged.""" + self._buffer = _ResamplingBuffer( + name, + max_len=config.max_buffer_len, + warn_len=config.warn_buffer_len, + source_properties=self._source_properties, + ) + # The buffer's method is used directly, as adding samples must be as fast + # as possible. + self.add_sample: Callable[[tuple[datetime, float]], None] = self._buffer.add + """Add a new sample to the buffer.""" @property def source_properties(self) -> SourceProperties: @@ -310,17 +308,6 @@ def source_properties(self) -> SourceProperties: """ return self._source_properties - def add_sample(self, sample: tuple[datetime, float]) -> None: - """Add a new sample to the internal buffer. - - Args: - sample: The sample to be added to the buffer. - """ - self._buffer.append(sample) - if self._source_properties.sampling_start is None: - self._source_properties.sampling_start = sample[0] - self._source_properties.received_samples += 1 - def _update_source_sample_period(self, now: datetime) -> bool: """Update the source sample period. @@ -388,44 +375,15 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: ) minimum_relevant_timestamp = timestamp - period * conf.max_data_age_in_periods - match conf.closed: - case WindowSide.LEFT: - bisect_func = bisect_left - case WindowSide.RIGHT: - bisect_func = bisect - case unexpected: - assert_never(unexpected) - - min_index = bisect_func( - self._buffer, - minimum_relevant_timestamp, - key=lambda s: s[0], - ) - - max_index = bisect_func(self._buffer, timestamp, key=lambda s: s[0]) - - # Dropped samples are counted here, as counting them when adding samples - # would slow down adding samples, which must be as fast as possible. - self._update_dropped_samples(min_index) - - # Using itertools for slicing doesn't look very efficient, but - # experiments with a custom (ring) buffer that can slice showed that - # it is not that bad. See: - # https://github.com/frequenz-floss/frequenz-sdk-python/pull/130 - # So if we need more performance beyond this point, we probably need to - # resort to some C (or similar) implementation. - relevant_samples = list(itertools.islice(self._buffer, min_index, max_index)) - if not relevant_samples: - self._log_no_relevant_samples(minimum_relevant_timestamp, timestamp) - # Samples older than the relevant ones won't be relevant for later windows # either, unless the input period is still unknown, as the look-back can # grow when it is estimated. - if props.sampling_period is not None: - for _ in range(min_index): - self._buffer.popleft() - self._removed_samples += min_index - self._log_buffer_too_big() + relevant_samples = self._buffer.advance_window( + minimum_relevant_timestamp, + timestamp, + conf.closed, + remove_older=props.sampling_period is not None, + ) value = ( conf.resampling_function(relevant_samples, conf, props) @@ -443,72 +401,6 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: return Sample(timestamp, None if value is None else Quantity(value)) - def _update_dropped_samples(self, min_index: int) -> None: - """Update the number of dropped samples, logging once if needed ones may be. - - Args: - min_index: The index of the oldest relevant sample in the buffer. - """ - props = self._source_properties - dropped = props.received_samples - self._removed_samples - len(self._buffer) - new_drops = dropped > props.dropped_samples - props.dropped_samples = dropped - # Dropped samples are older than the oldest one in the buffer, so they can - # only be needed if the oldest one in the buffer is not older than the - # relevant ones. Their timestamps are not kept, so they may also be older - # than the relevant ones. - if self._logged_dropped or not new_drops or min_index > 0: - return - self._logged_dropped = True - _logger.error( - "The buffer for timeseries %s is full (max_buffer_len=%s), so samples " - "needed for resampling may have been dropped. Use a bigger " - "max_buffer_len.", - self._name, - self._config.max_buffer_len, - ) - - def _log_buffer_too_big(self) -> None: - """Log, once, if the buffer holds more than `warn_buffer_len` samples.""" - if self._logged_too_big or len(self._buffer) <= self._config.warn_buffer_len: - return - self._logged_too_big = True - _logger.warning( - "The buffer for timeseries %s holds %s samples, more than " - "warn_buffer_len (%s)", - self._name, - len(self._buffer), - self._config.warn_buffer_len, - ) - - def _log_no_relevant_samples( - self, minimum_relevant_timestamp: datetime, timestamp: datetime - ) -> None: - """Log that no relevant samples were found. - - Args: - minimum_relevant_timestamp: Minimum timestamp that was requested - timestamp: Timestamp that was requested - """ - if not _logger.isEnabledFor(logging.WARNING): - return - - if self._buffer: - buffer_info = ( - f"{self._buffer[0][0]} - " - f"{self._buffer[-1][0]} ({len(self._buffer)} samples)" - ) - else: - buffer_info = "Empty" - - _logger.warning( - "No relevant samples found for: %s\n Requested: %s - %s\n Buffer: %s", - self._name, - minimum_relevant_timestamp, - timestamp, - buffer_info, - ) - class _StreamingHelper: """Resample data coming from a source, sending the results to a sink.""" diff --git a/tests/timeseries/_resampling/test_buffer.py b/tests/timeseries/_resampling/test_buffer.py new file mode 100644 index 000000000..a8962c3b5 --- /dev/null +++ b/tests/timeseries/_resampling/test_buffer.py @@ -0,0 +1,244 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for the resampling buffer.""" + +import logging +from datetime import datetime, timedelta, timezone + +import pytest + +from frequenz.sdk.timeseries import SourceProperties, WindowSide +from frequenz.sdk.timeseries._resampling._buffer import _ResamplingBuffer + +_LOGGER_NAME = "frequenz.sdk.timeseries._resampling._buffer" +_START = datetime(2020, 1, 1, tzinfo=timezone.utc) + + +def _at(seconds: float) -> datetime: + """Return the timestamp `seconds` after the start of the tests.""" + return _START + timedelta(seconds=seconds) + + +def _make_buffer( + *, max_len: int = 16, warn_len: int = 8 +) -> tuple[_ResamplingBuffer, SourceProperties]: + """Return a buffer and the source properties it keeps up to date.""" + props = SourceProperties() + buffer = _ResamplingBuffer( + "test", max_len=max_len, warn_len=warn_len, source_properties=props + ) + return buffer, props + + +def _logs(caplog: pytest.LogCaptureFixture, level: int) -> list[str]: + """Return the messages the buffer logged with the given level.""" + return [ + message + for name, record_level, message in caplog.record_tuples + if name == _LOGGER_NAME and record_level == level + ] + + +def test_add_updates_source_properties() -> None: + """Test adding samples updates the start time and the received samples.""" + buffer, props = _make_buffer() + + buffer.add((_at(1), 1.0)) + buffer.add((_at(2), 2.0)) + + assert len(buffer) == 2 + assert props.sampling_start == _at(1) + assert props.received_samples == 2 + + +@pytest.mark.parametrize( + "closed, expected", + [ + (WindowSide.LEFT, [(_at(1), 1.0), (_at(2), 2.0)]), + (WindowSide.RIGHT, [(_at(2), 2.0), (_at(3), 3.0)]), + ], +) +def test_advance_window_closed_side( + closed: WindowSide, expected: list[tuple[datetime, float]] +) -> None: + """Test the closed side decides whether samples at the edges are relevant.""" + buffer, _ = _make_buffer() + for seconds in range(5): + buffer.add((_at(seconds), float(seconds))) + + assert buffer.advance_window(_at(1), _at(3), closed, remove_older=False) == expected + + +@pytest.mark.parametrize("remove_older", [True, False]) +def test_advance_window_removes_older_samples(remove_older: bool) -> None: + """Test older samples are only removed when asked, and are not counted as dropped.""" + buffer, props = _make_buffer() + for seconds in range(5): + buffer.add((_at(seconds), float(seconds))) + + relevant = buffer.advance_window( + _at(2), _at(4), WindowSide.LEFT, remove_older=remove_older + ) + + assert relevant == [(_at(2), 2.0), (_at(3), 3.0)] + assert len(buffer) == (3 if remove_older else 5) + assert props.dropped_samples == 0 + + # Removed samples must not be counted as dropped later either + _ = buffer.advance_window(_at(2), _at(4), WindowSide.LEFT, remove_older=False) + assert props.dropped_samples == 0 + + +def test_dropped_samples_are_counted_when_advancing_window() -> None: + """Test samples dropped because the buffer is full are counted later.""" + buffer, props = _make_buffer(max_len=2, warn_len=1) + + for seconds in (0.25, 0.5, 0.75): + buffer.add((_at(seconds), seconds)) + assert props.dropped_samples == 0 + + _ = buffer.advance_window(_at(0), _at(1), WindowSide.LEFT, remove_older=False) + assert props.dropped_samples == 1 + + +def test_dropping_samples_that_may_be_relevant_is_logged_once( + caplog: pytest.LogCaptureFixture, +) -> None: + """Test dropping samples that may be relevant is logged once. + + The timestamps of dropped samples are not kept, so they may be relevant when + the oldest sample in the buffer is. + """ + buffer, props = _make_buffer(max_len=4, warn_len=2) + + for seconds in range(5): + buffer.add((_at(seconds), float(seconds))) + relevant = buffer.advance_window(_at(0), _at(5), WindowSide.LEFT, remove_older=True) + assert relevant == [(_at(s), float(s)) for s in range(1, 5)] + + buffer.add((_at(5), 5.0)) + _ = buffer.advance_window(_at(0), _at(6), WindowSide.LEFT, remove_older=True) + + assert props.dropped_samples == 2 + assert _logs(caplog, logging.ERROR) == [ + "The buffer for timeseries test is full (max_buffer_len=4), so samples " + "needed for resampling may have been dropped. Use a bigger max_buffer_len." + ] + + +@pytest.mark.parametrize("closed", [WindowSide.LEFT, WindowSide.RIGHT]) +def test_dropping_old_samples_is_not_logged( + closed: WindowSide, caplog: pytest.LogCaptureFixture +) -> None: + """Test dropping samples older than a buffered irrelevant one is not an error.""" + buffer, props = _make_buffer(max_len=3, warn_len=1) + + for seconds in (0.25, 0.5): + buffer.add((_at(seconds), seconds)) + _ = buffer.advance_window(_at(0), _at(1), closed, remove_older=True) + + # The buffer is full, so these push out the sample at 0.25, but the one at + # 0.5 is still in the buffer, and it is not relevant anymore + for seconds in (1.25, 1.5): + buffer.add((_at(seconds), seconds)) + relevant = buffer.advance_window(_at(1), _at(2), closed, remove_older=True) + + assert relevant == [(_at(1.25), 1.25), (_at(1.5), 1.5)] + assert props.dropped_samples == 1 + assert not _logs(caplog, logging.ERROR) + + +def test_bigger_than_warn_len_is_logged_once_after_removing_older_samples( + caplog: pytest.LogCaptureFixture, +) -> None: + """Test a buffer holding more than `warn_len` samples is logged once. + + It is only checked after removing older samples, as before that the buffer + can hold samples that are not relevant anymore. + """ + buffer, _ = _make_buffer(max_len=32, warn_len=4) + + for i in range(10): + buffer.add((_at(i / 10), 1.0)) + _ = buffer.advance_window(_at(0), _at(1), WindowSide.LEFT, remove_older=False) + assert not _logs(caplog, logging.WARNING) + + for window in range(1, 3): + for i in range(10): + buffer.add((_at(window + i / 10), 1.0)) + _ = buffer.advance_window( + _at(window), _at(window + 1), WindowSide.LEFT, remove_older=True + ) + + assert _logs(caplog, logging.WARNING) == [ + "The buffer for timeseries test holds 10 samples, more than " + "warn_buffer_len (4)" + ] + + +def test_no_relevant_samples_is_logged_in_one_line( + caplog: pytest.LogCaptureFixture, +) -> None: + """Test the warning about missing relevant samples is a single line.""" + buffer, _ = _make_buffer() + _ = buffer.advance_window(_at(0), _at(1), WindowSide.LEFT, remove_older=False) + + buffer, _ = _make_buffer() + buffer.add((_at(2), 2.0)) + buffer.add((_at(3), 3.0)) + _ = buffer.advance_window(_at(0), _at(1), WindowSide.LEFT, remove_older=False) + + assert _logs(caplog, logging.WARNING) == [ + f"No relevant samples found for timeseries test between {_at(0)} and " + f"{_at(1)} (buffer: empty)", + f"No relevant samples found for timeseries test between {_at(0)} and " + f"{_at(1)} (buffer: {_at(2)} to {_at(3)}, 2 samples)", + ] + + +def test_no_relevant_samples_is_logged_once_per_gap( + caplog: pytest.LogCaptureFixture, +) -> None: + """Test missing relevant samples are logged at the start and end of each gap.""" + caplog.set_level(logging.INFO, logger=_LOGGER_NAME) + buffer, props = _make_buffer() + + def resample(window: int) -> None: + _ = buffer.advance_window( + _at(window), _at(window + 1), WindowSide.LEFT, remove_older=True + ) + + resample(0) + resample(1) + assert props.total_windows_without_samples == 2 + assert props.current_windows_without_samples == 2 + buffer.add((_at(2.5), 2.5)) + resample(2) + assert props.total_windows_without_samples == 2 + assert props.current_windows_without_samples == 0 + resample(3) + assert props.total_windows_without_samples == 3 + assert props.current_windows_without_samples == 1 + + assert [ + (level, message) + for name, level, message in caplog.record_tuples + if name == _LOGGER_NAME + ] == [ + ( + logging.WARNING, + f"No relevant samples found for timeseries test between {_at(0)} and " + f"{_at(1)} (buffer: empty)", + ), + ( + logging.INFO, + "Relevant samples found for timeseries test after 2 windows without " + "them", + ), + ( + logging.WARNING, + f"No relevant samples found for timeseries test between {_at(3)} and " + f"{_at(4)} (buffer: {_at(2.5)} to {_at(2.5)}, 1 samples)", + ), + ] diff --git a/tests/timeseries/test_resampling.py b/tests/timeseries/test_resampling.py index a0fcbfbd8..133ac6c2c 100644 --- a/tests/timeseries/test_resampling.py +++ b/tests/timeseries/test_resampling.py @@ -212,7 +212,7 @@ async def test_helper_buffer_too_big( # Ignore errors produced by wrongly finalized gRPC server in unrelated tests assert _filter_logs(caplog.record_tuples, logger_level=logging.ERROR) == [ ( - "frequenz.sdk.timeseries._resampling._resampler", + "frequenz.sdk.timeseries._resampling._buffer", logging.ERROR, "The buffer for timeseries test is full " f"(max_buffer_len={DEFAULT_BUFFER_LEN_MAX}), so samples needed for " @@ -224,39 +224,6 @@ async def test_helper_buffer_too_big( assert len(helper._buffer) == DEFAULT_BUFFER_LEN_MAX -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) -@pytest.mark.parametrize("closed", [WindowSide.LEFT, WindowSide.RIGHT]) -async def test_helper_full_buffer_dropping_old_samples_is_not_logged( - config_class: type[ResamplerConfig], - closed: WindowSide, - caplog: pytest.LogCaptureFixture, -) -> None: - """Test dropping samples older than a buffered irrelevant one is not an error.""" - config = config_class( - resampling_period=timedelta(seconds=1), - max_data_age_in_periods=1, - closed=closed, - initial_buffer_len=1, - warn_buffer_len=1, - max_buffer_len=3, - ) - helper = _ResamplingHelper("test", config) - start = datetime(2020, 1, 1, tzinfo=timezone.utc) - - for seconds in (0.25, 0.5): - helper.add_sample((start + timedelta(seconds=seconds), seconds)) - assert helper.resample(start + timedelta(seconds=1)).value == Quantity(0.375) - - # The buffer is full, so these push out the sample at 0.25, but the one at - # 0.5 is still in the buffer, and it is not relevant anymore - for seconds in (1.25, 1.5): - helper.add_sample((start + timedelta(seconds=seconds), seconds)) - assert helper.resample(start + timedelta(seconds=2)).value == Quantity(1.375) - - assert helper.source_properties.dropped_samples == 1 - assert not _filter_logs(caplog.record_tuples, logger_level=logging.ERROR) - - @pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) async def test_helper_buffer_bigger_than_warn_len_is_logged_once( config_class: type[ResamplerConfig], @@ -280,7 +247,7 @@ async def test_helper_buffer_bigger_than_warn_len_is_logged_once( assert _filter_logs(caplog.record_tuples, logger_level=logging.WARNING) == [ ( - "frequenz.sdk.timeseries._resampling._resampler", + "frequenz.sdk.timeseries._resampling._buffer", logging.WARNING, "The buffer for timeseries test holds 10 samples, more than " "warn_buffer_len (4)", @@ -352,28 +319,6 @@ async def test_helper_first_window_uses_all_its_samples( assert helper.source_properties.dropped_samples == 0 -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) -async def test_helper_counts_dropped_samples_when_resampling( - config_class: type[ResamplerConfig], -) -> None: - """Test samples dropped because the buffer is full are counted when resampling.""" - config = config_class( - resampling_period=timedelta(seconds=1), - initial_buffer_len=2, - warn_buffer_len=1, - max_buffer_len=2, - ) - helper = _ResamplingHelper("test", config) - start = datetime(2020, 1, 1, tzinfo=timezone.utc) - - for seconds in (0.25, 0.5, 0.75): - helper.add_sample((start + timedelta(seconds=seconds), seconds)) - assert helper.source_properties.dropped_samples == 0 - - _ = helper.resample(start + timedelta(seconds=1)) - assert helper.source_properties.dropped_samples == 1 - - # Tick-delay test fixtures: time constants @pytest.fixture def window_end() -> datetime: @@ -1250,6 +1195,8 @@ async def test_resampling_with_one_window( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), + total_windows_without_samples=3, + current_windows_without_samples=3, ) assert _get_buffered_samples(resampler, source_receiver) == 0 @@ -1431,6 +1378,8 @@ async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-ma sampling_start=timestamp, received_samples=7, sampling_period=timedelta(seconds=6 / 7), + total_windows_without_samples=3, + current_windows_without_samples=3, ) assert _get_buffered_samples(resampler, source_receiver) == 0 @@ -1613,7 +1562,11 @@ async def test_resampling_with_two_windows( # pylint: disable=too-many-statemen current_iteration=5, ) assert source_props == SourceProperties( - sampling_start=timestamp, received_samples=7, sampling_period=None + sampling_start=timestamp, + received_samples=7, + sampling_period=None, + total_windows_without_samples=3, + current_windows_without_samples=3, ) assert _get_buffered_samples(resampler, source_receiver) == 7 @@ -1999,6 +1952,8 @@ async def test_resampling_all_zeros( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), + total_windows_without_samples=3, + current_windows_without_samples=3, ) assert _get_buffered_samples(resampler, source_receiver) == 0 @@ -2179,14 +2134,21 @@ def _get_buffered_samples(resampler: Resampler, source_receiver: Source) -> int: return len(resampler._resamplers[source_receiver]._helper._buffer) +_RESAMPLER_LOGGERS = ( + "frequenz.sdk.timeseries._resampling._resampler", + "frequenz.sdk.timeseries._resampling._buffer", +) + + def _filter_logs( record_tuples: list[tuple[str, int, str]], *, - logger_name: str = "frequenz.sdk.timeseries._resampling._resampler", + logger_name: str | None = None, logger_level: int | None = None, ) -> list[tuple[str, int, str]]: + names = _RESAMPLER_LOGGERS if logger_name is None else (logger_name,) return [ t for t in record_tuples - if t[0] == logger_name and (logger_level is None or logger_level == t[1]) + if t[0] in names and (logger_level is None or logger_level == t[1]) ]