diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 61ee6f2ad..6315f985b 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -12,6 +12,14 @@ +- `SourceProperties` has a new `dropped_samples` field, with the number of samples the resampler dropped because its buffer was full. + ## 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/_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/_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 d0d150df6..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,8 +371,7 @@ 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 @@ -459,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: @@ -469,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 @@ -485,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 bbcecb887..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,173 @@ 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]) +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 @@ -854,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), @@ -943,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() @@ -1037,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() @@ -1067,16 +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), ) - # 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() @@ -1094,7 +1251,7 @@ async def test_resampling_with_one_window( received_samples=5, sampling_period=timedelta(seconds=0.8), ) - 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 @@ -1165,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() @@ -1199,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() @@ -1228,17 +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), ) - # 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() @@ -1276,7 +1432,7 @@ async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-ma received_samples=7, sampling_period=timedelta(seconds=6 / 7), ) - 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 @@ -1347,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() @@ -1382,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() @@ -1416,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() @@ -1443,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() @@ -1459,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]) @@ -1787,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() @@ -1817,16 +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), ) - # 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() @@ -1844,7 +2000,7 @@ async def test_resampling_all_zeros( received_samples=5, sampling_period=timedelta(seconds=0.8), ) - assert _get_buffer_len(resampler, source_receiver) == 3 + assert _get_buffered_samples(resampler, source_receiver) == 0 @pytest.mark.parametrize("closed", [WindowSide.RIGHT, WindowSide.LEFT]) @@ -1920,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() @@ -1965,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]) @@ -2018,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(