Skip to main content

promql/
extension_plan.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
15mod absent;
16mod empty_metric;
17mod fused_series;
18mod histogram_fold;
19mod instant_manipulate;
20mod normalize;
21mod planner;
22mod range_manipulate;
23mod raw_series_source;
24mod scalar_calculate;
25mod series_divide;
26mod series_execution;
27mod series_repartition;
28#[cfg(test)]
29mod test_util;
30mod union_distinct_on;
31
32pub use absent::{Absent, AbsentExec, AbsentStream};
33use common_query::native_histogram::{SUM_FIELD, native_histogram_value_type};
34use common_query::prometheus::is_prometheus_stale_nan;
35use datafusion::arrow::array::{Array, Float64Array, StructArray};
36use datafusion::arrow::datatypes::{
37    ArrowPrimitiveType, DataType, TimeUnit, TimestampMillisecondType,
38};
39use datafusion::common::{Column, DFSchemaRef};
40use datafusion::error::{DataFusionError, Result as DataFusionResult};
41use datafusion::logical_expr::{Expr, Extension, LogicalPlan};
42use datatypes::data_type::DataType as _;
43pub use empty_metric::{EmptyMetric, EmptyMetricExec, EmptyMetricStream, build_special_time_expr};
44#[cfg(feature = "test-utils")]
45pub use fused_series::is_canonical_producer_exec;
46pub use fused_series::{
47    FieldKind, FusedOutputFormat, FusedSeries, FusedSeriesBinding, FusedSeriesExec,
48    FusedSeriesStream, InputLocality, input_locality, keys_survive_metadata_drop,
49    matching_operands_drop_key, tree_source_fields,
50};
51pub use histogram_fold::{
52    HistogramFold, HistogramFoldExec, HistogramFoldOperation, HistogramFoldStream,
53};
54pub use instant_manipulate::{InstantManipulate, InstantManipulateExec, InstantManipulateStream};
55pub use normalize::{SeriesNormalize, SeriesNormalizeExec, SeriesNormalizeStream};
56pub use planner::PromExtensionPlanner;
57pub use range_manipulate::{RangeManipulate, RangeManipulateExec, RangeManipulateStream};
58pub use raw_series_source::{RawSeriesSource, RawSeriesSourceExec};
59pub use scalar_calculate::ScalarCalculate;
60pub use series_divide::{SeriesDivide, SeriesDivideExec, SeriesDivideStream};
61pub use series_execution::{
62    HandedSeriesChunk, SendableSeriesStream, SeriesCharge, SeriesChunk, SeriesExecutionPlan,
63    checked_series_stream, series_execution_plan,
64};
65pub use series_repartition::{IdentityCompletion, SeriesRepartitionExec, SeriesRouting};
66pub use union_distinct_on::{UnionDistinctOn, UnionDistinctOnExec, UnionDistinctOnStream};
67
68pub type Millisecond = <TimestampMillisecondType as ArrowPrimitiveType>::Native;
69
70pub(crate) fn timestamp_unit(data_type: &DataType) -> datafusion::error::Result<TimeUnit> {
71    match data_type {
72        DataType::Timestamp(unit, _) => Ok(*unit),
73        _ => Err(datafusion::error::DataFusionError::Execution(
74            "Time index column is not a timestamp".into(),
75        )),
76    }
77}
78
79pub(crate) fn nanoseconds_per_native_tick(unit: TimeUnit) -> i128 {
80    match unit {
81        TimeUnit::Second => 1_000_000_000,
82        TimeUnit::Millisecond => 1_000_000,
83        TimeUnit::Microsecond => 1_000,
84        TimeUnit::Nanosecond => 1,
85    }
86}
87
88/// Recovers the offset serialized only by an immediately underlying normalize node.
89///
90/// This is decode-only recovery for manipulators whose wire messages have no offset field.
91/// Follow identity projections (as used by `timestamp()`), but stop at other nodes or changed
92/// time columns to avoid applying an inner selector's offset again to an outer subquery.
93pub(crate) fn local_offset(plan: &LogicalPlan, time_index: &str) -> Millisecond {
94    let Some(index) = plan.schema().index_of_column_by_name(None, time_index) else {
95        return 0;
96    };
97    let (qualifier, field) = plan.schema().qualified_field(index);
98    let mut time_index = Column::new(qualifier.cloned(), field.name().clone());
99    let mut plan = plan;
100
101    loop {
102        match plan {
103            LogicalPlan::Extension(Extension { node }) => {
104                return node
105                    .as_any()
106                    .downcast_ref::<SeriesNormalize>()
107                    .and_then(|normalize| normalize.offset_for_time_index(&time_index))
108                    .unwrap_or_default();
109            }
110            LogicalPlan::Projection(projection) => {
111                let Some(output_index) = projection.schema.maybe_index_of_column(&time_index)
112                else {
113                    return 0;
114                };
115                let expr = &projection.expr[output_index];
116                let source = match expr {
117                    Expr::Column(column) => column,
118                    Expr::Alias(alias) => {
119                        let Expr::Column(column) = alias.expr.as_ref() else {
120                            return 0;
121                        };
122                        if alias.name != column.name {
123                            return 0;
124                        }
125                        column
126                    }
127                    _ => return 0,
128                };
129                let Some(input_index) = projection.input.schema().maybe_index_of_column(source)
130                else {
131                    return 0;
132                };
133                let (qualifier, field) = projection.input.schema().qualified_field(input_index);
134                time_index = Column::new(qualifier.cloned(), field.name().clone());
135                plan = projection.input.as_ref();
136            }
137            _ => return 0,
138        }
139    }
140}
141
142const METRIC_NUM_SERIES: &str = "num_series";
143
144fn prometheus_stale_sample_column(column: &dyn Array) -> Option<(&dyn Array, &Float64Array)> {
145    let values = if let Some(values) = column.as_any().downcast_ref::<Float64Array>() {
146        values
147    } else {
148        let histograms = column.as_any().downcast_ref::<StructArray>()?;
149        if histograms.data_type() != &native_histogram_value_type().as_arrow_type() {
150            return None;
151        }
152        histograms
153            .column_by_name(SUM_FIELD)?
154            .as_any()
155            .downcast_ref::<Float64Array>()?
156    };
157    Some((column, values))
158}
159
160fn is_prometheus_stale_sample((column, values): (&dyn Array, &Float64Array), row: usize) -> bool {
161    column.is_valid(row) && values.is_valid(row) && is_prometheus_stale_nan(values.value(row))
162}
163
164/// Utilities for handling unfix logic in extension plans
165/// Convert column name to index for serialization
166pub fn serialize_column_index(schema: &DFSchemaRef, column_name: &str) -> u64 {
167    schema
168        .index_of_column_by_name(None, column_name)
169        .map(|idx| idx as u64)
170        .unwrap_or(u64::MAX) // make sure if not found, it will report error in deserialization
171}
172
173/// Convert index back to column name for deserialization
174pub fn resolve_column_name(
175    index: u64,
176    schema: &DFSchemaRef,
177    context: &str,
178    column_type: &str,
179) -> DataFusionResult<String> {
180    let columns = schema.columns();
181    columns
182        .get(index as usize)
183        .ok_or_else(|| {
184            DataFusionError::Internal(format!(
185                "Failed to get {} column at idx {} during unfixing {} with columns:{:?}",
186                column_type, index, context, columns
187            ))
188        })
189        .map(|field| field.name().to_string())
190}
191
192/// Batch process multiple column indices
193pub fn resolve_column_names(
194    indices: &[u64],
195    schema: &DFSchemaRef,
196    context: &str,
197    column_type: &str,
198) -> DataFusionResult<Vec<String>> {
199    indices
200        .iter()
201        .map(|idx| resolve_column_name(*idx, schema, context, column_type))
202        .collect()
203}
204
205#[cfg(test)]
206mod tests {
207    use std::sync::Arc;
208
209    use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
210    use datafusion::common::ToDFSchema;
211    use datafusion::logical_expr::{EmptyRelation, Extension, LogicalPlan, Projection};
212    use datafusion_expr::col;
213
214    use super::*;
215
216    fn input() -> LogicalPlan {
217        LogicalPlan::EmptyRelation(EmptyRelation {
218            produce_one_row: false,
219            schema: Arc::new(Schema::new(vec![
220                Field::new(
221                    "timestamp",
222                    DataType::Timestamp(TimeUnit::Millisecond, None),
223                    false,
224                ),
225                Field::new(
226                    "other_ts",
227                    DataType::Timestamp(TimeUnit::Millisecond, None),
228                    false,
229                ),
230                Field::new("value", DataType::Float64, true),
231            ]))
232            .to_dfschema_ref()
233            .unwrap(),
234        })
235    }
236
237    fn normalized() -> LogicalPlan {
238        LogicalPlan::Extension(Extension {
239            node: Arc::new(SeriesNormalize::new(
240                1_000,
241                "timestamp",
242                false,
243                Vec::new(),
244                input(),
245            )),
246        })
247    }
248
249    #[test]
250    fn local_offset_tracks_identity_preserving_projections() {
251        let projection =
252            Projection::try_new(vec![col("timestamp"), col("value")], Arc::new(normalized()))
253                .unwrap();
254        let projection = Projection::try_new(
255            vec![col("timestamp").alias("timestamp"), col("value")],
256            Arc::new(LogicalPlan::Projection(projection)),
257        )
258        .unwrap();
259
260        assert_eq!(
261            1_000,
262            local_offset(&LogicalPlan::Projection(projection), "timestamp")
263        );
264    }
265
266    #[test]
267    fn local_offset_rejects_a_different_timestamp_or_manipulator() {
268        let renamed = Projection::try_new(
269            vec![col("other_ts").alias("timestamp"), col("value")],
270            Arc::new(normalized()),
271        )
272        .unwrap();
273        assert_eq!(
274            0,
275            local_offset(&LogicalPlan::Projection(renamed), "timestamp")
276        );
277
278        let divide = LogicalPlan::Extension(Extension {
279            node: Arc::new(SeriesDivide::new(
280                Vec::new(),
281                "timestamp".to_string(),
282                normalized(),
283            )),
284        });
285        assert_eq!(0, local_offset(&divide, "timestamp"));
286    }
287}