From ecd18882af4e676820ad4b8ac1e78190f82c9023 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 27 Nov 2026 08:48:57 +0000 Subject: [PATCH 1/2] Count the samples dropped by the resampling buffer The resampling buffer drops its oldest sample when a new one arrives and it is full, and nothing tells users that samples were lost. SourceProperties now has a dropped_samples field with the number of samples dropped this way. It is calculated when resampling, as the received samples minus the ones in the buffer, because counting in add_sample() would slow down adding samples, which must be as fast as possible. For now, the buffer is sized to hold only the relevant samples, so dropping is also how old samples are removed and this counts them too. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 2 ++ .../sdk/timeseries/_resampling/_base_types.py | 7 +++++ .../sdk/timeseries/_resampling/_resampler.py | 1 + tests/timeseries/test_resampling.py | 28 +++++++++++++++++++ 4 files changed, 38 insertions(+) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 61ee6f2ad..acb4a1c90 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -12,6 +12,8 @@ +- `SourceProperties` has a new `dropped_samples` field, with the number of samples the resampler dropped because its buffer was full. + ## Bug Fixes diff --git a/src/frequenz/sdk/timeseries/_resampling/_base_types.py b/src/frequenz/sdk/timeseries/_resampling/_base_types.py index ac7791098..46f02e181 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_base_types.py +++ b/src/frequenz/sdk/timeseries/_resampling/_base_types.py @@ -56,3 +56,10 @@ class SourceProperties: `None` means it is unknown. """ + + dropped_samples: int = 0 + """The number of samples dropped because the resampling buffer was full. + + It is updated when resampling, so it doesn't include the samples dropped + since the last resampling. + """ diff --git a/src/frequenz/sdk/timeseries/_resampling/_resampler.py b/src/frequenz/sdk/timeseries/_resampling/_resampler.py index d0d150df6..b0c6e7583 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_resampler.py +++ b/src/frequenz/sdk/timeseries/_resampling/_resampler.py @@ -430,6 +430,7 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: conf = self._config props = self._source_properties + props.dropped_samples = props.received_samples - len(self._buffer) # To see which samples are relevant we need to consider if we are down # or upsampling. diff --git a/tests/timeseries/test_resampling.py b/tests/timeseries/test_resampling.py index bbcecb887..179455873 100644 --- a/tests/timeseries/test_resampling.py +++ b/tests/timeseries/test_resampling.py @@ -218,6 +218,28 @@ async def test_helper_buffer_too_big( assert helper._buffer.maxlen == DEFAULT_BUFFER_LEN_MAX +@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: @@ -1073,6 +1095,7 @@ async def test_resampling_with_one_window( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), + dropped_samples=2, ) # The buffer should be able to hold 2 seconds of data, and data is coming # every 0.8 seconds, so we should be able to store 3 samples. @@ -1093,6 +1116,7 @@ async def test_resampling_with_one_window( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), + dropped_samples=2, ) assert _get_buffer_len(resampler, source_receiver) == 3 @@ -1234,6 +1258,7 @@ 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), + dropped_samples=3, ) # The buffer should be able to hold 2 * 1.5 (3) seconds of data, and data # is coming every 6/7 seconds (~0.857s), so we should be able to store @@ -1275,6 +1300,7 @@ 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), + dropped_samples=3, ) assert _get_buffer_len(resampler, source_receiver) == 4 @@ -1823,6 +1849,7 @@ async def test_resampling_all_zeros( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), + dropped_samples=2, ) # The buffer should be able to hold 2 seconds of data, and data is coming # every 0.8 seconds, so we should be able to store 3 samples. @@ -1843,6 +1870,7 @@ async def test_resampling_all_zeros( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), + dropped_samples=2, ) assert _get_buffer_len(resampler, source_receiver) == 3 From b7132cee4ddb34792ff83b2da12b5358eb074447 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 15:56:07 +0000 Subject: [PATCH 2/2] Remove old resampling samples by time instead of by count The resampling buffer was a deque with a maximum length calculated from the resampling period, the input period and max_data_age_in_periods, so every new sample pushed out the oldest one, even if it was still needed. This dropped samples in two cases: - Before the input period was estimated, the buffer had initial_buffer_len slots, so the first windows after a start were resampled from only the last initial_buffer_len samples (#1471). - A sample of the next window arriving after a tick, but before the window of that tick was resampled (because of tick_delay or a late wakeup), pushed out a sample of that window. Now the buffer can hold max_buffer_len samples, and samples older than the relevant ones are removed when resampling, as they won't be relevant for later windows either. Until the input period is estimated, the look-back can still grow, so samples are only removed once it is known. Making the buffer bigger to cover the second case was not an option: a whole extra period would double the buffer of a 15-minute window, and anything smaller would be a guess. This changes what the buffer settings mean: initial_buffer_len is now the number of samples to receive before estimating the input period, warn_buffer_len warns when a buffer holds more samples than that after removing old ones, and max_buffer_len logs an error when samples needed to resample may have been dropped. Both messages are logged once per timeseries. SourceProperties.dropped_samples now leaves out the samples removed because they were too old, so it only counts the samples dropped because the buffer held max_buffer_len samples. That counter is also how the resampler finds out that samples were dropped, as checking when adding samples made adding them about 50% slower. The timestamps of dropped samples are not kept, so the resampler can't know whether they were needed. It logs the error when new samples were dropped and the oldest sample in the buffer is not older than the relevant ones, as then the dropped samples can be relevant too. Guessing their timestamps from the input period would be wrong with irregular samples, both missing real losses and reporting harmless ones as certain. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 6 + .../sdk/timeseries/_resampling/_config.py | 83 ++++--- .../sdk/timeseries/_resampling/_resampler.py | 141 ++++++----- tests/timeseries/test_resampling.py | 230 ++++++++++++++---- 4 files changed, 298 insertions(+), 162 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index acb4a1c90..6315f985b 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -17,3 +17,9 @@ ## Bug Fixes + +- The resampler no longer drops samples a window needs before its buffer holds `max_buffer_len` samples. This happened to the first windows after a start, which were resampled using only the last `initial_buffer_len` samples ([#1471](https://github.com/frequenz-floss/frequenz-sdk-python/issues/1471)), and to any window when a sample of the next window arrived before the window was resampled, for example because of `tick_delay`. Old samples are now removed when resampling, so the buffer only drops samples when it is full. Until the input sampling period is estimated, old samples are not removed, so the buffer can grow up to `max_buffer_len` samples. Because of this, these settings mean something slightly different now: + + - `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. diff --git a/src/frequenz/sdk/timeseries/_resampling/_config.py b/src/frequenz/sdk/timeseries/_resampling/_config.py index b420a55ee..0b1cca300 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_config.py +++ b/src/frequenz/sdk/timeseries/_resampling/_config.py @@ -22,26 +22,19 @@ DEFAULT_BUFFER_LEN_INIT = 16 -"""Default initial buffer length. - -Buffers will be created initially with this length, but they could grow or -shrink depending on the source properties, like sampling rate, to make -sure all the requested past sampling periods can be stored. +"""Default number of samples to receive before estimating the input sampling period. """ DEFAULT_BUFFER_LEN_MAX = 1024 -"""Default maximum allowed buffer length. +"""Default maximum number of samples a buffer can hold. -If a buffer length would get bigger than this, it will be truncated to this -length. +When a buffer is full, the oldest sample is dropped when a new one is added. """ DEFAULT_BUFFER_LEN_WARN = 128 -"""Default minimum buffer length that will produce a warning. - -If a buffer length would get bigger than this, a warning will be logged. +"""Default number of samples above which a buffer logs a warning. """ @@ -161,33 +154,41 @@ class ResamplerConfig: """ initial_buffer_len: int = DEFAULT_BUFFER_LEN_INIT - """The initial length of the resampling buffer. + """The number of samples to receive before estimating the input sampling period. + + The input sampling period is estimated once, at the first resampling after + receiving enough samples, and decides how old the relevant samples can be + when upsampling (see `max_data_age_in_periods`). Until it is known, samples + are not removed from the resampling buffer, except when it is full. - The buffer could grow or shrink depending on the source properties, - like sampling rate, to make sure all the requested past sampling periods - can be stored. + The number of received samples must also be at least the number of seconds + in `max_data_age_in_periods` resampling periods. For example, with a + resampling period of 60 seconds and a `max_data_age_in_periods` of 3, the + input sampling period is estimated after receiving at least 180 samples (see + [frequenz-sdk-python#1497](https://github.com/frequenz-floss/frequenz-sdk-python/issues/1497)). It must be at least 1 and at most `max_buffer_len`. """ warn_buffer_len: int = DEFAULT_BUFFER_LEN_WARN - """The minimum length of the resampling buffer that will emit a warning. + """The number of samples above which a resampling buffer logs a warning. - If a buffer grows bigger than this value, it will emit a warning in the - logs, so buffers don't grow too big inadvertently. + Old samples are removed from the buffer when resampling, so it only holds + the samples that are still relevant and the ones received since. If it + holds more samples than this value after removing old ones, a warning is + logged once, so buffers don't grow too big inadvertently. It must be at least 1 and at most `max_buffer_len`. """ max_buffer_len: int = DEFAULT_BUFFER_LEN_MAX - """The maximum length of the resampling buffer. + """The maximum number of samples a resampling buffer can hold. - Buffers won't be allowed to grow beyond this point even if it would be - needed to keep all the requested past sampling periods. An error will be - emitted in the logs if the buffer length needs to be truncated to this - value. + When the buffer is full, the oldest sample is dropped when a new one is + added, even if it would be needed to resample. An error is logged once if + samples needed to resample may have been dropped. - It must be at bigger than `warn_buffer_len`. + It must be bigger than `warn_buffer_len`. """ align_to: datetime | None = UNIX_EPOCH @@ -356,33 +357,41 @@ class ResamplerConfig2(ResamplerConfig): """ initial_buffer_len: int = DEFAULT_BUFFER_LEN_INIT - """The initial length of the resampling buffer. + """The number of samples to receive before estimating the input sampling period. + + The input sampling period is estimated once, at the first resampling after + receiving enough samples, and decides how old the relevant samples can be + when upsampling (see `max_data_age_in_periods`). Until it is known, samples + are not removed from the resampling buffer, except when it is full. - The buffer could grow or shrink depending on the source properties, - like sampling rate, to make sure all the requested past sampling periods - can be stored. + The number of received samples must also be at least the number of seconds + in `max_data_age_in_periods` resampling periods. For example, with a + resampling period of 60 seconds and a `max_data_age_in_periods` of 3, the + input sampling period is estimated after receiving at least 180 samples (see + [frequenz-sdk-python#1497](https://github.com/frequenz-floss/frequenz-sdk-python/issues/1497)). It must be at least 1 and at most `max_buffer_len`. """ warn_buffer_len: int = DEFAULT_BUFFER_LEN_WARN - """The minimum length of the resampling buffer that will emit a warning. + """The number of samples above which a resampling buffer logs a warning. - If a buffer grows bigger than this value, it will emit a warning in the - logs, so buffers don't grow too big inadvertently. + Old samples are removed from the buffer when resampling, so it only holds + the samples that are still relevant and the ones received since. If it + holds more samples than this value after removing old ones, a warning is + logged once, so buffers don't grow too big inadvertently. It must be at least 1 and at most `max_buffer_len`. """ max_buffer_len: int = DEFAULT_BUFFER_LEN_MAX - """The maximum length of the resampling buffer. + """The maximum number of samples a resampling buffer can hold. - Buffers won't be allowed to grow beyond this point even if it would be - needed to keep all the requested past sampling periods. An error will be - emitted in the logs if the buffer length needs to be truncated to this - value. + When the buffer is full, the oldest sample is dropped when a new one is + added, even if it would be needed to resample. An error is logged once if + samples needed to resample may have been dropped. - It must be at bigger than `warn_buffer_len`. + It must be bigger than `warn_buffer_len`. """ align_to: datetime | None = field(default=None, init=False) diff --git a/src/frequenz/sdk/timeseries/_resampling/_resampler.py b/src/frequenz/sdk/timeseries/_resampling/_resampler.py index b0c6e7583..17f0f0dd2 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_resampler.py +++ b/src/frequenz/sdk/timeseries/_resampling/_resampler.py @@ -8,7 +8,6 @@ import asyncio import itertools import logging -import math from bisect import bisect, bisect_left from collections import deque from datetime import datetime, timedelta, timezone @@ -269,11 +268,17 @@ def _calculate_window_end(self) -> tuple[datetime, timedelta]: class _ResamplingHelper: """Keeps track of *relevant* samples to pass them to the resampling function. - Samples are stored in an internal ring buffer. All collected samples that + Samples are stored in an internal buffer. All collected samples that are newer than `max(resampling_period, input_period) * max_data_age_in_periods` are considered *relevant* and are passed to the provided `resampling_function` when calling the `resample()` method. - All older samples are discarded. + + 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. """ def __init__(self, name: str, config: ResamplerConfig) -> None: @@ -286,9 +291,15 @@ def __init__(self, name: str, config: ResamplerConfig) -> None: self._name = name self._config = config self._buffer: deque[tuple[datetime, float]] = deque( - maxlen=config.initial_buffer_len + 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.""" @property def source_properties(self) -> SourceProperties: @@ -319,10 +330,6 @@ def _update_source_sample_period(self, now: datetime) -> bool: Returns: Whether the source sample period was changed (was really updated). """ - assert ( - self._buffer.maxlen is not None and self._buffer.maxlen > 0 - ), "We need a maxlen of at least 1 to update the sample period" - config = self._config props = self._source_properties @@ -332,7 +339,7 @@ def _update_source_sample_period(self, now: datetime) -> bool: or props.sampling_start is None or props.received_samples < config.resampling_period.total_seconds() * config.max_data_age_in_periods - or len(self._buffer) < self._buffer.maxlen + or props.received_samples < config.initial_buffer_len # There might be a race between the first sample being received and # this function being called or now <= props.sampling_start @@ -351,67 +358,6 @@ def _update_source_sample_period(self, now: datetime) -> bool: ) return True - def _update_buffer_len(self) -> bool: - """Update the length of the buffer based on the source properties. - - Returns: - Whether the buffer length was changed (was really updated). - """ - # To make type checking happy - assert self._buffer.maxlen is not None - assert self._source_properties.sampling_period is not None - - input_sampling_period = self._source_properties.sampling_period - - config = self._config - - new_buffer_len = math.ceil( - # If we are upsampling, one sample could be enough for - # back-filling, but we store max_data_age_in_periods for input - # periods, so resampling functions can do more complex - # inter/extrapolation if they need to. - (input_sampling_period.total_seconds() * config.max_data_age_in_periods) - if input_sampling_period > config.resampling_period - # If we are downsampling, we want a buffer that can hold - # max_data_age_in_periods * resampling_period of data, and we one - # sample every input_sampling_period. - else ( - config.resampling_period.total_seconds() - / input_sampling_period.total_seconds() - * config.max_data_age_in_periods - ) - ) - - new_buffer_len = max(1, new_buffer_len) - if new_buffer_len > config.max_buffer_len: - _logger.error( - "The new buffer length (%s) for timeseries %s is too big, using %s instead", - new_buffer_len, - self._name, - config.max_buffer_len, - ) - new_buffer_len = config.max_buffer_len - elif new_buffer_len > config.warn_buffer_len: - _logger.warning( - "The new buffer length (%s) for timeseries %s bigger than %s", - new_buffer_len, - self._name, - config.warn_buffer_len, - ) - - if new_buffer_len == self._buffer.maxlen: - return False - - _logger.debug( - "New buffer length calculated for %r: %s", - self._name, - new_buffer_len, - ) - - self._buffer = deque(self._buffer, maxlen=new_buffer_len) - - return True - def resample(self, timestamp: datetime) -> Sample[Quantity]: """Generate a new sample based on all the current *relevant* samples. @@ -425,12 +371,10 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: If there are no *relevant* samples, then the new sample will have `None` as `value`. """ - if self._update_source_sample_period(timestamp): - self._update_buffer_len() + self._update_source_sample_period(timestamp) conf = self._config props = self._source_properties - props.dropped_samples = props.received_samples - len(self._buffer) # To see which samples are relevant we need to consider if we are down # or upsampling. @@ -460,6 +404,10 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: 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: @@ -470,6 +418,15 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: 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() + value = ( conf.resampling_function(relevant_samples, conf, props) if relevant_samples @@ -486,6 +443,44 @@ 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: diff --git a/tests/timeseries/test_resampling.py b/tests/timeseries/test_resampling.py index 179455873..a0fcbfbd8 100644 --- a/tests/timeseries/test_resampling.py +++ b/tests/timeseries/test_resampling.py @@ -192,9 +192,10 @@ async def test_helper_buffer_too_big( fake_time: time_machine.Coordinates, caplog: pytest.LogCaptureFixture, ) -> None: - """Test checks on the resampling buffer.""" + """Test dropping relevant samples because the buffer is full is logged once.""" + # The window has one more sample than the buffer can hold config = config_class( - resampling_period=timedelta(seconds=DEFAULT_BUFFER_LEN_MAX + 1), + resampling_period=timedelta(seconds=DEFAULT_BUFFER_LEN_MAX + 2), max_data_age_in_periods=1, ) helper = _ResamplingHelper("test", config) @@ -204,18 +205,151 @@ async def test_helper_buffer_too_big( helper.add_sample(sample) await _advance_time(fake_time, 1) + _ = helper.resample(datetime.now(timezone.utc)) + # A new drop doesn't log again + helper.add_sample((datetime.now(timezone.utc), DEFAULT_BUFFER_LEN_MAX + 1)) _ = helper.resample(datetime.now(timezone.utc)) # Ignore errors produced by wrongly finalized gRPC server in unrelated tests - assert ( - "frequenz.sdk.timeseries._resampling._resampler", - logging.ERROR, - f"The new buffer length ({DEFAULT_BUFFER_LEN_MAX + 1}) " - f"for timeseries test is too big, using {DEFAULT_BUFFER_LEN_MAX} instead", - ) in _filter_logs( - caplog.record_tuples, - ) + assert _filter_logs(caplog.record_tuples, logger_level=logging.ERROR) == [ + ( + "frequenz.sdk.timeseries._resampling._resampler", + logging.ERROR, + "The buffer for timeseries test is full " + f"(max_buffer_len={DEFAULT_BUFFER_LEN_MAX}), so samples needed for " + "resampling may have been dropped. Use a bigger max_buffer_len.", + ) + ] + assert helper.source_properties.dropped_samples == 2 # pylint: disable=protected-access - assert helper._buffer.maxlen == DEFAULT_BUFFER_LEN_MAX + 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], + caplog: pytest.LogCaptureFixture, +) -> None: + """Test a buffer holding more than `warn_buffer_len` samples is logged once.""" + config = config_class( + resampling_period=timedelta(seconds=1), + max_data_age_in_periods=1, + closed=WindowSide.LEFT, + initial_buffer_len=2, + warn_buffer_len=4, + ) + helper = _ResamplingHelper("test", config) + start = datetime(2020, 1, 1, tzinfo=timezone.utc) + + for window in range(3): + for i in range(10): + helper.add_sample((start + timedelta(seconds=window + i / 10), 1.0)) + helper.resample(start + timedelta(seconds=window + 1)) + + assert _filter_logs(caplog.record_tuples, logger_level=logging.WARNING) == [ + ( + "frequenz.sdk.timeseries._resampling._resampler", + logging.WARNING, + "The buffer for timeseries test holds 10 samples, more than " + "warn_buffer_len (4)", + ) + ] + + +@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +async def test_helper_keeps_window_samples_when_next_window_starts( + config_class: type[ResamplerConfig], +) -> None: + """Test a sample of the next window doesn't push out the window being resampled. + + The sample can arrive after the tick, but before the window of that tick + is resampled, for example because of `tick_delay` or a late wakeup. + """ + config = config_class( + resampling_period=timedelta(seconds=1), + max_data_age_in_periods=1.0, + closed=WindowSide.LEFT, + initial_buffer_len=4, + ) + helper = _ResamplingHelper("test", config) + start = datetime(2020, 1, 1, tzinfo=timezone.utc) + step = timedelta(seconds=0.25) + + def add_samples(first: int, last: int) -> None: + for i in range(first, last + 1): + helper.add_sample((start + step * i, float(i))) + + # The first window gives an input period of exactly 0.25 seconds + add_samples(0, 3) + assert helper.resample(start + timedelta(seconds=1)).value == Quantity(1.5) + assert helper.source_properties.sampling_period == step + + # Sample 8 belongs to the next window, [2, 3), and arrives before the + # window [1, 2) is resampled. + add_samples(4, 8) + assert helper.resample(start + timedelta(seconds=2)).value == Quantity(5.5) + + add_samples(9, 12) + assert helper.resample(start + timedelta(seconds=3)).value == Quantity(9.5) + assert helper.source_properties.dropped_samples == 0 + + +@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +async def test_helper_first_window_uses_all_its_samples( + config_class: type[ResamplerConfig], +) -> None: + """Test the first window uses all its samples, before the input period is known. + + Before the input period was estimated, the buffer kept only the newest + `initial_buffer_len` samples, so the first window used only those. + """ + config = config_class( + resampling_period=timedelta(seconds=60), + max_data_age_in_periods=1.0, + closed=WindowSide.LEFT, + ) + helper = _ResamplingHelper("test", config) + start = datetime(2020, 1, 1, tzinfo=timezone.utc) + + for window in range(3): + window_start = start + timedelta(seconds=60 * window) + for i in range(60): + helper.add_sample((window_start + timedelta(seconds=i), float(i + 1))) + resampled = helper.resample(window_start + timedelta(seconds=60)) + assert resampled.value == Quantity(30.5), f"window {window}" + assert helper.source_properties.dropped_samples == 0 @pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) @@ -876,6 +1010,7 @@ async def test_timer_errors_are_logged( # pylint: disable=too-many-statements ) resampling_fun_mock.assert_called_once_with( a_sequence( + as_float_tuple(sample2_5s), as_float_tuple(sample3s), as_float_tuple(sample4s), as_float_tuple(sample4_5s), @@ -965,7 +1100,7 @@ async def test_future_samples_not_included( assert source_props == SourceProperties( sampling_start=timestamp, received_samples=3, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 3 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1059,7 +1194,7 @@ async def test_resampling_with_one_window( assert source_props == SourceProperties( sampling_start=timestamp, received_samples=2, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 2 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1089,17 +1224,16 @@ async def test_resampling_with_one_window( config, source_props, ) - # By now we have a full buffer (5 samples and a buffer of length 4), which - # we received in 4 seconds, so we have an input period of 0.8s. + # By now we received 5 samples, at least initial_buffer_len (4), in 4 + # seconds, so we have an input period of 0.8s. assert source_props == SourceProperties( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), - dropped_samples=2, ) - # The buffer should be able to hold 2 seconds of data, and data is coming - # every 0.8 seconds, so we should be able to store 3 samples. - assert _get_buffer_len(resampler, source_receiver) == 3 + # Now that the input period is known, samples older than the window (2, 4] + # are removed from the buffer. + assert _get_buffered_samples(resampler, source_receiver) == 3 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1116,9 +1250,8 @@ async def test_resampling_with_one_window( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), - dropped_samples=2, ) - assert _get_buffer_len(resampler, source_receiver) == 3 + assert _get_buffered_samples(resampler, source_receiver) == 0 # Even when a lot could be refactored to use smaller functions, I'm allowing @@ -1189,7 +1322,7 @@ async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-ma assert source_props == SourceProperties( sampling_start=timestamp, received_samples=2, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 2 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1223,7 +1356,7 @@ async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-ma assert source_props == SourceProperties( sampling_start=timestamp, received_samples=5, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 5 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1252,18 +1385,16 @@ async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-ma config, source_props, ) - # By now we have a full buffer (7 samples and a buffer of length 6), which - # we received in 4 seconds, so we have an input period of 6/7s. + # By now we received 7 samples, at least initial_buffer_len (7), in 6 + # seconds, so we have an input period of 6/7s. assert source_props == SourceProperties( sampling_start=timestamp, received_samples=7, sampling_period=timedelta(seconds=6 / 7), - dropped_samples=3, ) - # The buffer should be able to hold 2 * 1.5 (3) seconds of data, and data - # is coming every 6/7 seconds (~0.857s), so we should be able to store - # 4 samples. - assert _get_buffer_len(resampler, source_receiver) == 4 + # Now that the input period is known, samples older than 2 * 1.5 (3) + # seconds are removed from the buffer. + assert _get_buffered_samples(resampler, source_receiver) == 3 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1300,9 +1431,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), - dropped_samples=3, ) - assert _get_buffer_len(resampler, source_receiver) == 4 + assert _get_buffered_samples(resampler, source_receiver) == 0 # Even when a lot could be refactored to use smaller functions, I'm allowing @@ -1373,7 +1503,7 @@ async def test_resampling_with_two_windows( # pylint: disable=too-many-statemen assert source_props == SourceProperties( sampling_start=timestamp, received_samples=2, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 2 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1408,7 +1538,7 @@ async def test_resampling_with_two_windows( # pylint: disable=too-many-statemen assert source_props == SourceProperties( sampling_start=timestamp, received_samples=5, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 5 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1442,7 +1572,7 @@ async def test_resampling_with_two_windows( # pylint: disable=too-many-statemen assert source_props == SourceProperties( sampling_start=timestamp, received_samples=7, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 7 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1469,7 +1599,7 @@ async def test_resampling_with_two_windows( # pylint: disable=too-many-statemen assert source_props == SourceProperties( sampling_start=timestamp, received_samples=7, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 7 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1485,7 +1615,7 @@ async def test_resampling_with_two_windows( # pylint: disable=too-many-statemen assert source_props == SourceProperties( sampling_start=timestamp, received_samples=7, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 7 @pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) @@ -1813,7 +1943,7 @@ async def test_resampling_all_zeros( assert source_props == SourceProperties( sampling_start=timestamp, received_samples=2, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 2 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1843,17 +1973,16 @@ async def test_resampling_all_zeros( config, source_props, ) - # By now we have a full buffer (5 samples and a buffer of length 4), which - # we received in 4 seconds, so we have an input period of 0.8s. + # By now we received 5 samples, at least initial_buffer_len (4), in 4 + # seconds, so we have an input period of 0.8s. assert source_props == SourceProperties( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), - dropped_samples=2, ) - # The buffer should be able to hold 2 seconds of data, and data is coming - # every 0.8 seconds, so we should be able to store 3 samples. - assert _get_buffer_len(resampler, source_receiver) == 3 + # Now that the input period is known, samples older than the window (2, 4] + # are removed from the buffer. + assert _get_buffered_samples(resampler, source_receiver) == 3 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1870,9 +1999,8 @@ async def test_resampling_all_zeros( sampling_start=timestamp, received_samples=5, sampling_period=timedelta(seconds=0.8), - dropped_samples=2, ) - assert _get_buffer_len(resampler, source_receiver) == 3 + assert _get_buffered_samples(resampler, source_receiver) == 0 @pytest.mark.parametrize("closed", [WindowSide.RIGHT, WindowSide.LEFT]) @@ -1948,7 +2076,7 @@ async def test_resampler_closed_option( assert source_props == SourceProperties( sampling_start=timestamp, received_samples=3, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 3 sink_mock.reset_mock() resampling_fun_mock.reset_mock() @@ -1993,7 +2121,7 @@ async def test_resampler_closed_option( assert source_props == SourceProperties( sampling_start=timestamp, received_samples=6, sampling_period=None ) - assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len + assert _get_buffered_samples(resampler, source_receiver) == 6 @pytest.mark.parametrize("label", [WindowSide.LEFT, WindowSide.RIGHT]) @@ -2046,11 +2174,9 @@ async def test_resampler_label_option( ) -def _get_buffer_len(resampler: Resampler, source_receiver: Source) -> int: +def _get_buffered_samples(resampler: Resampler, source_receiver: Source) -> int: # pylint: disable-next=protected-access - blen = resampler._resamplers[source_receiver]._helper._buffer.maxlen - assert blen is not None - return blen + return len(resampler._resamplers[source_receiver]._helper._buffer) def _filter_logs(