promql/evaluated.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//! One slice of an evaluated series, as evaluators hand it to their consumers.
16
17use datafusion::error::{DataFusionError, Result};
18use datatypes::series::samples::Series;
19use datatypes::series::time::GridRange;
20
21/// One slice of one evaluated series: the rows holding a value that its evaluator handed over at
22/// once, which may form several runs of consecutive positions.
23///
24/// The series' [`TimeAxis`](datatypes::series::time::TimeAxis) covers the positions this chunk
25/// holds, and those positions are absolute on the grid: a consumer that concatenates the chunks of
26/// a series never reorders them, and never has to translate a chunk-local row number into a grid
27/// position. The rows of one chunk need not be adjacent -- a sparse chunk says which positions it
28/// holds through [`TimeAxis::positions`](datatypes::series::time::TimeAxis::positions) -- so a
29/// consumer reads them with that traversal instead of indexing from the first position.
30///
31/// A chunk carries only positions that hold a value. A position no chunk carries either holds no
32/// value or has not been decided yet, and a consumer cannot tell the two apart, so it must not
33/// infer progress from the last row it saw: only `is_last` says the series is complete. The gaps
34/// this leaves between the chunks of a series are what keeps a sparse series from costing a row
35/// per empty position. A single field may still hold a null at a position another field fills,
36/// since the fields of one chunk are row-aligned.
37///
38/// A series closes exactly once, on the chunk that carries `is_last`. A closed prefix is followed
39/// by a closing chunk when nothing is left, even when that chunk holds no values, so a consumer
40/// can tell "nothing more here" from "no more input".
41#[derive(Clone, Debug)]
42pub struct EvaluatedChunk {
43 /// The evaluated values, addressed on their absolute grid positions.
44 pub series: Series,
45 /// Whether this is the final chunk of this series.
46 pub is_last: bool,
47}
48
49impl EvaluatedChunk {
50 /// Wraps `series`, checking that it is addressed on a grid.
51 pub fn try_new(series: Series, is_last: bool) -> Result<Self> {
52 // Both grid axes are addressed on the grid; the explicit axes are not.
53 if series.time.grid().is_none() {
54 return Err(DataFusionError::Execution(
55 "an evaluated chunk must be addressed on a grid".to_string(),
56 ));
57 }
58 Ok(Self { series, is_last })
59 }
60
61 /// The absolute grid range this chunk holds rows for, when its rows form one run.
62 ///
63 /// Ranges of one series never go backwards and never overlap, and they need not be adjacent:
64 /// the positions between two chunks either hold no value or have not been decided yet. An
65 /// empty range is meaningful: it reports that the chunk closed the series without holding a
66 /// row of its own.
67 ///
68 /// `None` means the chunk holds several runs: it is addressed on a grid, but its rows are not
69 /// one range, and reading the positions between them would read holes. Walk the axis instead
70 /// ([`TimeAxis::positions`](datatypes::series::time::TimeAxis::positions)).
71 pub fn range(&self) -> Option<&GridRange> {
72 // `try_new` rejects everything but a grid axis, and `series` is public, so a chunk built
73 // by struct literal is answered from the axis rather than trusted.
74 self.series.time.as_grid_range()
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use std::sync::Arc;
81
82 use datatypes::arrow::array::Float64Array;
83 use datatypes::series::SeriesLabels;
84 use datatypes::series::samples::{FieldSpec, Samples, Series, SeriesFields, SeriesSchema};
85 use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis};
86
87 use super::EvaluatedChunk;
88
89 fn grid() -> Arc<EvalGrid> {
90 Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 60_000, 4).unwrap()).unwrap())
91 }
92
93 fn schema() -> SeriesSchema {
94 SeriesSchema {
95 fields: Arc::from([FieldSpec { name: "v0".into() }]),
96 eval_grid: Some(grid()),
97 }
98 }
99
100 fn metric() -> SeriesLabels {
101 SeriesLabels::try_new(Some("requests".into()), Vec::new()).unwrap()
102 }
103
104 /// `values` are the floats this chunk finished evaluating; `start` is their absolute offset.
105 fn chunk(
106 schema: &SeriesSchema,
107 start: usize,
108 values: Vec<f64>,
109 is_last: bool,
110 ) -> EvaluatedChunk {
111 let samples = Samples::from_float(Float64Array::from(values));
112 let range =
113 GridRange::try_new(schema.eval_grid.clone().unwrap(), start, samples.len()).unwrap();
114 let series = Series {
115 metric: metric(),
116 time: TimeAxis::Grid(range),
117 fields: SeriesFields::try_from_vec(vec![samples]).unwrap(),
118 };
119 EvaluatedChunk::try_new(series, is_last).unwrap()
120 }
121
122 /// A chunk without values is still a chunk: it is how a closed prefix is reported, and a
123 /// consumer needs it to tell "nothing more here" from "no more input".
124 #[test]
125 fn a_chunk_can_cover_no_positions() {
126 let schema = schema();
127 let empty = Samples::from_float(Float64Array::from(Vec::<f64>::new()));
128 let range = GridRange::try_new(schema.eval_grid.clone().unwrap(), 4, 0).unwrap();
129 assert!(range.is_empty());
130 let series = Series {
131 metric: metric(),
132 time: TimeAxis::Grid(range),
133 fields: SeriesFields::try_from_vec(vec![empty]).unwrap(),
134 };
135 let chunk = EvaluatedChunk::try_new(series, true).unwrap();
136 assert!(chunk.range().expect("one run").is_empty());
137 assert!(chunk.is_last);
138 }
139
140 /// The range is absolute, so concatenating two chunks of one series never reorders them.
141 #[test]
142 fn a_range_is_absolute_on_its_grid() {
143 let schema = schema();
144 let first = chunk(&schema, 0, vec![1.0, 2.0], false);
145 let second = chunk(&schema, 2, vec![3.0, 4.0], true);
146 assert!(!first.is_last);
147 assert!(second.is_last);
148 let first = first.range().expect("one run");
149 let second = second.range().expect("one run");
150 assert_eq!((first.start(), first.len()), (0, 2));
151 assert_eq!((second.start(), second.len()), (2, 2));
152 }
153
154 /// A chunk that is not addressed on a grid cannot be indexed by a consumer.
155 #[test]
156 fn a_chunk_must_be_addressed_on_a_grid() {
157 let samples = Samples::from_float(Float64Array::from(vec![1.0]));
158 let series = Series {
159 metric: metric(),
160 time: TimeAxis::Explicit(datatypes::arrow::buffer::ScalarBuffer::from(vec![0i64])),
161 fields: SeriesFields::try_from_vec(vec![samples]).unwrap(),
162 };
163 assert!(EvaluatedChunk::try_new(series, true).is_err());
164 }
165}