Skip to main content

promql/
instant_eval.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
15use std::ops::RangeInclusive;
16use std::sync::Arc;
17
18use common_query::prometheus::is_prometheus_stale_nan;
19use datafusion::error::{DataFusionError, Result};
20use datatypes::series::SeriesLabels;
21use datatypes::series::raw::RawTimestamps;
22use datatypes::series::samples::{SampleRef, Series, SeriesFields, SeriesSchema};
23
24use crate::grid_series::{GridSeriesBuilder, label_set, render_label_set};
25use crate::map::drop_metric_name;
26
27#[cfg(test)]
28mod tests;
29
30/// The source rows [`select_instants`] examined, counted per row.
31///
32/// The selector advances one cursor over the axis, so the rows it reads can never outnumber the
33/// rows of the axis: one pass, not one per grid point. Counting them is what keeps a second pass
34/// over the axis from being added back unobserved, since the selection it returns is the same
35/// either way.
36#[cfg(test)]
37pub(crate) static AXIS_ROWS_READ: std::sync::atomic::AtomicU64 =
38    std::sync::atomic::AtomicU64::new(0);
39
40/// Counts one row of the axis examined; a no-op outside tests.
41fn row_read() {
42    #[cfg(test)]
43    AXIS_ROWS_READ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
44}
45
46/// Selects the one source row an anchored instant reads, with the lookback, offset and staleness
47/// rules of [`select_instants`]: the last sample at or before `at_ms` (shifted by `offset_ms`) and
48/// not more than the lookback before it, unless a stale marker is the latest sample there.
49///
50/// `None` means the anchor selects nothing, which is what an anchor outside the series' data or one
51/// whose only candidate is too old or stale reports.
52pub fn select_instant_at(
53    time: &RawTimestamps,
54    fields: &SeriesFields,
55    at_ms: i64,
56    lookback_ms: i64,
57    offset_ms: i64,
58) -> Result<Option<u64>> {
59    // One point at the anchor is the same rule `select_instants` applies per grid point, so the
60    // anchor is asked of it rather than re-derived here: a second copy of the boundary arithmetic
61    // is a second place for the lookback edge to disagree.
62    let (indices, _) = select_instants(time, fields, at_ms..=at_ms, 1, lookback_ms, offset_ms)?;
63    Ok(indices.into_iter().next())
64}
65
66/// The candidate evaluation timestamps the instant kernel scans and reserves for.
67///
68/// These bounds include grid points which may select no row, including points rounded outward by
69/// alignment, the exclusive lookback edge, gaps and stale samples.
70#[derive(Debug, PartialEq, Eq)]
71pub(crate) struct InstantCandidateSpan {
72    pub(crate) start: i128,
73    pub(crate) end: i128,
74    pub(crate) count: i128,
75}
76
77/// Clips the candidate span using only the source axis endpoints; allocates nothing.
78///
79/// The caller validates `step_ms > 0`, `lookback_ms >= 0` and the ordered query range. The wide
80/// count leaves each caller's existing conversion to `usize` unchanged. The end is a scan bound,
81/// not necessarily a grid position when the query end is not aligned to its start.
82pub(crate) fn instant_candidate_span(
83    endpoints: Option<(i64, i64)>,
84    range: RangeInclusive<i64>,
85    step_ms: i64,
86    lookback_ms: i64,
87    offset_ms: i64,
88) -> InstantCandidateSpan {
89    let empty = InstantCandidateSpan {
90        start: 1,
91        end: 0,
92        count: 0,
93    };
94    let Some((first, last)) = endpoints else {
95        return empty;
96    };
97    let first = first as i128 + offset_ms as i128;
98    let last = last as i128 + offset_ms as i128;
99    let useful_last = if lookback_ms == 0 {
100        last
101    } else {
102        last + lookback_ms as i128 - 1
103    };
104    let query_start = *range.start() as i128;
105    let query_end = *range.end() as i128;
106    let step = step_ms as i128;
107    let max_start = first.max(query_start);
108    let min_end = useful_last.min(query_end);
109    if max_start > min_end {
110        return empty;
111    }
112    let start = query_start + (max_start - query_start) / step * step;
113    let end = query_end - (query_end - min_end) / step * step;
114    let count = (end - start) / step + 1;
115    InstantCandidateSpan { start, end, count }
116}
117
118/// Selects source rows for an aligned PromQL instant-evaluation range.
119///
120/// Returns original logical row indices and evaluation timestamps from a complete source axis of
121/// strictly increasing milliseconds. Any provided field's stale marker suppresses selection;
122/// missing samples are not stale and remain selectable.
123///
124/// The ordering of the axis is [`RawTimestamps`]' own guarantee, checked when it was built, so this
125/// walks the axis once -- one cursor advance per row -- and validates nothing about it again.
126///
127/// The two vectors it returns hold one `u64` source row index and one `i64` evaluation timestamp
128/// per selected point, so what it allocates is 16 bytes per point of the clipped grid rather than
129/// anything proportional to the samples of the axis. It reserves none of that: every caller grows
130/// a memory reservation for those two vectors before it calls, which is what bounds an instant
131/// selection now that the kernel carries no point limit of its own.
132pub fn select_instants(
133    time: &RawTimestamps,
134    fields: &SeriesFields,
135    range: RangeInclusive<i64>,
136    step_ms: i64,
137    lookback_ms: i64,
138    offset_ms: i64,
139) -> Result<(Vec<u64>, Vec<i64>)> {
140    let start = *range.start();
141    let end = *range.end();
142    if step_ms <= 0 {
143        return Err(DataFusionError::Execution(
144            "InstantManipulate interval must be positive".into(),
145        ));
146    }
147    if start > end {
148        return Err(DataFusionError::Execution(
149            "InstantManipulate start must not exceed end".into(),
150        ));
151    }
152    if lookback_ms < 0 {
153        return Err(DataFusionError::Execution(
154            "InstantManipulate lookback must be non-negative".into(),
155        ));
156    }
157    let timestamps = time.as_buffer();
158    if fields
159        .as_slice()
160        .iter()
161        .any(|field| field.len() != timestamps.len())
162    {
163        return Err(DataFusionError::Execution(
164            "series fields and time axis have unequal lengths".into(),
165        ));
166    }
167    if timestamps.is_empty() {
168        return Ok((Vec::new(), Vec::new()));
169    }
170
171    let span = instant_candidate_span(
172        Some((timestamps[0], timestamps[timestamps.len() - 1])),
173        range,
174        step_ms,
175        lookback_ms,
176        offset_ms,
177    );
178    let mut indices = Vec::with_capacity(span.count as usize);
179    let mut evaluation_timestamps = Vec::with_capacity(span.count as usize);
180    let mut sample_iters: Vec<_> = fields.iter().map(|field| field.iter()).collect();
181    let mut current_stale = false;
182    let mut cursor = 0usize;
183    for expected in (span.start..=span.end).step_by(step_ms as usize) {
184        let source_expected = expected - offset_ms as i128;
185        while cursor < timestamps.len() && timestamps[cursor] as i128 <= source_expected {
186            current_stale = false;
187            for samples in &mut sample_iters {
188                let sample = samples.next().ok_or_else(|| {
189                    DataFusionError::Execution(
190                        "series sample iterator ended before the time axis".into(),
191                    )
192                })?;
193                let stale = match sample {
194                    SampleRef::Float(value) => is_prometheus_stale_nan(value),
195                    SampleRef::Histogram(histogram) => is_prometheus_stale_nan(histogram.sum),
196                    SampleRef::Missing => false,
197                };
198                current_stale |= stale;
199            }
200            row_read();
201            cursor += 1;
202        }
203        let Some(candidate) = cursor.checked_sub(1) else {
204            continue;
205        };
206        let candidate_ts = timestamps[candidate] as i128 + offset_ms as i128;
207        let lower = expected - lookback_ms as i128;
208        if (candidate_ts == expected || candidate_ts > lower)
209            && candidate_ts <= expected
210            && !current_stale
211        {
212            indices.push(candidate as u64);
213            evaluation_timestamps.push(expected as i64);
214        }
215    }
216    Ok((indices, evaluation_timestamps))
217}
218
219/// `timestamp(v)` over an instant selector: at each point the selection holds, the original time of
220/// the selected sample in seconds, not the time it was looked up at, so an offset or `@` moves
221/// which sample is selected but not the time reported. The metric name, `__type__` and `__unit__`
222/// are dropped.
223///
224/// `indices` and `evaluation_timestamps` are a selection of `time` and `fields` as
225/// [`select_instants`] returns one: grid positions increasing, rows not decreasing. `schema` holds
226/// the evaluation grid the timestamps lie on and one field per field of `fields`. A field without a
227/// sample in the selected row has no result there.
228///
229/// `timestamp(x @ t)` selects at `t` for every point, so its selection repeats one row. This
230/// kernel reports the sample the caller selected and does not decide the selector's time
231/// modifiers: the native Instant caller selects the sample under the intersection of the ordinary
232/// anchored selector window and the timestamp function's unshifted window. `info()` retains ordinary
233/// selector offset behavior.
234pub fn timestamp_of_selection(
235    schema: &Arc<SeriesSchema>,
236    metric: &SeriesLabels,
237    time: &RawTimestamps,
238    fields: &SeriesFields,
239    indices: &[u64],
240    evaluation_timestamps: &[i64],
241) -> Result<Option<Series>> {
242    project_selection(
243        schema,
244        drop_metric_name(metric)?,
245        time,
246        fields,
247        indices,
248        evaluation_timestamps,
249        |_, time| Ok(time as f64 / 1000.0),
250    )
251}
252
253/// The series `info()` reads its data labels from: at each point the selection holds, the original
254/// time of the selected sample in milliseconds, as Prometheus' `evalSeries` records it for `info`.
255/// The labels are kept. Info series hold float samples, so a selected native histogram fails.
256///
257/// Takes the same selection as [`timestamp_of_selection`].
258pub fn info_sample_times(
259    schema: &Arc<SeriesSchema>,
260    metric: &SeriesLabels,
261    time: &RawTimestamps,
262    fields: &SeriesFields,
263    indices: &[u64],
264    evaluation_timestamps: &[i64],
265) -> Result<Option<Series>> {
266    project_selection(
267        schema,
268        metric.clone(),
269        time,
270        fields,
271        indices,
272        evaluation_timestamps,
273        |sample, time| match sample {
274            SampleRef::Histogram(_) => Err(DataFusionError::Execution(format!(
275                "this should be an info metric, with float samples: {}",
276                render_label_set(&label_set(metric))
277            ))),
278            _ => Ok(time as f64),
279        },
280    )
281}
282
283/// `timestamp(v)` over an evaluated `v`, such as `timestamp(abs(x))`: the evaluation time in
284/// seconds at each point a field of `series` holds a value. The metric name, `__type__` and
285/// `__unit__` are dropped.
286pub fn timestamp_of_evaluated(
287    schema: &Arc<SeriesSchema>,
288    series: &Series,
289) -> Result<Option<Series>> {
290    let grid = schema.eval_grid.as_ref().ok_or_else(|| {
291        DataFusionError::Execution("timestamp requires an evaluation grid".into())
292    })?;
293    if series.time.grid().map(|grid| grid.spec()) != Some(grid.spec())
294        || series.fields.len() != schema.fields.len()
295    {
296        return Err(DataFusionError::Execution(
297            "timestamp input does not match its schema".into(),
298        ));
299    }
300    let timestamps = grid.timestamps().map_err(crate::grid_series::external)?;
301    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
302    let mut cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
303    let mut row = Vec::with_capacity(cursors.len());
304    for (point, index) in series.time.positions() {
305        let seconds = timestamps[point] as f64 / 1000.0;
306        row.clear();
307        for cursor in &mut cursors {
308            let sample = cursor
309                .at(index)
310                .expect("the axis and the fields are aligned");
311            row.push((!matches!(sample, SampleRef::Missing)).then_some(seconds));
312        }
313        builder.push(point, &row)?;
314    }
315    builder.finish(drop_metric_name(&series.metric)?)
316}
317
318/// One series over an instant selection, each field holding `value(sample, original time)` where
319/// the selected row has a sample for it.
320///
321/// The selection is `indices` and `evaluation_timestamps` as [`select_instants`] returns them: one
322/// source row and one grid timestamp per selected point, with positions increasing and rows not
323/// decreasing. An `@` selection, which reads one row at every point, repeats that row; it is the
324/// caller's to build. A selection off the grid, going back, or naming a row the series does not
325/// have fails.
326fn project_selection(
327    schema: &Arc<SeriesSchema>,
328    metric: SeriesLabels,
329    time: &RawTimestamps,
330    fields: &SeriesFields,
331    indices: &[u64],
332    evaluation_timestamps: &[i64],
333    value: impl Fn(SampleRef<'_>, i64) -> Result<f64>,
334) -> Result<Option<Series>> {
335    let grid = schema.eval_grid.as_ref().ok_or_else(|| {
336        DataFusionError::Execution("an instant selection requires an evaluation grid".into())
337    })?;
338    if indices.len() != evaluation_timestamps.len()
339        || fields.len() != schema.fields.len()
340        || fields.iter().any(|field| field.len() != time.len())
341    {
342        return Err(DataFusionError::Execution(
343            "instant selection does not match its series or schema".into(),
344        ));
345    }
346    let spec = grid.spec();
347    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
348    let mut cursors: Vec<_> = fields.iter().map(|field| field.cursor()).collect();
349    // Consecutive points often select the same row, which a cursor reads only once.
350    let mut row: Vec<Option<f64>> = Vec::with_capacity(fields.len());
351    let mut last: Option<(i128, usize)> = None;
352    for (&index, &timestamp) in indices.iter().zip(evaluation_timestamps) {
353        let offset = timestamp as i128 - spec.start_ms as i128;
354        let position = offset / spec.step_ms as i128;
355        let index = usize::try_from(index)
356            .ok()
357            .filter(|index| *index < time.len());
358        let (Some(index), true) = (
359            index,
360            offset % spec.step_ms as i128 == 0
361                && (0..spec.len as i128).contains(&position)
362                && last.is_none_or(|(last_position, _)| last_position < position),
363        ) else {
364            return Err(DataFusionError::Execution(
365                "instant selection points off the grid or out of the series".into(),
366            ));
367        };
368        match last {
369            Some((_, last_index)) if last_index == index => {}
370            Some((_, last_index)) if last_index > index => {
371                return Err(DataFusionError::Execution(
372                    "instant selection rows must not go back".into(),
373                ));
374            }
375            _ => {
376                let time = time.timestamp(index).expect("checked against the axis");
377                row.clear();
378                for cursor in &mut cursors {
379                    let sample = cursor
380                        .at(index)
381                        .expect("rows increase and lie in fields as long as the axis");
382                    row.push(match sample {
383                        SampleRef::Missing => None,
384                        sample => Some(value(sample, time)?),
385                    });
386                }
387            }
388        }
389        last = Some((position, index));
390        builder.push(position as usize, &row)?;
391    }
392    builder.finish(metric)
393}