Skip to main content

query/optimizer/
parallelize_scan.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 common_telemetry::debug;
18use datafusion::config::ConfigOptions;
19use datafusion::physical_optimizer::PhysicalOptimizerRule;
20use datafusion::physical_plan::ExecutionPlan;
21use datafusion::physical_plan::sorts::sort::SortExec;
22use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
23use datafusion_common::{DataFusionError, Result};
24use store_api::region_engine::PartitionRange;
25use table::table::scan::RegionScanExec;
26pub use table::table::scan::assign_partition_ranges;
27
28use crate::optimizer::global_topk::filtered_scan_below_topk;
29
30#[derive(Debug)]
31pub struct ParallelizeScan;
32
33impl PhysicalOptimizerRule for ParallelizeScan {
34    fn optimize(
35        &self,
36        plan: Arc<dyn ExecutionPlan>,
37        config: &ConfigOptions,
38    ) -> Result<Arc<dyn ExecutionPlan>> {
39        Self::do_optimize(plan, config)
40    }
41
42    fn name(&self) -> &str {
43        "parallelize_scan"
44    }
45
46    fn schema_check(&self) -> bool {
47        true
48    }
49}
50
51impl ParallelizeScan {
52    fn do_optimize(
53        plan: Arc<dyn ExecutionPlan>,
54        config: &ConfigOptions,
55    ) -> Result<Arc<dyn ExecutionPlan>> {
56        let mut first_order_expr = None;
57        // Scans read by a TopK that keeps one heap, with whether the TopK is descending.
58        let mut global_topk_scans = Vec::new();
59        plan.apply(|node| {
60            if let Some(sort) = node.downcast_ref::<SortExec>()
61                && let Some(scan) =
62                    filtered_scan_below_topk(sort, config.execution.target_partitions)?
63            {
64                global_topk_scans.push((
65                    scan as *const RegionScanExec,
66                    sort.expr().first().options.descending,
67                ));
68            }
69            Ok(TreeNodeRecursion::Continue)
70        })?;
71
72        let result = plan
73            .transform_down(|plan| {
74                if let Some(sort_exec) = plan.downcast_ref::<SortExec>() {
75                    // save the first order expr
76                    first_order_expr = Some(sort_exec.expr().first()).cloned();
77                } else if let Some(region_scan_exec) = plan.downcast_ref::<RegionScanExec>() {
78                    let expected_partition_num = config.execution.target_partitions;
79                    if region_scan_exec.is_partition_set()
80                        || region_scan_exec.scanner_type().as_str() == "SinglePartition"
81                    {
82                        return Ok(Transformed::no(plan));
83                    }
84
85                    let ranges = region_scan_exec.get_partition_ranges();
86                    let total_range_num = ranges.len();
87
88                    // assign ranges to each partition
89                    let global_topk_descending = global_topk_scans
90                        .iter()
91                        .find(|(scan, _)| std::ptr::eq(*scan, region_scan_exec))
92                        .map(|(_, descending)| *descending);
93                    let mut partition_ranges = match global_topk_descending {
94                        // The scan skips a range once the TopK threshold excludes the
95                        // range's time span. Dealing ranges in time order makes the first
96                        // range of every partition one of the newest (or oldest), so the
97                        // threshold forms before older ranges are read.
98                        Some(descending) => assign_partition_ranges_by_time(
99                            ranges,
100                            expected_partition_num,
101                            descending,
102                        ),
103                        None => assign_partition_ranges(ranges, expected_partition_num),
104                    };
105                    debug!(
106                        "Assign {total_range_num} ranges to {expected_partition_num} partitions"
107                    );
108
109                    // Sort the ranges in each partition based on the order expr
110                    //
111                    // This optimistically assumes that the first order expr is on the time index column
112                    // to skip the validation of the order expr. As it's not harmful if this condition
113                    // is not met.
114                    if let Some(order_expr) = &first_order_expr
115                        && order_expr.options.descending
116                    {
117                        for ranges in partition_ranges.iter_mut() {
118                            // Primary: end descending (larger end first)
119                            // Secondary: start descending (shorter range first when ends are equal)
120                            ranges.sort_by(|a, b| {
121                                b.end.cmp(&a.end).then_with(|| b.start.cmp(&a.start))
122                            });
123                        }
124                    } else {
125                        for ranges in partition_ranges.iter_mut() {
126                            // Primary: start ascending (smaller start first)
127                            // Secondary: end ascending (shorter range first when starts are equal)
128                            ranges.sort_by(|a, b| {
129                                a.start.cmp(&b.start).then_with(|| a.end.cmp(&b.end))
130                            });
131                        }
132                    }
133
134                    // update the partition ranges
135                    let new_exec = region_scan_exec
136                        .with_new_partitions(partition_ranges, expected_partition_num)
137                        .map_err(|e| DataFusionError::External(e.into_inner()))?;
138                    return Ok(Transformed::yes(Arc::new(new_exec)));
139                }
140
141                // The plan might be modified, but it's modified in-place so we always return
142                // Transformed::no(plan) to indicate there is no "new child"
143                Ok(Transformed::no(plan))
144            })?
145            .data;
146
147        Ok(result)
148    }
149}
150
151/// Assigns ranges in time order, newest first when `descending`, each to the partition
152/// with the fewest rows so far, then the fewest ranges. Every partition starts with one
153/// of the newest ranges, and the rows stay balanced when range sizes vary. Ranges of
154/// old files may report 0 rows, meaning unknown; the range count spreads those.
155fn assign_partition_ranges_by_time(
156    mut ranges: Vec<PartitionRange>,
157    expected_partition_num: usize,
158    descending: bool,
159) -> Vec<Vec<PartitionRange>> {
160    if descending {
161        ranges.sort_by(|a, b| b.end.cmp(&a.end).then_with(|| b.start.cmp(&a.start)));
162    } else {
163        ranges.sort_by(|a, b| a.start.cmp(&b.start).then_with(|| a.end.cmp(&b.end)));
164    }
165    let mut partition_ranges = vec![vec![]; expected_partition_num];
166    let mut partition_rows = vec![0; expected_partition_num];
167    for range in ranges {
168        let target = (0..expected_partition_num)
169            .min_by_key(|&i| (partition_rows[i], partition_ranges[i].len(), i))
170            .unwrap();
171        partition_rows[target] += range.num_rows;
172        partition_ranges[target].push(range);
173    }
174    partition_ranges
175}
176
177#[cfg(test)]
178mod test {
179    use common_time::Timestamp;
180    use common_time::timestamp::TimeUnit;
181    use datafusion::physical_plan::union::UnionExec;
182    use datafusion_physical_expr::expressions::Column;
183    use store_api::region_engine::PartitionRange;
184
185    use super::*;
186    use crate::optimizer::test_util::{body_is_not_null, sort_by, unassigned_log_region_scan};
187
188    /// Consecutive ten-millisecond ranges with the given row counts, oldest first.
189    fn time_ranges(rows: &[usize]) -> Vec<PartitionRange> {
190        rows.iter()
191            .enumerate()
192            .map(|(i, &num_rows)| PartitionRange {
193                start: Timestamp::new(i as i64 * 10, TimeUnit::Millisecond),
194                end: Timestamp::new(i as i64 * 10 + 10, TimeUnit::Millisecond),
195                num_rows,
196                identifier: i,
197            })
198            .collect()
199    }
200
201    /// Older ranges are larger, as compacted files usually are, so assigning by rows
202    /// alone starts a partition with an old range.
203    const SHRINKING: [usize; 8] = [800, 700, 600, 500, 400, 300, 200, 100];
204
205    #[test]
206    fn test_assign_by_time() {
207        let firsts = |partitions: Vec<Vec<PartitionRange>>| {
208            let mut ids: Vec<_> = partitions.iter().map(|p| p[0].identifier).collect();
209            ids.sort();
210            ids
211        };
212        let assign = |rows: &[usize], partitions, descending| {
213            assign_partition_ranges_by_time(time_ranges(rows), partitions, descending)
214        };
215        // Every partition starts with one of the newest (or oldest) ranges.
216        assert_eq!(vec![5, 6, 7], firsts(assign(&SHRINKING, 3, true)));
217        assert_eq!(vec![0, 1, 2], firsts(assign(&SHRINKING, 3, false)));
218        // Rows stay balanced: when fewer than `fetch` rows match, every range is read.
219        let rows: Vec<usize> = assign(&[1000, 1, 1000, 1], 2, false)
220            .iter()
221            .map(|p| p.iter().map(|r| r.num_rows).sum())
222            .collect();
223        assert_eq!(vec![1001, 1001], rows);
224        // Ranges of old files report 0 rows, meaning unknown, and are spread by count.
225        let counts: Vec<_> = assign(&[0, 0, 0, 0], 2, true)
226            .iter()
227            .map(Vec::len)
228            .collect();
229        assert_eq!(vec![2, 2], counts);
230    }
231
232    #[test]
233    fn test_only_filtered_time_topk_scans_get_time_ordered_ranges() {
234        let filter = body_is_not_null(unassigned_log_region_scan(time_ranges(&SHRINKING)));
235        let topk = Arc::new(sort_by(filter, Column::new("ts", 1), true).with_fetch(Some(100)));
236        // A sibling scan that no TopK reads must keep the row-balanced assignment.
237        let plan = UnionExec::try_new(vec![
238            topk,
239            unassigned_log_region_scan(time_ranges(&SHRINKING)),
240        ])
241        .unwrap();
242
243        let mut config = ConfigOptions::default();
244        config.execution.target_partitions = 3;
245        let plan = ParallelizeScan.optimize(plan, &config).unwrap();
246
247        let mut assignments = vec![];
248        plan.apply(|node| {
249            if let Some(scan) = node.downcast_ref::<RegionScanExec>() {
250                assignments.push(members(&scan.get_uncollapsed_partition_ranges()));
251            }
252            Ok(TreeNodeRecursion::Continue)
253        })
254        .unwrap();
255        assert_eq!(
256            vec![
257                members(&assign_partition_ranges_by_time(
258                    time_ranges(&SHRINKING),
259                    3,
260                    true
261                )),
262                members(&assign_partition_ranges(time_ranges(&SHRINKING), 3)),
263            ],
264            assignments
265        );
266    }
267
268    /// The range identifiers of each partition, ignoring order within and across
269    /// partitions.
270    fn members(partitions: &[Vec<PartitionRange>]) -> Vec<Vec<usize>> {
271        let mut members: Vec<Vec<usize>> = partitions
272            .iter()
273            .map(|p| {
274                let mut ids: Vec<_> = p.iter().map(|r| r.identifier).collect();
275                ids.sort();
276                ids
277            })
278            .collect();
279        members.sort();
280        members
281    }
282
283    #[test]
284    fn test_assign_unbalance_partition_range() {
285        let ranges = vec![
286            PartitionRange {
287                start: Timestamp::new(0, TimeUnit::Second),
288                end: Timestamp::new(10, TimeUnit::Second),
289                num_rows: 100,
290                identifier: 1,
291            },
292            PartitionRange {
293                start: Timestamp::new(10, TimeUnit::Second),
294                end: Timestamp::new(20, TimeUnit::Second),
295                num_rows: 200,
296                identifier: 2,
297            },
298            PartitionRange {
299                start: Timestamp::new(20, TimeUnit::Second),
300                end: Timestamp::new(30, TimeUnit::Second),
301                num_rows: 150,
302                identifier: 3,
303            },
304            PartitionRange {
305                start: Timestamp::new(30, TimeUnit::Second),
306                end: Timestamp::new(40, TimeUnit::Second),
307                num_rows: 2500,
308                identifier: 4,
309            },
310        ];
311
312        // assign to 2 partitions
313        let expected_partition_num = 2;
314        let result = assign_partition_ranges(ranges.clone(), expected_partition_num);
315        let expected = vec![
316            vec![PartitionRange {
317                start: Timestamp::new(30, TimeUnit::Second),
318                end: Timestamp::new(40, TimeUnit::Second),
319                num_rows: 2500,
320                identifier: 4,
321            }],
322            vec![
323                PartitionRange {
324                    start: Timestamp::new(10, TimeUnit::Second),
325                    end: Timestamp::new(20, TimeUnit::Second),
326                    num_rows: 200,
327                    identifier: 2,
328                },
329                PartitionRange {
330                    start: Timestamp::new(20, TimeUnit::Second),
331                    end: Timestamp::new(30, TimeUnit::Second),
332                    num_rows: 150,
333                    identifier: 3,
334                },
335                PartitionRange {
336                    start: Timestamp::new(0, TimeUnit::Second),
337                    end: Timestamp::new(10, TimeUnit::Second),
338                    num_rows: 100,
339                    identifier: 1,
340                },
341            ],
342        ];
343        assert_eq!(result, expected);
344    }
345}