zhuqi-lucas commented on code in PR #27648:
URL: https://github.com/apache/datafusion/pull/27648#discussion_r4658293436


##########
datafusion/core/src/physical_planner.rs:
##########
@@ -3518,13 +3539,42 @@ impl DefaultPhysicalPlanner {
 
         let mut new_plan = Arc::clone(&plan);
         let optimizer_context = SessionOptimizerContext::new(session_state);
+        let enforcement = EnsureRequirements::new();
+        // Whether the requirements held after enforcement ran. Once they 
have, a rule
+        // that breaks them is followed by enforcement again, so no rule has 
to know
+        // what runs before or after it.
+        let mut enforced = false;
         for optimizer in optimizers {
             let before_schema = new_plan.schema();
+            let held = enforced.then(|| Arc::clone(&new_plan));
             new_plan = optimizer
                 .optimize_with_context(new_plan, &optimizer_context)
                 .map_err(|e| {
                     DataFusionError::Context(optimizer.name().to_string(), 
Box::new(e))
                 })?;
+            if optimizer.name() == enforcement.name() {
+                enforced = input_requirements_hold(&new_plan);
+            } else if let Some(held) = held
+                && !input_requirements_hold_since(&new_plan, &held)
+            {
+                // Repair only: added parallelism could split the input of a 
fetch.
+                let mut config = session_state.config_options().clone();
+                config.optimizer.enable_round_robin_repartition = false;

Review Comment:
   This repair also drops parallelism far from the broken node. 
`ensure_distribution` strips existing repartitions on every node and, with 
round-robin off, doesn't add them back. With `target_partitions = 4` and 
`RemoveSorts` appended:
   ```sql
   SELECT b, c, row_number() OVER (ORDER BY b) FROM
     (SELECT value % 7 AS b, count(*) AS c FROM generate_series(1, 1000000)
      WHERE value > 5 GROUP BY value % 7)
   ```
   the sort comes back, but the `RoundRobinBatch(4)` under the filter and 
partial aggregate is gone (`Hash(...), input_partitions=1`), so that part now 
runs on one partition.



##########
datafusion/core/src/physical_planner.rs:
##########
@@ -3761,11 +3811,12 @@ fn tuple_err<T, R>(value: (Result<T>, Result<R>)) -> 
Result<(T, R)> {
 
 /// Adds context to an error from the final [`check_plan_tree_sanity`].
 ///
-/// `EnsureRequirements` makes the order and distribution requirements hold,
-/// and every rule after it must keep them. When they do not hold for
-/// `final_plan`, the context names the rule that broke this contract: either
-/// `EnsureRequirements` itself, or the rule after which the requirements
-/// stopped holding. To find it, `optimizers` run again from `input_plan`, so
+/// `EnsureRequirements` makes the order and distribution requirements hold.
+/// When a later rule breaks them, the physical planner runs
+/// `EnsureRequirements` again, so they only fail to hold for `final_plan` when
+/// that run could not restore them. The context names the rule that broke
+/// them: either `EnsureRequirements` itself, or the rule after which the
+/// requirements stopped holding. To find it, `optimizers` run again from 
`input_plan`, so
 /// planning that succeeds keeps no intermediate plans.
 fn sanity_check_error(

Review Comment:
   The replay doesn't repair, so it can name the wrong rule. With `RemoveSorts` 
(repaired in the loop) followed by a rule whose break can't be repaired, the 
error says `stopped holding after physical optimizer rule 'remove_sorts'`. My 
second rule was contrived (a node that ignores new children), but the loop 
already knows which rule's repair failed, so recording it there would avoid the 
replay.



##########
datafusion/core/src/physical_planner.rs:
##########
@@ -3518,13 +3539,42 @@ impl DefaultPhysicalPlanner {
 
         let mut new_plan = Arc::clone(&plan);
         let optimizer_context = SessionOptimizerContext::new(session_state);
+        let enforcement = EnsureRequirements::new();
+        // Whether the requirements held after enforcement ran. Once they 
have, a rule
+        // that breaks them is followed by enforcement again, so no rule has 
to know
+        // what runs before or after it.
+        let mut enforced = false;
         for optimizer in optimizers {
             let before_schema = new_plan.schema();
+            let held = enforced.then(|| Arc::clone(&new_plan));
             new_plan = optimizer
                 .optimize_with_context(new_plan, &optimizer_context)
                 .map_err(|e| {
                     DataFusionError::Context(optimizer.name().to_string(), 
Box::new(e))
                 })?;
+            if optimizer.name() == enforcement.name() {
+                enforced = input_requirements_hold(&new_plan);
+            } else if let Some(held) = held
+                && !input_requirements_hold_since(&new_plan, &held)
+            {
+                // Repair only: added parallelism could split the input of a 
fetch.
+                let mut config = session_state.config_options().clone();
+                config.optimizer.enable_round_robin_repartition = false;
+                config.optimizer.repartition_file_scans = false;
+                let repair_context = RepairContext {
+                    session: &optimizer_context,
+                    config,
+                };
+                new_plan = enforcement
+                    .optimize_with_context(new_plan, &repair_context)
+                    .map_err(|e| {
+                        DataFusionError::Context(
+                            enforcement.name().to_string(),
+                            Box::new(e),
+                        )
+                    })?;
+                enforced = input_requirements_hold(&new_plan);

Review Comment:
   The observer below then sees the repaired plan under the rule that broke it, 
so EXPLAIN VERBOSE shows `physical_plan after remove_sorts: SAME TEXT AS ABOVE` 
(with the `SortExec`) and the repair is invisible. Could the repair be reported 
as its own `EnsureRequirements` step?



-- 
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