Skip to main content

promql/
info.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! `info(v, {selector})`: the series of `v` with the data labels of the info series that share
16//! their identifying labels, following Prometheus `combineWithInfoSeries` and
17//! `combineWithInfoVector`.
18//!
19//! Selecting the info series is the caller's: the series whose name and data labels match the
20//! selector, evaluated at every point of the grid like an instant selector, with the value
21//! replaced by the original timestamp of the selected sample, as Prometheus' `evalSeries` records
22//! it for `info`. This kernel only combines.
23
24#[cfg(test)]
25mod tests;
26
27use std::collections::btree_map::Entry;
28use std::collections::{BTreeMap, BTreeSet, HashMap};
29use std::sync::Arc;
30
31use datafusion::error::{DataFusionError, Result};
32use datatypes::series::samples::{SampleRef, Series, SeriesSchema};
33use datatypes::series::{Label, SeriesLabels};
34use regex::Regex;
35
36use crate::grid_series::{
37    GridSample, GridSeriesBuilder, LabelSet, external, label_set, owned, render_label_set,
38};
39use crate::select::MatchOp;
40use crate::vector_match::{Budget, HISTOGRAM_ROW_BYTES, owned_histogram_bytes};
41
42/// The labels an info series is joined on, as in Prometheus.
43const IDENTIFYING_LABELS: [&str; 2] = ["instance", "job"];
44
45/// The second argument of `info`, split the way Prometheus uses it.
46#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
47pub struct InfoSelector {
48    /// The `__name__` matchers, which choose the info metrics; none means `target_info`.
49    pub name_matchers: Vec<(MatchOp, Arc<str>)>,
50    /// The names of the other matchers: only these labels are copied. None copies every label
51    /// of the info series.
52    pub data_labels: Vec<Arc<str>>,
53    /// Whether every one of those other matchers matches the empty string, in which case a series
54    /// without a matching info series is kept as it is.
55    pub keep_unmatched: bool,
56}
57
58/// Combines `base` with the data labels of `info`.
59///
60/// `info` holds the info series the selector chooses, one float field each, whose value at a
61/// point is the original timestamp of the sample selected there. For each info metric a base
62/// series takes the info series with the same identifying labels. Several of them at one point are
63/// compared in input order, as Prometheus compares them in the order its storage returns them: a
64/// newer one replaces the one kept so far, and one exactly as new is an error. Labels
65/// the base series already has are kept, and two info metrics giving one label different values
66/// are an error. A base series without identifying labels matches no info series, since
67/// Prometheus fetches none for it, and a base series that is itself an info metric is passed
68/// through. Results that share a label set merge; a field held twice at one point is an error.
69pub fn info(
70    schema: &Arc<SeriesSchema>,
71    base: &[Series],
72    info: &[Series],
73    selector: &InfoSelector,
74) -> Result<Vec<Series>> {
75    info_inner(schema, base, info, selector, None)
76}
77
78/// [`info()`], handing the live workspace it holds to `reserve` before it allocates it.
79///
80/// What the index of the info series and the rows of the results keep is held until the operation
81/// returns; the merge of one label set's rows is a phase, and the builder's columns join the phase
82/// of the output they are finished as. A total `reserve` refuses ends the operation with that error.
83pub(crate) fn info_with_reservation(
84    schema: &Arc<SeriesSchema>,
85    base: &[Series],
86    info: &[Series],
87    selector: &InfoSelector,
88    reserve: &mut dyn FnMut(usize) -> Result<()>,
89) -> Result<Vec<Series>> {
90    let mut budget = Budget::new(reserve);
91    info_inner(schema, base, info, selector, Some(&mut budget))
92}
93
94/// The one info kernel, whether or not a caller accounts for its workspace.
95fn info_inner(
96    schema: &Arc<SeriesSchema>,
97    base: &[Series],
98    info: &[Series],
99    selector: &InfoSelector,
100    mut budget: Option<&mut Budget<'_>>,
101) -> Result<Vec<Series>> {
102    let grid = schema
103        .eval_grid
104        .as_ref()
105        .ok_or_else(|| DataFusionError::Execution("info requires an evaluated grid".into()))?;
106    let points = grid.spec().len as usize;
107    for series in base {
108        if series.time.grid().map(|grid| grid.spec()) != Some(grid.spec())
109            || series.fields.len() != schema.fields.len()
110        {
111            return Err(DataFusionError::Execution(
112                "info base series does not match its schema".into(),
113            ));
114        }
115    }
116    for series in info {
117        if series.time.grid().map(|grid| grid.spec()) != Some(grid.spec())
118            || series.fields.len() != 1
119        {
120            return Err(DataFusionError::Execution(
121                "info series must be single-field series on the base grid".into(),
122            ));
123        }
124    }
125    let name_matchers = effective_name_matchers(&selector.name_matchers)?;
126    let is_info_metric = |name: &str| name_matchers.iter().all(|matcher| matcher.matches(name));
127    let width = schema.fields.len();
128
129    // The presence of the base at each point and the identifying values of every base series
130    // stay live until the operation returns.
131    if let Some(budget) = budget.as_deref_mut() {
132        budget.hold(points.saturating_add(base.len().saturating_mul(PATTERN_BYTES)))?;
133    }
134    let mut base_present = vec![false; points];
135    let mut sampled = vec![false; base.len()];
136    for (series, sampled) in base.iter().zip(&mut sampled) {
137        for field in series.fields.iter() {
138            for ((point, _), sample) in series.time.positions().zip(field.iter()) {
139                if !matches!(sample, SampleRef::Missing) {
140                    base_present[point] = true;
141                    *sampled = true;
142                }
143            }
144        }
145    }
146
147    let mut error = FirstError::default();
148
149    // Prometheus fetches info series per presence pattern of the identifying labels among the
150    // base series it enriches: a present label matches any value the pattern's base series have,
151    // an absent one matches only absence. An info series no pattern admits is never fetched, so
152    // it neither enriches nor conflicts.
153    // A base series without a sample is not in Prometheus' base matrix at all, so it selects no
154    // info series.
155    let mut patterns: HashMap<Vec<bool>, Vec<BTreeSet<Arc<str>>>> = HashMap::new();
156    for (series, _) in base.iter().zip(&sampled).filter(|(_, sampled)| **sampled) {
157        if is_info_metric(series.metric.name().unwrap_or("")) {
158            continue;
159        }
160        let values = identifying_values(&series.metric);
161        let presence: Vec<bool> = values.iter().map(Option::is_some).collect();
162        if !presence.contains(&true) {
163            continue;
164        }
165        let sets = patterns
166            .entry(presence)
167            .or_insert_with(|| vec![BTreeSet::new(); IDENTIFYING_LABELS.len()]);
168        for (set, value) in sets.iter_mut().zip(values) {
169            set.extend(value);
170        }
171    }
172
173    // The info series kept for each signature at each point.
174    let mut by_signature: HashMap<Signature, BTreeMap<usize, (f64, usize)>> = HashMap::new();
175    let mut info_names: BTreeSet<Arc<str>> = BTreeSet::new();
176    for (index, series) in info.iter().enumerate() {
177        let values = identifying_values(&series.metric);
178        let presence: Vec<bool> = values.iter().map(Option::is_some).collect();
179        let fetched = patterns.get(&presence).is_some_and(|sets| {
180            sets.iter()
181                .zip(&values)
182                .all(|(set, value)| value.as_ref().is_none_or(|value| set.contains(value)))
183        });
184        if !fetched {
185            continue;
186        }
187        // The entry of a signature and the newest series it keeps at each point the series
188        // holds a sample, charged before they are allocated.
189        if let Some(budget) = budget.as_deref_mut() {
190            budget.hold(
191                series
192                    .time
193                    .len()
194                    .saturating_mul(KEPT_POINT_BYTES)
195                    .saturating_add(SIGNATURE_BYTES),
196            )?;
197        }
198        let name: Arc<str> = Arc::from(series.metric.name().unwrap_or(""));
199        info_names.insert(name.clone());
200        let kept = by_signature.entry((name, values)).or_default();
201        let mut cursor = series.fields.as_slice()[0].cursor();
202        for (point, row) in series.time.positions() {
203            let timestamp = match cursor.at(row).expect("the axis and the fields are aligned") {
204                SampleRef::Missing => continue,
205                SampleRef::Float(timestamp) => timestamp,
206                SampleRef::Histogram(_) => {
207                    return Err(DataFusionError::Internal(
208                        "info series must hold the original sample timestamps as floats".into(),
209                    ));
210                }
211            };
212            match kept.entry(point) {
213                Entry::Vacant(entry) => {
214                    entry.insert((timestamp, index));
215                }
216                Entry::Occupied(mut entry) => {
217                    let (existing, existing_index) = *entry.get();
218                    if timestamp > existing {
219                        entry.insert((timestamp, index));
220                    } else if timestamp == existing && base_present[point] {
221                        error.record(point, 0, || {
222                            format!(
223                                "found duplicate series for info metric: existing {} @ {}, new \
224                                 {} @ {}",
225                                render_label_set(&label_set(&info[existing_index].metric)),
226                                existing as i64,
227                                render_label_set(&label_set(&series.metric)),
228                                timestamp as i64
229                            )
230                        });
231                    }
232                }
233            }
234        }
235    }
236
237    let mut result_index: HashMap<LabelSet, usize> = HashMap::new();
238    let mut results: Vec<(SeriesLabels, Vec<Row>)> = Vec::new();
239    let mut added: Vec<(Arc<str>, Arc<str>)> = Vec::new();
240    let mut chosen: Vec<usize> = Vec::new();
241    for series in base {
242        let ignored = is_info_metric(series.metric.name().unwrap_or(""));
243        // The signature of each info metric is fixed for a series, so its kept series are looked
244        // up once; a point then only reads which of them is kept there.
245        let candidates: Vec<&BTreeMap<usize, (f64, usize)>> = if ignored {
246            Vec::new()
247        } else {
248            let values = identifying_values(&series.metric);
249            info_names
250                .iter()
251                .filter_map(|name| by_signature.get(&(name.clone(), values.clone())))
252                .collect()
253        };
254        // The result of the previous point, reused while the same info series are kept.
255        let mut previous: Option<Choice> = None;
256        // A row of this series is kept by the result it goes to, so every row it can have is held
257        // before the walk; a histogram is held as it is copied.
258        if let Some(budget) = budget.as_deref_mut() {
259            budget.hold(series.time.len().saturating_mul(row_bytes(width)))?;
260        }
261        let mut cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
262        for (point, row) in series.time.positions() {
263            let mut values = Vec::with_capacity(width);
264            for cursor in &mut cursors {
265                let sample = cursor.at(row).expect("the axis and the fields are aligned");
266                if let (Some(budget), SampleRef::Histogram(view)) = (budget.as_deref_mut(), &sample)
267                {
268                    budget.hold(owned_histogram_bytes(view))?;
269                }
270                values.push(owned(sample)?);
271            }
272            if values.iter().all(Option::is_none) {
273                continue;
274            }
275            chosen.clear();
276            chosen.extend(
277                candidates
278                    .iter()
279                    .filter_map(|kept| kept.get(&point).map(|&(_, index)| index)),
280            );
281            let reuse = previous
282                .as_ref()
283                .is_some_and(|previous| previous.info == chosen);
284            if !reuse {
285                added.clear();
286                let mut conflict = None;
287                for &index in &chosen {
288                    if let Err(label) =
289                        add_data_labels(&info[index].metric, &series.metric, selector, &mut added)
290                    {
291                        conflict = Some(label);
292                        break;
293                    }
294                }
295                let result = if chosen.is_empty() && !selector.keep_unmatched && !ignored {
296                    None
297                } else {
298                    let mut metric = series.metric.clone();
299                    for (name, value) in &added {
300                        metric.set(name, value.clone()).map_err(external)?;
301                    }
302                    Some(match result_index.entry(label_set(&metric)) {
303                        std::collections::hash_map::Entry::Occupied(entry) => *entry.get(),
304                        std::collections::hash_map::Entry::Vacant(entry) => {
305                            if let Some(budget) = budget.as_deref_mut() {
306                                budget.hold(result_set_bytes(&metric))?;
307                            }
308                            results.push((metric, Vec::new()));
309                            *entry.insert(results.len() - 1)
310                        }
311                    })
312                };
313                previous = Some(Choice {
314                    info: chosen.clone(),
315                    result,
316                    conflict,
317                });
318            }
319            let choice = previous.as_ref().expect("set above");
320            if let Some(label) = &choice.conflict {
321                error.record(point, 1, || format!("conflicting label: {label}"));
322            }
323            if let Some(result) = choice.result {
324                results[result].1.push((point, values));
325            }
326        }
327    }
328
329    // Rows of one label set arrive per base series; sorted by point, a field held twice at one
330    // point is a collision.
331    for (metric, rows) in &mut results {
332        // The sort's buffer and the merged rows, while the rows they replace are still alive.
333        if let Some(budget) = budget.as_deref_mut() {
334            budget.phase(rows.len().saturating_mul(2 * std::mem::size_of::<Row>()))?;
335        }
336        rows.sort_by_key(|(point, _)| *point);
337        let mut merged: Vec<Row> = Vec::with_capacity(rows.len());
338        for (point, values) in rows.drain(..) {
339            match merged.last_mut() {
340                Some((last, slots)) if *last == point => {
341                    for (slot, value) in slots.iter_mut().zip(values) {
342                        if value.is_none() {
343                            continue;
344                        }
345                        if slot.is_some() {
346                            error.record(point, 2, || {
347                                format!(
348                                    "vector cannot contain metrics with the same labelset {}",
349                                    render_label_set(&label_set(metric))
350                                )
351                            });
352                        }
353                        *slot = value;
354                    }
355                }
356                _ => merged.push((point, values)),
357            }
358        }
359        *rows = merged;
360    }
361    if let Some((_, _, message)) = error.0 {
362        return Err(DataFusionError::Execution(message));
363    }
364
365    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
366    let mut output = Vec::with_capacity(results.len());
367    if let Some(budget) = budget.as_deref_mut() {
368        budget.phase(0)?;
369    }
370    for (metric, rows) in results {
371        builder.begin_series();
372        // This series' columns, reserved before its first row. They stay live inside the series
373        // it is finished as, so the phase keeps them.
374        if let Some(budget) = budget.as_deref_mut() {
375            budget.grow(column_bytes(&rows, width))?;
376        }
377        builder.reserve_rows(rows.len())?;
378        for (point, row) in rows {
379            builder.push_samples(point, &row)?;
380        }
381        output.extend(builder.finish(metric)?);
382    }
383    Ok(output)
384}
385
386/// The samples of one result series at one grid point, one per field.
387type Row = (usize, Vec<Option<GridSample>>);
388
389/// The identifying values one base series adds to its presence pattern, charged twice for the
390/// spare room of the sets they go to.
391const PATTERN_BYTES: usize = 2 * IDENTIFYING_LABELS.len() * std::mem::size_of::<Arc<str>>();
392
393/// The entry of one info series' signature: its key, its map of kept series, and the name the
394/// info metric list keeps, charged twice for the spare room of the tables.
395const SIGNATURE_BYTES: usize = 2
396    * (std::mem::size_of::<(Signature, BTreeMap<usize, (f64, usize)>)>()
397        + IDENTIFYING_LABELS.len() * std::mem::size_of::<Option<Arc<str>>>()
398        + std::mem::size_of::<Arc<str>>());
399
400/// The series one signature keeps at one point, charged twice for the B-tree's spare room.
401const KEPT_POINT_BYTES: usize = 2 * std::mem::size_of::<(usize, (f64, usize))>();
402
403/// One row a result keeps: its entry in the result's row list, charged twice for the list's
404/// growth, and its samples, allocated at their exact count.
405fn row_bytes(width: usize) -> usize {
406    (2 * std::mem::size_of::<Row>())
407        .saturating_add(width.saturating_mul(std::mem::size_of::<Option<GridSample>>()))
408}
409
410/// The bytes a result label set keeps: its metric, rebuilt by each label it is given, the label set
411/// it is filed under with the copy of the name that set makes, and its entries in the result list
412/// and index.
413fn result_set_bytes(metric: &SeriesLabels) -> usize {
414    let labels = metric.tags().len().saturating_add(1);
415    labels
416        .saturating_mul(
417            2 * std::mem::size_of::<Label>() + std::mem::size_of::<(Arc<str>, Arc<str>)>(),
418        )
419        .saturating_add(metric.name().map_or(0, str::len))
420        .saturating_add(
421            metric
422                .tags()
423                .iter()
424                .map(|tag| tag.name.len())
425                .sum::<usize>(),
426        )
427        .saturating_add(2 * std::mem::size_of::<(SeriesLabels, Vec<Row>)>())
428        .saturating_add(2 * std::mem::size_of::<(LabelSet, usize)>())
429}
430
431/// The bytes one result series' columns take: per row, the grid index, the value and validity
432/// column of every field, charged twice for the capacity each grows to, and a histogram index; per
433/// histogram, a row of the builder's histogram table and the buckets copied into it.
434fn column_bytes(rows: &[Row], width: usize) -> usize {
435    let row = std::mem::size_of::<usize>()
436        + 2 * width.saturating_mul(std::mem::size_of::<f64>() + 1)
437        + width.saturating_mul(std::mem::size_of::<Option<u32>>());
438    rows.iter().flat_map(|(_, values)| values).fold(
439        rows.len().saturating_mul(row),
440        |bytes, value| match value {
441            Some(GridSample::Histogram(histogram)) => bytes
442                .saturating_add(HISTOGRAM_ROW_BYTES)
443                .saturating_add(histogram.heap_bytes()),
444            _ => bytes,
445        },
446    )
447}
448
449/// What the info series kept at a point make of one base series.
450struct Choice {
451    /// The info series, one per info metric that has one.
452    info: Vec<usize>,
453    /// The result series the point goes to, `None` when the point is dropped.
454    result: Option<usize>,
455    /// A label two of the info series set to different values.
456    conflict: Option<Arc<str>>,
457}
458
459/// The error Prometheus reports: the one of the first failing step, and within a step the first
460/// of its checks (the info series, then each base series, then the result label sets).
461#[derive(Default)]
462struct FirstError(Option<(usize, u8, String)>);
463
464impl FirstError {
465    /// Records an error of check `rank` at `point`, formatting it only if it comes first.
466    fn record(&mut self, point: usize, rank: u8, message: impl FnOnce() -> String) {
467        if self
468            .0
469            .as_ref()
470            .is_none_or(|(first, first_rank, _)| (point, rank) < (*first, *first_rank))
471        {
472            self.0 = Some((point, rank, message()));
473        }
474    }
475}
476
477/// An info metric name and the identifying label values present on a series.
478type Signature = (Arc<str>, Vec<Option<Arc<str>>>);
479
480/// The value of each identifying label, `None` where the series does not have it.
481///
482/// The values share the series' own label strings, which the retained operands already hold and
483/// charge, so the patterns and signatures built from them allocate no label text of their own.
484fn identifying_values(metric: &SeriesLabels) -> Vec<Option<Arc<str>>> {
485    IDENTIFYING_LABELS
486        .iter()
487        .map(|label| {
488            metric
489                .tags()
490                .iter()
491                .find(|tag| tag.name.as_ref() == *label)
492                .filter(|tag| !tag.value.is_empty())
493                .map(|tag| Arc::clone(&tag.value))
494        })
495        .collect()
496}
497
498/// Adds the data labels `info` gives a series with labels `base` to `added`; returns the name of
499/// a label another info metric already set to a different value.
500fn add_data_labels(
501    info: &SeriesLabels,
502    base: &SeriesLabels,
503    selector: &InfoSelector,
504    added: &mut Vec<(Arc<str>, Arc<str>)>,
505) -> std::result::Result<(), Arc<str>> {
506    for tag in info.tags() {
507        if tag.value.is_empty()
508            || (!selector.data_labels.is_empty() && !selector.data_labels.contains(&tag.name))
509        {
510            continue;
511        }
512        if let Some((_, value)) = added.iter().find(|(name, _)| *name == tag.name) {
513            if *value != tag.value {
514                return Err(tag.name.clone());
515            }
516            continue;
517        }
518        if base.get(&tag.name).is_some_and(|value| !value.is_empty()) {
519            continue;
520        }
521        added.push((tag.name.clone(), tag.value.clone()));
522    }
523    Ok(())
524}
525
526struct NameMatcher {
527    op: MatchOp,
528    value: Arc<str>,
529    regex: Option<Regex>,
530}
531
532impl NameMatcher {
533    fn try_new(op: MatchOp, value: Arc<str>) -> Result<Self> {
534        let regex = match op {
535            MatchOp::Regex | MatchOp::NotRegex => {
536                Some(Regex::new(&format!("^(?s:{value})$")).map_err(|error| {
537                    DataFusionError::Plan(format!("invalid regular expression {value}: {error}"))
538                })?)
539            }
540            MatchOp::Equal | MatchOp::NotEqual => None,
541        };
542        Ok(Self { op, value, regex })
543    }
544
545    fn matches(&self, name: &str) -> bool {
546        match (self.op, &self.regex) {
547            (MatchOp::Equal, _) => name == &*self.value,
548            (MatchOp::NotEqual, _) => name != &*self.value,
549            (MatchOp::Regex, Some(regex)) => regex.is_match(name),
550            (MatchOp::NotRegex, Some(regex)) => !regex.is_match(name),
551            _ => unreachable!("regex matchers compile their regex"),
552        }
553    }
554}
555
556/// Prometheus `effectiveInfoNameMatchers`: the name matchers as given when one of them selects,
557/// prefixed with `.+_info` when all of them only exclude, and `target_info` when there are none.
558fn effective_name_matchers(matchers: &[(MatchOp, Arc<str>)]) -> Result<Vec<NameMatcher>> {
559    let mut effective = Vec::with_capacity(matchers.len() + 1);
560    if matchers.is_empty() {
561        effective.push(NameMatcher::try_new(
562            MatchOp::Equal,
563            Arc::from("target_info"),
564        )?);
565    } else if matchers
566        .iter()
567        .all(|(op, _)| matches!(op, MatchOp::NotEqual | MatchOp::NotRegex))
568    {
569        effective.push(NameMatcher::try_new(MatchOp::Regex, Arc::from(".+_info"))?);
570    }
571    for (op, value) in matchers {
572        effective.push(NameMatcher::try_new(*op, value.clone())?);
573    }
574    Ok(effective)
575}