You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "ozankabak (via GitHub)" <gi...@apache.org> on 2024/01/10 13:08:36 UTC

[PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

ozankabak opened a new pull request, #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817

   ## Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #.
   
   ## Rationale for this change
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   ## What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   ## Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   ## Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1447628922


##########
datafusion/common/src/tree_node.rs:
##########
@@ -18,7 +18,6 @@
 //! This module provides common traits for visiting or rewriting tree
 //! data structures easily.
 
-use std::borrow::Cow;

Review Comment:
   > If you check `apply_children()`, it seems like you duplicate its logic to 4 places in this PR.\\
   
   Right. The point is that there is a fixed number of `apply_children` implementations (one doesn't need to implement it per rule or per use case). However, 1 is obviously better than 4 and we will iterate on this.
   
   > Also, the `Cow` was there to avoid cloning in `Expr` but now we have cloning again.
   
   Yes, and I am looking at ways to eliminate it. This is the only use case remaining for`Cow`, and there may be a good way to remove it and still avoid cloning. The strategy in the WIP stage is to first explicitly implement everything and then progressively deduplicate by refining design. Maybe we will converge to the same `Cow` design, in that case we will simply revert.
   
   Thanks for taking a look 🚀 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1913618531

   Epic work!


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1902666804

   As this PR (with `PlanContext` and `ExprContext`) takes some parts of the code into a certain direction, I think it would help review and would be useful for deciding on further improvements if you could document where do you think hidden composition requirements are. I'm referring to those that are not visible from the current upstram code but do exists in your downstream code or you think it might be useful in the future. To give more context @ozankabak wrote in https://github.com/apache/arrow-datafusion/issues/8913 that:
   
   > The main concern I have is composability. Downstream, we have many use cases where the flow goes something like this:
   > 
   > 1. Visit/transform a given tree, and save per-node data during the process.
   > 2. Make a decision based depending on the final result of the visitation.
   > 3. Visit/transform the tree again, re-use the saved per-node data and only modify when necessary.
   > 
   > (this can repeat multiple times)
   
   > Having worked with most of the physical optimization rules as well as some logical rules for a long time now (upstream and downstream), I think I can safely that this is necessary. As I mentioned before, it is also on our roadmap to contribute more physical optimizations upstream in the near future and they need this kind of composability/reusability.
   
   Do you think you can leave some comments to identidy the affected areas of the code?
   
   cc @alamb 


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1467280447


##########
datafusion/core/src/physical_optimizer/join_selection.rs:
##########
@@ -840,26 +828,51 @@ mod tests_statistical {
         (big, medium, small)
     }
 
+    pub(crate) fn crosscheck_plans(plan: Arc<dyn ExecutionPlan>) -> Result<()> {
+        let pipeline = PipelineStatePropagator::new_default(plan);
+        let subrules: Vec<Box<PipelineFixerSubrule>> = vec![
+            Box::new(hash_join_convert_symmetric_subrule),
+            Box::new(hash_join_swap_subrule),
+        ];
+        let state = pipeline
+            .transform_up(&|p| apply_subrules(p, &subrules, &ConfigOptions::new()))
+            .and_then(check_integrity)?;
+        // TODO: End state payloads will be checked here.

Review Comment:
   Same for the other todo items



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1913349482

   Thanks everyone!


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1902671038

   > As soon as the draft is complete, we will fill in the PR body with this information. The quick summary is that `PlanContext` and `ExprContext` structs store partial results for all nodes so that one does not need to recompute them in multi-step transformations.
   
   I got that, but why would you store these if it not needed in some cases?


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1466696309


##########
datafusion/common/src/tree_node.rs:
##########
@@ -33,27 +46,17 @@ use crate::Result;
 /// [`PhysicalExpr`]: https://docs.rs/datafusion/latest/datafusion/physical_plan/trait.PhysicalExpr.html
 /// [`LogicalPlan`]: https://docs.rs/datafusion-expr/latest/datafusion_expr/logical_plan/enum.LogicalPlan.html
 /// [`Expr`]: https://docs.rs/datafusion-expr/latest/datafusion_expr/expr/enum.Expr.html
-pub trait TreeNode: Sized + Clone {
-    /// Returns all children of the TreeNode
-    fn children_nodes(&self) -> Vec<Cow<Self>>;
-
+pub trait TreeNode: Sized {
     /// Use preorder to iterate the node on the tree so that we can
     /// stop fast for some cases.
     ///
     /// The `op` closure can be used to collect some info from the
     /// tree node or do some checking for the tree node.

Review Comment:
   Perhaps this documentation can be updated, something like
   
   ```suggestion
       /// Applies `op` to the node and its children, with traversal controlled by 
       /// [`VisitRecursion`]
       ///
       /// The `op` closure can be used to collect some info from the
       /// tree node or do some checking for the tree node.
   ```



##########
datafusion/common/src/tree_node.rs:
##########
@@ -18,11 +18,24 @@
 //! This module provides common traits for visiting or rewriting tree
 //! data structures easily.
 
-use std::borrow::Cow;
 use std::sync::Arc;
 
 use crate::Result;
 
+#[macro_export]
+macro_rules! handle_tree_recursion {

Review Comment:
   Perhaps we can document what this macro does (aka `return`s from the function if Skip or Stop)



##########
datafusion/common/src/tree_node.rs:
##########
@@ -366,12 +350,47 @@ impl<T: DynTreeNode + ?Sized> TreeNode for Arc<T> {
     {
         let children = self.arc_children();
         if !children.is_empty() {
-            let new_children: Result<Vec<_>> =
-                children.into_iter().map(transform).collect();
+            let new_children =
+                children.into_iter().map(transform).collect::<Result<_>>()?;
             let arc_self = Arc::clone(&self);
-            self.with_new_arc_children(arc_self, new_children?)
+            self.with_new_arc_children(arc_self, new_children)
         } else {
             Ok(self)
         }
     }
 }
+
+pub trait ConcreteTreeNode: Sized {

Review Comment:
   I think we should document this trait, focusing what it should be used for, perhaps using some of the great description from this PR?
   
   I think documenting what the functions do and their expectations, `take_children` in particular, would be valuable as well



##########
datafusion/core/src/physical_optimizer/enforce_distribution.rs:
##########
@@ -1286,151 +1214,78 @@ fn ensure_distribution(
     )
     .collect::<Result<Vec<_>>>()?;
 
-    let new_distribution_context = DistributionContext {
-        plan: if plan.as_any().is::<UnionExec>()
-            && can_interleave(children_nodes.iter().map(|c| c.plan.clone()))
-        {
-            // Add a special case for [`UnionExec`] since we want to "bubble up"
-            // hash-partitioned data. So instead of
-            //
-            // Agg:
-            //   Repartition (hash):
-            //     Union:
-            //       - Agg:
-            //           Repartition (hash):
-            //             Data
-            //       - Agg:
-            //           Repartition (hash):
-            //             Data
-            //
-            // we can use:
-            //
-            // Agg:
-            //   Interleave:
-            //     - Agg:
-            //         Repartition (hash):
-            //           Data
-            //     - Agg:
-            //         Repartition (hash):
-            //           Data
-            Arc::new(InterleaveExec::try_new(
-                children_nodes.iter().map(|c| c.plan.clone()).collect(),
-            )?)
-        } else {
-            plan.with_new_children(
-                children_nodes.iter().map(|c| c.plan.clone()).collect(),
-            )?
-        },
-        distribution_connection,
-        children_nodes,
+    let children_plans = children.iter().map(|c| c.plan.clone()).collect::<Vec<_>>();
+    plan = if plan.as_any().is::<UnionExec>() && can_interleave(children_plans.iter()) {
+        // Add a special case for [`UnionExec`] since we want to "bubble up"
+        // hash-partitioned data. So instead of
+        //
+        // Agg:
+        //   Repartition (hash):
+        //     Union:
+        //       - Agg:
+        //           Repartition (hash):
+        //             Data
+        //       - Agg:
+        //           Repartition (hash):
+        //             Data
+        //
+        // we can use:
+        //
+        // Agg:
+        //   Interleave:
+        //     - Agg:
+        //         Repartition (hash):
+        //           Data
+        //     - Agg:
+        //         Repartition (hash):
+        //           Data
+        Arc::new(InterleaveExec::try_new(children_plans)?)
+    } else {
+        plan.with_new_children(children_plans)?
     };
 
-    Ok(Transformed::Yes(new_distribution_context))
-}
-
-/// A struct to keep track of distribution changing operators
-/// (`RepartitionExec`, `SortPreservingMergeExec`, `CoalescePartitionsExec`),
-/// and their associated parents inside `plan`. Using this information,
-/// we can optimize distribution of the plan if/when necessary.
-#[derive(Debug, Clone)]
-struct DistributionContext {
-    plan: Arc<dyn ExecutionPlan>,
-    /// Indicates whether this plan is connected to a distribution-changing
-    /// operator.
-    distribution_connection: bool,
-    children_nodes: Vec<Self>,
-}
-
-impl DistributionContext {

Review Comment:
   it is really cool to see this same pattern extracted out



##########
datafusion/core/src/physical_optimizer/join_selection.rs:
##########
@@ -840,26 +828,51 @@ mod tests_statistical {
         (big, medium, small)
     }
 
+    pub(crate) fn crosscheck_plans(plan: Arc<dyn ExecutionPlan>) -> Result<()> {
+        let pipeline = PipelineStatePropagator::new_default(plan);
+        let subrules: Vec<Box<PipelineFixerSubrule>> = vec![
+            Box::new(hash_join_convert_symmetric_subrule),
+            Box::new(hash_join_swap_subrule),
+        ];
+        let state = pipeline
+            .transform_up(&|p| apply_subrules(p, &subrules, &ConfigOptions::new()))
+            .and_then(check_integrity)?;
+        // TODO: End state payloads will be checked here.

Review Comment:
   Is this still TODO?



##########
datafusion/core/src/physical_optimizer/enforce_sorting.rs:
##########
@@ -812,6 +634,50 @@ mod tests {
             let session_ctx = SessionContext::new_with_config(config);
             let state = session_ctx.state();
 
+            // This file has 4 rules that use tree node, apply these rules as in the
+            // EnforSorting::optimize implementation
+            // After these operations tree nodes should be in a consistent state.
+            // This code block makes sure that these rules doesn't violate tree node integrity.
+            {
+                let plan_requirements = PlanWithCorrespondingSort::new_default($PLAN.clone());
+                let adjusted = plan_requirements
+                    .transform_up(&ensure_sorting)
+                    .and_then(check_integrity)?;
+                // TODO: End state payloads will be checked here.

Review Comment:
   are these still TODO items? Did you intent to complete the as part of this PR? If not, perhaps we can file a ticket to track their completion



##########
datafusion/physical-plan/src/tree_node.rs:
##########
@@ -35,3 +38,58 @@ impl DynTreeNode for dyn ExecutionPlan {
         with_new_children_if_necessary(arc_self, new_children).map(Transformed::into)
     }
 }
+
+#[derive(Debug)]
+pub struct PlanContext<T: Sized> {

Review Comment:
   Could we also document what this is used for? It seems it is used for rewriting execution plans where some additional information needs to be stored in addition to the plan itself
   
   Maybe a more descriptive name would be `PlanAndContext`? Though perhaps that is too verbose



##########
datafusion/core/src/physical_optimizer/test_utils.rs:
##########
@@ -361,3 +364,17 @@ pub fn sort_exec(
     let sort_exprs = sort_exprs.into_iter().collect();
     Arc::new(SortExec::new(sort_exprs, input))
 }
+
+pub fn check_integrity<T: Clone>(context: PlanContext<T>) -> Result<PlanContext<T>> {
+    context.transform_up(&|node| {
+        let children_plans = node.plan.children();
+        assert_eq!(node.children.len(), children_plans.len());
+        for (child_plan, child_node) in children_plans.iter().zip(node.children.iter()) {
+            assert_eq!(

Review Comment:
   Can you instead simply compare the plans directly rather than converting them to strings?



##########
datafusion/physical-expr/src/tree_node.rs:
##########
@@ -35,3 +38,57 @@ impl DynTreeNode for dyn PhysicalExpr {
         with_new_children_if_necessary(arc_self, new_children)
     }
 }
+
+#[derive(Debug)]
+pub struct ExprContext<T: Sized> {

Review Comment:
   Likewise documentation here would be awesome



##########
datafusion/core/src/physical_optimizer/test_utils.rs:
##########
@@ -361,3 +364,17 @@ pub fn sort_exec(
     let sort_exprs = sort_exprs.into_iter().collect();
     Arc::new(SortExec::new(sort_exprs, input))
 }
+
+pub fn check_integrity<T: Clone>(context: PlanContext<T>) -> Result<PlanContext<T>> {

Review Comment:
   Can you document what this is doing? 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1467509655


##########
datafusion/core/src/physical_optimizer/test_utils.rs:
##########
@@ -361,3 +364,17 @@ pub fn sort_exec(
     let sort_exprs = sort_exprs.into_iter().collect();
     Arc::new(SortExec::new(sort_exprs, input))
 }
+
+pub fn check_integrity<T: Clone>(context: PlanContext<T>) -> Result<PlanContext<T>> {
+    context.transform_up(&|node| {
+        let children_plans = node.plan.children();
+        assert_eq!(node.children.len(), children_plans.len());
+        for (child_plan, child_node) in children_plans.iter().zip(node.children.iter()) {
+            assert_eq!(

Review Comment:
   Makes sense -- maybe that is something that can be embedded in a comment to help anyone else that may have the same question



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1908029297

   I kept my eye on this PR and IMO it looks good (my concers have been addressed) and actually a nice refactor that unifies many different derived trees into `PlanContext` and `ExprContext`.
   
   Also, thanks for the general multi-stage example @ozankabak. Once this PR gets merged I would rebase my https://github.com/apache/arrow-datafusion/pull/8664 to see if it can improve some of the transformations while also simplify the tansform logic.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1447501407


##########
datafusion/common/src/tree_node.rs:
##########
@@ -18,7 +18,6 @@
 //! This module provides common traits for visiting or rewriting tree
 //! data structures easily.
 
-use std::borrow::Cow;

Review Comment:
   @viirya's PR was a good step towards deduplicating the `apply_children()` implementations. This PR further deduplicates not only `apply_children()`, but also `map_children()`, bringing them together in one place. 
   
   Like the `children()` method introduced by @viirya, which returns a `Cow`, `map_children()` requires two different methods: one to separate the children from self for mutation, and another for reattaching them afterwards. Since obtaining ownership of the children without owning self is not possible, I think `Cow`'s purpose becomes not much relevant in this use case. Now we have two children related methods: one with a reference and one with ownership. The original `fn children(&self) -> Vec<Cow<Self>>` can still be used, but it has become redundant. If the user requires write access, `take_children()` should be used.
   
   Rather than implementing functions such as `apply_children()` and `map_children()`, which provide too much flexibility and are prone to design an unclear flow, I think it is more appropriate to implement these 3 methods, which express the relationships of self nodes with their children, both in terms of ease of use and simplicity.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1447520439


##########
datafusion/common/src/tree_node.rs:
##########
@@ -18,7 +18,6 @@
 //! This module provides common traits for visiting or rewriting tree
 //! data structures easily.
 
-use std::borrow::Cow;

Review Comment:
   If you check `apply_children()`, it seems like you duplicate its logic to 4 places in this PR.
   Also, the `Cow` was there to avoid cloning in `Expr` but now we have cloning again.
   I'm ok with the new `children(&self)` and `take_children(self)` methods, but it seems like they are not properly used here and there...



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1884825411

   ## TODO
   
   - Calls to `add_sort_above` should change `PlanContext` tree accordingly.
   - `pushdown_sorts`: Has an unnecessary `SortPushdown::new_default`, should go away when `add_sort_above` is fixed.
   - `reorder_partitioned_join_keys`: Changes plan, should take in `PlanWithKeyRequirements` and modify it (and thus remove `new_default` calls).
   - `reorder_aggregate_keys` -> Changes plan, should take in `PlanWithKeyRequirements` and modify it (and thus remove `new_default` calls).
   - `remove_corresponding_coalesce_in_sub_plan`: Changes plan, should modify the `PlanWithCorrespondingCoalescePartitions` tree it takes in.
       - This way we will get rid of the `new_default` calls in `parallelize_sorts`.
   
   ## TEST TODO
   - Tests should validate derived trees match with original trees
   - Tests should validate data/payloads are set correctly after transform completes (to ensure composability)


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1467278612


##########
datafusion/core/src/physical_optimizer/test_utils.rs:
##########
@@ -361,3 +364,17 @@ pub fn sort_exec(
     let sort_exprs = sort_exprs.into_iter().collect();
     Arc::new(SortExec::new(sort_exprs, input))
 }
+
+pub fn check_integrity<T: Clone>(context: PlanContext<T>) -> Result<PlanContext<T>> {
+    context.transform_up(&|node| {
+        let children_plans = node.plan.children();
+        assert_eq!(node.children.len(), children_plans.len());
+        for (child_plan, child_node) in children_plans.iter().zip(node.children.iter()) {
+            assert_eq!(

Review Comment:
   Since `ExecutionPlan`'s do not implement `PartialEq`, we lack a straightforward way to compare them. However, I believe there are no obstacles to implementing `PartialEq` support for `ExecutionPlan`'s.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1908015505

   > Is this PR ready for review? I ask because the title still says WIP but maybe that is just outdated.
   
   Yes, I forgot to change it


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1447401307


##########
datafusion/common/src/tree_node.rs:
##########
@@ -18,7 +18,6 @@
 //! This module provides common traits for visiting or rewriting tree
 //! data structures easily.
 
-use std::borrow::Cow;

Review Comment:
   It seems like this PR reverts @viirya's https://github.com/apache/arrow-datafusion/pull/8672. Why is that?



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1467508214


##########
datafusion/core/src/physical_optimizer/enforce_sorting.rs:
##########
@@ -812,6 +634,50 @@ mod tests {
             let session_ctx = SessionContext::new_with_config(config);
             let state = session_ctx.state();
 
+            // This file has 4 rules that use tree node, apply these rules as in the
+            // EnforSorting::optimize implementation
+            // After these operations tree nodes should be in a consistent state.
+            // This code block makes sure that these rules doesn't violate tree node integrity.
+            {
+                let plan_requirements = PlanWithCorrespondingSort::new_default($PLAN.clone());
+                let adjusted = plan_requirements
+                    .transform_up(&ensure_sorting)
+                    .and_then(check_integrity)?;
+                // TODO: End state payloads will be checked here.

Review Comment:
   A separate ticket is a great idea -- can you please file one and add the link to these comments?



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1902670469

   As soon as the draft is complete, we will fill in the PR body with this information. The quick summary is that `PlanContext` and `ExprContext` structs store partial results for all nodes so that one does not need to recompute them in multi-step transformations.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1908050551

   I plan to review this shortly


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1447520439


##########
datafusion/common/src/tree_node.rs:
##########
@@ -18,7 +18,6 @@
 //! This module provides common traits for visiting or rewriting tree
 //! data structures easily.
 
-use std::borrow::Cow;

Review Comment:
   If you check `apply_children()`, it seems like you duplicates its logic to 4 places in this PR.
   Also the `Cow` was there to avoid cloning in `Expr` but now we have cloning again.
   I'm ok with the new `children(&self)` and `take_children(self)` methods, but it seems like they are not properly used here and there...



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1884828199

   I will work on TODO's.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1901185514

   Related discussion / epic: https://github.com/apache/arrow-datafusion/issues/8913


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#discussion_r1467280368


##########
datafusion/core/src/physical_optimizer/enforce_sorting.rs:
##########
@@ -812,6 +634,50 @@ mod tests {
             let session_ctx = SessionContext::new_with_config(config);
             let state = session_ctx.state();
 
+            // This file has 4 rules that use tree node, apply these rules as in the
+            // EnforSorting::optimize implementation
+            // After these operations tree nodes should be in a consistent state.
+            // This code block makes sure that these rules doesn't violate tree node integrity.
+            {
+                let plan_requirements = PlanWithCorrespondingSort::new_default($PLAN.clone());
+                let adjusted = plan_requirements
+                    .transform_up(&ensure_sorting)
+                    .and_then(check_integrity)?;
+                // TODO: End state payloads will be checked here.

Review Comment:
   Adding payload checks to each test is time-consuming, and verifying the accuracy of the results necessitates a separate analysis. I suggest we track these tasks in a separate ticket as todo, so we don't delay this PR any further.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1911562968

   > I left some remarks mostly about improving / increasing comments, but I think they could be done as follow on PRs (or never)
   
   Thank you @alamb for your valuable feedbacks. I will push a commit addressing your suggestions.
   


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1908003262

   Is this PR ready for review? I ask because the title still says WIP but maybe that is just outdated. 


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak merged PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] TreeNode refactor code deduplication: Part 3 [arrow-datafusion]

Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #8817:
URL: https://github.com/apache/arrow-datafusion/pull/8817#issuecomment-1903810929

   Another use case of persisting states could be interval values of PhysicalExpr's. At each execution, rather than constructing a new graph from the previous interval values, and then updating them could be simplified as one existing and continuously modified way.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org