1use std::collections::hash_map::Entry;
24use std::collections::{HashMap, HashSet};
25use std::sync::Arc;
26
27use common_query::promql_annotations::PromqlAnnotationCollector;
28use datafusion::error::{DataFusionError, Result};
29use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
30use datatypes::series::histogram::{CounterResetHint, HistogramBatchBuilder, HistogramView};
31use datatypes::series::samples::{
32 DenseSamplesRef, FieldSpec, RowCursor, SampleRef, Series, SeriesSchema,
33};
34use datatypes::series::time::{EvalGrid, GridRunPair, GridSpan, TimeAxis};
35use datatypes::series::{Label, SeriesLabels};
36
37use crate::functions::{NativeHistogramAdd, NativeHistogramSub};
38use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS, external, owned};
39use crate::histogram_eval::float_histogram::FloatHistogram;
40use crate::map::{ArithmeticOp, ComparisonOp};
41
42#[cfg(test)]
43mod tests;
44
45#[cfg(test)]
52thread_local! {
53 static VISITED_PAIRS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
54}
55
56#[cfg(test)]
58pub(crate) fn reset_visited_pairs() {
59 VISITED_PAIRS.with(|visited| visited.set(0));
60}
61
62#[cfg(test)]
69pub(crate) fn visited_pairs() -> usize {
70 VISITED_PAIRS.with(std::cell::Cell::get)
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
75pub enum BinaryOp {
76 Add,
77 Sub,
78 Mul,
79 Div,
80 Mod,
81 Pow,
82 Atan2,
83 Eq,
84 Ne,
85 Gt,
86 Lt,
87 Ge,
88 Le,
89}
90
91#[derive(Clone, Copy, Debug)]
93pub enum BinaryKind {
94 Arithmetic(ArithmeticOp),
95 Comparison(ComparisonOp),
96}
97
98impl BinaryOp {
99 #[inline]
103 pub fn kind(self) -> BinaryKind {
104 match self {
105 Self::Add => BinaryKind::Arithmetic(ArithmeticOp::Add),
106 Self::Sub => BinaryKind::Arithmetic(ArithmeticOp::Subtract),
107 Self::Mul => BinaryKind::Arithmetic(ArithmeticOp::Multiply),
108 Self::Div => BinaryKind::Arithmetic(ArithmeticOp::Divide),
109 Self::Mod => BinaryKind::Arithmetic(ArithmeticOp::Modulo),
110 Self::Pow => BinaryKind::Arithmetic(ArithmeticOp::Power),
111 Self::Atan2 => BinaryKind::Arithmetic(ArithmeticOp::Atan2),
112 Self::Eq => BinaryKind::Comparison(ComparisonOp::Equal),
113 Self::Ne => BinaryKind::Comparison(ComparisonOp::NotEqual),
114 Self::Gt => BinaryKind::Comparison(ComparisonOp::Greater),
115 Self::Lt => BinaryKind::Comparison(ComparisonOp::Less),
116 Self::Ge => BinaryKind::Comparison(ComparisonOp::GreaterEqual),
117 Self::Le => BinaryKind::Comparison(ComparisonOp::LessEqual),
118 }
119 }
120
121 pub fn is_comparison(self) -> bool {
122 matches!(self.kind(), BinaryKind::Comparison(_))
123 }
124
125 #[inline]
127 fn apply(self, lhs: f64, rhs: f64) -> (f64, bool) {
128 match self.kind() {
129 BinaryKind::Arithmetic(op) => (op.calculate(lhs, rhs), true),
130 BinaryKind::Comparison(op) => (lhs, op.apply(lhs, rhs)),
131 }
132 }
133}
134
135#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
137pub enum MatchingLabels {
138 On(Vec<Arc<str>>),
140 Ignoring(Vec<Arc<str>>),
143}
144
145#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
147pub enum Cardinality {
148 OneToOne,
149 ManyToOne(Vec<Arc<str>>),
151 OneToMany(Vec<Arc<str>>),
153}
154
155#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
157pub struct BinaryMatching {
158 pub op: BinaryOp,
159 pub return_bool: bool,
161 pub labels: MatchingLabels,
162 pub cardinality: Cardinality,
163 pub fill: FillValues,
164}
165
166#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
170pub struct FillValues {
171 pub lhs: Option<f64>,
172 pub rhs: Option<f64>,
173}
174
175impl PartialEq for FillValues {
177 fn eq(&self, other: &Self) -> bool {
178 let bits = |value: Option<f64>| value.map(f64::to_bits);
179 bits(self.lhs) == bits(other.lhs) && bits(self.rhs) == bits(other.rhs)
180 }
181}
182
183impl Eq for FillValues {}
184impl std::hash::Hash for FillValues {
185 fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
186 std::hash::Hash::hash(&self.lhs.map(f64::to_bits), h);
187 std::hash::Hash::hash(&self.rhs.map(f64::to_bits), h);
188 }
189}
190
191#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
193pub enum SetOp {
194 And,
195 Or,
196 Unless,
197}
198
199pub fn binary_output_schema(lhs: &SeriesSchema, rhs: &SeriesSchema) -> Result<Arc<SeriesSchema>> {
201 let grid = same_grid(lhs, rhs)?;
202 let fields = lhs.fields.len().min(rhs.fields.len());
203 Ok(Arc::new(SeriesSchema {
204 fields: lhs.fields[..fields].to_vec().into(),
205 eval_grid: Some(grid),
206 }))
207}
208
209pub fn binary_vectors(
217 matching: &BinaryMatching,
218 lhs_schema: &SeriesSchema,
219 lhs: &[Series],
220 rhs_schema: &SeriesSchema,
221 rhs: &[Series],
222) -> Result<Vec<Series>> {
223 binary_vectors_inner(matching, lhs_schema, lhs, rhs_schema, rhs, None, None, None)
224}
225
226#[derive(Clone, Copy)]
236pub(crate) struct NodeEvidence<'a> {
237 pub(crate) node: usize,
238 pub(crate) evidence: &'a DuplicateEvidence,
239}
240
241struct FieldEvidence<'a> {
242 node: usize,
243 field: usize,
244 evidence: &'a DuplicateEvidence,
245}
246
247#[allow(clippy::too_many_arguments)]
248pub(crate) fn binary_vectors_with_reservation(
249 matching: &BinaryMatching,
250 lhs_schema: &SeriesSchema,
251 lhs: &[Series],
252 rhs_schema: &SeriesSchema,
253 rhs: &[Series],
254 evidence: Option<NodeEvidence<'_>>,
255 annotations: Option<&PromqlAnnotationCollector>,
256 reserve: &mut dyn FnMut(usize) -> Result<()>,
257) -> Result<Vec<Series>> {
258 let mut budget = Budget::new(reserve);
259 binary_vectors_inner(
260 matching,
261 lhs_schema,
262 lhs,
263 rhs_schema,
264 rhs,
265 evidence,
266 annotations,
267 Some(&mut budget),
268 )
269}
270
271#[allow(clippy::too_many_arguments)]
274fn binary_vectors_inner(
275 matching: &BinaryMatching,
276 lhs_schema: &SeriesSchema,
277 lhs: &[Series],
278 rhs_schema: &SeriesSchema,
279 rhs: &[Series],
280 evidence: Option<NodeEvidence<'_>>,
281 annotations: Option<&PromqlAnnotationCollector>,
282 mut budget: Option<&mut Budget<'_>>,
283) -> Result<Vec<Series>> {
284 let grid = same_grid(lhs_schema, rhs_schema)?;
286 let width = lhs_schema.fields.len().min(rhs_schema.fields.len());
290 if let Some(budget) = budget.as_deref_mut() {
291 budget.hold(output_bytes(width))?;
292 }
293 let output = binary_output_schema(lhs_schema, rhs_schema)?;
294 let mut errors = Vec::new();
295 let mut fields = Vec::with_capacity(width);
296 for field in 0..width {
297 let lhs = Operand::try_new(lhs_schema, lhs, field)?;
298 let rhs = Operand::try_new(rhs_schema, rhs, field)?;
299 let field_evidence = evidence.map(|evidence| FieldEvidence {
300 node: evidence.node,
301 field,
302 evidence: evidence.evidence,
303 });
304 let results = binary_field(
305 matching,
306 &grid,
307 &lhs,
308 &rhs,
309 &mut errors,
310 field_evidence,
311 annotations,
312 budget.as_deref_mut(),
313 )?;
314 if let Some(budget) = budget.as_deref_mut() {
317 budget.phase(0)?;
318 }
319 fields.push(results);
320 }
321 earliest_error(errors)?;
322 merge_fields(fields, output, budget)
325}
326
327const VEC_MIN_CAPACITY: usize = 4;
329
330const KEY_LABEL_BYTES: usize = 2 * std::mem::size_of::<(Arc<str>, Arc<str>)>();
332
333const MATCHING_NAME_BYTES: usize = std::mem::size_of::<&str>();
336
337const GROUP_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, Vec<usize>)>();
339
340const MATCH_SLOT_BYTES: usize = 2 * std::mem::size_of::<(usize, usize)>();
342
343const RESULT_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, ResultRows)>();
345
346const RESULT_ROW_BYTES: usize =
350 2 * std::mem::size_of::<usize>() + std::mem::size_of::<Option<GridSample>>();
351
352const SORT_ROW_BYTES: usize =
356 4 * std::mem::size_of::<usize>() + 2 * std::mem::size_of::<Option<GridSample>>();
357
358const MERGE_SLOT_BYTES: usize =
360 2 * std::mem::size_of::<(GroupKey, (SeriesLabels, Vec<(usize, usize, GridSample)>))>();
361
362pub(crate) const HISTOGRAM_ROW_BYTES: usize = 4 * std::mem::size_of::<f64>()
364 + 2 * std::mem::size_of::<i32>()
365 + std::mem::size_of::<i64>()
366 + 7 * std::mem::size_of::<i32>();
367
368const ERROR_TEXT_BYTES: usize = 256;
370
371fn output_bytes(fields: usize) -> usize {
374 fields
375 .saturating_mul(std::mem::size_of::<Results>() + 2 * std::mem::size_of::<FieldSpec>())
376 .saturating_add(std::mem::size_of::<SeriesSchema>())
377}
378
379pub(crate) struct Budget<'a> {
394 reserve: &'a mut dyn FnMut(usize) -> Result<()>,
396 held: usize,
398 phase: usize,
400 requested: Option<usize>,
402}
403
404impl<'a> Budget<'a> {
405 pub(crate) fn new(reserve: &'a mut dyn FnMut(usize) -> Result<()>) -> Self {
406 Self {
407 reserve,
408 held: 0,
409 phase: 0,
410 requested: None,
411 }
412 }
413
414 pub(crate) fn hold(&mut self, bytes: usize) -> Result<()> {
416 self.held = self.held.saturating_add(bytes);
417 self.admit()
418 }
419
420 pub(crate) fn phase(&mut self, bytes: usize) -> Result<()> {
422 self.phase = bytes;
423 self.admit()
424 }
425
426 pub(crate) fn grow(&mut self, bytes: usize) -> Result<()> {
428 self.phase = self.phase.saturating_add(bytes);
429 self.admit()
430 }
431
432 fn admit(&mut self) -> Result<()> {
435 let total = self.held.saturating_add(self.phase);
436 if self.requested != Some(total) {
437 self.requested = Some(total);
438 (self.reserve)(total)?;
439 }
440 Ok(())
441 }
442}
443
444#[derive(Default)]
446struct FieldMetadata {
447 tables: usize,
449 errors: usize,
452 largest_key: usize,
454 pairing: usize,
456}
457
458fn field_metadata_bytes(
468 matching: &BinaryMatching,
469 include: &[Arc<str>],
470 points: usize,
471 many: &Operand<'_>,
472 one: &Operand<'_>,
473) -> FieldMetadata {
474 let mut bytes = points.saturating_mul(3);
475 let mut largest_key = 0usize;
476 for series in one.series {
477 bytes = bytes
478 .saturating_add(match_key_bytes(&series.metric, &matching.labels))
479 .saturating_add(2 * std::mem::size_of::<usize>())
480 .saturating_add(GROUP_SLOT_BYTES)
481 .saturating_add(2 * std::mem::size_of::<&GroupKey>())
482 .saturating_add(2 * std::mem::size_of::<(&GroupKey, usize)>());
483 largest_key = largest_key.max(result_key_bytes(&series.metric));
484 }
485 let mut lookup = 0usize;
486 for series in many.series {
487 lookup = lookup.max(match_key_bytes(&series.metric, &matching.labels));
488 largest_key = largest_key.max(result_key_bytes(&series.metric));
489 }
490 let include_text = include.iter().fold(0usize, |bytes, name| {
493 bytes.saturating_add(name.len()).saturating_add(6)
494 });
495 let text = many
496 .series
497 .iter()
498 .chain(one.series)
499 .fold(include_text, |bytes, series| {
500 bytes.max(label_text_bytes(&series.metric).saturating_add(include_text))
501 });
502 let pairing = widest_metric(many)
505 .zip(widest_metric(one))
506 .map_or(0, |(many, one)| pair_bytes(many, one, matching, include));
507 FieldMetadata {
508 tables: bytes.saturating_add(lookup),
509 errors: 3usize.saturating_mul(ERROR_TEXT_BYTES.saturating_add(text)),
510 largest_key: largest_key.saturating_add(include.len().saturating_mul(KEY_LABEL_BYTES)),
511 pairing: pairing.saturating_add(histogram_phase_bytes(many, one)),
512 }
513}
514
515fn widest_metric<'a>(operand: &'a Operand<'_>) -> Option<&'a SeriesLabels> {
518 operand
519 .series
520 .iter()
521 .map(|series| &series.metric)
522 .max_by_key(|metric| metric.tags().len())
523}
524
525fn pair_bytes(
537 many: &SeriesLabels,
538 one: &SeriesLabels,
539 matching: &BinaryMatching,
540 include: &[Arc<str>],
541) -> usize {
542 let labels = 3usize
546 .saturating_mul(many.tags().len().saturating_add(include.len()))
547 .saturating_mul(std::mem::size_of::<Label>());
548 let key = many
549 .tags()
550 .len()
551 .saturating_add(include.len())
552 .saturating_add(1)
553 .saturating_mul(KEY_LABEL_BYTES)
554 .saturating_add(many.name().map_or(0, str::len));
555 let names = match (&matching.cardinality, &matching.labels) {
558 (Cardinality::OneToOne, MatchingLabels::On(names))
559 | (Cardinality::OneToOne, MatchingLabels::Ignoring(names)) => {
560 names.len().saturating_mul(MATCHING_NAME_BYTES)
561 }
562 _ => 0,
563 };
564 labels
565 .saturating_add(copied_bytes(one, include))
566 .saturating_add(key)
567 .saturating_add(names)
568}
569
570fn copied_bytes(one: &SeriesLabels, include: &[Arc<str>]) -> usize {
573 include
574 .iter()
575 .fold(0usize, |bytes, name| match one.get(name) {
576 Some(value) if !value.is_empty() => {
577 bytes.saturating_add(value.len()).saturating_add(name.len())
578 }
579 _ => bytes,
580 })
581}
582
583fn result_key_bytes(metric: &SeriesLabels) -> usize {
586 metric
587 .tags()
588 .len()
589 .saturating_add(1)
590 .saturating_mul(KEY_LABEL_BYTES)
591 .saturating_add(metric.name().map_or(0, str::len))
592}
593
594fn result_set_bytes(metric: &SeriesLabels, one: &SeriesLabels, include: &[Arc<str>]) -> usize {
597 metric
598 .tags()
599 .len()
600 .saturating_mul(std::mem::size_of::<Label>())
601 .saturating_add(copied_bytes(one, include))
602 .saturating_add(result_key_bytes(metric))
603 .saturating_add(RESULT_SLOT_BYTES)
604}
605
606fn merge_bytes(
616 kept: usize,
617 sets: usize,
618 fields: usize,
619 histograms: usize,
620 histogram_heap: usize,
621) -> usize {
622 let row = (2 * std::mem::size_of::<(usize, usize, GridSample)>())
625 .saturating_add(2 * std::mem::size_of::<usize>())
626 .saturating_add(2 * std::mem::size_of::<GridSpan>());
627 kept.saturating_mul(row)
628 .saturating_add(
630 sets.saturating_mul(MERGE_SLOT_BYTES.saturating_add(2 * std::mem::size_of::<Series>())),
631 )
632 .saturating_add(2 * fields.saturating_mul(std::mem::size_of::<Option<GridSample>>()))
634 .saturating_add(fields.saturating_mul(std::mem::size_of::<HistogramBatchBuilder>()))
638 .saturating_add(histograms.saturating_mul(2 * HISTOGRAM_ROW_BYTES))
639 .saturating_add(2 * histogram_heap)
640}
641
642fn match_key_bytes(metric: &SeriesLabels, labels: &MatchingLabels) -> usize {
648 match labels {
649 MatchingLabels::On(names) => {
650 names
651 .iter()
652 .fold(0usize, |bytes, name| match metric.get(name) {
653 Some(value) if !value.is_empty() => bytes
654 .saturating_add(KEY_LABEL_BYTES)
655 .saturating_add(value.len()),
656 _ => bytes,
657 })
658 }
659 MatchingLabels::Ignoring(names) => metric
660 .tags()
661 .iter()
662 .filter(|tag| !tag.value.is_empty() && !names.contains(&tag.name))
663 .count()
664 .saturating_mul(KEY_LABEL_BYTES),
665 }
666}
667
668fn label_text_bytes(metric: &SeriesLabels) -> usize {
671 let named = metric
672 .name()
673 .map_or(0, |name| name.len().saturating_add(10));
674 metric.tags().iter().fold(named, |bytes, tag| {
675 bytes
676 .saturating_add(tag.name.len())
677 .saturating_add(tag.value.len())
678 .saturating_add(6)
679 })
680}
681
682pub(crate) fn owned_histogram_bytes(view: &HistogramView<'_>) -> usize {
685 let sides = [view.positive, view.negative];
686 let buckets = sides
687 .iter()
688 .map(|side| {
689 side.buckets
690 .len()
691 .saturating_mul(std::mem::size_of::<(i32, f64)>())
692 })
693 .fold(0usize, usize::saturating_add);
694 let spans = sides
695 .iter()
696 .map(|side| {
697 side.span_offsets
698 .len()
699 .saturating_mul(std::mem::size_of::<(i32, i32)>())
700 })
701 .fold(0usize, usize::saturating_add);
702 std::mem::size_of::<FloatHistogram>()
703 .saturating_add(buckets)
704 .saturating_add(spans)
705 .saturating_add(
706 view.custom_values
707 .len()
708 .saturating_mul(std::mem::size_of::<f64>()),
709 )
710}
711
712fn result_histogram_bytes(histogram: &FloatHistogram) -> usize {
715 std::mem::size_of::<FloatHistogram>().saturating_add(histogram.heap_bytes())
716}
717
718fn histogram_phase_bytes(many: &Operand<'_>, one: &Operand<'_>) -> usize {
724 let operand = |operand: &Operand<'_>| match operand.widest_histogram() {
726 Some(view) => (
727 owned_histogram_bytes(&view),
728 view.positive
729 .buckets
730 .len()
731 .saturating_add(view.negative.buckets.len()),
732 view.custom_values.len(),
733 ),
734 None => (0, 0, 0),
735 };
736 let (lhs_owned, lhs_buckets, lhs_bounds) = operand(many);
737 let (rhs_owned, rhs_buckets, rhs_bounds) = operand(one);
738 if lhs_owned == 0 && rhs_owned == 0 {
739 return 0;
740 }
741 lhs_owned
742 .saturating_add(rhs_owned)
743 .saturating_add(
744 lhs_buckets
745 .saturating_add(rhs_buckets)
746 .saturating_mul(2 * std::mem::size_of::<(i32, f64)>()),
747 )
748 .saturating_add(
749 lhs_bounds
750 .max(rhs_bounds)
751 .saturating_mul(2 * std::mem::size_of::<f64>()),
752 )
753 .saturating_add(2 * std::mem::size_of::<FloatHistogram>())
754}
755
756#[allow(clippy::too_many_arguments)]
763fn binary_field(
764 matching: &BinaryMatching,
765 grid: &EvalGrid,
766 lhs: &Operand<'_>,
767 rhs: &Operand<'_>,
768 errors: &mut Vec<(usize, u8, String)>,
769 evidence: Option<FieldEvidence<'_>>,
770 annotations: Option<&PromqlAnnotationCollector>,
771 mut budget: Option<&mut Budget<'_>>,
772) -> Result<Results> {
773 let (many, one, include, one_is_left) = match &matching.cardinality {
774 Cardinality::OneToOne => (lhs, rhs, &[][..], false),
775 Cardinality::ManyToOne(include) => (lhs, rhs, &include[..], false),
776 Cardinality::OneToMany(include) => (rhs, lhs, &include[..], true),
777 };
778 let points = grid.spec().len as usize;
779 let timestamp_at = |point: usize| {
780 (grid.spec().start_ms as i128 + point as i128 * grid.spec().step_ms as i128) as i64
781 };
782 let errors_before = errors.len();
783 let metadata = match budget.as_deref_mut() {
787 Some(budget) => {
788 let metadata = field_metadata_bytes(matching, include, points, many, one);
789 budget.phase(metadata.tables.saturating_add(metadata.pairing))?;
790 metadata
791 }
792 None => FieldMetadata::default(),
793 };
794 let fill = if one_is_left {
797 FillValues {
798 lhs: matching.fill.rhs,
799 rhs: matching.fill.lhs,
800 }
801 } else {
802 matching.fill
803 };
804 let filling = fill.lhs.is_some() || fill.rhs.is_some();
807 let lhs_present = lhs.presence(points);
808 let rhs_present = rhs.presence(points);
809 if let Some(evidence) = &evidence {
810 evidence.evidence.publish(
811 evidence.node,
812 evidence.field,
813 &lhs_present,
814 &rhs_present,
815 filling,
816 )?;
817 }
818 let evaluated: Vec<bool> = lhs_present
819 .iter()
820 .copied()
821 .zip(rhs_present.iter().copied())
822 .map(|(lhs, rhs)| if filling { lhs || rhs } else { lhs && rhs })
823 .collect();
824
825 let one_groups = group(one, &matching.labels);
826 let mut one_duplicate: Option<(usize, &GroupKey)> = None;
827 for (key, members) in &one_groups {
828 let mut duplicate_at: Option<usize> = None;
832 let mut group_key: Option<Arc<GroupKey>> = None;
833 overlap(
834 one,
835 members,
836 |point| {
837 if evaluated[point] {
838 if duplicate_at.is_none_or(|first| point < first) {
842 duplicate_at = Some(point);
843 }
844 } else if let Some(evidence) = &evidence {
845 let side = if one_is_left { "left" } else { "right" };
849 evidence.evidence.record_candidate(
850 evidence.node,
851 evidence.field,
852 point,
853 Arc::clone(group_key.get_or_insert_with(|| Arc::new(key.clone()))),
854 side,
855 timestamp_at(point),
856 )?;
857 }
858 Ok(())
859 },
860 metadata.tables.saturating_add(metadata.pairing),
861 budget.as_deref_mut(),
862 )?;
863 if let Some(point) = duplicate_at
864 && one_duplicate.is_none_or(|(first, _)| point < first)
865 {
866 one_duplicate = Some((point, key));
867 }
868 }
869
870 let drop_name = !matching.op.is_comparison() || matching.return_bool;
871 let mut results = Results::default();
872 let mut pairs = Pairs {
873 matching,
874 one_is_left,
875 annotations,
876 group_keys: Vec::new(),
877 group_ids: HashMap::new(),
878 matched: (matching.cardinality == Cardinality::OneToOne || fill.lhs.is_some())
882 .then(HashSet::new),
883 implicit_many_to_one: None,
884 };
885 for (many_index, many_series) in many.series.iter().enumerate() {
886 let key = group_key(&many_series.metric, &matching.labels);
887 let candidates = one_groups.get(&key).map_or(&[][..], Vec::as_slice);
888 if candidates.is_empty() && fill.rhs.is_none() {
889 continue;
890 }
891 let group = pairs.group_id(&key);
892 for &one_index in candidates {
893 #[cfg(test)]
897 VISITED_PAIRS.with(|visited| visited.set(visited.get() + 1));
898 let metric = result_metric(
902 &many_series.metric,
903 &one.series[one_index].metric,
904 matching,
905 include,
906 drop_name,
907 )?;
908 let label_set = if budget.is_some() {
909 result_set_bytes(&metric, &one.series[one_index].metric, include)
910 } else {
911 0
912 };
913 let (mut many_cursor, mut one_cursor) =
920 (many.cursor(many_index), one.cursor(one_index));
921 let mut slot = RowSlot::Unfiled(&mut results.series);
924 for pair in many.shared_runs(many_index, one, one_index) {
925 for offset in 0..pair.len {
926 let point = pair.position + offset;
927 let (many_value, one_value) = (
928 many_cursor
929 .at(pair.row + offset)
930 .expect("a row never goes back"),
931 one_cursor
932 .at(pair.other_row + offset)
933 .expect("a row never goes back"),
934 );
935 slot = pairs.apply(
936 slot,
937 &mut results.totals,
938 &metric,
939 label_set,
940 group,
941 point,
942 many_value,
943 one_value,
944 true,
945 budget.as_deref_mut(),
946 )?;
947 }
948 }
949 }
950 if let Some(value) = fill.rhs {
953 let metric = result_metric(
954 &many_series.metric,
955 &metric_of(&key)?,
956 matching,
957 include,
958 drop_name,
959 )?;
960 let label_set = if budget.is_some() {
961 result_set_bytes(&metric, &many_series.metric, include)
962 } else {
963 0
964 };
965 let mut cursor = many.cursor(many_index);
966 let mut candidate_cursors: Vec<RowCursor<'_>> =
967 candidates.iter().map(|&index| one.cursor(index)).collect();
968 let mut slot = RowSlot::Unfiled(&mut results.series);
970 for (point, row) in many.positions(many_index) {
971 let sample = cursor.at(row).expect("a row never goes back");
972 let matched = candidates
973 .iter()
974 .zip(&mut candidate_cursors)
975 .any(|(&index, cursor)| one.present(index, point, cursor));
976 if !matched {
977 slot = pairs.apply(
979 slot,
980 &mut results.totals,
981 &metric,
982 label_set,
983 group,
984 point,
985 sample,
986 SampleRef::Float(value),
987 false,
988 budget.as_deref_mut(),
989 )?;
990 }
991 }
992 }
993 }
994 if let Some(value) = fill.lhs {
997 for (one_index, one_series) in one.series.iter().enumerate() {
998 let key = group_key(&one_series.metric, &matching.labels);
999 let group = pairs.group_id(&key);
1000 let metric = result_metric(
1001 &metric_of(&key)?,
1002 &one_series.metric,
1003 matching,
1004 include,
1005 drop_name,
1006 )?;
1007 let label_set = if budget.is_some() {
1008 result_set_bytes(&metric, &one_series.metric, include)
1009 } else {
1010 0
1011 };
1012 let mut cursor = one.cursor(one_index);
1013 let mut slot = RowSlot::Unfiled(&mut results.series);
1014 for (point, row) in one.positions(one_index) {
1015 if !pairs
1016 .matched
1017 .as_ref()
1018 .is_some_and(|matched| matched.contains(&(group, point)))
1019 {
1020 let sample = cursor.at(row).expect("a row never goes back");
1021 slot = pairs.apply(
1024 slot,
1025 &mut results.totals,
1026 &metric,
1027 label_set,
1028 group,
1029 point,
1030 SampleRef::Float(value),
1031 sample,
1032 false,
1033 budget.as_deref_mut(),
1034 )?;
1035 }
1036 }
1037 }
1038 }
1039 let Pairs {
1042 group_keys,
1043 implicit_many_to_one,
1044 ..
1045 } = pairs;
1046 if let Some(budget) = budget.as_deref_mut() {
1049 budget.phase(
1050 metadata
1051 .tables
1052 .saturating_add(metadata.errors)
1053 .saturating_add(metadata.largest_key)
1054 .saturating_add(results.totals.rows.saturating_mul(SORT_ROW_BYTES)),
1055 )?;
1056 }
1057 if let Some((point, key)) = one_duplicate {
1060 let side = if one_is_left { "left" } else { "right" };
1061 errors.push((point, 0, duplicate_message(key, side, timestamp_at(point))));
1062 }
1063 if let Some((point, group)) = implicit_many_to_one {
1064 let key = &group_keys[group];
1065 errors.push((
1066 point,
1067 1,
1068 format!(
1069 "multiple matches for labels {} at {} ms: many-to-one matching must be explicit \
1070 (group_left/group_right)",
1071 render(key),
1072 timestamp_at(point)
1073 ),
1074 ));
1075 }
1076 if let Some(duplicate) = results.sort_rows() {
1077 let grouping = duplicate.within_group && matching.cardinality != Cardinality::OneToOne;
1078 errors.push(if grouping {
1079 (
1080 duplicate.point,
1081 1,
1082 format!(
1083 "multiple matches for labels {} at {} ms: grouping labels must ensure \
1084 unique matches",
1085 render(&duplicate.key),
1086 timestamp_at(duplicate.point)
1087 ),
1088 )
1089 } else {
1090 (
1091 duplicate.point,
1092 2,
1093 same_labelset(&duplicate.key, timestamp_at(duplicate.point)),
1094 )
1095 });
1096 }
1097 if let Some(budget) = budget {
1100 let appended = errors[errors_before..]
1101 .iter()
1102 .fold(0usize, |bytes, (_, _, text)| {
1103 bytes
1104 .saturating_add(std::mem::size_of::<String>())
1105 .saturating_add(text.capacity())
1106 });
1107 budget.hold(appended)?;
1108 }
1109 Ok(results)
1110}
1111
1112struct Pairs<'a> {
1117 matching: &'a BinaryMatching,
1118 one_is_left: bool,
1119 annotations: Option<&'a PromqlAnnotationCollector>,
1120 group_keys: Vec<GroupKey>,
1121 group_ids: HashMap<GroupKey, usize>,
1122 matched: Option<HashSet<(usize, usize)>>,
1126 implicit_many_to_one: Option<(usize, usize)>,
1127}
1128
1129impl Pairs<'_> {
1130 fn group_id(&mut self, key: &GroupKey) -> usize {
1132 if let Some(&id) = self.group_ids.get(key) {
1133 return id;
1134 }
1135 let id = self.group_keys.len();
1136 self.group_keys.push(key.clone());
1137 self.group_ids.insert(key.clone(), id);
1138 id
1139 }
1140
1141 #[allow(clippy::too_many_arguments)]
1150 fn apply<'s>(
1151 &mut self,
1152 slot: RowSlot<'s>,
1153 totals: &mut ResultTotals,
1154 metric: &SeriesLabels,
1155 label_set: usize,
1156 group: usize,
1157 point: usize,
1158 many_value: SampleRef<'_>,
1159 one_value: SampleRef<'_>,
1160 actual_pair: bool,
1161 mut budget: Option<&mut Budget<'_>>,
1162 ) -> Result<RowSlot<'s>> {
1163 if matches!(many_value, SampleRef::Missing) || matches!(one_value, SampleRef::Missing) {
1164 return Ok(slot);
1165 }
1166 let (lhs_value, rhs_value) = if self.one_is_left {
1167 (one_value, many_value)
1168 } else {
1169 (many_value, one_value)
1170 };
1171 let dropped_op = if self.annotations.is_some() {
1177 unsupported_histogram_arithmetic(self.matching.op, &lhs_value, &rhs_value)
1178 } else {
1179 None
1180 };
1181 let pair_annotations = if actual_pair { self.annotations } else { None };
1184 let Some((result, keep)) =
1185 elem_binop(self.matching.op, lhs_value, rhs_value, pair_annotations)?
1186 else {
1187 if let (Some(collector), Some(op)) = (self.annotations, dropped_op) {
1188 collector.record_info(format!(
1189 "{op}: dropped native histogram samples because this binary operation is not supported for native histograms"
1190 ));
1191 }
1192 return Ok(slot);
1194 };
1195 if let Some(matched) = &mut self.matched {
1198 if matched.len() + 1 > matched.capacity()
1202 && let Some(budget) = budget.as_deref_mut()
1203 {
1204 let grown = (2 * matched.capacity()).max(VEC_MIN_CAPACITY);
1205 budget.grow(
1206 grown
1207 .saturating_sub(matched.capacity())
1208 .saturating_mul(MATCH_SLOT_BYTES),
1209 )?;
1210 }
1211 if !matched.insert((group, point))
1212 && self.matching.cardinality == Cardinality::OneToOne
1213 && self
1214 .implicit_many_to_one
1215 .is_none_or(|(first, _)| point < first)
1216 {
1217 self.implicit_many_to_one = Some((point, group));
1218 }
1219 }
1220 let value = if self.matching.return_bool {
1223 drop(result);
1224 Some(GridSample::Float(if keep { 1.0 } else { 0.0 }))
1225 } else if keep {
1226 Some(result)
1227 } else {
1228 drop(result);
1229 None
1230 };
1231 slot.file(totals, metric, label_set, group, point, value, budget)
1232 }
1233}
1234
1235fn metric_of(key: &GroupKey) -> Result<SeriesLabels> {
1237 let mut name = None;
1238 let mut labels = Vec::with_capacity(key.len());
1239 for (label, value) in key {
1240 if &**label == "__name__" {
1241 name = Some(value.clone());
1242 } else {
1243 labels.push(Label {
1244 name: label.clone(),
1245 value: value.clone(),
1246 });
1247 }
1248 }
1249 SeriesLabels::try_new(name, labels).map_err(external)
1250}
1251
1252fn earliest_error(errors: Vec<(usize, u8, String)>) -> Result<()> {
1253 match errors
1254 .into_iter()
1255 .min_by_key(|(point, rank, _)| (*point, *rank))
1256 {
1257 Some((_, _, error)) => Err(DataFusionError::Execution(error)),
1258 None => Ok(()),
1259 }
1260}
1261
1262pub fn set_vectors(
1265 op: SetOp,
1266 labels: &MatchingLabels,
1267 lhs_schema: &SeriesSchema,
1268 lhs: &[Series],
1269 rhs_schema: &SeriesSchema,
1270 rhs: &[Series],
1271) -> Result<Vec<Series>> {
1272 set_vectors_inner(op, labels, lhs_schema, lhs, rhs_schema, rhs, None)
1273}
1274
1275pub(crate) fn set_vectors_with_reservation(
1281 op: SetOp,
1282 labels: &MatchingLabels,
1283 lhs_schema: &SeriesSchema,
1284 lhs: &[Series],
1285 rhs_schema: &SeriesSchema,
1286 rhs: &[Series],
1287 reserve: &mut dyn FnMut(usize) -> Result<()>,
1288) -> Result<Vec<Series>> {
1289 let mut budget = Budget::new(reserve);
1290 set_vectors_inner(
1291 op,
1292 labels,
1293 lhs_schema,
1294 lhs,
1295 rhs_schema,
1296 rhs,
1297 Some(&mut budget),
1298 )
1299}
1300
1301fn set_vectors_inner(
1303 op: SetOp,
1304 labels: &MatchingLabels,
1305 lhs_schema: &SeriesSchema,
1306 lhs: &[Series],
1307 rhs_schema: &SeriesSchema,
1308 rhs: &[Series],
1309 mut budget: Option<&mut Budget<'_>>,
1310) -> Result<Vec<Series>> {
1311 let grid = same_grid(lhs_schema, rhs_schema)?;
1312 if lhs_schema.fields.len() != rhs_schema.fields.len() {
1313 return Err(DataFusionError::NotImplemented(
1314 "set operators between vectors with different field counts".into(),
1315 ));
1316 }
1317 let width = lhs_schema.fields.len();
1318 if let Some(budget) = budget.as_deref_mut() {
1319 budget.hold(output_bytes(width))?;
1320 }
1321 let output = Arc::new(SeriesSchema {
1322 fields: lhs_schema.fields.clone(),
1323 eval_grid: Some(grid.clone()),
1324 });
1325 let mut errors = Vec::new();
1326 let mut fields = Vec::with_capacity(width);
1327 for field in 0..width {
1328 let lhs = Operand::try_new(lhs_schema, lhs, field)?;
1329 let rhs = Operand::try_new(rhs_schema, rhs, field)?;
1330 let results = set_field(
1331 op,
1332 labels,
1333 &grid,
1334 &lhs,
1335 &rhs,
1336 &mut errors,
1337 budget.as_deref_mut(),
1338 )?;
1339 if let Some(budget) = budget.as_deref_mut() {
1341 budget.phase(0)?;
1342 }
1343 fields.push(results);
1344 }
1345 earliest_error(errors)?;
1346 merge_fields(fields, output, budget)
1347}
1348
1349struct SetFieldMetadata {
1351 tables: usize,
1353 scratch: usize,
1356 error: usize,
1358}
1359
1360fn set_field_metadata(
1361 labels: &MatchingLabels,
1362 kept: &Operand<'_>,
1363 filter: &Operand<'_>,
1364) -> SetFieldMetadata {
1365 let mut tables = 0usize;
1366 for series in filter.series {
1367 tables = tables
1368 .saturating_add(match_key_bytes(&series.metric, labels))
1369 .saturating_add(GROUP_SLOT_BYTES);
1370 }
1371 let (mut scratch, mut text) = (0usize, 0usize);
1374 for series in kept.series.iter().chain(filter.series) {
1375 scratch = scratch
1376 .max(match_key_bytes(&series.metric, labels))
1377 .max(result_key_bytes(&series.metric));
1378 text = text.max(label_text_bytes(&series.metric));
1379 }
1380 SetFieldMetadata {
1381 tables,
1382 scratch,
1383 error: ERROR_TEXT_BYTES.saturating_add(text),
1384 }
1385}
1386
1387fn set_field(
1390 op: SetOp,
1391 labels: &MatchingLabels,
1392 grid: &EvalGrid,
1393 lhs: &Operand<'_>,
1394 rhs: &Operand<'_>,
1395 errors: &mut Vec<(usize, u8, String)>,
1396 mut budget: Option<&mut Budget<'_>>,
1397) -> Result<Results> {
1398 let (kept, filter, keep_matched) = match op {
1399 SetOp::And => (lhs, rhs, true),
1400 SetOp::Unless => (lhs, rhs, false),
1401 SetOp::Or => (rhs, lhs, false),
1402 };
1403 let metadata = match budget.as_deref_mut() {
1406 Some(budget) => {
1407 let metadata = set_field_metadata(labels, kept, filter);
1408 budget.phase(metadata.tables.saturating_add(metadata.scratch))?;
1409 Some(metadata)
1410 }
1411 None => None,
1412 };
1413 let presence = group_presence(
1414 filter,
1415 labels,
1416 grid.spec().len as usize,
1417 budget.as_deref_mut(),
1418 )?;
1419 let charged = budget.is_some();
1422 let label_set = |metric: &SeriesLabels| {
1423 if charged {
1424 result_set_bytes(metric, metric, &[])
1425 } else {
1426 0
1427 }
1428 };
1429 let mut results = Results::default();
1430 if op == SetOp::Or {
1431 for index in 0..lhs.series.len() {
1432 let metric = &lhs.series[index].metric;
1433 let label_set = label_set(metric);
1434 let mut cursor = lhs.cursor(index);
1435 let mut slot = RowSlot::Unfiled(&mut results.series);
1438 for (point, row) in lhs.positions(index) {
1439 if let Some(value) = owned(cursor.at(row).expect("a row never goes back"))? {
1440 slot = slot.file(
1441 &mut results.totals,
1442 metric,
1443 label_set,
1444 0,
1445 point,
1446 Some(value),
1447 budget.as_deref_mut(),
1448 )?;
1449 }
1450 }
1451 }
1452 }
1453 for (index, series) in kept.series.iter().enumerate() {
1454 let label_set = label_set(&series.metric);
1455 let bits = presence.get(&group_key(&series.metric, labels));
1456 let mut cursor = kept.cursor(index);
1457 let mut slot = RowSlot::Unfiled(&mut results.series);
1458 for (point, row) in kept.positions(index) {
1459 let sample = cursor.at(row).expect("a row never goes back");
1460 if matches!(sample, SampleRef::Missing) {
1461 continue;
1462 }
1463 let matched = bits.is_some_and(|bits| bits[point / 64] & (1 << (point % 64)) != 0);
1464 if matched == keep_matched {
1465 let value = owned(sample)?;
1466 slot = slot.file(
1467 &mut results.totals,
1468 &series.metric,
1469 label_set,
1470 0,
1471 point,
1472 value,
1473 budget.as_deref_mut(),
1474 )?;
1475 }
1476 }
1477 }
1478 drop(presence);
1481 if let (Some(budget), Some(metadata)) = (budget.as_deref_mut(), &metadata) {
1482 budget.phase(
1483 metadata
1484 .error
1485 .saturating_add(metadata.scratch)
1486 .saturating_add(results.totals.rows.saturating_mul(SORT_ROW_BYTES)),
1487 )?;
1488 }
1489 if let Some(duplicate) = results.sort_rows() {
1490 let timestamp = (grid.spec().start_ms as i128
1491 + duplicate.point as i128 * grid.spec().step_ms as i128) as i64;
1492 let message = same_labelset(&duplicate.key, timestamp);
1493 if let Some(budget) = budget {
1495 budget.hold(std::mem::size_of::<String>().saturating_add(message.capacity()))?;
1496 }
1497 errors.push((duplicate.point, 0, message));
1498 }
1499 Ok(results)
1500}
1501
1502fn group_presence(
1509 operand: &Operand<'_>,
1510 labels: &MatchingLabels,
1511 points: usize,
1512 mut budget: Option<&mut Budget<'_>>,
1513) -> Result<HashMap<GroupKey, Vec<u64>>> {
1514 let words = points.div_ceil(64);
1515 let mut presence: HashMap<GroupKey, Vec<u64>> = HashMap::new();
1516 for (index, series) in operand.series.iter().enumerate() {
1517 let bits = match presence.entry(group_key(&series.metric, labels)) {
1518 Entry::Occupied(entry) => entry.into_mut(),
1519 Entry::Vacant(entry) => {
1520 if let Some(budget) = budget.as_deref_mut() {
1521 budget.grow(words.saturating_mul(std::mem::size_of::<u64>()))?;
1522 }
1523 entry.insert(vec![0; words])
1524 }
1525 };
1526 let mut cursor = operand.cursor(index);
1527 for (point, row) in operand.positions(index) {
1528 if !matches!(
1529 cursor.at(row).expect("a row never goes back"),
1530 SampleRef::Missing
1531 ) {
1532 bits[point / 64] |= 1 << (point % 64);
1533 }
1534 }
1535 }
1536 Ok(presence)
1537}
1538
1539fn merge_fields(
1548 fields: Vec<Results>,
1549 schema: Arc<SeriesSchema>,
1550 mut budget: Option<&mut Budget<'_>>,
1551) -> Result<Vec<Series>> {
1552 let width = schema.fields.len();
1553 if let Some(budget) = budget.as_deref_mut() {
1556 let mut sets = 0usize;
1557 let mut merge = (0usize, 0usize, 0usize);
1558 for results in &fields {
1559 sets = sets.saturating_add(results.series.len());
1560 merge = (
1561 merge.0.saturating_add(results.totals.kept),
1562 merge.1.saturating_add(results.totals.histograms),
1563 merge.2.saturating_add(results.totals.histogram_heap),
1564 );
1565 }
1566 budget.phase(merge_bytes(merge.0, sets, width, merge.1, merge.2))?;
1567 }
1568 if width == 1 && fields.len() == 1 {
1571 return merge_single_field(fields, schema, budget);
1572 }
1573 merge_multi_field(fields, schema, budget)
1574}
1575
1576fn merge_multi_field(
1581 fields: Vec<Results>,
1582 schema: Arc<SeriesSchema>,
1583 mut budget: Option<&mut Budget<'_>>,
1584) -> Result<Vec<Series>> {
1585 let width = schema.fields.len();
1586 type Merged = (SeriesLabels, Vec<(usize, usize, GridSample)>);
1588 let mut merged: HashMap<GroupKey, Merged> = HashMap::new();
1589 for (field, results) in fields.into_iter().enumerate() {
1590 for (key, rows) in results.series {
1591 let (_, samples) = merged
1592 .entry(key)
1593 .or_insert_with(|| (rows.metric.clone(), Vec::new()));
1594 for (&point, value) in rows.points.iter().zip(rows.values) {
1595 if let Some(value) = value {
1596 samples.push((point, field, value));
1597 }
1598 }
1599 }
1600 }
1601 let mut builder = GridSeriesBuilder::try_new(schema)?;
1602 let mut row: Vec<Option<GridSample>> = Vec::with_capacity(width);
1603 let mut output = Vec::with_capacity(merged.len());
1604 for (metric, mut samples) in merged.into_values() {
1605 builder.begin_series();
1607 samples.sort_unstable_by_key(|(point, field, _)| (*point, *field));
1608 if let Some(budget) = budget.as_deref_mut() {
1611 budget.grow(merge_series_columns(&samples, width))?;
1612 }
1613 let mut samples = samples.into_iter().peekable();
1614 while let Some((point, field, value)) = samples.next() {
1615 row.clear();
1616 row.resize_with(width, || None);
1617 row[field] = Some(value);
1618 while let Some((_, field, value)) = samples.next_if(|next| next.0 == point) {
1619 row[field] = Some(value);
1620 }
1621 builder.push_samples(point, &row)?;
1622 }
1623 output.extend(builder.finish(metric)?);
1624 }
1625 Ok(output)
1626}
1627
1628fn merge_single_field(
1642 fields: Vec<Results>,
1643 schema: Arc<SeriesSchema>,
1644 mut budget: Option<&mut Budget<'_>>,
1645) -> Result<Vec<Series>> {
1646 let mut builder = GridSeriesBuilder::try_new(schema)?;
1647 let series = fields.iter().map(|results| results.series.len()).sum();
1648 let mut output = Vec::with_capacity(series);
1649 for results in fields {
1650 for (_, rows) in results.series {
1651 builder.begin_series();
1653 if let Some(budget) = budget.as_deref_mut() {
1657 budget.grow(merge_series_columns_of(
1658 rows.points
1659 .iter()
1660 .zip(&rows.values)
1661 .filter(|(_, value)| value.is_some())
1662 .map(|(point, _)| *point),
1663 1,
1664 ))?;
1665 }
1666 for (&point, value) in rows.points.iter().zip(&rows.values) {
1667 if value.is_some() {
1668 builder.push_samples(point, std::slice::from_ref(value))?;
1670 }
1671 }
1672 output.extend(builder.finish(rows.metric)?);
1673 }
1674 }
1675 Ok(output)
1676}
1677
1678fn merge_series_columns(samples: &[(usize, usize, GridSample)], fields: usize) -> usize {
1681 merge_series_columns_of(samples.iter().map(|(point, ..)| *point), fields)
1682}
1683
1684fn merge_series_columns_of(points: impl Iterator<Item = usize>, fields: usize) -> usize {
1693 let row = 2 * fields.saturating_mul(std::mem::size_of::<f64>() + 1)
1694 + fields.saturating_mul(std::mem::size_of::<Option<u32>>());
1695 let mut rows = 0usize;
1696 let mut consumed: Option<usize> = None;
1697 for point in points {
1698 if consumed != Some(point) {
1699 rows = rows.saturating_add(1);
1700 consumed = Some(point);
1701 }
1702 }
1703 rows.saturating_mul(row)
1704}
1705
1706fn same_grid(lhs: &SeriesSchema, rhs: &SeriesSchema) -> Result<Arc<EvalGrid>> {
1707 match (&lhs.eval_grid, &rhs.eval_grid) {
1708 (Some(lhs), Some(rhs)) if lhs.spec() == rhs.spec() => Ok(lhs.clone()),
1709 _ => Err(DataFusionError::Execution(
1710 "vector operands must be evaluated on the same grid".into(),
1711 )),
1712 }
1713}
1714
1715fn duplicate_message(key: &GroupKey, side: &str, timestamp: i64) -> String {
1716 format!(
1717 "found duplicate series for the match group {} on the {side} hand-side of the \
1718 operation at {timestamp} ms; many-to-many matching not allowed: matching labels must be \
1719 unique on one side",
1720 render(key),
1721 )
1722}
1723
1724pub type GroupKey = Vec<(Arc<str>, Arc<str>)>;
1727
1728pub struct DuplicateEvidence {
1730 slots: std::sync::Mutex<HashMap<(usize, usize), DuplicateSlot>>,
1731 reservation: std::sync::Mutex<MemoryReservation>,
1732 remaining: std::sync::atomic::AtomicUsize,
1733 aborted: std::sync::atomic::AtomicBool,
1734 final_verdict: std::sync::Mutex<Option<DuplicateCandidate>>,
1735}
1736
1737#[derive(Default)]
1738struct DuplicateSlot {
1739 grid_len: Option<usize>,
1740 lhs_present: Vec<bool>,
1741 rhs_present: Vec<bool>,
1742 candidates: HashMap<usize, DuplicateCandidate>,
1743 filling: Option<bool>,
1744}
1745
1746#[derive(Clone, Debug, PartialEq, Eq)]
1748pub struct DuplicateCandidate {
1749 pub point: usize,
1750 pub group: Arc<GroupKey>,
1751 pub side: &'static str,
1753 pub timestamp: i64,
1754}
1755
1756impl DuplicateCandidate {
1757 pub fn message(&self) -> String {
1759 duplicate_message(&self.group, self.side, self.timestamp)
1760 }
1761}
1762
1763fn candidate_owned_bytes(group: &GroupKey) -> usize {
1764 group
1766 .iter()
1767 .map(|(name, value)| name.len().saturating_add(value.len()))
1768 .sum::<usize>()
1769 .saturating_add(
1770 group
1771 .capacity()
1772 .saturating_mul(std::mem::size_of::<(Arc<str>, Arc<str>)>()),
1773 )
1774 .saturating_add(std::mem::size_of::<DuplicateCandidate>())
1775}
1776
1777impl DuplicateEvidence {
1778 pub fn new(pool: &Arc<dyn MemoryPool>, partitions: usize) -> Self {
1780 Self {
1781 slots: std::sync::Mutex::new(HashMap::new()),
1782 reservation: std::sync::Mutex::new(
1783 MemoryConsumer::new("DuplicateEvidence").register(pool),
1784 ),
1785 remaining: std::sync::atomic::AtomicUsize::new(partitions),
1786 aborted: std::sync::atomic::AtomicBool::new(false),
1787 final_verdict: std::sync::Mutex::new(None),
1788 }
1789 }
1790
1791 pub fn complete(&self) -> bool {
1793 self.exit_claim(false)
1794 }
1795
1796 pub fn finished(&self) -> bool {
1798 self.remaining.load(std::sync::atomic::Ordering::Acquire) == 0
1799 }
1800
1801 pub fn aborted(&self) -> bool {
1803 self.aborted.load(std::sync::atomic::Ordering::Acquire)
1804 }
1805
1806 #[cfg(test)]
1807 pub(crate) fn slot_count(&self) -> usize {
1808 self.slots.lock().unwrap().len()
1809 }
1810
1811 pub fn abort(&self) {
1812 self.exit_claim(true);
1813 }
1814
1815 fn clear_slots(&self) {
1816 let mut final_verdict = self.final_verdict.lock().unwrap();
1817 let mut slots = self.slots.lock().unwrap();
1818 final_verdict.take();
1819 slots.clear();
1820 let reservation = self.reservation.lock().unwrap();
1821 let size = reservation.size();
1822 reservation.shrink(size);
1823 }
1824
1825 fn exit_claim(&self, aborted: bool) -> bool {
1826 if aborted {
1827 self.aborted
1828 .store(true, std::sync::atomic::Ordering::Release);
1829 self.clear_slots();
1830 }
1831 let last = loop {
1832 let current = self.remaining.load(std::sync::atomic::Ordering::Acquire);
1833 if current == 0 {
1834 return false;
1835 }
1836 if self
1837 .remaining
1838 .compare_exchange(
1839 current,
1840 current - 1,
1841 std::sync::atomic::Ordering::AcqRel,
1842 std::sync::atomic::Ordering::Acquire,
1843 )
1844 .is_ok()
1845 {
1846 break current == 1;
1847 }
1848 };
1849 if last {
1850 let mut final_verdict = self.final_verdict.lock().unwrap();
1851 if !self.aborted.load(std::sync::atomic::Ordering::Acquire) {
1852 *final_verdict = self.current_verdict();
1853 }
1854 let retained_bytes = final_verdict
1855 .as_ref()
1856 .map(|candidate| candidate_owned_bytes(&candidate.group))
1857 .unwrap_or(0);
1858 self.slots.lock().unwrap().clear();
1859 let reservation = self.reservation.lock().unwrap();
1860 let release = reservation.size().saturating_sub(retained_bytes);
1861 reservation.shrink(release);
1862 }
1863 last && !self.aborted.load(std::sync::atomic::Ordering::Acquire)
1864 }
1865
1866 pub fn verdict(&self) -> Option<DuplicateCandidate> {
1867 if self.remaining.load(std::sync::atomic::Ordering::Acquire) == 0 {
1868 return self.final_verdict.lock().unwrap().clone();
1869 }
1870 self.current_verdict()
1871 }
1872
1873 pub fn take_verdict(&self) -> Option<DuplicateCandidate> {
1875 if self.remaining.load(std::sync::atomic::Ordering::Acquire) != 0 {
1876 return None;
1877 }
1878 let mut final_verdict = self.final_verdict.lock().unwrap();
1879 let candidate = final_verdict.take()?;
1880 let reservation = self.reservation.lock().unwrap();
1881 let size = reservation.size();
1882 reservation.shrink(size);
1883 Some(candidate)
1884 }
1885
1886 fn current_verdict(&self) -> Option<DuplicateCandidate> {
1887 if self.aborted.load(std::sync::atomic::Ordering::Acquire) {
1888 return None;
1889 }
1890 let slots = self.slots.lock().unwrap();
1891 slots
1892 .iter()
1893 .filter_map(|(&(node, field), slot)| {
1894 let filling = slot.filling?;
1895 slot.candidates
1896 .iter()
1897 .filter_map(|(&point, candidate)| {
1898 let lhs = slot.lhs_present.get(point).copied().unwrap_or(false);
1899 let rhs = slot.rhs_present.get(point).copied().unwrap_or(false);
1900 (if filling { lhs || rhs } else { lhs && rhs }).then(|| candidate.clone())
1901 })
1902 .min_by_key(|candidate| candidate.point)
1903 .map(|candidate| ((candidate.point, node, field), candidate))
1904 })
1905 .min_by_key(|(key, _)| *key)
1906 .map(|(_, candidate)| candidate)
1907 }
1908
1909 pub fn publish(
1910 &self,
1911 node_index: usize,
1912 field: usize,
1913 lhs_present: &[bool],
1914 rhs_present: &[bool],
1915 filling: bool,
1916 ) -> Result<()> {
1917 let mut slots = self.slots.lock().unwrap();
1918 if self.aborted.load(std::sync::atomic::Ordering::Acquire) {
1919 return Ok(());
1920 }
1921 let slot = slots.entry((node_index, field)).or_default();
1922 if let Some(existing_len) = slot.grid_len {
1923 if existing_len != lhs_present.len() || existing_len != rhs_present.len() {
1924 return Err(DataFusionError::Internal(
1925 "binary match grid length differs across partitions".into(),
1926 ));
1927 }
1928 } else {
1929 if lhs_present.len() != rhs_present.len() {
1930 return Err(DataFusionError::Internal(
1931 "binary match operand grid lengths differ".into(),
1932 ));
1933 }
1934 if slot
1935 .candidates
1936 .keys()
1937 .any(|point| *point >= lhs_present.len())
1938 {
1939 return Err(DataFusionError::Internal(
1940 "duplicate candidate is outside its binary grid".into(),
1941 ));
1942 }
1943 slot.grid_len = Some(lhs_present.len());
1944 }
1945 if let Some(existing) = slot.filling {
1946 if existing != filling {
1947 return Err(DataFusionError::Internal(
1948 "binary match filling differs across partitions".into(),
1949 ));
1950 }
1951 } else {
1952 slot.filling = Some(filling);
1953 }
1954 let len = lhs_present.len();
1955 if len > slot.lhs_present.len() {
1956 let additional = (len - slot.lhs_present.len())
1957 .saturating_mul(2)
1958 .saturating_mul(std::mem::size_of::<bool>());
1959 self.reservation.lock().unwrap().try_grow(additional)?;
1960 slot.lhs_present.resize(len, false);
1961 slot.rhs_present.resize(len, false);
1962 }
1963 for (dst, src) in slot.lhs_present.iter_mut().zip(lhs_present) {
1964 *dst |= *src;
1965 }
1966 for (dst, src) in slot.rhs_present.iter_mut().zip(rhs_present) {
1967 *dst |= *src;
1968 }
1969 Ok(())
1970 }
1971
1972 pub fn record_candidate(
1974 &self,
1975 node_index: usize,
1976 field: usize,
1977 point: usize,
1978 group: Arc<GroupKey>,
1979 side: &'static str,
1980 timestamp: i64,
1981 ) -> Result<()> {
1982 let mut slots = self.slots.lock().unwrap();
1983 if self.aborted.load(std::sync::atomic::Ordering::Acquire) {
1984 return Ok(());
1985 }
1986 let slot = slots.entry((node_index, field)).or_default();
1987 if slot.grid_len.is_some_and(|len| point >= len) {
1988 return Err(DataFusionError::Internal(
1989 "duplicate candidate is outside its binary grid".into(),
1990 ));
1991 }
1992 if slot.candidates.contains_key(&point) {
1993 return Ok(());
1994 }
1995 let entry_bytes = candidate_owned_bytes(&group)
1996 .saturating_add(std::mem::size_of::<(usize, DuplicateCandidate)>());
1997 self.reservation.lock().unwrap().try_grow(entry_bytes)?;
1998 if let Err(error) = slot.candidates.try_reserve(1) {
1999 self.reservation.lock().unwrap().shrink(entry_bytes);
2000 return Err(DataFusionError::Execution(error.to_string()));
2001 }
2002 slot.candidates.insert(
2003 point,
2004 DuplicateCandidate {
2005 point,
2006 group,
2007 side,
2008 timestamp,
2009 },
2010 );
2011 Ok(())
2012 }
2013}
2014
2015pub(crate) fn group_key(metric: &SeriesLabels, labels: &MatchingLabels) -> GroupKey {
2016 let mut key: GroupKey = match labels {
2017 MatchingLabels::On(names) => names
2018 .iter()
2019 .filter_map(|name| {
2020 let value = metric.get(name)?;
2021 (!value.is_empty()).then(|| (name.clone(), Arc::from(value)))
2022 })
2023 .collect(),
2024 MatchingLabels::Ignoring(names) => metric
2025 .tags()
2026 .iter()
2027 .filter(|tag| !tag.value.is_empty() && !names.contains(&tag.name))
2028 .map(|tag| (tag.name.clone(), tag.value.clone()))
2029 .collect(),
2030 };
2031 key.sort();
2032 key.dedup();
2033 key
2034}
2035
2036fn key_of(metric: &SeriesLabels) -> GroupKey {
2037 let mut key = group_key(metric, &MatchingLabels::Ignoring(Vec::new()));
2038 if let Some(name) = metric.name() {
2039 key.insert(0, (Arc::from("__name__"), Arc::from(name)));
2040 }
2041 key
2042}
2043
2044fn render(key: &GroupKey) -> String {
2045 let labels: Vec<_> = key
2046 .iter()
2047 .map(|(name, value)| format!("{name}=\"{value}\""))
2048 .collect();
2049 format!("{{{}}}", labels.join(", "))
2050}
2051
2052fn group(operand: &Operand<'_>, labels: &MatchingLabels) -> HashMap<GroupKey, Vec<usize>> {
2054 let mut groups: HashMap<GroupKey, Vec<usize>> = HashMap::new();
2055 for (index, series) in operand.series.iter().enumerate() {
2056 groups
2057 .entry(group_key(&series.metric, labels))
2058 .or_default()
2059 .push(index);
2060 }
2061 groups
2062}
2063
2064fn overlap(
2071 operand: &Operand<'_>,
2072 members: &[usize],
2073 mut on_duplicate: impl FnMut(usize) -> Result<()>,
2074 base: usize,
2075 mut budget: Option<&mut Budget<'_>>,
2076) -> Result<()> {
2077 if members.len() < 2 {
2078 return Ok(());
2079 }
2080 let mut points = Vec::new();
2082 for &member in members {
2083 let mut cursor = operand.cursor(member);
2084 for (point, row) in operand.positions(member) {
2085 if !matches!(
2086 cursor.at(row).expect("a row never goes back"),
2087 SampleRef::Missing
2088 ) {
2089 if let Some(budget) = budget.as_deref_mut()
2091 && points.len() == points.capacity()
2092 {
2093 let capacity = points.capacity().saturating_mul(2).max(VEC_MIN_CAPACITY);
2094 let list = capacity.saturating_mul(std::mem::size_of::<usize>());
2095 budget.phase(base.saturating_add(list))?;
2096 }
2097 points.push(point);
2098 }
2099 }
2100 }
2101 points.sort_unstable();
2102 for (index, pair) in points.windows(2).enumerate() {
2103 if pair[0] == pair[1] && (index == 0 || points[index - 1] != pair[0]) {
2104 on_duplicate(pair[0])?;
2105 }
2106 }
2107 if let Some(budget) = budget {
2109 budget.phase(base)?;
2110 }
2111 Ok(())
2112}
2113
2114fn result_metric(
2115 many: &SeriesLabels,
2116 one: &SeriesLabels,
2117 matching: &BinaryMatching,
2118 include: &[Arc<str>],
2119 drop_name: bool,
2120) -> Result<SeriesLabels> {
2121 let mut metric = many.clone();
2122 if drop_name {
2123 metric.remove_all(&METADATA_LABELS);
2124 }
2125 if matching.cardinality == Cardinality::OneToOne {
2126 match &matching.labels {
2127 MatchingLabels::On(names) => {
2128 metric.keep_only(&names.iter().map(|name| &**name).collect::<Vec<_>>())
2129 }
2130 MatchingLabels::Ignoring(names) => {
2131 metric.remove_all(&names.iter().map(|name| &**name).collect::<Vec<_>>())
2132 }
2133 }
2134 }
2135 for name in include {
2136 match one.get(name) {
2137 Some(value) if !value.is_empty() => metric
2138 .set(name, Arc::from(value))
2139 .map_err(|error| DataFusionError::External(Box::new(error)))?,
2140 _ => metric.remove(name),
2141 }
2142 }
2143 Ok(metric)
2144}
2145
2146pub(crate) fn validate_binary_operand(schema: &SeriesSchema, series: &[Series]) -> Result<()> {
2154 let grid = schema.eval_grid.as_ref().map(|grid| grid.spec());
2155 for item in series {
2156 let Some(item_grid) = item.time.grid() else {
2158 return Err(DataFusionError::Execution(
2159 "vector operand series must be on the evaluation grid".into(),
2160 ));
2161 };
2162 if Some(item_grid.spec()) != grid
2163 || item.fields.len() != schema.fields.len()
2164 || item
2165 .fields
2166 .iter()
2167 .any(|field| field.len() != item.time.len())
2168 {
2169 return Err(DataFusionError::Execution(
2170 "vector operand series does not match its schema".into(),
2171 ));
2172 }
2173 }
2174 Ok(())
2175}
2176
2177struct Operand<'a> {
2185 series: &'a [Series],
2186 field: usize,
2187}
2188
2189impl<'a> Operand<'a> {
2190 fn try_new(schema: &SeriesSchema, series: &'a [Series], field: usize) -> Result<Self> {
2191 validate_binary_operand(schema, series)?;
2192 Ok(Self { series, field })
2193 }
2194
2195 fn axis(&self, index: usize) -> &'a TimeAxis {
2196 &self.series[index].time
2197 }
2198
2199 fn widest_histogram(&self) -> Option<HistogramView<'a>> {
2205 let mut widest: Option<(HistogramView<'a>, usize)> = None;
2206 for series in self.series {
2207 let field = &series.fields.as_slice()[self.field];
2208 let holds_histograms = field.segments().iter().any(|segment| {
2209 matches!(
2210 segment.dense(),
2211 Some(DenseSamplesRef::Histogram(_) | DenseSamplesRef::Mixed(_))
2212 )
2213 });
2214 if !holds_histograms {
2215 continue;
2216 }
2217 for sample in field.iter() {
2218 let SampleRef::Histogram(view) = sample else {
2219 continue;
2220 };
2221 if widest.is_none_or(|(_, widest)| owned_histogram_bytes(&view) > widest) {
2222 widest = Some((view, owned_histogram_bytes(&view)));
2223 }
2224 }
2225 }
2226 widest.map(|(view, _)| view)
2227 }
2228
2229 fn positions(&self, index: usize) -> datatypes::series::time::Positions<'a> {
2231 self.series[index].time.positions()
2232 }
2233
2234 fn cursor(&self, index: usize) -> RowCursor<'a> {
2240 self.series[index].fields.as_slice()[self.field].cursor()
2241 }
2242
2243 fn present(&self, index: usize, point: usize, cursor: &mut RowCursor<'a>) -> bool {
2249 self.axis(index).row_of(point).is_some_and(|row| {
2250 !matches!(
2251 cursor.at(row).expect("a row never goes back"),
2252 SampleRef::Missing
2253 )
2254 })
2255 }
2256
2257 fn shared_runs(
2262 &self,
2263 own: usize,
2264 other: &Operand<'a>,
2265 theirs: usize,
2266 ) -> impl Iterator<Item = GridRunPair> + 'a {
2267 self.axis(own).intersect_runs(other.axis(theirs))
2268 }
2269
2270 fn presence(&self, points: usize) -> Vec<bool> {
2272 let mut presence = vec![false; points];
2273 for index in 0..self.series.len() {
2274 let mut cursor = self.cursor(index);
2275 for (point, row) in self.positions(index) {
2276 if !presence[point]
2277 && !matches!(
2278 cursor.at(row).expect("a row never goes back"),
2279 SampleRef::Missing
2280 )
2281 {
2282 presence[point] = true;
2283 }
2284 }
2285 }
2286 presence
2287 }
2288}
2289
2290fn unsupported_histogram_arithmetic(
2293 op: BinaryOp,
2294 lhs: &SampleRef<'_>,
2295 rhs: &SampleRef<'_>,
2296) -> Option<&'static str> {
2297 let symbol = match op {
2298 BinaryOp::Add => "+",
2299 BinaryOp::Sub => "-",
2300 BinaryOp::Mul => "*",
2301 BinaryOp::Div => "/",
2302 BinaryOp::Mod => "%",
2303 BinaryOp::Pow => "^",
2304 BinaryOp::Atan2 => "atan2",
2305 _ => return None,
2306 };
2307 let unsupported = match (lhs, rhs) {
2308 (SampleRef::Histogram(_), SampleRef::Histogram(_)) => {
2309 !matches!(op, BinaryOp::Add | BinaryOp::Sub)
2310 }
2311 (SampleRef::Histogram(_), SampleRef::Float(_)) => {
2312 !matches!(op, BinaryOp::Mul | BinaryOp::Div)
2313 }
2314 (SampleRef::Float(_), SampleRef::Histogram(_)) => op != BinaryOp::Mul,
2315 _ => false,
2316 };
2317 unsupported.then_some(symbol)
2318}
2319
2320fn elem_binop(
2325 op: BinaryOp,
2326 lhs: SampleRef<'_>,
2327 rhs: SampleRef<'_>,
2328 annotations: Option<&PromqlAnnotationCollector>,
2329) -> Result<Option<(GridSample, bool)>> {
2330 let histogram = |view: &HistogramView<'_>| FloatHistogram::try_from_view(view);
2331 let mut result = match (lhs, rhs) {
2332 (SampleRef::Float(lhs), SampleRef::Float(rhs)) => {
2333 let (value, keep) = op.apply(lhs, rhs);
2334 return Ok(Some((GridSample::Float(value), keep)));
2335 }
2336 (SampleRef::Float(factor), SampleRef::Histogram(h))
2337 | (SampleRef::Histogram(h), SampleRef::Float(factor))
2338 if op == BinaryOp::Mul =>
2339 {
2340 let mut h = histogram(&h)?;
2341 h.mul(factor);
2342 h
2343 }
2344 (SampleRef::Histogram(h), SampleRef::Float(divisor)) if op == BinaryOp::Div => {
2345 let mut h = histogram(&h)?;
2346 h.div(divisor);
2347 h
2348 }
2349 (SampleRef::Histogram(lhs), SampleRef::Histogram(rhs)) => {
2350 let (mut lhs, rhs) = (histogram(&lhs)?, histogram(&rhs)?);
2351 match op {
2352 BinaryOp::Eq | BinaryOp::Ne => {
2353 let keep = lhs.equals(&rhs) == (op == BinaryOp::Eq);
2354 return Ok(Some((GridSample::Histogram(Box::new(lhs)), keep)));
2355 }
2356 BinaryOp::Add | BinaryOp::Sub => {
2357 let name = if op == BinaryOp::Add {
2358 NativeHistogramAdd::name()
2359 } else {
2360 NativeHistogramSub::name()
2361 };
2362 if lhs.uses_custom_buckets() != rhs.uses_custom_buckets() {
2367 if let Some(collector) = annotations {
2368 collector.record_warning(format!(
2369 "{name}: dropped native histogram sample with incompatible schemas"
2370 ));
2371 }
2372 return Ok(None);
2373 }
2374 if matches!(
2378 (lhs.reset_hint, rhs.reset_hint),
2379 (
2380 CounterResetHint::CounterReset,
2381 CounterResetHint::NotCounterReset
2382 ) | (
2383 CounterResetHint::NotCounterReset,
2384 CounterResetHint::CounterReset
2385 )
2386 ) {
2387 if let Some(collector) = annotations {
2388 collector.record_warning(format!(
2389 "{name}: native histogram counter reset hints contradict"
2390 ));
2391 }
2392 return Ok(None);
2393 }
2394 let outcome = if op == BinaryOp::Add {
2395 lhs.add(&rhs)?
2396 } else {
2397 lhs.sub(&rhs)?
2398 };
2399 if outcome.custom_bounds_reconciled
2400 && let Some(collector) = annotations
2401 {
2402 collector.record_info(format!(
2403 "{name}: reconciled native histograms with different custom buckets"
2404 ));
2405 }
2406 if op == BinaryOp::Sub {
2407 lhs.reset_hint = CounterResetHint::Gauge;
2408 }
2409 lhs
2410 }
2411 _ => return Ok(None),
2412 }
2413 }
2414 _ => return Ok(None),
2415 };
2416 result.compact();
2417 Ok(Some((GridSample::Histogram(Box::new(result)), true)))
2418}
2419
2420#[derive(Default)]
2425struct Results {
2426 series: HashMap<GroupKey, ResultRows>,
2427 totals: ResultTotals,
2429}
2430
2431#[derive(Default)]
2437struct ResultTotals {
2438 rows: usize,
2439 kept: usize,
2440 histograms: usize,
2441 histogram_heap: usize,
2442}
2443
2444struct ResultRows {
2447 metric: SeriesLabels,
2448 points: Vec<usize>,
2449 groups: Vec<usize>,
2450 values: Vec<Option<GridSample>>,
2451}
2452
2453struct Duplicate {
2455 point: usize,
2456 key: GroupKey,
2457 within_group: bool,
2459}
2460
2461fn same_labelset(key: &GroupKey, timestamp: i64) -> String {
2462 format!(
2463 "vector cannot contain metrics with the same labelset {} at {timestamp} ms",
2464 render(key)
2465 )
2466}
2467
2468enum RowSlot<'a> {
2476 Unfiled(&'a mut HashMap<GroupKey, ResultRows>),
2478 Row(&'a mut ResultRows),
2480}
2481
2482impl<'a> RowSlot<'a> {
2483 #[allow(clippy::too_many_arguments)]
2491 fn file(
2492 self,
2493 totals: &mut ResultTotals,
2494 metric: &SeriesLabels,
2495 label_set: usize,
2496 group: usize,
2497 point: usize,
2498 value: Option<GridSample>,
2499 mut budget: Option<&mut Budget<'_>>,
2500 ) -> Result<Self> {
2501 let rows = match self {
2502 Self::Row(rows) => rows,
2503 Self::Unfiled(series) => match series.entry(key_of(metric)) {
2504 Entry::Occupied(entry) => entry.into_mut(),
2505 Entry::Vacant(entry) => {
2506 if let Some(budget) = budget.as_deref_mut() {
2509 budget.hold(label_set)?;
2510 }
2511 entry.insert(ResultRows {
2512 metric: metric.clone(),
2513 points: Vec::new(),
2514 groups: Vec::new(),
2515 values: Vec::new(),
2516 })
2517 }
2518 },
2519 };
2520 if rows.points.len() == rows.points.capacity()
2523 && let Some(budget) = budget.as_deref_mut()
2524 {
2525 let grown = (2 * rows.points.capacity()).max(VEC_MIN_CAPACITY);
2526 budget.hold(
2527 grown
2528 .saturating_sub(rows.points.capacity())
2529 .saturating_mul(RESULT_ROW_BYTES),
2530 )?;
2531 }
2532 totals.rows = totals.rows.saturating_add(1);
2533 if let Some(value) = &value {
2534 totals.kept = totals.kept.saturating_add(1);
2535 if let GridSample::Histogram(histogram) = value {
2536 totals.histograms = totals.histograms.saturating_add(1);
2537 totals.histogram_heap =
2538 totals.histogram_heap.saturating_add(histogram.heap_bytes());
2539 if let Some(budget) = budget {
2540 budget.hold(result_histogram_bytes(histogram))?;
2541 }
2542 }
2543 }
2544 rows.points.push(point);
2545 rows.groups.push(group);
2546 rows.values.push(value);
2547 Ok(Self::Row(rows))
2548 }
2549}
2550
2551impl Results {
2552 fn sort_rows(&mut self) -> Option<Duplicate> {
2556 let mut first: Option<(usize, bool, &GroupKey)> = None;
2557 for (key, rows) in &mut self.series {
2558 if !rows.points.is_sorted() {
2559 let mut order: Vec<usize> = (0..rows.points.len()).collect();
2560 order.sort_by_key(|&row| rows.points[row]);
2561 rows.points = order.iter().map(|&row| rows.points[row]).collect();
2562 rows.groups = order.iter().map(|&row| rows.groups[row]).collect();
2563 let mut values = std::mem::take(&mut rows.values);
2564 rows.values = order.iter().map(|&row| values[row].take()).collect();
2565 }
2566 let mut start = 0;
2567 while start < rows.points.len() {
2568 let point = rows.points[start];
2569 let end = start + rows.points[start..].partition_point(|&p| p == point);
2570 if end - start > 1 {
2571 let mut groups = rows.groups[start..end].to_vec();
2572 groups.sort_unstable();
2573 let within_group = groups.windows(2).any(|pair| pair[0] == pair[1]);
2574 if first.is_none_or(|(first_point, first_within, _)| {
2575 (point, !within_group) < (first_point, !first_within)
2576 }) {
2577 first = Some((point, within_group, key));
2578 }
2579 break;
2580 }
2581 start = end;
2582 }
2583 }
2584 first.map(|(point, within_group, key)| Duplicate {
2585 point,
2586 key: key.clone(),
2587 within_group,
2588 })
2589 }
2590}
2591
2592#[cfg(test)]
2597mod merge_shape_tests {
2598 type LabelPairs = Vec<(String, String)>;
2599 type RowValues = Vec<(usize, u64)>;
2600 type HistogramValues = Vec<(usize, [u64; 3])>;
2601 type SeriesRows = (LabelPairs, RowValues);
2602 type SeriesHistograms = (LabelPairs, HistogramValues);
2603 type MergeFn =
2604 fn(Vec<Results>, Arc<SeriesSchema>, Option<&mut Budget<'_>>) -> Result<Vec<Series>>;
2605
2606 use datatypes::series::time::GridSpec;
2607
2608 use super::*;
2609 use crate::grid_series::reference::OwnedHistogram;
2610
2611 fn grid() -> Arc<EvalGrid> {
2613 Arc::new(
2614 EvalGrid::try_new(GridSpec::try_new(0, 1_000, 12).expect("valid grid"))
2615 .expect("valid grid"),
2616 )
2617 }
2618
2619 fn schema() -> Arc<SeriesSchema> {
2621 Arc::new(SeriesSchema {
2622 fields: vec![FieldSpec {
2623 name: Arc::from("value"),
2624 }]
2625 .into(),
2626 eval_grid: Some(grid()),
2627 })
2628 }
2629
2630 fn metric(name: &str, host: &str) -> SeriesLabels {
2631 SeriesLabels::try_new(
2632 Some(Arc::from(name)),
2633 vec![Label {
2634 name: Arc::from("host"),
2635 value: Arc::from(host),
2636 }],
2637 )
2638 .expect("valid labels")
2639 }
2640
2641 fn result_rows(metric: SeriesLabels, rows: &[(usize, Option<f64>)]) -> ResultRows {
2643 ResultRows {
2644 metric,
2645 points: rows.iter().map(|(point, _)| *point).collect(),
2646 groups: vec![0; rows.len()],
2649 values: rows
2650 .iter()
2651 .map(|(_, value)| value.map(GridSample::Float))
2652 .collect(),
2653 }
2654 }
2655
2656 fn histogram_rows(metric: SeriesLabels, rows: &[(usize, Option<&str>)]) -> ResultRows {
2659 ResultRows {
2660 metric,
2661 points: rows.iter().map(|(point, _)| *point).collect(),
2662 groups: vec![0; rows.len()],
2663 values: rows
2664 .iter()
2665 .map(|(_, text)| {
2666 text.map(|text| {
2667 GridSample::Histogram(Box::new(
2668 FloatHistogram::try_from_view(&OwnedHistogram::parse(text).view())
2669 .expect("the histogram is readable"),
2670 ))
2671 })
2672 })
2673 .collect(),
2674 }
2675 }
2676
2677 fn field_of(filed: Vec<ResultRows>) -> Results {
2679 let mut results = Results::default();
2680 for rows in filed {
2681 results.totals.rows = results.totals.rows.saturating_add(rows.points.len());
2682 results.totals.kept = results
2683 .totals
2684 .kept
2685 .saturating_add(rows.values.iter().filter(|value| value.is_some()).count());
2686 for value in rows.values.iter().flatten() {
2687 if let GridSample::Histogram(histogram) = value {
2688 results.totals.histograms = results.totals.histograms.saturating_add(1);
2689 results.totals.histogram_heap = results
2690 .totals
2691 .histogram_heap
2692 .saturating_add(histogram.heap_bytes());
2693 }
2694 }
2695 results.series.insert(key_of(&rows.metric), rows);
2696 }
2697 results
2698 }
2699
2700 fn field_results() -> Results {
2703 field_of(vec![
2704 result_rows(
2705 metric("m1", "a"),
2706 &[
2707 (0, Some(1.5)),
2708 (1, None),
2709 (3, Some(3.5)),
2710 (4, Some(4.5)),
2711 (7, Some(7.5)),
2712 ],
2713 ),
2714 result_rows(
2715 metric("m2", "b"),
2716 &[(2, Some(2.5)), (5, Some(5.5)), (6, None)],
2717 ),
2718 result_rows(metric("m3", "c"), &[(0, None), (2, None)]),
2719 ])
2720 }
2721
2722 const FIRST_HISTOGRAM: &str = "0/0/3ff0000000000000/4014000000000000/4028000000000000/0/////";
2724 const SECOND_HISTOGRAM: &str = "0/0/0/401c000000000000/4034000000000000/0/////";
2726
2727 fn histogram_results() -> Results {
2730 field_of(vec![
2731 histogram_rows(
2732 metric("h1", "a"),
2733 &[
2734 (1, Some(FIRST_HISTOGRAM)),
2735 (2, None),
2736 (4, Some(SECOND_HISTOGRAM)),
2737 ],
2738 ),
2739 histogram_rows(metric("h2", "b"), &[(0, None), (3, None)]),
2740 ])
2741 }
2742
2743 fn labels(name: &str, host: &str) -> Vec<(String, String)> {
2745 vec![
2746 ("__name__".to_string(), name.to_string()),
2747 ("host".to_string(), host.to_string()),
2748 ]
2749 }
2750
2751 fn series_labels(series: &Series) -> Vec<(String, String)> {
2753 let mut labels: Vec<(String, String)> = series
2754 .metric
2755 .tags()
2756 .iter()
2757 .map(|tag| (tag.name.to_string(), tag.value.to_string()))
2758 .collect();
2759 if let Some(name) = series.metric.name() {
2760 labels.push(("__name__".to_string(), name.to_string()));
2761 }
2762 labels.sort();
2763 labels
2764 }
2765
2766 fn rows_of_series(series: &Series) -> SeriesRows {
2769 let mut cursor = series.fields.as_slice()[0].cursor();
2770 let rows = series
2771 .time
2772 .positions()
2773 .map(|(position, row)| {
2774 match cursor.at(row).expect("the axis and the fields are aligned") {
2775 SampleRef::Float(value) => (position, value.to_bits()),
2776 _ => panic!("expected a float sample"),
2777 }
2778 })
2779 .collect();
2780 (series_labels(series), rows)
2781 }
2782
2783 fn histograms_of_series(series: &Series) -> SeriesHistograms {
2786 let mut cursor = series.fields.as_slice()[0].cursor();
2787 let rows = series
2788 .time
2789 .positions()
2790 .map(|(position, row)| {
2791 match cursor.at(row).expect("the axis and the fields are aligned") {
2792 SampleRef::Histogram(view) => {
2793 let histogram = FloatHistogram::try_from_view(&view)
2794 .expect("the histogram is readable");
2795 (
2796 position,
2797 [
2798 histogram.zero_count.to_bits(),
2799 histogram.count.to_bits(),
2800 histogram.sum.to_bits(),
2801 ],
2802 )
2803 }
2804 _ => panic!("expected a histogram sample"),
2805 }
2806 })
2807 .collect();
2808 (series_labels(series), rows)
2809 }
2810
2811 fn rows_of(series: &[Series]) -> Vec<SeriesRows> {
2813 let mut rows: Vec<_> = series.iter().map(rows_of_series).collect();
2814 rows.sort();
2815 rows
2816 }
2817
2818 fn histograms_of(series: &[Series]) -> Vec<SeriesHistograms> {
2820 let mut rows: Vec<_> = series.iter().map(histograms_of_series).collect();
2821 rows.sort();
2822 rows
2823 }
2824
2825 fn reserved_bytes(merge: MergeFn) -> usize {
2827 let reserved = std::cell::Cell::new(0usize);
2828 let mut reserve = |bytes: usize| {
2829 reserved.set(bytes);
2830 Ok(())
2831 };
2832 let mut budget = Budget::new(&mut reserve);
2833 merge(vec![field_results()], schema(), Some(&mut budget)).expect("the merge of one field");
2834 reserved.get()
2835 }
2836
2837 #[test]
2838 fn the_one_field_merge_writes_the_rows_the_multi_field_merge_writes() {
2839 let multi = merge_multi_field(vec![field_results()], schema(), None)
2840 .expect("the multi-field merge of one field");
2841 let single =
2842 merge_single_field(vec![field_results()], schema(), None).expect("the one-field merge");
2843 let expected = vec![
2846 (
2847 labels("m1", "a"),
2848 vec![
2849 (0, 1.5f64.to_bits()),
2850 (3, 3.5f64.to_bits()),
2851 (4, 4.5f64.to_bits()),
2852 (7, 7.5f64.to_bits()),
2853 ],
2854 ),
2855 (
2856 labels("m2", "b"),
2857 vec![(2, 2.5f64.to_bits()), (5, 5.5f64.to_bits())],
2858 ),
2859 ];
2860 assert_eq!(rows_of(&multi), expected);
2861 assert_eq!(rows_of(&single), expected);
2862 }
2863
2864 #[test]
2867 fn a_histogram_field_keeps_its_rows_and_histograms_through_the_one_field_merge() {
2868 let expected = vec![(
2869 labels("h1", "a"),
2870 vec![
2871 (1, [1.0f64.to_bits(), 5.0f64.to_bits(), 12.0f64.to_bits()]),
2872 (4, [0.0f64.to_bits(), 7.0f64.to_bits(), 20.0f64.to_bits()]),
2873 ],
2874 )];
2875 let fast =
2876 merge_fields(vec![histogram_results()], schema(), None).expect("the one field's merge");
2877 let multi = merge_multi_field(vec![histogram_results()], schema(), None)
2878 .expect("the grouped, sorted merge of the same field");
2879 assert_eq!(histograms_of(&multi), expected);
2880 assert_eq!(histograms_of(&fast), expected);
2881 }
2882
2883 #[test]
2886 fn a_fully_filtered_label_set_writes_no_series() {
2887 let filtered = field_of(vec![result_rows(
2888 metric("m9", "z"),
2889 &[(0, None), (1, None)],
2890 )]);
2891 assert_eq!(1, filtered.series.len(), "the field filed the label set");
2892 let merged = merge_fields(vec![filtered], schema(), None).expect("the merge of one field");
2893 assert!(merged.is_empty(), "{merged:?}");
2894 }
2895
2896 #[test]
2899 fn the_one_field_merge_bills_the_rows_the_multi_field_merge_bills() {
2900 let multi = reserved_bytes(merge_multi_field);
2901 let single = reserved_bytes(merge_single_field);
2902 assert!(single > 0, "the one-field merge reserved nothing");
2903 assert_eq!(
2904 multi, single,
2905 "the one-field merge reserved {single} bytes, the multi-field merge {multi}"
2906 );
2907 }
2908
2909 #[test]
2912 fn a_column_reservation_over_the_limit_reaches_the_caller() {
2913 let entry = std::cell::Cell::new(None);
2915 let mut record = |total: usize| {
2916 if entry.get().is_none() {
2917 entry.set(Some(total));
2918 }
2919 Ok(())
2920 };
2921 let merged = merge_fields(
2922 vec![field_results()],
2923 schema(),
2924 Some(&mut Budget::new(&mut record)),
2925 )
2926 .expect("the merge of one field under an unbounded budget");
2927 assert!(!merged.is_empty(), "the fixture writes series");
2928 let limit = entry.get().expect("the merge enters its phase figure");
2929 assert!(limit > 0, "the phase figure is what the fixture holds");
2930
2931 let mut refused = Vec::new();
2933 let mut reserve = |total: usize| {
2934 if total > limit {
2935 refused.push(total);
2936 return Err(DataFusionError::ResourcesExhausted(format!(
2937 "the one-field merge needs {total} bytes, more than the {limit} admitted"
2938 )));
2939 }
2940 Ok(())
2941 };
2942 let error = merge_fields(
2943 vec![field_results()],
2944 schema(),
2945 Some(&mut Budget::new(&mut reserve)),
2946 )
2947 .expect_err("a column reservation over the limit is refused");
2948 assert!(
2949 matches!(error, DataFusionError::ResourcesExhausted(_)),
2950 "{error}"
2951 );
2952 assert!(
2953 !refused.is_empty(),
2954 "the refusal is a reservation past the phase figure"
2955 );
2956 }
2957}