jayzhan211 commented on code in PR #27833:
URL: https://github.com/apache/datafusion/pull/27833#discussion_r4755072645


##########
datafusion/physical-optimizer/src/output_requirements.rs:
##########
@@ -36,39 +32,64 @@ use datafusion_physical_plan::{
     SendableRecordBatchStream, StatisticsArgs,
 };
 
-/// This rule either adds or removes [`OutputRequirements`]s to/from the 
physical
-/// plan according to its `mode` attribute, which is set by the constructors
-/// `new_add_mode` and `new_remove_mode`. With this rule, we can keep track of
-/// the global requirements (ordering and distribution) across rules.
+/// OptimizerRule that preserves the final query output ordering and
+/// distribution requirements across physical plan rewrites.
 ///
-/// The primary use case of this node and rule is to specify and preserve the 
desired output
-/// ordering and distribution the entire plan. When sending to a single 
client, a single partition may
-/// be desirable, but when sending to a multi-partitioned writer, keeping 
multiple partitions may be
-/// better.
+/// This rule is needed because the optimizer may rewrite the plan in ways 
that lose
+/// the original ordering and distribution requirements.
+///
+/// # Example
+///
+/// For example, the query `SELECT a FROM t ORDER BY a` requires that the final
+/// output be sorted by `a`.
+///
+/// If a single partition data source is already sorted by `a`, the simplified
+/// physical plan starts with a sort above the scan:
+///
+/// ```text
+/// SortExec: expr=[a@0 ASC NULLS LAST]
+///   DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
+/// ```
+///
+/// The optimizer can remove the redundant sort because the scan already
+/// produces the requested order.
+/// ```text
+/// DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
+/// ```
+///
+/// However, other rewrites might split the scan across multiple partitions,
+/// which could produce a final output that is not globally sorted. In order to
+/// prevent such a rewrite, this rule adds a [`OutputRequirementExec`] above 
the
+/// original sort to record the output requirements. The optimizer can then
+/// remove the sort, and the output requirements remain encoded in the plan.

Review Comment:
   The wrapper doesn't prevent the scan from being split. Sorted scans are 
still split, for example `parquet_sorted_statistics.slt:109` plans 
`SortPreservingMergeExec` over a 2-group `DataSourceExec`. What the wrapper 
does is report the requirements as its required input ordering and 
distribution, so `EnsureRequirements` adds the merge after the sort is removed. 
A wording that matches the code (`cargo doc -D warnings` passes with it):
   
   ```suggestion
   /// However, a later rewrite may split the scan into several partitions to 
read
   /// it in parallel, and the split plan is no longer globally sorted. So this 
rule
   /// adds an [`OutputRequirementExec`] above the original sort. It reports the
   /// query's requirements as its required input ordering and distribution, so
   /// after the sort is removed, [`EnsureRequirements`] still adds a
   /// [`SortPreservingMergeExec`] above a split scan.
   ///
   /// [`EnsureRequirements`]: crate::ensure_requirements::EnsureRequirements
   ```



##########
datafusion/physical-optimizer/src/output_requirements.rs:
##########
@@ -36,39 +32,64 @@ use datafusion_physical_plan::{
     SendableRecordBatchStream, StatisticsArgs,
 };
 
-/// This rule either adds or removes [`OutputRequirements`]s to/from the 
physical
-/// plan according to its `mode` attribute, which is set by the constructors
-/// `new_add_mode` and `new_remove_mode`. With this rule, we can keep track of
-/// the global requirements (ordering and distribution) across rules.
+/// OptimizerRule that preserves the final query output ordering and
+/// distribution requirements across physical plan rewrites.
 ///
-/// The primary use case of this node and rule is to specify and preserve the 
desired output
-/// ordering and distribution the entire plan. When sending to a single 
client, a single partition may
-/// be desirable, but when sending to a multi-partitioned writer, keeping 
multiple partitions may be
-/// better.
+/// This rule is needed because the optimizer may rewrite the plan in ways 
that lose
+/// the original ordering and distribution requirements.
+///
+/// # Example
+///
+/// For example, the query `SELECT a FROM t ORDER BY a` requires that the final
+/// output be sorted by `a`.
+///
+/// If a single partition data source is already sorted by `a`, the simplified
+/// physical plan starts with a sort above the scan:
+///
+/// ```text
+/// SortExec: expr=[a@0 ASC NULLS LAST]
+///   DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
+/// ```
+///
+/// The optimizer can remove the redundant sort because the scan already
+/// produces the requested order.
+/// ```text
+/// DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
+/// ```
+///
+/// However, other rewrites might split the scan across multiple partitions,
+/// which could produce a final output that is not globally sorted. In order to
+/// prevent such a rewrite, this rule adds a [`OutputRequirementExec`] above 
the
+/// original sort to record the output requirements. The optimizer can then
+/// remove the sort, and the output requirements remain encoded in the plan.
+///
+/// ```text
+/// OutputRequirementExec: order_by=[(a@0, asc)], dist_by=SinglePartition
+///   SortExec: expr=[a@0 ASC NULLS LAST], preserve_partitioning=[false]
+///     DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
+/// ```
+///
+/// # Add and Remove Modes
+///
+/// At the start of physical optimization, the rule runs in **add** mode to
+/// place the [`OutputRequirementExec`] if needed.
+///
+/// At the end of optimization, the rule runs in **remove** mode to remove the
+/// [`OutputRequirementExec`] before execution.

Review Comment:
   Two parts of this section don't match the code. Add mode always places a 
wrapper: `explain.slt:225` shows `OutputRequirementExec: order_by=[], 
dist_by=Unspecified` for a query with no `ORDER BY`. Remove mode doesn't run at 
the end either: in `optimizer.rs` it runs right after 
`EnsureRequirements`/`ProjectionPushdown`, and nine rules follow it 
(`LimitPushdown`, `TopKRepartition`, `PushdownSort`, ...). Those later rules 
are the ones the #27772 thread is about, so it seems worth saying what they 
must do:
   
   ```suggestion
   /// At the start of physical optimization, the rule runs in **add** mode and
   /// always places an [`OutputRequirementExec`]. Without a `SortExec` or
   /// `SortPreservingMergeExec` to take requirements from, it goes at the root
   /// with no ordering and an unspecified distribution.
   ///
   /// After [`EnsureRequirements`] has made the plan satisfy the requirements, 
the
   /// rule runs in **remove** mode to take the [`OutputRequirementExec`] out. 
Rules
   /// that run after remove mode can no longer see the requirements, so they 
must
   /// keep the plan's output ordering and partitioning themselves.
   ```



##########
datafusion/physical-optimizer/src/output_requirements.rs:
##########
@@ -36,39 +32,64 @@ use datafusion_physical_plan::{
     SendableRecordBatchStream, StatisticsArgs,
 };
 
-/// This rule either adds or removes [`OutputRequirements`]s to/from the 
physical
-/// plan according to its `mode` attribute, which is set by the constructors
-/// `new_add_mode` and `new_remove_mode`. With this rule, we can keep track of
-/// the global requirements (ordering and distribution) across rules.
+/// OptimizerRule that preserves the final query output ordering and
+/// distribution requirements across physical plan rewrites.
 ///
-/// The primary use case of this node and rule is to specify and preserve the 
desired output
-/// ordering and distribution the entire plan. When sending to a single 
client, a single partition may
-/// be desirable, but when sending to a multi-partitioned writer, keeping 
multiple partitions may be
-/// better.
+/// This rule is needed because the optimizer may rewrite the plan in ways 
that lose
+/// the original ordering and distribution requirements.
+///
+/// # Example
+///
+/// For example, the query `SELECT a FROM t ORDER BY a` requires that the final
+/// output be sorted by `a`.
+///
+/// If a single partition data source is already sorted by `a`, the simplified
+/// physical plan starts with a sort above the scan:
+///
+/// ```text
+/// SortExec: expr=[a@0 ASC NULLS LAST]
+///   DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
+/// ```
+///
+/// The optimizer can remove the redundant sort because the scan already
+/// produces the requested order.
+/// ```text
+/// DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
+/// ```
+///
+/// However, other rewrites might split the scan across multiple partitions,
+/// which could produce a final output that is not globally sorted. In order to
+/// prevent such a rewrite, this rule adds a [`OutputRequirementExec`] above 
the
+/// original sort to record the output requirements. The optimizer can then
+/// remove the sort, and the output requirements remain encoded in the plan.
+///
+/// ```text
+/// OutputRequirementExec: order_by=[(a@0, asc)], dist_by=SinglePartition
+///   SortExec: expr=[a@0 ASC NULLS LAST], preserve_partitioning=[false]
+///     DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
+/// ```
+///
+/// # Add and Remove Modes
+///
+/// At the start of physical optimization, the rule runs in **add** mode to
+/// place the [`OutputRequirementExec`] if needed.
+///
+/// At the end of optimization, the rule runs in **remove** mode to remove the
+/// [`OutputRequirementExec`] before execution.
 #[derive(Debug)]
 pub struct OutputRequirements {
     mode: RuleMode,
 }
 
 impl OutputRequirements {
-    /// Create a new rule which works in `Add` mode; i.e. it simply adds a
-    /// top-level [`OutputRequirementExec`] into the physical plan to keep 
track
-    /// of global ordering and distribution requirements if there are any.
-    /// Note that this rule should run at the beginning. It is idempotent: when
-    /// invoked on a plan that already contains an `OutputRequirementExec` (at
-    /// the root or below it), it returns the plan unchanged.
+    /// Creates an [`OutputRequirements`] rule in add mode.

Review Comment:
   Optional: could we keep the idempotency note here? #22522 added it because 
ballista's adaptive execution re-runs this rule after every stage. This 
constructor is the public place where users of the rule will look for that 
guarantee.
   
   ```suggestion
       /// Creates an [`OutputRequirements`] rule in add mode.
       ///
       /// Idempotent: on a plan that already contains an 
[`OutputRequirementExec`]
       /// (at the root or below it), it returns the plan unchanged.
   ```



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