Skip to main content

promql/
select.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//! Operators that depend on the whole set of evaluated series at each grid point: `topk`,
16//! `bottomk`, `limitk`, `limit_ratio`, `scalar`, `absent` and the instant-result sorts.
17//!
18//! Semantics follow Prometheus (`aggregationK`, `HashRatioSampler`, `funcScalar`, `funcAbsent`,
19//! `createLabelsForAbsentFunction`, `funcSort*`). A scalar is a grid series without labels that
20//! has a value at every point, so `vector(s)` is `s` itself and has no kernel.
21
22use std::cmp::Ordering;
23use std::collections::HashMap;
24use std::sync::Arc;
25
26use datafusion::arrow::array::Float64Array;
27use datafusion::error::{DataFusionError, Result};
28use datatypes::series::samples::{
29    RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
30};
31use datatypes::series::time::{EvalGrid, GridRange, TimeAxis, union_positions};
32use datatypes::series::{Label, SeriesLabels};
33
34use crate::go_sort;
35use crate::grid_series::{GridSeriesBuilder, external};
36
37#[cfg(test)]
38mod tests;
39
40/// The labels that form an aggregation group.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub enum Grouping {
43    /// `by(...)`: only these labels, `__name__` included when listed.
44    By(Vec<Arc<str>>),
45    /// `without(...)`: every label except these and `__name__`.
46    Without(Vec<Arc<str>>),
47}
48
49/// The order `sort_instant` arranges an instant result in.
50#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
51pub enum SortOrder {
52    /// `sort`: ascending values, NaN last.
53    Asc,
54    /// `sort_desc`: descending values, NaN last.
55    Desc,
56    /// `sort_by_label`: natural order of the listed label values, then the label sets.
57    ByLabel(Vec<Arc<str>>),
58    /// `sort_by_label_desc`.
59    ByLabelDesc(Vec<Arc<str>>),
60}
61
62/// `topk(k, ...)` (`top`) or `bottomk(k, ...)` with a constant `k`.
63///
64/// At every point each group keeps the `k` largest (or smallest) values, NaN ranking last for
65/// both; the selected samples keep their series' labels and values. Histogram samples are not
66/// ranked, as Prometheus ignores them here. Prometheus breaks ties by
67/// the order its storage returns series in, which is not a property of the series; here ties
68/// go to the series whose label set sorts first.
69pub fn topk(
70    k: f64,
71    top: bool,
72    grouping: &Grouping,
73    schema: &SeriesSchema,
74    series: &[Series],
75) -> Result<Vec<Series>> {
76    let k = k_param(k, series.len())?;
77    topk_at(|_| Ok(k), top, grouping, schema, series)
78}
79
80/// `topk`/`bottomk` with `k` evaluated independently at each grid point.
81pub fn topk_at(
82    k_at: impl Fn(usize) -> Result<Option<usize>>,
83    top: bool,
84    grouping: &Grouping,
85    schema: &SeriesSchema,
86    series: &[Series],
87) -> Result<Vec<Series>> {
88    single_field(schema, "topk/bottomk")?;
89    // Validates the series against the schema and its grid; the walk below visits the carried
90    // positions, not the whole grid.
91    grid_points(schema, series)?;
92    let mut order: Vec<usize> = (0..series.len()).collect();
93    // The label pairs of a series are built once: a comparator that compared two metrics would
94    // rebuild both lists per comparison, and the groups read the same lists again.
95    let mut label_sets: Vec<Vec<(Arc<str>, Arc<str>)>> = series
96        .iter()
97        .map(|item| labels_with_name(&item.metric))
98        .collect();
99    order.sort_by(|&a, &b| label_sets[a].cmp(&label_sets[b]));
100    let mut groups: HashMap<GroupKey, Vec<usize>> = HashMap::new();
101    for index in order {
102        groups
103            .entry(group_key_from(&label_sets[index], grouping))
104            .or_default()
105            .push(index);
106    }
107    // The groups hold what they need, so the label lists are freed before the point walk.
108    label_sets.clear();
109
110    let mut selected: Vec<Vec<(usize, usize)>> = vec![Vec::new(); series.len()];
111    let mut candidates: Vec<(usize, usize, f64)> = Vec::new();
112    // The values of one point, for the partial selection below: ranking them there leaves the
113    // candidates in member order, which is what hands ties to the earlier label set.
114    let mut values: Vec<f64> = Vec::new();
115    for members in groups.values() {
116        // A point no member carries holds no candidate, so only the union of the members'
117        // positions is visited: a hole in the grid never reaches the ranking. Each member reads
118        // through one forward cursor, whose rows only increase as the union walk advances.
119        let mut cursors: Vec<RowCursor<'_>> = members
120            .iter()
121            .map(|&member| series[member].fields.as_slice()[0].cursor())
122            .collect();
123        for point in union_positions(members.iter().map(|&member| &series[member].time)) {
124            candidates.clear();
125            for (slot, &member) in members.iter().enumerate() {
126                let Some(row) = series[member].time.row_of(point) else {
127                    continue;
128                };
129                if let SampleRef::Float(value) = cursors[slot]
130                    .at(row)
131                    .expect("the axis and the fields are aligned")
132                {
133                    candidates.push((member, row, value));
134                }
135            }
136            let Some(k) = k_at(point)? else {
137                continue;
138            };
139            // Which candidates win is the result; the order they were found in is not. The ranking
140            // is a partial selection of the k best values rather than an ordering of the whole
141            // group, and it runs on a copy of the values so that the candidates keep the member
142            // order the ties are resolved in.
143            let k = k.min(candidates.len());
144            if k == 0 {
145                continue;
146            }
147            let boundary = (k < candidates.len()).then(|| {
148                values.clear();
149                values.extend(candidates.iter().map(|candidate| candidate.2));
150                values.select_nth_unstable_by(k, |a, b| rank(*a, *b, top));
151                values[k]
152            });
153            // The partition splits the run of values equal to its boundary, while ties go to the
154            // earlier label set: the ones equal to the boundary inside the front are the slots left
155            // for them, and the scan below fills those slots in member order, which is label order.
156            let mut tied = match boundary {
157                Some(boundary) => values[..k]
158                    .iter()
159                    .filter(|&&value| rank(value, boundary, top) == Ordering::Equal)
160                    .count(),
161                None => 0,
162            };
163            for &(member, row, value) in &candidates {
164                if let Some(boundary) = boundary {
165                    match rank(value, boundary, top) {
166                        Ordering::Less => {}
167                        Ordering::Equal if tied > 0 => tied -= 1,
168                        _ => continue,
169                    }
170                }
171                selected[member].push((point, row));
172            }
173        }
174    }
175
176    let output = Arc::new(schema.clone());
177    let mut builder = GridSeriesBuilder::try_new(output)?;
178    let mut result = Vec::new();
179    for (index, points) in selected.into_iter().enumerate() {
180        if points.is_empty() {
181            continue;
182        }
183        let mut sorted = points;
184        sorted.sort_unstable();
185        // One builder serves every result series, so each one starts explicitly: only
186        // `begin_series` resets the positions it accepts.
187        builder.begin_series();
188        // The selected positions of one series only increase, so one cursor reads their rows.
189        let mut cursor = series[index].fields.as_slice()[0].cursor();
190        for (point, row) in sorted {
191            builder.push(point, &[cursor_value(&mut cursor, row)?])?;
192        }
193        result.extend(builder.finish(series[index].metric.clone())?);
194    }
195    Ok(result)
196}
197
198/// `limitk(k, ...)` with a constant `k`.
199///
200/// At every point each group keeps the first `k` series in input order that hold a sample there,
201/// float or histogram, with their labels and values. Prometheus takes them in the order its
202/// storage returns series: label order once a query reads several queriers (the head and a
203/// block), creation order when the TSDB head alone answers it. A caller that wants Prometheus'
204/// result over persisted data passes the series in label order.
205pub fn limitk(
206    k: f64,
207    grouping: &Grouping,
208    schema: &SeriesSchema,
209    series: &[Series],
210) -> Result<Vec<Series>> {
211    single_field(schema, "limitk")?;
212    grid_points(schema, series)?;
213    let Some(k) = k_param(k, series.len())? else {
214        return Ok(Vec::new());
215    };
216    let mut groups: HashMap<GroupKey, Vec<usize>> = HashMap::new();
217    for (index, item) in series.iter().enumerate() {
218        groups
219            .entry(group_key(&item.metric, grouping))
220            .or_default()
221            .push(index);
222    }
223    let mut selected: Vec<Vec<(usize, usize)>> = vec![Vec::new(); series.len()];
224    for members in groups.values() {
225        let mut cursors: Vec<RowCursor<'_>> = members
226            .iter()
227            .map(|&member| series[member].fields.as_slice()[0].cursor())
228            .collect();
229        for point in union_positions(members.iter().map(|&member| &series[member].time)) {
230            let mut taken = 0;
231            for (slot, &member) in members.iter().enumerate() {
232                if taken == k {
233                    break;
234                }
235                let Some(row) = series[member].time.row_of(point) else {
236                    continue;
237                };
238                if !matches!(
239                    cursors[slot]
240                        .at(row)
241                        .expect("the axis and the fields are aligned"),
242                    SampleRef::Missing
243                ) {
244                    selected[member].push((point, row));
245                    taken += 1;
246                }
247            }
248        }
249    }
250
251    let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
252    let mut result = Vec::new();
253    for (index, points) in selected.into_iter().enumerate() {
254        if points.is_empty() {
255            continue;
256        }
257        builder.begin_series();
258        // A series belongs to one group, whose points are visited in order.
259        let mut cursor = series[index].fields.as_slice()[0].cursor();
260        for (point, row) in points {
261            // The sample is moved, not computed, so it goes straight into the result.
262            let sample = cursor.at(row).expect("the axis and the fields are aligned");
263            builder.push_refs(point, &[sample])?;
264        }
265        result.extend(builder.finish(series[index].metric.clone())?);
266    }
267    Ok(result)
268}
269
270/// `limit_ratio(r, ...)` with a constant `r`.
271///
272/// Keeps whole series: Prometheus derives an offset in `[0, 1)` from the hash of a series' labels
273/// and keeps the series when the offset is below `r`, or, for a negative `r`, at least `1 + r`.
274/// Which series are kept does not depend on the grouping, so it is not a parameter. The hash is
275/// the one of Prometheus' default `stringlabels` build; the other label builds hash differently.
276pub fn limit_ratio(ratio: f64, schema: &SeriesSchema, series: &[Series]) -> Result<Vec<Series>> {
277    grid_points(schema, series)?;
278    if ratio.is_nan() {
279        return Err(DataFusionError::Execution("Ratio value is NaN".into()));
280    }
281    let ratio = ratio.clamp(-1.0, 1.0);
282    let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
283    let mut result = Vec::new();
284    let mut row: Vec<SampleRef<'_>> = Vec::with_capacity(schema.fields.len());
285    for item in series {
286        let offset = sample_offset(&item.metric);
287        let kept = if ratio >= 0.0 {
288            offset < ratio
289        } else {
290            offset >= 1.0 + ratio
291        };
292        if !kept {
293            continue;
294        }
295        // Rebuilt rather than cloned: an input may carry rows without a value, a result may not.
296        builder.begin_series();
297        let mut cursors: Vec<RowCursor<'_>> =
298            item.fields.iter().map(|field| field.cursor()).collect();
299        for (point, index) in item.time.positions() {
300            row.clear();
301            // The samples are moved, not computed, so the row is read and pushed as it stands.
302            for cursor in &mut cursors {
303                row.push(
304                    cursor
305                        .at(index)
306                        .expect("the axis and the fields are aligned"),
307                );
308            }
309            builder.push_refs(point, &row)?;
310        }
311        result.extend(builder.finish(item.metric.clone())?);
312    }
313    Ok(result)
314}
315
316/// Prometheus `HashRatioSampler.SampleOffset`: the xxHash64 of the labels as `stringlabels`
317/// encodes them, each name and value prefixed by its length, over `u64::MAX`.
318fn sample_offset(metric: &SeriesLabels) -> f64 {
319    let mut data = Vec::new();
320    for (name, value) in labels_with_name(metric) {
321        // Prometheus label sets hold no empty value.
322        if value.is_empty() {
323            continue;
324        }
325        for text in [&name, &value] {
326            let len = text.len();
327            if len < 255 {
328                data.push(len as u8);
329            } else {
330                data.extend([255, len as u8, (len >> 8) as u8, (len >> 16) as u8]);
331            }
332            data.extend_from_slice(text.as_bytes());
333        }
334    }
335    twox_hash::XxHash64::oneshot(0, &data) as f64 / u64::MAX as f64
336}
337
338/// `scalar(v)`: the value of the only float sample present at each point, NaN otherwise.
339///
340/// Native histogram samples are ignored, as Prometheus' `funcScalar` ignores them: they hold no
341/// float value, and they are not an element either, so they never make a point hold more than one
342/// sample. A point whose only sample is a histogram therefore answers NaN, a histogram beside one
343/// float answers that float, and two floats answer NaN.
344///
345/// A scalar holds a value at every point of the grid, so its value array is written where the input
346/// is read rather than staged and rebuilt: the one buffer of values becomes the result's array, and
347/// the counts that decide between a value and a NaN are dropped before it is handed over. Building
348/// it therefore costs one `f64` and one count per point and nothing else per point -- no optional
349/// value, no row index, no second copy of the answer -- which is what the caller reserves for it.
350pub fn scalar(schema: &SeriesSchema, series: &[Series]) -> Result<Series> {
351    single_field(schema, "scalar")?;
352    let (grid, points) = grid_and_points(schema, series)?;
353    // A point no float has reached answers the Go NaN, which is where it starts. The first float of
354    // a point writes its value there; the second takes the point back to NaN, and so does any float
355    // after it, so a point holding more than one float never reads as holding one.
356    let mut values = vec![GO_NAN; points];
357    let mut counts = vec![0u8; points];
358    for item in series {
359        // Walk the rows this series carries: a sparse axis must not be read as its envelope, and
360        // a forward cursor keeps the read proportional to them.
361        let mut field = item.fields.as_slice()[0].cursor();
362        for (point, row) in item.time.positions() {
363            match field.at(row).expect("the axis and the fields are aligned") {
364                SampleRef::Float(value) => {
365                    let count = &mut counts[point];
366                    values[point] = if *count == 0 { value } else { GO_NAN };
367                    *count = count.saturating_add(1);
368                }
369                // Neither a histogram nor a position holding no sample is an element of the
370                // vector, so neither decides what the point answers.
371                SampleRef::Histogram(_) | SampleRef::Missing => {}
372            }
373        }
374    }
375    // The counts have decided every value above; handing them back first leaves the values as the
376    // only per-point buffer alive when the answer is built.
377    drop(counts);
378    let fields = SeriesFields::one(Samples::from_float(Float64Array::from(values)));
379    // Every point of the grid holds a value, so the axis is the whole grid as one run.
380    let time = TimeAxis::Grid(GridRange::try_new(grid, 0, points).map_err(external)?);
381    let empty = SeriesLabels::try_new(None, Vec::new()).map_err(external)?;
382    Series::try_new(schema, empty, time, fields).map_err(external)
383}
384
385/// `absent(v)`: 1 with `labels` at every point where no series is present.
386///
387/// `absent_over_time(v[r])` is this over the result of `present_over_time(v[r])`. When `v[r]` is
388/// a range selector, `labels` come from its matchers as for `absent(v)`; for a subquery
389/// Prometheus derives no labels.
390///
391/// All of it is one label set, so the result is one series. A point where one field is present and
392/// another is absent keeps its row, with a null in the field that is present; a point where every
393/// field is present contributes no row, and the axis names the runs of points that do. `None` means
394/// no point is absent in any field, so no row survives.
395pub fn absent(
396    schema: &SeriesSchema,
397    series: &[Series],
398    labels: SeriesLabels,
399) -> Result<Option<Series>> {
400    let points = grid_points(schema, series)?;
401    let fields = schema.fields.len();
402    // Each field is absent on its own.
403    let mut present = vec![false; points * fields];
404    for item in series {
405        for (field, samples) in item.fields.iter().enumerate() {
406            // One cursor per field, driven by the positions the axis carries.
407            let mut cursor = samples.cursor();
408            for (point, row) in item.time.positions() {
409                if !matches!(
410                    cursor.at(row).expect("the axis and the fields are aligned"),
411                    SampleRef::Missing
412                ) {
413                    present[point * fields + field] = true;
414                }
415            }
416        }
417    }
418    let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
419    let mut row = vec![None; fields];
420    for point in 0..points {
421        for (field, value) in row.iter_mut().enumerate() {
422            *value = (!present[point * fields + field]).then_some(1.0);
423        }
424        builder.push(point, &row)?;
425    }
426    builder.finish(labels)
427}
428
429/// A label matcher of the selector `absent` is applied to.
430#[derive(Clone, Debug, PartialEq, Eq)]
431pub struct LabelMatcher {
432    pub name: Arc<str>,
433    pub op: MatchOp,
434    pub value: Arc<str>,
435    /// Whether the matcher accepts an empty value, i.e. a missing label; the caller evaluates
436    /// regular expressions.
437    pub matches_empty: bool,
438}
439
440/// The operator of a [`LabelMatcher`].
441#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
442pub enum MatchOp {
443    Equal,
444    NotEqual,
445    Regex,
446    NotRegex,
447}
448
449/// The labels of an `absent` result, as Prometheus `createLabelsForAbsentFunction` derives them:
450/// the first equality matcher of a name sets that label, any other matcher of the name removes
451/// it, and `__name__` is skipped.
452///
453/// Prometheus reads the matchers after TSDB's `PostingsForMatchers` has reordered them in place,
454/// moving the matchers that narrow the result before those that only subtract from it; that is
455/// the order users see whenever the storage holds data, and the order used here. It changes the
456/// result only when a name has both an equality and another matcher.
457pub fn absent_labels(matchers: &[LabelMatcher]) -> Result<SeriesLabels> {
458    let must_be_set: Vec<&str> = matchers
459        .iter()
460        .filter(|matcher| !matcher.matches_empty)
461        .map(|matcher| &*matcher.name)
462        .collect();
463    let subtracting = |matcher: &LabelMatcher| {
464        !must_be_set.contains(&&*matcher.name)
465            || (matches!(matcher.op, MatchOp::NotEqual | MatchOp::NotRegex)
466                && matcher.matches_empty)
467    };
468    let ordered = matchers
469        .iter()
470        .filter(|matcher| !subtracting(matcher))
471        .chain(matchers.iter().filter(|matcher| subtracting(matcher)));
472
473    let mut labels: Vec<Label> = Vec::new();
474    let mut set: Vec<&str> = Vec::new();
475    for matcher in ordered {
476        if &*matcher.name == "__name__" {
477            continue;
478        }
479        if matcher.op == MatchOp::Equal && !set.contains(&&*matcher.name) {
480            labels.retain(|label| label.name != matcher.name);
481            labels.push(Label {
482                name: matcher.name.clone(),
483                value: matcher.value.clone(),
484            });
485            set.push(&matcher.name);
486        } else {
487            labels.retain(|label| label.name != matcher.name);
488        }
489    }
490    labels.retain(|label| !label.value.is_empty());
491    SeriesLabels::try_new(None, labels).map_err(external)
492}
493
494/// Orders the series of an instant result. A range result keeps its order: Prometheus does not
495/// sort matrices.
496///
497/// `sort` and `sort_desc` drop histogram samples, in a range result too: Prometheus filters them
498/// out at every step (`filterFloats`) before it sorts. The label sorts keep every sample.
499pub fn sort_instant(
500    order: &SortOrder,
501    schema: &SeriesSchema,
502    mut series: Vec<Series>,
503) -> Result<Vec<Series>> {
504    let points = grid_points(schema, &series)?;
505    if matches!(order, SortOrder::Asc | SortOrder::Desc) {
506        single_field(schema, "sort")?;
507        let mut floats = Vec::with_capacity(series.len());
508        for item in series {
509            floats.extend(float_samples(schema, item)?);
510        }
511        series = floats;
512    }
513    if points != 1 {
514        return Ok(series);
515    }
516    match order {
517        SortOrder::Asc | SortOrder::Desc => {
518            let mut keyed = Vec::with_capacity(series.len());
519            for item in series {
520                let value = value_at(&item, 0)?;
521                keyed.push((value.unwrap_or(f64::NAN), item));
522            }
523            let descending = *order == SortOrder::Desc;
524            // `sort.Sort(sort.Reverse(h))` with Prometheus' heap `Less`, which holds whenever
525            // its first value is NaN.
526            go_sort::sort_by(&mut keyed, |(a, _), (b, _)| {
527                b.is_nan() || if descending { b < a } else { b > a }
528            });
529            Ok(keyed.into_iter().map(|(_, item)| item).collect())
530        }
531        SortOrder::ByLabel(labels) | SortOrder::ByLabelDesc(labels) => {
532            let descending = matches!(order, SortOrder::ByLabelDesc(_));
533            go_sort::sort_by(&mut series, |a, b| {
534                for label in labels {
535                    let (a, b) = (
536                        a.metric.get(label).unwrap_or(""),
537                        b.metric.get(label).unwrap_or(""),
538                    );
539                    if a == b {
540                        continue;
541                    }
542                    return natural_less(a, b) != descending;
543                }
544                let order = compare_labels(&a.metric, &b.metric);
545                if descending {
546                    order == Ordering::Greater
547                } else {
548                    order == Ordering::Less
549                }
550            });
551            Ok(series)
552        }
553    }
554}
555
556/// `series` without its histogram samples, `None` when nothing else is left. One field, as `sort`
557/// reads.
558fn float_samples(schema: &SeriesSchema, series: Series) -> Result<Option<Series>> {
559    let field = &series.fields.as_slice()[0];
560    if !field
561        .iter()
562        .any(|sample| matches!(sample, SampleRef::Histogram(_)))
563    {
564        return Ok(Some(series));
565    }
566    let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
567    let mut cursor = field.cursor();
568    for (point, row) in series.time.positions() {
569        let value = match cursor.at(row).expect("the axis and the fields are aligned") {
570            SampleRef::Float(value) => Some(value),
571            SampleRef::Missing | SampleRef::Histogram(_) => None,
572        };
573        builder.push(point, &[value])?;
574    }
575    builder.finish(series.metric)
576}
577
578/// Go's `math.NaN()` bit pattern, which Prometheus returns for an undefined scalar.
579const GO_NAN: f64 = f64::from_bits(0x7FF8_0000_0000_0001);
580
581/// The order of `a` and `b` for `topk` (`top`) or `bottomk`; NaN ranks last for both.
582fn rank(a: f64, b: f64, top: bool) -> Ordering {
583    #[cfg(test)]
584    calls::record_rank();
585    match (a.is_nan(), b.is_nan()) {
586        (true, true) => Ordering::Equal,
587        (true, false) => Ordering::Greater,
588        (false, true) => Ordering::Less,
589        _ if top => b.partial_cmp(&a).expect("not NaN"),
590        _ => a.partial_cmp(&b).expect("not NaN"),
591    }
592}
593
594/// The `k` of `topk`, `bottomk` and `limitk` as Prometheus reads it: nothing for `k` below 1, an
595/// error for NaN or a value out of int64, otherwise `k` truncated and capped at the number of
596/// input series.
597pub(crate) fn k_param(k: f64, series: usize) -> Result<Option<usize>> {
598    if k < 1.0 {
599        return Ok(None);
600    }
601    if k.is_nan() {
602        return Err(DataFusionError::Execution("Parameter value is NaN".into()));
603    }
604    // Prometheus' `maxInt64`, the largest float64 below 2^63.
605    if k >= 9_223_372_036_854_774_784.0 {
606        return Err(DataFusionError::Execution(format!(
607            "Scalar value {k} overflows int64"
608        )));
609    }
610    Ok(Some(k.trunc().min(series as f64) as usize))
611}
612
613/// Validates the complete parameter series for Prometheus topk/bottomk/limitk semantics.
614///
615/// The values are read where the node holds them, in one pass. The caller keeps both the series the
616/// parameter arrived as and the values it was read into, so a second copy of the present ones would
617/// be memory neither of them is charged for.
618pub(crate) fn validate_topk_parameters(values: &[Option<f64>]) -> Result<()> {
619    // A position the series decided nothing at is no parameter value, so only the present ones are
620    // read. NaN is tracked rather than folded into the bounds: it is a value Prometheus refuses
621    // outright, not the largest one, and it is refused even where every value is below 1.
622    let (mut max, mut min, mut nan) = (f64::NEG_INFINITY, f64::INFINITY, false);
623    for value in values.iter().flatten() {
624        if value.is_nan() {
625            nan = true;
626        } else {
627            max = max.max(*value);
628            min = min.min(*value);
629        }
630    }
631    if nan {
632        return Err(DataFusionError::Execution("Parameter value is NaN".into()));
633    }
634    // A `k` below 1 selects nothing, so a value that would not fit an int64 is never read.
635    if max < 1.0 {
636        return Ok(());
637    }
638    if min <= -9_223_372_036_854_775_808.0 {
639        return Err(DataFusionError::Execution(format!(
640            "Scalar value {min} underflows int64"
641        )));
642    }
643    if max >= 9_223_372_036_854_774_784.0 {
644        return Err(DataFusionError::Execution(format!(
645            "Scalar value {max} overflows int64"
646        )));
647    }
648    Ok(())
649}
650
651/// Label pairs identifying a group; empty values are absent, as in Prometheus.
652type GroupKey = Vec<(Arc<str>, Arc<str>)>;
653
654fn group_key(metric: &SeriesLabels, grouping: &Grouping) -> GroupKey {
655    group_key_from(&labels_with_name(metric), grouping)
656}
657
658/// The group `labels` belong to, for callers that already hold the series' label pairs.
659fn group_key_from(labels: &[(Arc<str>, Arc<str>)], grouping: &Grouping) -> GroupKey {
660    let mut key: Vec<_> = labels
661        .iter()
662        .filter(|(name, value)| {
663            !value.is_empty()
664                && match grouping {
665                    Grouping::By(names) => names.contains(name),
666                    Grouping::Without(names) => &**name != "__name__" && !names.contains(name),
667                }
668        })
669        .cloned()
670        .collect();
671    key.sort();
672    key
673}
674
675/// The label pairs of `metric` with `__name__` among them, sorted by name.
676fn labels_with_name(metric: &SeriesLabels) -> Vec<(Arc<str>, Arc<str>)> {
677    #[cfg(test)]
678    calls::record_label_list();
679    let mut labels: Vec<_> = metric
680        .tags()
681        .iter()
682        .map(|tag| (tag.name.clone(), tag.value.clone()))
683        .collect();
684    if let Some(name) = metric.name() {
685        labels.push((Arc::from("__name__"), Arc::from(name)));
686    }
687    labels.sort();
688    labels
689}
690
691/// Prometheus `labels.Compare`: label pairs in name order, then the shorter set first.
692fn compare_labels(a: &SeriesLabels, b: &SeriesLabels) -> Ordering {
693    labels_with_name(a).cmp(&labels_with_name(b))
694}
695
696/// `github.com/facette/natsort.Compare`, which `sort_by_label` uses: digit runs compare as
697/// integers when both parse, other runs as strings.
698fn natural_less(a: &str, b: &str) -> bool {
699    let (chunks_a, chunks_b) = (chunks(a), chunks(b));
700    for (i, chunk_a) in chunks_a.iter().enumerate() {
701        let Some(chunk_b) = chunks_b.get(i) else {
702            return false;
703        };
704        let equal = match (chunk_a.parse::<i64>(), chunk_b.parse::<i64>()) {
705            (Ok(a), Ok(b)) if a != b => return a < b,
706            (Ok(_), Ok(_)) => true,
707            _ => chunk_a == chunk_b,
708        };
709        if !equal {
710            return chunk_a < chunk_b;
711        }
712        if i == chunks_a.len() - 1 {
713            return true;
714        } else if i == chunks_b.len() - 1 {
715            return false;
716        }
717    }
718    false
719}
720
721/// Maximal runs of ASCII digits and of other characters, like the regexp `(\d+|\D+)`.
722fn chunks(s: &str) -> Vec<&str> {
723    let mut chunks = Vec::new();
724    let mut start = 0;
725    let bytes = s.as_bytes();
726    for i in 1..=bytes.len() {
727        if i == bytes.len() || bytes[i].is_ascii_digit() != bytes[start].is_ascii_digit() {
728            chunks.push(&s[start..i]);
729            start = i;
730        }
731    }
732    chunks
733}
734
735fn single_field(schema: &SeriesSchema, operator: &str) -> Result<()> {
736    if schema.fields.len() != 1 {
737        return Err(DataFusionError::NotImplemented(format!(
738            "{operator} over series with {} fields",
739            schema.fields.len()
740        )));
741    }
742    Ok(())
743}
744
745/// Checks every series against `schema` and returns the grid length.
746fn grid_points(schema: &SeriesSchema, series: &[Series]) -> Result<usize> {
747    Ok(grid_and_points(schema, series)?.1)
748}
749
750/// Checks every series against `schema` and returns the grid it validated them on, with its length.
751///
752/// An operator that addresses points on the grid needs the grid itself, not just its length, and
753/// resolving it twice would let the two answers disagree.
754fn grid_and_points(schema: &SeriesSchema, series: &[Series]) -> Result<(Arc<EvalGrid>, usize)> {
755    let grid = schema.eval_grid.as_ref().ok_or_else(|| {
756        DataFusionError::Execution("select operators need an evaluation grid".into())
757    })?;
758    for item in series {
759        // Both grid axes are addressed on a grid; what matters is that it is this schema's.
760        let matches = match item.time.grid() {
761            Some(item_grid) => {
762                item_grid.spec() == grid.spec() && item.fields.len() == schema.fields.len()
763            }
764            None => false,
765        };
766        if !matches {
767            return Err(DataFusionError::Execution(
768                "series does not match the select operator schema".into(),
769            ));
770        }
771    }
772    Ok((Arc::clone(grid), grid.spec().len as usize))
773}
774
775/// The first field's value of `series` at grid `point`, looked up by position.
776///
777/// A point read: its only caller, `sort_instant`, reads one point of each instant series, so there
778/// is no walk for a cursor to follow. The row of a position is searched for, not counted from the
779/// first one, and a position the axis does not carry answers `None` rather than a row read from
780/// another offset.
781fn value_at(series: &Series, point: usize) -> Result<Option<f64>> {
782    let Some(row) = series.time.row_of(point) else {
783        return Ok(None);
784    };
785    // `Samples::sample` walks the chunk descriptors, not the rows, which is what a random read
786    // costs; a cursor would have to replay every row before this one.
787    into_value(series.fields.as_slice()[0].sample(row))
788}
789
790/// A sample as a value for an operator that ranks or sorts reads it.
791///
792/// The callers read floats only -- `sort` drops the histogram samples before it keys a series by a
793/// value, and `topk` collects float candidates -- so a histogram here is a broken invariant rather
794/// than an input.
795fn into_value(sample: SampleRef<'_>) -> Result<Option<f64>> {
796    match sample {
797        SampleRef::Missing => Ok(None),
798        SampleRef::Float(value) => Ok(Some(value)),
799        SampleRef::Histogram(_) => Err(DataFusionError::NotImplemented(
800            "select operators over histogram samples".into(),
801        )),
802    }
803}
804
805/// The value a forward cursor reads at compact `row`; the rows asked for only increase.
806fn cursor_value(cursor: &mut RowCursor<'_>, row: usize) -> Result<Option<f64>> {
807    into_value(cursor.at(row).expect("the axis and the fields are aligned"))
808}
809
810/// How often this thread built a series' label list or compared two candidates, so a test can hold
811/// `topk` to the work it should not do rather than to the result, which every shape produces.
812/// Test-only: a decorated sort and a partial selection select the same candidates.
813#[cfg(test)]
814pub(crate) mod calls {
815    use std::cell::Cell;
816
817    thread_local! {
818        /// Label lists [`super::labels_with_name`] built on this thread.
819        static LABEL_LISTS: Cell<usize> = const { Cell::new(0) };
820        /// Candidate pairs [`super::rank`] looked at on this thread.
821        static RANKS: Cell<usize> = const { Cell::new(0) };
822    }
823
824    /// Records one label list.
825    pub(crate) fn record_label_list() {
826        LABEL_LISTS.with(|lists| lists.set(lists.get() + 1));
827    }
828
829    /// Records one comparison of two candidates.
830    pub(crate) fn record_rank() {
831        RANKS.with(|ranks| ranks.set(ranks.get() + 1));
832    }
833
834    /// The label lists built on this thread since the last call, which starts a new count.
835    pub(crate) fn take_label_lists() -> usize {
836        LABEL_LISTS.with(|lists| lists.replace(0))
837    }
838
839    /// The candidate comparisons made on this thread since the last call, which starts a new count.
840    pub(crate) fn take_ranks() -> usize {
841        RANKS.with(|ranks| ranks.replace(0))
842    }
843}