1use std::borrow::Cow;
19
20use common_query::promql_annotations::PromqlAnnotationCollector;
21use datafusion::error::Result;
22use datatypes::series::histogram::CounterResetHint;
23
24use crate::functions::{EdgeKind, count_edges, instant_delta};
25use crate::grid_series::GridSample;
26use crate::histogram_eval::HistogramAggregate;
27use crate::histogram_eval::float_histogram::FloatHistogram;
28use crate::histogram_eval::sum_or_avg;
29use crate::range_eval::function::{ExtrapolationSpan, extrapolation_factor, seconds};
30use crate::range_eval::{FloatWindow, RangeFunction, WindowKernel};
31
32type Histograms = [(i64, FloatHistogram)];
34
35#[allow(clippy::too_many_arguments)]
38pub(super) fn evaluate(
39 function: RangeFunction,
40 floats: Option<FloatWindow<'_>>,
41 histograms: &Histograms,
42 eval_ts: i64,
43 range_ms: i64,
44 offset_ms: i64,
45 kernel: &mut WindowKernel,
46 collector: Option<&PromqlAnnotationCollector>,
47) -> Result<Option<GridSample>> {
48 use RangeFunction::*;
49 if floats.is_some()
50 && !matches!(
51 function,
52 MinOverTime
53 | MaxOverTime
54 | StddevOverTime
55 | StdvarOverTime
56 | QuantileOverTime(_)
57 | Deriv
58 | PredictLinear(_)
59 | DoubleExponentialSmoothing { .. }
60 | MadOverTime
61 | TsOfMinOverTime
62 | TsOfMaxOverTime
63 | CountOverTime
64 | PresentOverTime
65 | LastOverTime
66 | FirstOverTime
67 | TsOfFirstOverTime
68 | TsOfLastOverTime
69 | Resets
70 | Changes
71 | Irate
72 | Idelta
73 )
74 {
75 record_warning(
76 collector,
77 format!(
78 "{}: encountered a mix of float and native histogram samples",
79 function_name(function)
80 ),
81 );
82 }
83 if floats.is_some()
88 && matches!(
89 function,
90 MinOverTime
91 | MaxOverTime
92 | StddevOverTime
93 | StdvarOverTime
94 | QuantileOverTime(_)
95 | Deriv
96 | PredictLinear(_)
97 | DoubleExponentialSmoothing { .. }
98 )
99 {
100 record_info(
101 collector,
102 format!(
103 "{}: ignored native histogram samples",
104 function_name(function)
105 ),
106 );
107 }
108 let float = |value: f64| Some(GridSample::Float(value));
109 let (last_ts, last) = &histograms[histograms.len() - 1];
110 let (first_ts, first) = &histograms[0];
111 Ok(match function {
112 MinOverTime
114 | MaxOverTime
115 | StddevOverTime
116 | StdvarOverTime
117 | QuantileOverTime(_)
118 | Deriv
119 | PredictLinear(_)
120 | DoubleExponentialSmoothing { .. }
121 | MadOverTime
122 | TsOfMinOverTime
123 | TsOfMaxOverTime => floats.and_then(kernel).map(GridSample::Float),
124 CountOverTime => {
125 float((floats.map_or(0, |window| window.values.len()) + histograms.len()) as f64)
126 }
127 PresentOverTime => float(1.0),
128 LastOverTime => match floats {
129 Some(window) if last_ts < window.timestamps.last().expect("not empty") => {
130 float(window.values[window.values.len() - 1])
131 }
132 _ => Some(GridSample::Histogram(Box::new(last.clone()))),
133 },
134 FirstOverTime => match floats {
135 Some(window) if window.timestamps[0] < *first_ts => float(window.values[0]),
136 _ => Some(GridSample::Histogram(Box::new(first.clone()))),
137 },
138 TsOfFirstOverTime => {
139 let ts = floats.map_or(*first_ts, |window| window.timestamps[0].min(*first_ts));
140 float(seconds(ts - offset_ms))
141 }
142 TsOfLastOverTime => {
144 let histogram_ts = last_ts - offset_ms;
145 let ts = match floats {
146 Some(window) => {
147 (window.timestamps.last().expect("not empty") - offset_ms).max(histogram_ts)
148 }
149 None => histogram_ts.max(0),
150 };
151 float(seconds(ts))
152 }
153 Resets => float(edges(floats, histograms, EdgeKind::Resets, offset_ms)? as f64),
154 Changes => float(edges(floats, histograms, EdgeKind::Changes, offset_ms)? as f64),
155 SumOverTime | AvgOverTime if floats.is_none() => {
156 let op = if function == SumOverTime {
157 HistogramAggregate::Sum
158 } else {
159 HistogramAggregate::Avg
160 };
161 if has_contradictory_reset_hints(histograms.iter().map(|(_, h)| h)) {
165 record_warning(
166 collector,
167 format!(
168 "{}: native histogram counter reset hints contradict",
169 function_name(function)
170 ),
171 );
172 }
173 let (result, custom_reconciled) =
177 sum_or_avg(op, histograms.iter().map(|(_, h)| Ok(h.clone())))?;
178 if result.is_none() {
179 record_warning(
180 collector,
181 format!(
182 "{}: dropped native histogram range with incompatible schemas",
183 function_name(function)
184 ),
185 );
186 }
187 if custom_reconciled {
188 record_info(
189 collector,
190 format!(
191 "{}: reconciled native histograms with different custom buckets",
192 function_name(function)
193 ),
194 );
195 }
196 result.map(|h| GridSample::Histogram(Box::new(h)))
197 }
198 Rate | Increase if floats.is_none() && histograms.len() == 1 => {
199 let (first_ts, first) = &histograms[0];
200 let range_start = eval_ts - range_ms;
201 if first.start_timestamp.is_some_and(|start| {
202 start != 0
203 && start.checked_add(offset_ms).is_some_and(|shifted_start| {
204 range_start < shifted_start && shifted_start < *first_ts
205 })
206 }) {
207 record_histogram_flavor_warning(collector, function, histograms);
208 let mut result = first.clone();
209 let factor = if function == Rate {
210 1.0 / seconds(range_ms)
211 } else {
212 1.0
213 };
214 result.mul(factor);
215 result.reset_hint = CounterResetHint::Gauge;
216 Some(GridSample::Histogram(Box::new(result)))
217 } else {
218 None
219 }
220 }
221 Rate | Increase | Delta if floats.is_none() && histograms.len() > 1 => {
222 let is_counter = function != Delta;
223 record_histogram_flavor_warning(collector, function, histograms);
224 record_histogram_pair_annotations(collector, function, histograms);
225 let range_start = eval_ts - range_ms;
226 let synthetic_zero = is_counter
227 .then_some(first.start_timestamp)
228 .flatten()
229 .and_then(|start| start.checked_add(offset_ms).map(|shifted| (start, shifted)))
230 .filter(|(start, shifted)| {
231 *start != 0 && range_start < *shifted && *shifted < *first_ts
232 })
233 .map(|(_, shifted)| shifted);
234 let Some(mut result) = histogram_rate(histograms, is_counter, offset_ms)? else {
235 record_warning(
236 collector,
237 format!(
238 "{}: dropped native histogram range with incompatible schemas",
239 function_name(function)
240 ),
241 );
242 return Ok(None);
243 };
244 let effective_first_ts = synthetic_zero.unwrap_or(*first_ts);
245 if *last_ts <= effective_first_ts {
246 return Ok(None);
247 }
248 let zero_point = if synthetic_zero.is_some() {
252 Some(0.0)
253 } else {
254 (is_counter && result.count > 0.0 && first.count >= 0.0)
255 .then(|| first.count / result.count)
256 };
257 let factor = extrapolation_factor(
262 ExtrapolationSpan {
263 sampled_from: effective_first_ts,
264 average_from: *first_ts,
265 last: *last_ts,
266 samples_minus_one: histograms.len() - 1,
267 },
268 eval_ts,
269 range_ms,
270 is_counter,
271 function == Rate,
272 zero_point,
273 );
274 if synthetic_zero.is_some() && result.add(first).is_err() {
275 record_warning(
276 collector,
277 format!(
278 "{}: dropped native histogram range with incompatible schemas",
279 function_name(function)
280 ),
281 );
282 return Ok(None);
283 }
284 result.mul(factor);
285 Some(GridSample::Histogram(Box::new(result)))
286 }
287 Irate | Idelta => {
288 let had_floats = floats.is_some();
290 record_mixed_last_two(collector, function, floats.as_ref(), histograms);
291 let tail_histograms = &histograms[histograms.len().saturating_sub(2)..];
292 if tail_histograms.len() == 2 {
293 record_histogram_flavor_warning(collector, function, tail_histograms);
294 if tail_histograms[1].0 > tail_histograms[0].0 {
295 record_histogram_pair_annotations(collector, function, tail_histograms);
296 }
297 }
298 let result = if function == Irate {
299 last_two::<true>(floats, histograms, offset_ms)?
300 } else {
301 last_two::<false>(floats, histograms, offset_ms)?
302 };
303 if result.is_none() && !had_floats && tail_histograms.len() == 2 {
304 record_warning(
305 collector,
306 format!(
307 "{}: dropped native histogram range with incompatible schemas",
308 function_name(function)
309 ),
310 );
311 }
312 result
313 }
314 SumOverTime | AvgOverTime | Rate | Increase | Delta => None,
317 })
318}
319
320fn function_name(function: RangeFunction) -> &'static str {
321 use RangeFunction::*;
322 match function {
323 Rate => "rate",
324 Increase => "increase",
325 Delta => "delta",
326 Irate => "irate",
327 Idelta => "idelta",
328 AvgOverTime => "avg_over_time",
329 MinOverTime => "min_over_time",
330 MaxOverTime => "max_over_time",
331 SumOverTime => "sum_over_time",
332 CountOverTime => "count_over_time",
333 LastOverTime => "last_over_time",
334 PresentOverTime => "present_over_time",
335 StddevOverTime => "stddev_over_time",
336 StdvarOverTime => "stdvar_over_time",
337 QuantileOverTime(_) => "quantile_over_time",
338 Resets => "resets",
339 Changes => "changes",
340 Deriv => "deriv",
341 PredictLinear(_) => "predict_linear",
342 DoubleExponentialSmoothing { .. } => "double_exponential_smoothing",
343 FirstOverTime => "first_over_time",
344 MadOverTime => "mad_over_time",
345 TsOfFirstOverTime => "ts_of_first_over_time",
346 TsOfLastOverTime => "ts_of_last_over_time",
347 TsOfMinOverTime => "ts_of_min_over_time",
348 TsOfMaxOverTime => "ts_of_max_over_time",
349 }
350}
351
352fn record_warning(collector: Option<&PromqlAnnotationCollector>, message: String) {
353 if let Some(collector) = collector {
354 collector.record_warning(message);
355 }
356}
357fn record_info(collector: Option<&PromqlAnnotationCollector>, message: String) {
358 if let Some(collector) = collector {
359 collector.record_info(message);
360 }
361}
362fn has_contradictory_reset_hints<'a>(
363 samples: impl IntoIterator<Item = &'a FloatHistogram>,
364) -> bool {
365 let mut saw_counter = false;
366 let mut saw_not_counter = false;
367 for histogram in samples {
368 saw_counter |= histogram.reset_hint == CounterResetHint::CounterReset;
369 saw_not_counter |= histogram.reset_hint == CounterResetHint::NotCounterReset;
370 }
371 saw_counter && saw_not_counter
372}
373
374fn record_histogram_flavor_warning(
381 collector: Option<&PromqlAnnotationCollector>,
382 function: RangeFunction,
383 histograms: &Histograms,
384) {
385 let is_counter = matches!(
386 function,
387 RangeFunction::Rate | RangeFunction::Increase | RangeFunction::Irate
388 );
389 let wrong_flavor = if is_counter {
390 histograms
391 .iter()
392 .any(|(_, histogram)| histogram.reset_hint == CounterResetHint::Gauge)
393 } else {
394 histograms
395 .first()
396 .is_some_and(|(_, histogram)| histogram.reset_hint != CounterResetHint::Gauge)
397 || histograms
398 .last()
399 .is_some_and(|(_, histogram)| histogram.reset_hint != CounterResetHint::Gauge)
400 };
401 if wrong_flavor {
402 let expected = if is_counter { "counter" } else { "gauge" };
403 record_warning(
404 collector,
405 format!(
406 "{}: native histogram input should be a {expected} histogram",
407 function_name(function)
408 ),
409 );
410 }
411}
412
413fn record_histogram_pair_annotations(
414 collector: Option<&PromqlAnnotationCollector>,
415 function: RangeFunction,
416 histograms: &Histograms,
417) {
418 let reconciled = histograms.windows(2).any(|pair| {
419 pair[0].1.uses_custom_buckets()
420 && pair[1].1.uses_custom_buckets()
421 && pair[0].1.custom_values != pair[1].1.custom_values
422 });
423 if reconciled {
424 record_info(
425 collector,
426 format!(
427 "{}: reconciled native histograms with different custom buckets",
428 function_name(function)
429 ),
430 );
431 }
432}
433
434fn record_mixed_last_two(
435 collector: Option<&PromqlAnnotationCollector>,
436 function: RangeFunction,
437 floats: Option<&FloatWindow<'_>>,
438 histograms: &Histograms,
439) {
440 if collector.is_none() {
443 return;
444 }
445 let Some(floats) = floats else {
446 return;
447 };
448 let mut float_index = floats.values.len();
449 let mut histogram_index = histograms.len();
450 let mut last = None;
451 let mut previous = None;
452 for _ in 0..2 {
453 let sample = match (float_index.checked_sub(1), histogram_index.checked_sub(1)) {
454 (Some(fi), Some(hi)) if floats.timestamps[fi] >= histograms[hi].0 => {
455 float_index = fi;
456 Some(Sample::Float(floats.values[fi]))
457 }
458 (Some(_), Some(hi)) => {
459 histogram_index = hi;
460 Some(Sample::Histogram(&histograms[hi].1))
461 }
462 (Some(fi), None) => {
463 float_index = fi;
464 Some(Sample::Float(floats.values[fi]))
465 }
466 (None, Some(hi)) => {
467 histogram_index = hi;
468 Some(Sample::Histogram(&histograms[hi].1))
469 }
470 (None, None) => None,
471 };
472 let Some(sample) = sample else { break };
473 previous = last;
474 last = Some(sample);
475 }
476 if matches!(
477 (previous, last),
478 (Some(Sample::Float(_)), Some(Sample::Histogram(_)))
479 | (Some(Sample::Histogram(_)), Some(Sample::Float(_)))
480 ) {
481 record_warning(
482 collector,
483 format!(
484 "{}: encountered a mix of float and native histogram samples in the last two points",
485 function_name(function)
486 ),
487 );
488 }
489}
490
491#[derive(Clone, Copy)]
493enum Sample<'a> {
494 Float(f64),
495 Histogram(&'a FloatHistogram),
496}
497
498fn merged<'a>(
500 floats: Option<FloatWindow<'a>>,
501 histograms: &'a Histograms,
502) -> impl Iterator<Item = (i64, Sample<'a>)> {
503 let mut floats = floats
504 .into_iter()
505 .flat_map(|window| window.timestamps.iter().zip(window.values))
506 .map(|(&ts, &value)| (ts, Sample::Float(value)))
507 .peekable();
508 let mut histograms = histograms
509 .iter()
510 .map(|(ts, h)| (*ts, Sample::Histogram(h)))
511 .peekable();
512 std::iter::from_fn(move || match (floats.peek(), histograms.peek()) {
513 (Some((float_ts, _)), Some((histogram_ts, _))) if float_ts < histogram_ts => floats.next(),
514 (_, Some(_)) => histograms.next(),
515 (Some(_), None) => floats.next(),
516 (None, None) => None,
517 })
518}
519
520fn edges(
523 floats: Option<FloatWindow<'_>>,
524 histograms: &Histograms,
525 kind: EdgeKind,
526 offset_ms: i64,
527) -> Result<u64> {
528 let mut count = 0;
529 let mut previous: Option<(i64, Sample<'_>)> = None;
530 for (timestamp, current) in merged(floats, histograms) {
531 if let Some((previous_ts, previous)) = previous {
532 count += match (previous, current) {
533 (Sample::Float(a), Sample::Float(b)) => count_edges(&[a, b], kind),
534 (Sample::Histogram(a), Sample::Histogram(b)) => u64::from(match kind {
535 EdgeKind::Resets => {
548 b.detect_counter_reset_shifted(a, previous_ts, timestamp, offset_ms)
549 }
550 EdgeKind::Changes => !b.equals(a),
551 }),
552 _ => 1,
553 };
554 }
555 previous = Some((timestamp, current));
556 }
557 Ok(count)
558}
559
560fn last_two<const IS_RATE: bool>(
563 floats: Option<FloatWindow<'_>>,
564 histograms: &Histograms,
565 offset_ms: i64,
566) -> Result<Option<GridSample>> {
567 let floats = floats.map(|window| {
568 let from = window.values.len().saturating_sub(2);
569 FloatWindow {
570 timestamps: &window.timestamps[from..],
571 values: &window.values[from..],
572 ..window
573 }
574 });
575 let histograms = &histograms[histograms.len().saturating_sub(2)..];
576 let tail: Vec<_> = merged(floats, histograms).collect();
577 let [.., (prev_ts, prev), (last_ts, last)] = tail[..] else {
578 return Ok(None);
579 };
580 Ok(match (prev, last) {
581 (Sample::Float(prev), Sample::Float(last)) => {
582 instant_delta::<IS_RATE>((prev_ts, prev), (last_ts, last)).map(GridSample::Float)
583 }
584 (Sample::Histogram(prev), Sample::Histogram(last)) => {
585 let interval = last_ts - prev_ts;
586 let mut result = last.clone();
587 if !IS_RATE || !last.detect_counter_reset_shifted(prev, prev_ts, last_ts, offset_ms) {
591 if result.uses_custom_buckets() != prev.uses_custom_buckets() {
592 return Ok(None);
593 }
594 result.sub(prev)?;
595 }
596 result.reset_hint = CounterResetHint::Gauge;
597 result.compact();
598 if IS_RATE {
599 result.div(interval as f64 / 1000.0);
600 }
601 Some(GridSample::Histogram(Box::new(result)))
602 }
603 _ => None,
604 })
605}
606
607fn histogram_rate(
610 points: &Histograms,
611 is_counter: bool,
612 offset_ms: i64,
613) -> Result<Option<FloatHistogram>> {
614 let last = &points[points.len() - 1].1;
615 let mut prev = Cow::Borrowed(&points[0].1);
616 let mut uses_custom_buckets = prev.uses_custom_buckets();
617 if is_counter {
621 let (second_ts, second) = &points[1];
622 if second.detect_counter_reset_shifted(&prev, points[0].0, *second_ts, offset_ms) {
623 prev = Cow::Owned(second.empty_like());
624 uses_custom_buckets = second.uses_custom_buckets();
625 }
626 }
627 if last.uses_custom_buckets() != uses_custom_buckets {
628 return Ok(None);
629 }
630 let mut min_schema = last.schema.min(prev.schema);
631 if is_counter {
632 for (_, current) in &points[1..points.len() - 1] {
633 min_schema = min_schema.min(current.schema);
634 if current.uses_custom_buckets() != uses_custom_buckets {
635 return Ok(None);
636 }
637 }
638 }
639 let mut result = last.copy_to_schema(min_schema)?;
640 result.sub(&prev)?;
641 if is_counter {
642 for (index, (current_ts, current)) in points.iter().enumerate().skip(1) {
643 if current.detect_counter_reset_shifted(
644 &prev,
645 points[index - 1].0,
646 *current_ts,
647 offset_ms,
648 ) {
649 result.add(&prev)?;
650 }
651 prev = Cow::Borrowed(current);
652 }
653 }
654 result.reset_hint = CounterResetHint::Gauge;
655 result.compact();
656 Ok(Some(result))
657}