1mod aggregate;
21mod bounds;
22mod classic;
23#[cfg_attr(not(test), allow(dead_code))]
26pub(crate) mod float_histogram;
27pub(crate) mod legacy_bridge;
28mod native;
29#[cfg(test)]
30mod tests;
31
32use std::collections::HashMap;
33use std::sync::Arc;
34
35use common_query::promql_annotations::PromqlAnnotationCollector;
36use datafusion::error::{DataFusionError, Result};
37use datatypes::series::SeriesLabels;
38use datatypes::series::histogram::HistogramView;
39use datatypes::series::samples::{DenseSamplesRef, RowCursor, SampleRef, Series, SeriesSchema};
40use datatypes::series::time::{TimeAxis, union_positions};
41
42pub(crate) use aggregate::{HistogramAggregate, sum_or_avg};
43
44use crate::go_format::format_open_metrics_float;
45use crate::go_sort;
46use crate::grid_series::{
47 GridSeriesBuilder, LabelSet, METADATA_LABELS, external, label_set, merge_same_labelset,
48};
49use crate::map::validate_grid_series;
50
51pub(crate) const BUCKET_LABEL: &str = "le";
52
53pub(crate) const HISTOGRAM_ROUTING_EXCLUDED_LABELS: [&str; 4] =
56 [BUCKET_LABEL, "__name__", "__type__", "__unit__"];
57
58#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
60pub enum HistogramFunction {
61 Quantile(f64),
63 Fraction { lower: f64, upper: f64 },
65}
66
67pub fn histogram_quantiles(
76 label: &str,
77 quantiles: &[f64],
78 schema: &Arc<SeriesSchema>,
79 series: &[Series],
80) -> Result<Vec<Series>> {
81 let mut output = Vec::new();
82 for &quantile in quantiles {
83 let value: Arc<str> = Arc::from(format_open_metrics_float(quantile));
84 for mut result in
85 evaluate_histograms(HistogramFunction::Quantile(quantile), schema, series)?
86 {
87 result.metric.set(label, value.clone()).map_err(external)?;
88 output.push(result);
89 }
90 }
91 merge_same_labelset(schema, output)
92}
93
94pub fn evaluate_histograms(
103 function: HistogramFunction,
104 schema: &Arc<SeriesSchema>,
105 series: &[Series],
106) -> Result<Vec<Series>> {
107 evaluate_histograms_with_annotations(function, schema, series, None, None)
108}
109
110#[derive(Debug, Clone, Copy)]
112pub struct HistogramParameters<'a> {
113 pub quantile: Option<&'a [Option<f64>]>,
114 pub lower: Option<&'a [Option<f64>]>,
115 pub upper: Option<&'a [Option<f64>]>,
116}
117
118pub(crate) fn evaluate_histograms_with_annotations(
122 function: HistogramFunction,
123 schema: &Arc<SeriesSchema>,
124 series: &[Series],
125 parameters: Option<HistogramParameters<'_>>,
126 collector: Option<&PromqlAnnotationCollector>,
127) -> Result<Vec<Series>> {
128 let mut index: HashMap<LabelSet, usize> = HashMap::new();
131 let mut groups: Vec<Group<'_>> = Vec::new();
132 let mut group_of = |metric: SeriesLabels| {
133 *index.entry(label_set(&metric)).or_insert_with(|| {
134 groups.push(Group::new(metric));
135 groups.len() - 1
136 })
137 };
138 let mut members: Vec<(usize, Option<f64>, &Series)> = Vec::new();
139 for series in series {
140 grid_axis(series)?;
141 if let Some(upper_bound) = series
142 .metric
143 .get(BUCKET_LABEL)
144 .and_then(classic::parse_bound)
145 {
146 let mut metric = series.metric.clone();
147 metric.remove(BUCKET_LABEL);
148 members.push((group_of(metric), Some(upper_bound), series));
149 }
150 if has_histograms(series) {
151 members.push((group_of(series.metric.clone()), None, series));
152 }
153 }
154 for (slot, upper_bound, series) in members {
155 let group = &mut groups[slot];
156 match upper_bound {
157 Some(upper_bound) => group.classic.push((upper_bound, series)),
158 None => {
159 debug_assert!(
162 group.native.is_none(),
163 "one label set carries at most one native histogram series; a second one for \
164 the same label set means the input handed one label set over as several \
165 series, which a gap in the axis is there to avoid"
166 );
167 group.native = Some(series);
168 }
169 }
170 }
171
172 let mut output = Vec::with_capacity(groups.len());
173 let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
174 let mut classic_buckets = Vec::new();
175 let mut native_buckets = Vec::new();
176 let mut values = vec![None; schema.fields.len()];
177 for mut group in groups {
178 builder.begin_series();
180 let axes = group
183 .classic
184 .iter()
185 .map(|member| &member.1.time)
186 .chain(group.native.map(|native| &native.time));
187 let members = group
191 .classic
192 .iter()
193 .map(|&(_, series)| series)
194 .chain(group.native);
195 let mut cursors: Vec<Vec<RowCursor<'_>>> = members
196 .map(|series| series.fields.iter().map(|field| field.cursor()).collect())
197 .collect();
198 let classic_members = group.classic.len();
199 for point in union_positions(axes) {
200 for (field, value) in values.iter_mut().enumerate() {
201 classic_buckets.clear();
202 for (member, &(upper_bound, series)) in group.classic.iter().enumerate() {
203 let count = series.time.row_of(point).and_then(|row| {
204 match cursors[member][field]
205 .at(row)
206 .expect("a row never goes back")
207 {
208 SampleRef::Float(count) => Some(count),
209 _ => None,
210 }
211 });
212 if let Some(count) = count {
213 classic_buckets.push(classic::Bucket { upper_bound, count });
214 }
215 }
216 go_sort::sort_by(&mut classic_buckets, |a, b| a.upper_bound < b.upper_bound);
220 let native = group.native.and_then(|series| {
221 let row = series.time.row_of(point)?;
222 match cursors[classic_members][field]
223 .at(row)
224 .expect("a row never goes back")
225 {
226 SampleRef::Histogram(h) => Some(h),
227 _ => None,
228 }
229 });
230 let argument = |values: Option<&[Option<f64>]>, bound: f64| -> Option<f64> {
231 match values {
232 Some(values) => values.get(point).copied().flatten(),
233 None => Some(bound),
234 }
235 };
236 let function = match function {
237 HistogramFunction::Quantile(q) => {
238 let Some(q) = argument(parameters.and_then(|p| p.quantile), q) else {
239 *value = None;
240 continue;
241 };
242 HistogramFunction::Quantile(q)
243 }
244 HistogramFunction::Fraction { lower, upper } => {
245 let (Some(lower), Some(upper)) = (
246 argument(parameters.and_then(|p| p.lower), lower),
247 argument(parameters.and_then(|p| p.upper), upper),
248 ) else {
249 *value = None;
250 continue;
251 };
252 HistogramFunction::Fraction { lower, upper }
253 }
254 };
255 *value = match (native, classic_buckets.is_empty()) {
257 (Some(_), false) => {
258 if let Some(collector) = collector {
259 collector.record_warning(format!("{}: native histogram and classic buckets both present; dropping both", match function {
260 HistogramFunction::Quantile(_) => "histogram_quantile",
261 HistogramFunction::Fraction { .. } => "histogram_fraction",
262 }));
263 }
264 None
265 }
266 (None, true) => None,
267 (Some(h), true) => Some(match function {
268 HistogramFunction::Quantile(q) => {
269 native::quantile(q, &h, &mut native_buckets)?
270 }
271 HistogramFunction::Fraction { lower, upper } => {
272 native::fraction(lower, upper, &h, &mut native_buckets)?
273 }
274 }),
275 (None, false) => Some(match function {
276 HistogramFunction::Quantile(q) => {
277 classic::bucket_quantile(q, &mut classic_buckets)
278 }
279 HistogramFunction::Fraction { lower, upper } => {
280 classic::bucket_fraction(lower, upper, &mut classic_buckets)
281 }
282 }),
283 };
284 }
285 builder.push(point, &values)?;
286 }
287 group.metric.remove_all(&METADATA_LABELS);
288 output.extend(builder.finish(group.metric)?);
289 }
290 merge_same_labelset(schema, output)
291}
292
293struct Group<'a> {
296 metric: SeriesLabels,
297 classic: Vec<(f64, &'a Series)>,
298 native: Option<&'a Series>,
299}
300
301impl Group<'_> {
302 fn new(metric: SeriesLabels) -> Self {
303 Self {
304 metric,
305 classic: Vec::new(),
306 native: None,
307 }
308 }
309}
310
311fn grid_axis(series: &Series) -> Result<&TimeAxis> {
313 if series.time.grid().is_none() {
314 return Err(DataFusionError::Execution(
315 "histogram functions require evaluated series".into(),
316 ));
317 }
318 Ok(&series.time)
319}
320
321fn has_histograms(series: &Series) -> bool {
322 series.fields.iter().any(|samples| {
323 samples
324 .segments()
325 .iter()
326 .any(|segment| !matches!(segment.dense(), Some(DenseSamplesRef::Float(_))))
327 })
328}
329
330pub(crate) fn histogram_string(h: &HistogramView<'_>) -> Result<String> {
333 native::go_string(h)
334}
335
336#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
338pub enum NativeHistogramFunction {
339 Count,
340 Sum,
341 Avg,
342 StdDev,
343 StdVar,
344}
345
346pub fn map_native_histogram(
355 function: NativeHistogramFunction,
356 schema: &Arc<SeriesSchema>,
357 series: &Series,
358) -> Result<Option<Series>> {
359 validate_grid_series(schema, series)?;
360 let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
361 let mut buckets = Vec::new();
362 let mut values = vec![None; schema.fields.len()];
363 let mut cursors = series
366 .fields
367 .iter()
368 .map(|field| field.cursor())
369 .collect::<Vec<_>>();
370 for (point, row) in series.time.positions() {
371 for (field, value) in values.iter_mut().enumerate() {
372 *value = match cursors[field]
373 .at(row)
374 .expect("the axis and the fields are aligned")
375 {
376 SampleRef::Histogram(h) => Some(function.apply(&h, &mut buckets)?),
377 _ => None,
378 };
379 }
380 builder.push(point, &values)?;
381 }
382 let mut metric = series.metric.clone();
383 metric.remove("__name__");
385 builder.finish(metric)
386}
387
388impl NativeHistogramFunction {
389 pub fn name(self) -> &'static str {
391 match self {
392 Self::Count => "histogram_count",
393 Self::Sum => "histogram_sum",
394 Self::Avg => "histogram_avg",
395 Self::StdDev => "histogram_stddev",
396 Self::StdVar => "histogram_stdvar",
397 }
398 }
399
400 fn apply(self, h: &HistogramView<'_>, buckets: &mut Vec<native::NativeBucket>) -> Result<f64> {
401 Ok(match self {
402 Self::Count => h.count,
403 Self::Sum => h.sum,
404 Self::Avg => h.sum / h.count,
405 Self::StdDev => native::variance(h, buckets)?.sqrt(),
406 Self::StdVar => native::variance(h, buckets)?,
407 })
408 }
409}
410
411impl PartialEq for HistogramFunction {
412 fn eq(&self, o: &Self) -> bool {
413 match (self, o) {
414 (Self::Quantile(a), Self::Quantile(b)) => a.to_bits() == b.to_bits(),
415 (Self::Fraction { lower: a, upper: b }, Self::Fraction { lower: c, upper: d }) => {
416 a.to_bits() == c.to_bits() && b.to_bits() == d.to_bits()
417 }
418 _ => false,
419 }
420 }
421}
422impl Eq for HistogramFunction {}
423impl std::hash::Hash for HistogramFunction {
424 fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
425 match self {
426 Self::Quantile(x) => {
427 0u8.hash(h);
428 x.to_bits().hash(h)
429 }
430 Self::Fraction { lower, upper } => {
431 1u8.hash(h);
432 lower.to_bits().hash(h);
433 upper.to_bits().hash(h)
434 }
435 }
436 }
437}