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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@

<!-- Here goes the main new features and examples or instructions on how to use them -->

- `SourceProperties` has a new `dropped_samples` field, with the number of samples the resampler dropped because its buffer was full.

## Bug Fixes

<!-- Here goes notable bug fixes that are worth a special mention or explanation -->

- 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.
7 changes: 7 additions & 0 deletions src/frequenz/sdk/timeseries/_resampling/_base_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
83 changes: 46 additions & 37 deletions src/frequenz/sdk/timeseries/_resampling/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
140 changes: 68 additions & 72 deletions src/frequenz/sdk/timeseries/_resampling/_resampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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.

Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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:
Expand Down
Loading