Skip to main content

query/optimizer/
pass_distribution.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 datafusion::config::ConfigOptions;
18use datafusion::physical_optimizer::PhysicalOptimizerRule;
19use datafusion::physical_plan::projection::ProjectionExec;
20use datafusion::physical_plan::repartition::RepartitionExec;
21use datafusion::physical_plan::{ExecutionPlan, Partitioning};
22use datafusion_common::Result as DfResult;
23use datafusion_physical_expr::Distribution;
24use datafusion_physical_expr::utils::map_columns_before_projection;
25
26use crate::dist_plan::MergeScanExec;
27
28/// This is a [`PhysicalOptimizerRule`] to pass distribution requirement to
29/// [`MergeScanExec`] to avoid unnecessary shuffling.
30///
31/// This rule is expected to be run before [`EnforceDistribution`].
32///
33/// [`EnforceDistribution`]: datafusion::physical_optimizer::enforce_distribution::EnforceDistribution
34/// [`MergeScanExec`]: crate::dist_plan::MergeScanExec
35#[derive(Debug)]
36pub struct PassDistribution;
37
38impl PhysicalOptimizerRule for PassDistribution {
39    fn optimize(
40        &self,
41        plan: Arc<dyn ExecutionPlan>,
42        config: &ConfigOptions,
43    ) -> DfResult<Arc<dyn ExecutionPlan>> {
44        Self::do_optimize(plan, config)
45    }
46
47    fn name(&self) -> &str {
48        "PassDistributionRule"
49    }
50
51    fn schema_check(&self) -> bool {
52        false
53    }
54}
55
56impl PassDistribution {
57    fn do_optimize(
58        plan: Arc<dyn ExecutionPlan>,
59        _config: &ConfigOptions,
60    ) -> DfResult<Arc<dyn ExecutionPlan>> {
61        // Start from root with no requirement
62        Self::rewrite_with_distribution(plan, None)
63    }
64
65    /// Top-down rewrite that propagates distribution requirements to children.
66    fn rewrite_with_distribution(
67        plan: Arc<dyn ExecutionPlan>,
68        current_req: Option<Distribution>,
69    ) -> DfResult<Arc<dyn ExecutionPlan>> {
70        // If this is a MergeScanExec, try to apply the current requirement.
71        if let Some(merge_scan) = plan.as_any().downcast_ref::<MergeScanExec>()
72            && let Some(Distribution::HashPartitioned(hash_exprs)) = current_req.as_ref()
73        {
74            if let Partitioning::Hash(current_hash_exprs, _) = &merge_scan.properties().partitioning
75                && *current_hash_exprs == *hash_exprs
76            {
77                return Ok(plan);
78            }
79
80            if let Some(new_plan) = merge_scan
81                .try_with_new_distribution(Distribution::HashPartitioned(hash_exprs.clone()))
82            {
83                // Leaf node; no children to process
84                return Ok(Arc::new(new_plan) as _);
85            }
86
87            let partitioning = Partitioning::Hash(
88                hash_exprs.clone(),
89                merge_scan.properties().partitioning.partition_count(),
90            );
91            return Ok(Arc::new(RepartitionExec::try_new(plan, partitioning)?) as _);
92        }
93
94        // Compute per-child requirements from the current node.
95        let children = plan.children();
96        if children.is_empty() {
97            return Ok(plan);
98        }
99
100        let required = plan.required_input_distribution();
101        let mut new_children = Vec::with_capacity(children.len());
102        for (idx, child) in children.into_iter().enumerate() {
103            let child_req = match required.get(idx) {
104                Some(Distribution::UnspecifiedDistribution) if idx == 0 => {
105                    Self::map_hash_requirement_through_projection(plan.as_ref(), &current_req)
106                }
107                Some(Distribution::UnspecifiedDistribution) => None,
108                None => current_req.clone(),
109                Some(req) => Some(req.clone()),
110            };
111            let new_child = Self::rewrite_with_distribution(child.clone(), child_req)?;
112            new_children.push(new_child);
113        }
114
115        // Rebuild the node only if any child changed (pointer inequality)
116        let unchanged = plan
117            .children()
118            .into_iter()
119            .zip(new_children.iter())
120            .all(|(old, new)| Arc::ptr_eq(old, new));
121        if unchanged {
122            Ok(plan)
123        } else {
124            plan.with_new_children(new_children)
125        }
126    }
127
128    fn map_hash_requirement_through_projection(
129        plan: &dyn ExecutionPlan,
130        current_req: &Option<Distribution>,
131    ) -> Option<Distribution> {
132        let Some(Distribution::HashPartitioned(required_exprs)) = current_req else {
133            return None;
134        };
135
136        let projection = plan.as_any().downcast_ref::<ProjectionExec>()?;
137        let proj_exprs = projection
138            .expr()
139            .iter()
140            .map(|expr| (Arc::clone(&expr.expr), expr.alias.clone()))
141            .collect::<Vec<_>>();
142        let mapped = map_columns_before_projection(required_exprs, &proj_exprs);
143
144        (mapped.len() == required_exprs.len()).then_some(Distribution::HashPartitioned(mapped))
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use std::collections::{BTreeMap, BTreeSet};
151
152    use api::v1::region::{RemoteDynFilterUnregister, RemoteDynFilterUpdate};
153    use arrow_schema::{DataType, Field, Schema, SchemaRef, TimeUnit};
154    use async_trait::async_trait;
155    use common_query::request::QueryRequest;
156    use common_recordbatch::SendableRecordBatchStream;
157    use datafusion::common::NullEquality;
158    use datafusion::execution::SessionStateBuilder;
159    use datafusion::physical_optimizer::PhysicalOptimizerRule;
160    use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
161    use datafusion::physical_plan::projection::{ProjectionExec, ProjectionExpr};
162    use datafusion::physical_plan::{ExecutionPlanProperties, Partitioning};
163    use datafusion_expr::{JoinType, LogicalPlanBuilder};
164    use datafusion_physical_expr::PhysicalExpr;
165    use datafusion_physical_expr::expressions::Column as PhysicalColumn;
166    use session::ReadPreference;
167    use session::context::QueryContext;
168    use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
169    use store_api::storage::RegionId;
170    use table::table_name::TableName;
171
172    use super::*;
173    use crate::dist_plan::RemoteDynFilterProducerId;
174    use crate::error::Result as QueryResult;
175    use crate::region_query::RegionQueryHandler;
176
177    struct NoopRegionQueryHandler;
178
179    #[async_trait]
180    impl RegionQueryHandler for NoopRegionQueryHandler {
181        async fn do_get(
182            &self,
183            _read_preference: ReadPreference,
184            _request: QueryRequest,
185        ) -> QueryResult<SendableRecordBatchStream> {
186            unreachable!("pass distribution tests should not execute remote queries")
187        }
188
189        async fn handle_remote_dyn_filter_update(
190            &self,
191            _region_id: RegionId,
192            _query_id: String,
193            _update: RemoteDynFilterUpdate,
194        ) -> QueryResult<()> {
195            unreachable!("pass distribution tests should not send remote dyn filter updates")
196        }
197
198        async fn handle_remote_dyn_filter_unregister(
199            &self,
200            _region_id: RegionId,
201            _query_id: String,
202            _unregister: RemoteDynFilterUnregister,
203        ) -> QueryResult<()> {
204            unreachable!("pass distribution tests should not send remote dyn filter unregisters")
205        }
206    }
207
208    #[test]
209    fn passes_hash_requirement_through_projection_to_merge_scan() {
210        let schema = test_schema();
211        let left_merge_scan = Arc::new(test_merge_scan_exec(schema.clone()));
212        let right_merge_scan = Arc::new(test_merge_scan_exec(schema.clone()));
213        let left_projection = Arc::new(
214            ProjectionExec::try_new(
215                vec![
216                    ProjectionExpr::new(partition_column("greptime_value", 3), "greptime_value"),
217                    ProjectionExpr::new(
218                        partition_column(DATA_SCHEMA_TSID_COLUMN_NAME, 1),
219                        DATA_SCHEMA_TSID_COLUMN_NAME,
220                    ),
221                    ProjectionExpr::new(
222                        partition_column("greptime_timestamp", 2),
223                        "greptime_timestamp",
224                    ),
225                ],
226                left_merge_scan,
227            )
228            .unwrap(),
229        ) as Arc<dyn datafusion::physical_plan::ExecutionPlan>;
230        let join = Arc::new(
231            HashJoinExec::try_new(
232                left_projection,
233                right_merge_scan,
234                vec![
235                    (
236                        partition_column(DATA_SCHEMA_TSID_COLUMN_NAME, 1),
237                        partition_column(DATA_SCHEMA_TSID_COLUMN_NAME, 1),
238                    ),
239                    (
240                        partition_column("greptime_timestamp", 2),
241                        partition_column("greptime_timestamp", 2),
242                    ),
243                ],
244                None,
245                &JoinType::Inner,
246                None,
247                PartitionMode::Partitioned,
248                NullEquality::NullEqualsNull,
249                false,
250            )
251            .unwrap(),
252        ) as Arc<dyn datafusion::physical_plan::ExecutionPlan>;
253
254        let optimized = PassDistribution
255            .optimize(join, &ConfigOptions::default())
256            .unwrap();
257        let hash_join = optimized.as_any().downcast_ref::<HashJoinExec>().unwrap();
258        let left_projection = hash_join
259            .left()
260            .as_any()
261            .downcast_ref::<ProjectionExec>()
262            .unwrap();
263        let left_partitioning = left_projection.input().output_partitioning();
264        let right_partitioning = hash_join.right().output_partitioning();
265
266        let Partitioning::Hash(left_exprs, left_count) = left_partitioning else {
267            panic!("expected left merge scan hash partitioning");
268        };
269        let Partitioning::Hash(right_exprs, right_count) = right_partitioning else {
270            panic!("expected right merge scan hash partitioning");
271        };
272
273        assert_eq!(*left_count, 32);
274        assert_eq!(*right_count, 32);
275        assert_eq!(
276            column_names(left_exprs),
277            vec![DATA_SCHEMA_TSID_COLUMN_NAME, "greptime_timestamp"]
278        );
279        assert_eq!(
280            column_names(right_exprs),
281            vec![DATA_SCHEMA_TSID_COLUMN_NAME, "greptime_timestamp"]
282        );
283    }
284
285    #[test]
286    fn merge_scan_rejects_hash_requirement_on_partition_key_subset() {
287        let merge_scan = test_merge_scan_exec(test_schema());
288
289        let new_plan = merge_scan.try_with_new_distribution(Distribution::HashPartitioned(vec![
290            partition_column(DATA_SCHEMA_TSID_COLUMN_NAME, 1),
291        ]));
292
293        assert!(
294            new_plan.is_none(),
295            "partitioning by a subset of multi-column partition keys is not sufficient"
296        );
297    }
298
299    fn test_merge_scan_exec(schema: SchemaRef) -> MergeScanExec {
300        let session_state = SessionStateBuilder::new().with_default_features().build();
301        let partition_cols = BTreeMap::from([
302            (
303                DATA_SCHEMA_TSID_COLUMN_NAME.to_string(),
304                BTreeSet::from([datafusion_common::Column::from_name(
305                    DATA_SCHEMA_TSID_COLUMN_NAME,
306                )]),
307            ),
308            (
309                "greptime_timestamp".to_string(),
310                BTreeSet::from([datafusion_common::Column::from_name("greptime_timestamp")]),
311            ),
312        ]);
313        let plan = LogicalPlanBuilder::empty(false).build().unwrap();
314
315        MergeScanExec::new(
316            &session_state,
317            TableName::new("greptime", "public", "test"),
318            vec![RegionId::new(1, 0), RegionId::new(1, 1)],
319            plan,
320            schema.as_ref(),
321            Arc::new(NoopRegionQueryHandler),
322            QueryContext::arc(),
323            32,
324            partition_cols,
325            Some(RemoteDynFilterProducerId::new(1)),
326            false,
327        )
328        .unwrap()
329    }
330
331    fn test_schema() -> SchemaRef {
332        Arc::new(Schema::new(vec![
333            Field::new("host", DataType::Utf8, true),
334            Field::new(DATA_SCHEMA_TSID_COLUMN_NAME, DataType::UInt64, false),
335            Field::new(
336                "greptime_timestamp",
337                DataType::Timestamp(TimeUnit::Millisecond, None),
338                false,
339            ),
340            Field::new("greptime_value", DataType::Float64, true),
341        ]))
342    }
343
344    fn partition_column(name: &str, index: usize) -> Arc<dyn PhysicalExpr> {
345        Arc::new(PhysicalColumn::new(name, index))
346    }
347
348    fn column_names(exprs: &[Arc<dyn PhysicalExpr>]) -> Vec<&str> {
349        exprs
350            .iter()
351            .map(|expr| {
352                expr.as_any()
353                    .downcast_ref::<PhysicalColumn>()
354                    .unwrap()
355                    .name()
356            })
357            .collect()
358    }
359}