Skip to main content

query/optimizer/
windowed_sort.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::sync::Arc;
16
17use arrow_schema::DataType;
18use datafusion::physical_optimizer::PhysicalOptimizerRule;
19use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
20use datafusion::physical_plan::coop::CooperativeExec;
21use datafusion::physical_plan::filter::FilterExec;
22use datafusion::physical_plan::projection::ProjectionExec;
23use datafusion::physical_plan::repartition::RepartitionExec;
24use datafusion::physical_plan::sorts::sort::SortExec;
25use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
26use datafusion::physical_plan::{ChildrenPropertiesMode, ExecutionPlan, ReplaceChildrenOptions};
27use datafusion_common::Result as DataFusionResult;
28use datafusion_common::tree_node::{Transformed, TreeNode};
29use datafusion_physical_expr::expressions::{CastExpr, Column as PhysicalColumn};
30use datafusion_physical_expr::{PhysicalExpr, ScalarFunctionExpr};
31use store_api::region_engine::PartitionRange;
32use table::table::scan::RegionScanExec;
33
34use crate::part_sort::PartSortExec;
35use crate::window_sort::WindowedSortExec;
36
37/// Optimize rule for windowed sort.
38///
39/// This is expected to run after [`ScanHint`] and [`ParallelizeScan`].
40/// It would change the original sort to a custom plan. To make sure
41/// other rules are applied correctly, this rule can be run as later as
42/// possible.
43///
44/// [`ScanHint`]: crate::optimizer::scan_hint::ScanHintRule
45/// [`ParallelizeScan`]: crate::optimizer::parallelize_scan::ParallelizeScan
46#[derive(Debug)]
47pub struct WindowedSortPhysicalRule;
48
49impl PhysicalOptimizerRule for WindowedSortPhysicalRule {
50    fn optimize(
51        &self,
52        plan: Arc<dyn ExecutionPlan>,
53        config: &datafusion::config::ConfigOptions,
54    ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
55        Self::do_optimize(plan, config)
56    }
57
58    fn name(&self) -> &str {
59        "WindowedSortRule"
60    }
61
62    fn schema_check(&self) -> bool {
63        false
64    }
65}
66
67impl WindowedSortPhysicalRule {
68    fn do_optimize(
69        plan: Arc<dyn ExecutionPlan>,
70        _config: &datafusion::config::ConfigOptions,
71    ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
72        let result = plan
73            .transform_down(|plan| {
74                if let Some(sort_exec) = plan.downcast_ref::<SortExec>() {
75                    // TODO: support multiple expr in windowed sort
76                    if sort_exec.expr().len() != 1 {
77                        return Ok(Transformed::no(plan));
78                    }
79
80                    let preserve_partitioning = sort_exec.preserve_partitioning();
81
82                    let sort_input = remove_repartition(sort_exec.input().clone())?.data;
83
84                    // Gets scanner info from the input without repartition before filter.
85                    let Some(scanner_info) = fetch_partition_range(sort_input.clone())? else {
86                        return Ok(Transformed::no(plan));
87                    };
88                    // Windowed sorting requires partition ranges, which file-engine scans lack.
89                    if scanner_info.partition_ranges.is_empty() {
90                        return Ok(Transformed::no(plan));
91                    }
92                    let input_schema = sort_input.schema();
93
94                    let first_sort_expr = sort_exec.expr().first();
95                    if let Some(column_expr) = first_sort_expr.expr.downcast_ref::<PhysicalColumn>()
96                        && matches!(
97                            input_schema.field(column_expr.index()).data_type(),
98                            DataType::Timestamp(_, _)
99                        )
100                        && is_time_index_expr(&sort_input, &first_sort_expr.expr)?
101                        && sort_exec.fetch().is_none()
102                    // skip if there is a limit, as dyn filter along is good enough in this case
103                    {
104                    } else {
105                        return Ok(Transformed::no(plan));
106                    }
107
108                    // PartSortExec is unnecessary if:
109                    // - there is no tag column, and
110                    // - the sort is ascending on the time index column
111                    let new_input = if scanner_info.tag_columns.is_empty()
112                        && !first_sort_expr.options.descending
113                    {
114                        sort_input
115                    } else {
116                        Arc::new(PartSortExec::try_new(
117                            first_sort_expr.clone(),
118                            sort_exec.fetch(),
119                            scanner_info.partition_ranges.clone(),
120                            sort_input,
121                        )?)
122                    };
123
124                    let windowed_sort_exec = WindowedSortExec::try_new(
125                        first_sort_expr.clone(),
126                        sort_exec.fetch(),
127                        scanner_info.partition_ranges,
128                        new_input,
129                    )?;
130
131                    if !preserve_partitioning {
132                        let order_preserving_merge = SortPreservingMergeExec::new(
133                            sort_exec.expr().clone(),
134                            Arc::new(windowed_sort_exec),
135                        );
136                        return Ok(Transformed {
137                            data: Arc::new(order_preserving_merge),
138                            transformed: true,
139                            tnr: datafusion_common::tree_node::TreeNodeRecursion::Stop,
140                        });
141                    } else {
142                        return Ok(Transformed {
143                            data: Arc::new(windowed_sort_exec),
144                            transformed: true,
145                            tnr: datafusion_common::tree_node::TreeNodeRecursion::Stop,
146                        });
147                    }
148                }
149
150                Ok(Transformed::no(plan))
151            })?
152            .data;
153
154        Ok(result)
155    }
156}
157
158#[derive(Debug)]
159struct ScannerInfo {
160    partition_ranges: Vec<Vec<PartitionRange>>,
161    tag_columns: Vec<String>,
162}
163
164fn fetch_partition_range(input: Arc<dyn ExecutionPlan>) -> DataFusionResult<Option<ScannerInfo>> {
165    let mut partition_ranges = None;
166    let mut tag_columns = None;
167
168    input.transform_up(|plan| {
169        if plan.is::<CooperativeExec>() {
170            return Ok(Transformed::no(plan));
171        }
172
173        // Unappliable case, reset the state.
174        if plan.is::<RepartitionExec>()
175            || plan.is::<CoalescePartitionsExec>()
176            || plan.is::<SortExec>()
177            || plan.is::<WindowedSortExec>()
178        {
179            partition_ranges = None;
180        }
181
182        // only a very limited set of plans can exist between region scan and sort exec
183        // other plans might make this optimize wrong, so be safe here by limiting it
184        if !(plan.is::<ProjectionExec>() || plan.is::<FilterExec>()) {
185            partition_ranges = None;
186        }
187
188        if let Some(region_scan_exec) = plan.downcast_ref::<RegionScanExec>() {
189            // Series scans redistribute rows across source ranges, including Narthex SQL
190            // scans whose request does not explicitly specify `PerSeries`.
191            if region_scan_exec.distribution()
192                == Some(store_api::storage::TimeSeriesDistribution::PerSeries)
193                || region_scan_exec.scanner_type() == "SeriesScan"
194            {
195                partition_ranges = None;
196                return Ok(Transformed::no(plan));
197            }
198
199            partition_ranges = Some(region_scan_exec.get_uncollapsed_partition_ranges());
200            tag_columns = Some(region_scan_exec.tag_columns());
201
202            region_scan_exec.with_distinguish_partition_range(true);
203        }
204
205        Ok(Transformed::no(plan))
206    })?;
207
208    let result = (|| {
209        Some(ScannerInfo {
210            partition_ranges: partition_ranges?,
211            tag_columns: tag_columns?,
212        })
213    })();
214
215    Ok(result)
216}
217
218pub(crate) fn is_time_index_expr(
219    plan: &Arc<dyn ExecutionPlan>,
220    expr: &Arc<dyn PhysicalExpr>,
221) -> DataFusionResult<bool> {
222    if let Some(column_expr) = expr.downcast_ref::<PhysicalColumn>() {
223        return is_time_index_column(plan, column_expr);
224    }
225
226    if let Some(cast_expr) = expr.downcast_ref::<CastExpr>() {
227        let source_type = cast_expr.expr().data_type(plan.schema().as_ref())?;
228        return if preserves_timestamp_values(cast_expr.cast_type(), &source_type) {
229            is_time_index_expr(plan, cast_expr.expr())
230        } else {
231            Ok(false)
232        };
233    }
234
235    if let Some(scalar_function_expr) = expr.downcast_ref::<ScalarFunctionExpr>() {
236        if !is_supported_time_index_wrapper(scalar_function_expr)
237            || scalar_function_expr.args().len() != 1
238        {
239            return Ok(false);
240        }
241
242        // Wrappers such as `to_timestamp_seconds` cast their argument to another time unit
243        // inside the function. That cast does not show up as a `CastExpr` in the plan, but it
244        // changes the values of the sort column exactly like a cast in the plan does, so the
245        // wrapper is only still the time index if its result keeps both the unit and the values
246        // of its argument.
247        let arg = &scalar_function_expr.args()[0];
248        let return_type = scalar_function_expr.data_type(plan.schema().as_ref())?;
249        let arg_type = arg.data_type(plan.schema().as_ref())?;
250        return if preserves_timestamp_values(&return_type, &arg_type) {
251            is_time_index_expr(plan, arg)
252        } else {
253            Ok(false)
254        };
255    }
256
257    Ok(false)
258}
259
260/// Returns true if a cast, or a function wrapper, that turns `source` into `target` keeps both the
261/// time unit and the underlying values of a timestamp.
262///
263/// A cast (or a hidden cast inside a function wrapper) that changes the time unit changes the
264/// values of the sort column, so the working ranges derived from the time index, which keep the
265/// unit of the time index, no longer apply. The optimizer conservatively rejects every cast that
266/// adds a timezone to a naive timestamp, including UTC, even though UTC has a zero offset. Only a
267/// target that keeps both the unit and the values of its source can still be the time index.
268fn preserves_timestamp_values(target: &DataType, source: &DataType) -> bool {
269    matches!(
270        (target, source),
271        (
272            DataType::Timestamp(target_unit, target_tz),
273            DataType::Timestamp(source_unit, source_tz)
274        ) if target_unit == source_unit && (source_tz.is_some() || target_tz.is_none())
275    )
276}
277
278fn is_time_index_column(
279    plan: &Arc<dyn ExecutionPlan>,
280    column_expr: &PhysicalColumn,
281) -> DataFusionResult<bool> {
282    if let Some(projection) = plan.downcast_ref::<ProjectionExec>() {
283        let Some(projection_expr) = projection.expr().get(column_expr.index()) else {
284            return Ok(false);
285        };
286        return is_time_index_expr(projection.input(), &projection_expr.expr);
287    }
288
289    if let Some(filter) = plan.downcast_ref::<FilterExec>() {
290        let child_column_expr = filter
291            .projection()
292            .as_ref()
293            .and_then(|projection| projection.get(column_expr.index()).copied())
294            .map(|input_index| {
295                PhysicalColumn::new(
296                    filter.input().schema().field(input_index).name(),
297                    input_index,
298                )
299            })
300            .unwrap_or_else(|| column_expr.clone());
301        let child_expr = Arc::new(child_column_expr) as Arc<dyn PhysicalExpr>;
302        return is_time_index_expr(filter.input(), &child_expr);
303    }
304
305    if let Some(region_scan_exec) = plan.downcast_ref::<RegionScanExec>() {
306        let schema = plan.schema();
307        let column_field = schema.field(column_expr.index());
308        return Ok(
309            matches!(column_field.data_type(), DataType::Timestamp(_, _))
310                && *column_field.name() == region_scan_exec.time_index(),
311        );
312    }
313
314    let Some(child) = passthrough_child(plan.as_ref()) else {
315        return Ok(false);
316    };
317    let child_expr = Arc::new(column_expr.clone()) as Arc<dyn PhysicalExpr>;
318    is_time_index_expr(&child, &child_expr)
319}
320
321fn passthrough_child(plan: &dyn ExecutionPlan) -> Option<Arc<dyn ExecutionPlan>> {
322    if plan.is::<CoalescePartitionsExec>()
323        || plan.is::<RepartitionExec>()
324        || plan.is::<CooperativeExec>()
325    {
326        return schema_preserving_child(plan);
327    }
328
329    None
330}
331
332fn schema_preserving_child(plan: &dyn ExecutionPlan) -> Option<Arc<dyn ExecutionPlan>> {
333    let child = plan.children().first().cloned().cloned()?;
334    (plan.schema().as_ref() == child.schema().as_ref()).then_some(child)
335}
336
337fn is_supported_time_index_wrapper(expr: &ScalarFunctionExpr) -> bool {
338    (expr.name().eq_ignore_ascii_case("to_timestamp")
339        || expr.name().eq_ignore_ascii_case("to_timestamp_seconds")
340        || expr.name().eq_ignore_ascii_case("to_timestamp_millis")
341        || expr.name().eq_ignore_ascii_case("to_timestamp_micros")
342        || expr.name().eq_ignore_ascii_case("to_timestamp_nanos"))
343        && matches!(expr.return_type(), DataType::Timestamp(_, _))
344}
345
346/// Removes the repartition plan between the filter and region scan.
347fn remove_repartition(
348    plan: Arc<dyn ExecutionPlan>,
349) -> DataFusionResult<Transformed<Arc<dyn ExecutionPlan>>> {
350    plan.transform_down(|plan| {
351        if plan.is::<FilterExec>() {
352            // Checks child.
353            let maybe_repartition = plan.children()[0];
354            if maybe_repartition.is::<RepartitionExec>() {
355                let maybe_scan = maybe_repartition.children()[0];
356                if maybe_scan.is::<RegionScanExec>() {
357                    let new_filter = plan.clone().replace_children(
358                        vec![maybe_scan.clone()],
359                        ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
360                    )?;
361                    return Ok(Transformed::yes(new_filter));
362                }
363            }
364        }
365
366        Ok(Transformed::no(plan))
367    })
368}
369
370#[cfg(test)]
371mod test {
372    use std::sync::Arc;
373
374    use api::v1::SemanticType;
375    use arrow_schema::{Field, TimeUnit};
376    use common_recordbatch::RecordBatches;
377    use datafusion::config::ConfigOptions;
378    use datafusion::physical_plan::filter::FilterExecBuilder;
379    use datafusion_common::ScalarValue;
380    use datafusion_functions::datetime::{to_timestamp, to_timestamp_millis, to_timestamp_seconds};
381    use datafusion_physical_expr::expressions::{CastExpr, Literal};
382    use datatypes::data_type::ConcreteDataType;
383    use datatypes::schema::{ColumnSchema, Schema};
384    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
385    use store_api::region_engine::SinglePartitionScanner;
386    use store_api::storage::{RegionId, ScanRequest};
387
388    use super::*;
389
390    #[test]
391    fn test_keep_ordinary_sort_when_scan_has_no_partition_ranges() {
392        let ordering = datafusion_physical_expr::LexOrdering::new([
393            datafusion_physical_expr::PhysicalSortExpr {
394                expr: Arc::new(PhysicalColumn::new("ts", 1)),
395                options: Default::default(),
396            },
397        ])
398        .unwrap();
399        let sort = Arc::new(SortExec::new(ordering, new_region_scan()));
400        let optimized =
401            WindowedSortPhysicalRule::do_optimize(sort, &ConfigOptions::default()).unwrap();
402        assert!(optimized.is::<SortExec>());
403    }
404
405    #[test]
406    fn test_is_time_index_expr_tracks_aliases_through_projection() {
407        let scan = new_region_scan();
408        let projection = Arc::new(
409            ProjectionExec::try_new(
410                vec![(
411                    Arc::new(PhysicalColumn::new("ts", 1)) as Arc<dyn PhysicalExpr>,
412                    "alias_ts".to_string(),
413                )],
414                scan,
415            )
416            .unwrap(),
417        ) as Arc<dyn ExecutionPlan>;
418        let expr = Arc::new(PhysicalColumn::new("alias_ts", 0)) as Arc<dyn PhysicalExpr>;
419
420        assert!(is_time_index_expr(&projection, &expr).unwrap());
421    }
422
423    #[test]
424    fn test_is_time_index_expr_tracks_multi_level_aliases() {
425        let scan = new_region_scan();
426        let first_projection = Arc::new(
427            ProjectionExec::try_new(
428                vec![(
429                    Arc::new(PhysicalColumn::new("ts", 1)) as Arc<dyn PhysicalExpr>,
430                    "alias_1".to_string(),
431                )],
432                scan,
433            )
434            .unwrap(),
435        ) as Arc<dyn ExecutionPlan>;
436        let second_projection = Arc::new(
437            ProjectionExec::try_new(
438                vec![(
439                    Arc::new(PhysicalColumn::new("alias_1", 0)) as Arc<dyn PhysicalExpr>,
440                    "alias_2".to_string(),
441                )],
442                first_projection,
443            )
444            .unwrap(),
445        ) as Arc<dyn ExecutionPlan>;
446        let expr = Arc::new(PhysicalColumn::new("alias_2", 0)) as Arc<dyn PhysicalExpr>;
447
448        assert!(is_time_index_expr(&second_projection, &expr).unwrap());
449    }
450
451    #[test]
452    fn test_is_time_index_expr_tracks_value_preserving_wrapper_through_projection() {
453        let scan = new_region_scan_with_unit(TimeUnit::Millisecond);
454        let config = Arc::new(ConfigOptions::default());
455        let wrapper = ScalarFunctionExpr::try_new(
456            to_timestamp_millis(config.as_ref()),
457            vec![Arc::new(PhysicalColumn::new("ts", 1))],
458            scan.schema().as_ref(),
459            config,
460        )
461        .unwrap();
462        // `to_timestamp_millis` keeps both the unit and the values of a millisecond timestamp.
463        assert_eq!(
464            wrapper.data_type(scan.schema().as_ref()).unwrap(),
465            DataType::Timestamp(TimeUnit::Millisecond, None)
466        );
467        let projection = Arc::new(
468            ProjectionExec::try_new(
469                vec![(Arc::new(wrapper) as Arc<dyn PhysicalExpr>, "ts".to_string())],
470                scan,
471            )
472            .unwrap(),
473        ) as Arc<dyn ExecutionPlan>;
474        let expr = Arc::new(PhysicalColumn::new("ts", 0)) as Arc<dyn PhysicalExpr>;
475
476        // So the wrapper is still the time index.
477        assert!(is_time_index_expr(&projection, &expr).unwrap());
478    }
479
480    #[test]
481    fn test_is_time_index_expr_rejects_unit_changing_wrapper() {
482        let config = Arc::new(ConfigOptions::default());
483
484        // `to_timestamp_millis` casts its argument to milliseconds, which truncates the values of
485        // a nanosecond time index, so the wrapper is no longer the time index.
486        let nanosecond_scan = new_region_scan();
487        let truncates_to_millis = Arc::new(
488            ScalarFunctionExpr::try_new(
489                to_timestamp_millis(config.as_ref()),
490                vec![Arc::new(PhysicalColumn::new("ts", 1))],
491                nanosecond_scan.schema().as_ref(),
492                config.clone(),
493            )
494            .unwrap(),
495        ) as Arc<dyn PhysicalExpr>;
496        assert_eq!(
497            truncates_to_millis
498                .data_type(nanosecond_scan.schema().as_ref())
499                .unwrap(),
500            DataType::Timestamp(TimeUnit::Millisecond, None)
501        );
502        assert!(!is_time_index_expr(&nanosecond_scan, &truncates_to_millis).unwrap());
503
504        // Same for a millisecond time index wrapped in `to_timestamp_seconds`.
505        let millisecond_scan = new_region_scan_with_unit(TimeUnit::Millisecond);
506        let truncates_to_seconds = Arc::new(
507            ScalarFunctionExpr::try_new(
508                to_timestamp_seconds(config.as_ref()),
509                vec![Arc::new(PhysicalColumn::new("ts", 1))],
510                millisecond_scan.schema().as_ref(),
511                config.clone(),
512            )
513            .unwrap(),
514        ) as Arc<dyn PhysicalExpr>;
515        assert_eq!(
516            truncates_to_seconds
517                .data_type(millisecond_scan.schema().as_ref())
518                .unwrap(),
519            DataType::Timestamp(TimeUnit::Second, None)
520        );
521        assert!(!is_time_index_expr(&millisecond_scan, &truncates_to_seconds).unwrap());
522
523        // A supported wrapper whose argument is not a timestamp is never the time index.
524        let from_integer = Arc::new(
525            ScalarFunctionExpr::try_new(
526                to_timestamp_millis(config.as_ref()),
527                vec![Arc::new(Literal::new(ScalarValue::Int64(Some(0))))],
528                nanosecond_scan.schema().as_ref(),
529                config,
530            )
531            .unwrap(),
532        ) as Arc<dyn PhysicalExpr>;
533        assert!(!is_time_index_expr(&nanosecond_scan, &from_integer).unwrap());
534    }
535
536    #[test]
537    fn test_is_time_index_expr_rejects_unit_changing_cast_through_projection() {
538        let scan = new_region_scan();
539        let projection = Arc::new(
540            ProjectionExec::try_new(
541                vec![(
542                    Arc::new(CastExpr::new(
543                        Arc::new(PhysicalColumn::new("ts", 1)),
544                        DataType::Timestamp(TimeUnit::Millisecond, None),
545                        None,
546                    )) as Arc<dyn PhysicalExpr>,
547                    "ts_ms".to_string(),
548                )],
549                scan,
550            )
551            .unwrap(),
552        ) as Arc<dyn ExecutionPlan>;
553        let expr = Arc::new(PhysicalColumn::new("ts_ms", 0)) as Arc<dyn PhysicalExpr>;
554
555        // The cast changes the time unit (ns → ms), so it is no longer the time index.
556        assert!(!is_time_index_expr(&projection, &expr).unwrap());
557    }
558
559    #[test]
560    fn test_is_time_index_expr_rejects_timezone_adding_cast() {
561        let scan = new_region_scan();
562
563        // The optimizer conservatively rejects casts adding any timezone to a naive timestamp.
564        let adds_timezone = Arc::new(CastExpr::new(
565            Arc::new(PhysicalColumn::new("ts", 1)),
566            DataType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("+07:00"))),
567            None,
568        )) as Arc<dyn PhysicalExpr>;
569        assert!(!is_time_index_expr(&scan, &adds_timezone).unwrap());
570
571        // UTC has a zero offset, but naive-to-aware timestamp casts are all rejected.
572        let adds_utc_timezone = Arc::new(CastExpr::new(
573            Arc::new(PhysicalColumn::new("ts", 1)),
574            DataType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("UTC"))),
575            None,
576        )) as Arc<dyn PhysicalExpr>;
577        assert!(!is_time_index_expr(&scan, &adds_utc_timezone).unwrap());
578
579        // `to_timestamp` returns an aware timestamp in the session time zone for a naive
580        // timestamp argument. That re-interprets the underlying values in the same way as a
581        // timezone-adding cast, so the wrapper is rejected as well.
582        let mut config = ConfigOptions::default();
583        config.execution.time_zone = Some("+08:00".to_string());
584        let config = Arc::new(config);
585        let aware_source = ScalarFunctionExpr::try_new(
586            to_timestamp(config.as_ref()),
587            vec![Arc::new(PhysicalColumn::new("ts", 1))],
588            scan.schema().as_ref(),
589            config.clone(),
590        )
591        .unwrap();
592        let projection = Arc::new(
593            ProjectionExec::try_new(
594                vec![(
595                    Arc::new(aware_source) as Arc<dyn PhysicalExpr>,
596                    "ts_aware".to_string(),
597                )],
598                scan,
599            )
600            .unwrap(),
601        ) as Arc<dyn ExecutionPlan>;
602        assert_eq!(
603            projection.schema().field(0).data_type(),
604            &DataType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("+08:00")))
605        );
606        let expr = Arc::new(PhysicalColumn::new("ts_aware", 0)) as Arc<dyn PhysicalExpr>;
607
608        assert!(!is_time_index_expr(&projection, &expr).unwrap());
609
610        // A cast between two aware timestamps of the same unit keeps the underlying values, see
611        // `test_preserves_timestamp_values`, but it is still rejected here as its input is not
612        // the time index.
613        let aware_cast = Arc::new(CastExpr::new(
614            Arc::new(PhysicalColumn::new("ts_aware", 0)),
615            DataType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("+07:00"))),
616            None,
617        )) as Arc<dyn PhysicalExpr>;
618
619        assert!(!is_time_index_expr(&projection, &aware_cast).unwrap());
620    }
621
622    #[test]
623    fn test_preserves_timestamp_values() {
624        let naive_nanosecond = DataType::Timestamp(TimeUnit::Nanosecond, None);
625        let naive_millisecond = DataType::Timestamp(TimeUnit::Millisecond, None);
626        let aware_nanosecond = DataType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("+08:00")));
627        let other_aware_nanosecond =
628            DataType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("+07:00")));
629
630        // Keeping the unit and the values of a timestamp.
631        assert!(preserves_timestamp_values(
632            &naive_nanosecond,
633            &naive_nanosecond
634        ));
635        assert!(preserves_timestamp_values(
636            &aware_nanosecond,
637            &other_aware_nanosecond
638        ));
639
640        // Changing the time unit, adding a timezone to a naive timestamp, or leaving the timestamp
641        // domain entirely all change the values of the timestamp.
642        assert!(!preserves_timestamp_values(
643            &naive_millisecond,
644            &naive_nanosecond
645        ));
646        assert!(!preserves_timestamp_values(
647            &aware_nanosecond,
648            &naive_nanosecond
649        ));
650        assert!(!preserves_timestamp_values(
651            &naive_nanosecond,
652            &DataType::Int64
653        ));
654        assert!(!preserves_timestamp_values(
655            &DataType::Int64,
656            &naive_nanosecond
657        ));
658
659        // Dropping an aware timestamp's timezone keeps the underlying values. Adding one to a
660        // naive timestamp is conservatively treated as non-preserving by the predicate.
661        assert!(preserves_timestamp_values(
662            &naive_nanosecond,
663            &aware_nanosecond
664        ));
665    }
666
667    #[test]
668    fn test_is_time_index_expr_rejects_unsupported_wrappers() {
669        let scan = new_region_scan();
670        let config = Arc::new(ConfigOptions::default());
671        let return_field = Arc::new(Field::new(
672            "ts",
673            DataType::Timestamp(TimeUnit::Millisecond, None),
674            false,
675        ));
676        let projection = Arc::new(
677            ProjectionExec::try_new(
678                vec![(
679                    Arc::new(ScalarFunctionExpr::new(
680                        "date_trunc",
681                        to_timestamp_millis(config.as_ref()),
682                        vec![Arc::new(PhysicalColumn::new("ts", 1))],
683                        return_field,
684                        config,
685                    )) as Arc<dyn PhysicalExpr>,
686                    "ts".to_string(),
687                )],
688                scan,
689            )
690            .unwrap(),
691        ) as Arc<dyn ExecutionPlan>;
692        let expr = Arc::new(PhysicalColumn::new("ts", 0)) as Arc<dyn PhysicalExpr>;
693
694        assert!(!is_time_index_expr(&projection, &expr).unwrap());
695    }
696
697    #[test]
698    fn test_is_supported_time_index_wrapper_ignores_function_name_case() {
699        let config = Arc::new(ConfigOptions::default());
700        let return_field = Arc::new(Field::new(
701            "ts",
702            DataType::Timestamp(TimeUnit::Millisecond, None),
703            false,
704        ));
705        let expr = ScalarFunctionExpr::new(
706            "To_Timestamp_Millis",
707            to_timestamp_millis(config.as_ref()),
708            vec![Arc::new(PhysicalColumn::new("ts", 1))],
709            return_field,
710            config,
711        );
712
713        assert!(is_supported_time_index_wrapper(&expr));
714    }
715
716    #[test]
717    fn test_is_time_index_expr_rejects_non_timestamp_casts() {
718        let scan = new_region_scan();
719        let cast_expr = Arc::new(CastExpr::new(
720            Arc::new(PhysicalColumn::new("ts", 1)),
721            DataType::Timestamp(TimeUnit::Millisecond, None),
722            None,
723        )) as Arc<dyn PhysicalExpr>;
724        // The cast changes the time unit (ns → ms), so it is no longer the time index.
725        assert!(!is_time_index_expr(&scan, &cast_expr).unwrap());
726
727        let non_timestamp_cast = Arc::new(CastExpr::new(
728            Arc::new(PhysicalColumn::new("ts", 1)),
729            DataType::Int64,
730            None,
731        )) as Arc<dyn PhysicalExpr>;
732        assert!(!is_time_index_expr(&scan, &non_timestamp_cast).unwrap());
733    }
734
735    #[test]
736    fn test_is_time_index_expr_tracks_time_index_through_filter() {
737        let scan = new_region_scan();
738        let filter = Arc::new(
739            FilterExec::try_new(
740                Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))),
741                scan,
742            )
743            .unwrap(),
744        ) as Arc<dyn ExecutionPlan>;
745        let expr = Arc::new(PhysicalColumn::new("ts", 1)) as Arc<dyn PhysicalExpr>;
746
747        assert!(is_time_index_expr(&filter, &expr).unwrap());
748    }
749
750    #[test]
751    fn test_is_time_index_expr_tracks_time_index_through_passthrough_wrapper_and_filter_projection()
752    {
753        let scan = new_region_scan();
754        let projected_filter = Arc::new(
755            FilterExecBuilder::new(
756                Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))),
757                scan,
758            )
759            .apply_projection(Some(vec![1]))
760            .unwrap()
761            .build()
762            .unwrap(),
763        ) as Arc<dyn ExecutionPlan>;
764        let cooperative =
765            Arc::new(CooperativeExec::new(projected_filter)) as Arc<dyn ExecutionPlan>;
766        let expr = Arc::new(PhysicalColumn::new("ts", 0)) as Arc<dyn PhysicalExpr>;
767
768        assert!(is_time_index_expr(&cooperative, &expr).unwrap());
769    }
770
771    #[test]
772    fn test_schema_preserving_child_rejects_schema_changing_projection() {
773        let scan = new_region_scan();
774        let projection = ProjectionExec::try_new(
775            vec![(
776                Arc::new(PhysicalColumn::new("ts", 1)) as Arc<dyn PhysicalExpr>,
777                "ts".to_string(),
778            )],
779            scan,
780        )
781        .unwrap();
782
783        assert!(schema_preserving_child(&projection).is_none());
784    }
785
786    #[test]
787    fn test_cooperative_exec_satisfies_passthrough_schema_contract() {
788        let child = new_region_scan();
789        let plan = Arc::new(CooperativeExec::new(child.clone())) as Arc<dyn ExecutionPlan>;
790
791        assert_passthrough_schema_contract(plan, child);
792    }
793
794    #[test]
795    fn test_repartition_exec_satisfies_passthrough_schema_contract() {
796        let child = new_region_scan();
797        let plan = Arc::new(
798            RepartitionExec::try_new(
799                child.clone(),
800                datafusion_physical_expr::Partitioning::RoundRobinBatch(2),
801            )
802            .unwrap(),
803        ) as Arc<dyn ExecutionPlan>;
804
805        assert_passthrough_schema_contract(plan, child);
806    }
807
808    #[test]
809    fn test_coalesce_partitions_exec_satisfies_passthrough_schema_contract() {
810        let child = new_region_scan();
811        let plan = Arc::new(CoalescePartitionsExec::new(child.clone())) as Arc<dyn ExecutionPlan>;
812
813        assert_passthrough_schema_contract(plan, child);
814    }
815
816    fn assert_passthrough_schema_contract(
817        plan: Arc<dyn ExecutionPlan>,
818        child: Arc<dyn ExecutionPlan>,
819    ) {
820        assert_eq!(plan.schema().as_ref(), child.schema().as_ref());
821
822        let passthrough = passthrough_child(plan.as_ref()).expect("wrapper should preserve schema");
823        assert_eq!(passthrough.schema().as_ref(), child.schema().as_ref());
824    }
825
826    fn new_region_scan() -> Arc<dyn ExecutionPlan> {
827        new_region_scan_with_unit(TimeUnit::Nanosecond)
828    }
829
830    fn new_region_scan_with_unit(unit: TimeUnit) -> Arc<dyn ExecutionPlan> {
831        let timestamp_type = ConcreteDataType::timestamp_datatype(unit.into());
832        let schema = Arc::new(Schema::new(vec![
833            ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false),
834            ColumnSchema::new("ts", timestamp_type.clone(), false),
835        ]));
836        let recordbatches = RecordBatches::try_new(schema.clone(), vec![]).unwrap();
837        let stream = recordbatches.as_stream();
838
839        let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1));
840        builder
841            .push_column_metadata(ColumnMetadata {
842                column_schema: ColumnSchema::new(
843                    "value",
844                    ConcreteDataType::int32_datatype(),
845                    false,
846                ),
847                semantic_type: SemanticType::Field,
848                column_id: 1,
849            })
850            .push_column_metadata(ColumnMetadata {
851                column_schema: ColumnSchema::new("ts", timestamp_type, false),
852                semantic_type: SemanticType::Timestamp,
853                column_id: 2,
854            });
855
856        let scanner = Box::new(SinglePartitionScanner::new(
857            stream,
858            false,
859            Arc::new(builder.build().unwrap()),
860            None,
861        ));
862        Arc::new(RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap())
863    }
864}