andygrove commented on code in PR #2749:
URL: 
https://github.com/apache/datafusion-ballista/pull/2749#discussion_r4601746875


##########
ballista/scheduler/src/state/aqe/test/stage_build_side.rs:
##########
@@ -164,3 +164,44 @@ async fn 
reuses_the_staged_exchange_when_the_build_side_measures_too_large() {
               StatsExec: partitions=4, rows=Exact(1000000000), 
bytes=Exact(42949672960)
     ");
 }
+
+/// Enabling filters must not interfere with AQE's measured join decisions.
+#[tokio::test]
+async fn runtime_filters_preserve_adaptive_planning() {

Review Comment:
   I think this one still can't fail. The `q8_shaped_ctx` tables are 
`StatsExec`, not `DataSourceExec`, so no tap or apply is placed in either pass 
and both plans match trivially. Could it use `MemTable` scans like the new 
fallback test, so a filter is actually placed? An `assert_plan!` snapshot of 
the instrumented stages for the broadcast and fallback flows would also pin the 
plan shape the way the other AQE rule tests do.



##########
ballista/scheduler/src/state/aqe/runtime_filter_planner.rs:
##########
@@ -0,0 +1,562 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Add runtime filters only to executable stage copies. The AQE tree stays
+//! untouched so scan recognition, join selection and stage boundaries do not
+//! depend on whether runtime filtering is enabled.
+
+use super::execution_plan::{DynamicJoinSelectionExec, ExchangeExec};
+use super::optimizer_rule::SelectJoinRule;
+use ballista_core::execution_plans::runtime_filter::supports_key;
+use ballista_core::execution_plans::{RuntimeFilterApplyExec, 
RuntimeFilterBuildExec};
+use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
+use datafusion::common::{JoinType, Result};
+use datafusion::datasource::source::DataSourceExec;
+use datafusion::physical_expr::{PhysicalExpr, expressions::Column};
+use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::HashJoinExec;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::repartition::RepartitionExec;
+use datafusion::physical_plan::{ExecutionPlan, replace_children_if_necessary};
+use std::collections::{BTreeMap, HashSet};
+use std::sync::Arc;
+
+#[derive(Clone)]
+struct Filter {
+    id: u64,
+    key: Arc<dyn PhysicalExpr>,
+}
+
+#[derive(Clone, Default)]
+pub(super) struct RuntimeFilterPlanner {
+    builds: BTreeMap<(usize, usize), Filter>,
+    probes: BTreeMap<usize, Vec<Filter>>,
+    planned: HashSet<usize>,
+}
+
+impl RuntimeFilterPlanner {
+    /// Discover summaries before their producer stages are submitted. A 
pending
+    /// join may still swap sides, so only the final join binds a scan 
consumer.
+    /// Independent shuffle consumers can be bound now: filtering either input
+    /// is safe for the supported join types, even if the join later swaps.
+    pub fn discover(&mut self, plan: &Arc<dyn ExecutionPlan>) -> Result<()> {
+        plan.apply(|node| {
+            if node
+                .downcast_ref::<ExchangeExec>()
+                .is_some_and(|e| e.shuffle_created())
+            {
+                return Ok(TreeNodeRecursion::Jump);
+            }
+            let (left, right, on, kind, null_aware) = if let Some(join) =
+                node.downcast_ref::<HashJoinExec>()
+            {
+                (
+                    join.left(),
+                    join.right(),
+                    join.on(),
+                    *join.join_type(),
+                    join.null_aware,
+                )
+            } else if let Some(join) = 
node.downcast_ref::<DynamicJoinSelectionExec>() {
+                (
+                    &join.left,
+                    &join.right,
+                    join.on.as_slice(),
+                    join.join_type,
+                    join.null_aware,
+                )
+            } else {
+                return Ok(TreeNodeRecursion::Continue);
+            };
+            if supported_join(kind, null_aware)
+                && let Some((left_key, right_key)) = on.first()
+            {
+                if left.is::<ExchangeExec>() {
+                    self.discover_pair(left, right, left_key, right_key)?;
+                } else if node.is::<DynamicJoinSelectionExec>() {
+                    self.discover_pair(right, left, right_key, left_key)?;
+                }
+            }
+            Ok(TreeNodeRecursion::Continue)
+        })?;
+        Ok(())
+    }
+
+    fn discover_pair(
+        &mut self,
+        build: &Arc<dyn ExecutionPlan>,
+        probe: &Arc<dyn ExecutionPlan>,
+        build_key: &Arc<dyn PhysicalExpr>,
+        probe_key: &Arc<dyn PhysicalExpr>,
+    ) -> Result<()> {
+        let Some(exchange) = build.downcast_ref::<ExchangeExec>() else {
+            return Ok(());
+        };
+        let Some(stage) = exchange.stage_id() else {
+            return Ok(());
+        };
+        let Some(column) = build_key.downcast_ref::<Column>() else {
+            return Ok(());
+        };
+        let data_type = build_key.data_type(build.schema().as_ref())?;
+        if !supports_key(&data_type)
+            || data_type != probe_key.data_type(probe.schema().as_ref())?
+        {
+            return Ok(());
+        }
+        let probe_exchange = probe.downcast_ref::<ExchangeExec>();
+        let (probe_input, probe_stage) = if let Some(probe) = probe_exchange {
+            let Some(id) = probe.stage_id() else {
+                return Ok(());
+            };
+            // Both boundaries have been made runnable in this pass. Never
+            // wait for a future stage, or create a boundary to obtain a 
filter.
+            if probe.shuffle_created() || self.planned.contains(&id) {
+                return Ok(());
+            }
+            (probe.input().clone(), Some(id))
+        } else {
+            (probe.clone(), None)
+        };
+        if probe_column(
+            probe_input.as_ref(),
+            probe_key.as_ref(),
+            probe_stage.is_some(),
+        )
+        .is_none()
+        {
+            return Ok(());
+        }
+        let producer_key = (stage, column.index());
+        // A fallback probe can be created after its producer completed. Reuse
+        // that producer's existing summary; only new taps need an unplanned 
stage.
+        if !self.builds.contains_key(&producer_key) {
+            if exchange.shuffle_created() || self.planned.contains(&stage) {
+                return Ok(());
+            }
+            // Unfinished exchanges have unknown statistics. Compare their 
inputs
+            // to avoid collecting a known larger prospective build side.
+            if SelectJoinRule::supports_swap_join_order(
+                exchange.input().as_ref(),
+                probe_input.as_ref(),
+            )? {
+                return Ok(());
+            }
+            self.builds.insert(
+                producer_key,
+                Filter {
+                    id: self.builds.len() as u64,
+                    key: build_key.clone(),
+                },
+            );
+        }
+        let filter = &self.builds[&producer_key];
+        if let Some(probe_stage) = probe_stage {
+            let probes = self.probes.entry(probe_stage).or_default();
+            if !probes.iter().any(|p| p.id == filter.id) {
+                probes.push(Filter {
+                    id: filter.id,
+                    key: probe_key.clone(),
+                });
+            }
+        }
+        Ok(())
+    }
+
+    pub fn instrument(
+        &mut self,
+        boundary: Arc<dyn ExecutionPlan>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        let stage = if let Some(exchange) = 
boundary.downcast_ref::<ExchangeExec>() {
+            exchange.stage_id().unwrap()

Review Comment:
   Small one from last time. A panic here takes down the scheduler. Could these 
`unwrap()`s return an internal error instead, for example with `ok_or_else(|| 
internal_datafusion_err!(...))`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to