Skip to main content

saluki_components/transforms/aggregate/
config.rs

1use saluki_core::data_model::event::metric::HistogramSummary;
2use stringtheory::MetaString;
3use tracing::error;
4
5/// A histogram statistic to calculate.
6#[derive(Clone)]
7#[cfg_attr(test, derive(Debug, PartialEq, serde::Serialize))]
8pub enum HistogramStatistic {
9    /// Total count of values in the histogram.
10    Count,
11
12    /// Sum of all values in the histogram.
13    Sum,
14
15    /// Minimum value in the histogram.
16    Minimum,
17
18    /// Maximum value in the histogram.
19    Maximum,
20
21    /// Average value in the histogram.
22    Average,
23
24    /// Median value in the histogram.
25    Median,
26
27    /// Calculate the given percentile from the histogram.
28    Percentile {
29        /// Quantile value to calculate.
30        q: f64,
31
32        /// Suffix to append to the metric name, representing the percentile.
33        ///
34        /// For example, a percentile of 95% (quantile value of 0.95) would have a suffix of `95percentile`.
35        suffix: MetaString,
36    },
37}
38
39impl HistogramStatistic {
40    /// Returns the suffix to be used for metrics representing this statistic.
41    pub fn suffix(&self) -> &str {
42        match self {
43            HistogramStatistic::Count => "count",
44            HistogramStatistic::Sum => "sum",
45            HistogramStatistic::Minimum => "min",
46            HistogramStatistic::Maximum => "max",
47            HistogramStatistic::Average => "avg",
48            HistogramStatistic::Median => "median",
49            HistogramStatistic::Percentile { suffix, .. } => suffix,
50        }
51    }
52
53    /// Returns `true` if this statistics should be represented as a rate.
54    pub fn is_rate_statistic(&self) -> bool {
55        matches!(self, HistogramStatistic::Count)
56    }
57
58    /// Returns the value of this statistic from the given histogram summary.
59    pub fn value_from_histogram(&self, summary: &HistogramSummary<'_>) -> f64 {
60        match self {
61            HistogramStatistic::Count => summary.count() as f64,
62            HistogramStatistic::Sum => summary.sum(),
63            HistogramStatistic::Minimum => summary.min().unwrap_or(0.0),
64            HistogramStatistic::Maximum => summary.max().unwrap_or(0.0),
65            HistogramStatistic::Average => summary.avg(),
66            HistogramStatistic::Median => summary.median().unwrap_or(0.0),
67            HistogramStatistic::Percentile { q, .. } => {
68                saluki_antithesis::always_ge!(*q, 0.0, "histogram percentile quantile at or above zero");
69                saluki_antithesis::always_le!(*q, 1.0, "histogram percentile quantile at or below one");
70                summary.quantile(*q).unwrap_or(0.0)
71            }
72        }
73    }
74}
75
76/// Why a configured histogram percentile was skipped.
77enum InvalidPercentile {
78    /// The entry isn't a number.
79    Unparseable(std::num::ParseFloatError),
80
81    /// The entry is a number, but not between `0.0` and `1.0`.
82    OutOfRange,
83}
84
85/// Parses a configured percentile in quantile form, such as `0.95`, into a whole percentile, such as `95`.
86fn parse_percentile(faux_percentile: &str) -> Result<u32, InvalidPercentile> {
87    let quantile = faux_percentile.parse::<f64>().map_err(InvalidPercentile::Unparseable)?;
88    if !(0.0..=1.0).contains(&quantile) {
89        return Err(InvalidPercentile::OutOfRange);
90    }
91    Ok((quantile * 100.0 + 0.5) as u32)
92}
93
94/// Returns the metric name suffix for a whole percentile, such as `95percentile`.
95fn percentile_suffix(percentile: u32) -> MetaString {
96    format!("{}percentile", percentile).into()
97}
98
99/// Statistics to calculate over histograms, and how to copy them to distributions.
100#[derive(Clone)]
101#[cfg_attr(test, derive(Debug, PartialEq))]
102pub struct HistogramConfiguration {
103    statistics: Vec<HistogramStatistic>,
104    copy_to_distribution: bool,
105    copy_to_distribution_prefix: String,
106}
107
108impl HistogramConfiguration {
109    /// Creates a new `HistogramConfiguration` from the aggregates and percentiles to calculate.
110    ///
111    /// Aggregates name a statistic to compute over each histogram: `count`, `sum`, `min`, `max`, `avg`, or `median`.
112    /// Percentiles are expressed in quantile form, between `0.0` and `1.0` inclusive: 95% becomes `0.95`. Quantiles
113    /// that extend beyond two decimal places are rounded to the nearest whole percentile.
114    ///
115    /// Like the Datadog Agent, an invalid entry is logged and skipped rather than failing the configuration, and the
116    /// remaining entries still apply:
117    ///
118    /// - an aggregate that names an unsupported statistic
119    ///   (<https://github.com/DataDog/datadog-agent/blob/e02f16838240688a60db91d6b99cd8fbecbd9750/pkg/metrics/histogram.go#L268>)
120    /// - a percentile that isn't a number between `0.0` and `1.0`
121    ///   (<https://github.com/DataDog/datadog-agent/blob/e02f16838240688a60db91d6b99cd8fbecbd9750/pkg/metrics/histogram.go#L60-L78>)
122    ///
123    /// The Datadog Agent logs an unsupported aggregate on every flush; this logs each invalid entry once, when the
124    /// configuration is built.
125    pub fn new(
126        aggregates: &[String], percentiles: &[String], copy_to_distribution: bool, copy_to_distribution_prefix: String,
127    ) -> Self {
128        let mut statistics = Vec::new();
129
130        for aggregate in aggregates {
131            match aggregate.as_str() {
132                "count" => statistics.push(HistogramStatistic::Count),
133                "sum" => statistics.push(HistogramStatistic::Sum),
134                "min" => statistics.push(HistogramStatistic::Minimum),
135                "max" => statistics.push(HistogramStatistic::Maximum),
136                "avg" => statistics.push(HistogramStatistic::Average),
137                "median" => statistics.push(HistogramStatistic::Median),
138                _ => error!(
139                    "Configured aggregate '{}' in 'histogram_aggregates' is not implemented, skipping.",
140                    aggregate
141                ),
142            }
143        }
144
145        for faux_percentile in percentiles {
146            match parse_percentile(faux_percentile) {
147                Ok(percentile) => statistics.push(HistogramStatistic::Percentile {
148                    q: f64::from(percentile) / 100.0,
149                    suffix: percentile_suffix(percentile),
150                }),
151                Err(InvalidPercentile::Unparseable(e)) => error!(
152                    "Could not parse '{}' from 'histogram_percentiles' (skipping): {}",
153                    faux_percentile, e
154                ),
155                Err(InvalidPercentile::OutOfRange) => error!(
156                    "'histogram_percentiles' must be between 0 and 1: skipping '{}'.",
157                    faux_percentile
158                ),
159            }
160        }
161
162        Self {
163            statistics,
164            copy_to_distribution,
165            copy_to_distribution_prefix,
166        }
167    }
168
169    /// Returns the metric name suffixes, such as `95percentile`, that the valid entries in `percentiles` produce.
170    ///
171    /// Entries are parsed exactly as [`HistogramConfiguration::new`] parses them, so the suffixes always match the
172    /// percentile series it emits. Invalid entries are skipped without logging: `new` already logs each one.
173    pub fn percentile_suffixes(percentiles: &[String]) -> Vec<MetaString> {
174        percentiles
175            .iter()
176            .filter_map(|faux_percentile| parse_percentile(faux_percentile).ok())
177            .map(percentile_suffix)
178            .collect()
179    }
180
181    /// Creates a configuration from already-parsed statistics, for tests that exercise histogram aggregation rather
182    /// than configuration.
183    #[cfg(test)]
184    pub fn from_statistics(
185        statistics: &[HistogramStatistic], copy_to_distribution: bool, copy_to_distribution_prefix: String,
186    ) -> Self {
187        Self {
188            statistics: statistics.to_vec(),
189            copy_to_distribution,
190            copy_to_distribution_prefix,
191        }
192    }
193
194    /// Returns the configured aggregate statistics to calculate.
195    pub fn statistics(&self) -> &[HistogramStatistic] {
196        &self.statistics
197    }
198
199    /// Returns `true` if histograms should be copied to distributions.
200    pub fn copy_to_distribution(&self) -> bool {
201        self.copy_to_distribution
202    }
203
204    /// Returns the prefix to append to the distributions copied from histograms.
205    pub fn copy_to_distribution_prefix(&self) -> &str {
206        &self.copy_to_distribution_prefix
207    }
208}
209
210/// Fixture values for tests that exercise histogram aggregation rather than configuration.
211#[cfg(test)]
212impl Default for HistogramConfiguration {
213    fn default() -> Self {
214        Self {
215            statistics: vec![
216                HistogramStatistic::Maximum,
217                HistogramStatistic::Median,
218                HistogramStatistic::Average,
219                HistogramStatistic::Count,
220                HistogramStatistic::Percentile {
221                    q: 0.95,
222                    suffix: "95percentile".into(),
223                },
224            ],
225            copy_to_distribution: false,
226            copy_to_distribution_prefix: "".into(),
227        }
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    /// Like the Datadog Agent, invalid entries are skipped, and the valid entries around them still apply: an aggregate
236    /// that names no supported statistic, and a percentile that isn't a quantile between `0.0` and `1.0`.
237    #[test]
238    fn unsupported_aggregates_and_percentiles_are_skipped() {
239        let to_strings = |values: &[&str]| values.iter().map(|v| v.to_string()).collect::<Vec<_>>();
240        let config = HistogramConfiguration::new(
241            &to_strings(&["max", "p99", "count"]),
242            &to_strings(&["abc", "0.95", "1.1", "-0.1"]),
243            false,
244            String::new(),
245        );
246
247        assert_eq!(
248            config.statistics(),
249            &[
250                HistogramStatistic::Maximum,
251                HistogramStatistic::Count,
252                HistogramStatistic::Percentile {
253                    q: 0.95,
254                    suffix: "95percentile".into(),
255                },
256            ]
257        );
258    }
259
260    #[test]
261    fn all_invalid_entries_leave_no_statistics() {
262        let config = HistogramConfiguration::new(&["p99".to_string()], &["abc".to_string()], false, String::new());
263        assert!(config.statistics().is_empty());
264    }
265
266    #[test]
267    fn percentile_suffixes_match_agent_rounding() {
268        let config = HistogramConfiguration::new(&[], &["0.299".to_string(), "0.73".to_string()], false, String::new());
269
270        assert_eq!(
271            config.statistics(),
272            &[
273                HistogramStatistic::Percentile {
274                    q: 0.30,
275                    suffix: "30percentile".into(),
276                },
277                HistogramStatistic::Percentile {
278                    q: 0.73,
279                    suffix: "73percentile".into(),
280                },
281            ]
282        );
283    }
284
285    #[test]
286    fn percentile_suffixes_match_the_emitted_percentile_statistics() {
287        // The post-aggregate filter relies on these suffixes matching the percentile series the aggregate transform
288        // emits, including for skipped and rounded entries.
289        let percentiles = ["0.5", "0.299", "abc", "1.5", "-0.1", "0.0", "1.0"].map(String::from);
290        let config = HistogramConfiguration::new(&[], &percentiles, false, String::new());
291
292        let emitted = config
293            .statistics()
294            .iter()
295            .map(|statistic| statistic.suffix().to_string())
296            .collect::<Vec<_>>();
297        let suffixes = HistogramConfiguration::percentile_suffixes(&percentiles)
298            .iter()
299            .map(|suffix| suffix.to_string())
300            .collect::<Vec<_>>();
301
302        assert_eq!(
303            suffixes,
304            ["50percentile", "30percentile", "0percentile", "100percentile"]
305        );
306        assert_eq!(suffixes, emitted);
307    }
308}