comphead commented on code in PR #7817:
URL: https://github.com/apache/datafusion-comet/pull/7817#discussion_r4762657211


##########
spark/src/main/scala/org/apache/spark/sql/comet/operators.scala:
##########
@@ -2854,9 +2864,22 @@ case class CometSortAggregateExec(
     resultExpressions: Seq[NamedExpression],
     input: Seq[Attribute],
     child: SparkPlan,
-    override val serializedPlanOpt: SerializedPlan)
+    override val serializedPlanOpt: SerializedPlan,
+    droppedInputSort: Option[Seq[SortOrder]] = None,
+    orderedOutput: Boolean = true)
     extends CometBaseAggregateExec {
 
+  override def outputOrdering: Seq[SortOrder] =
+    if (orderedOutput) super.outputOrdering else Nil
+
+  // Spark's sort aggregate reads its input in grouping-key order, so put the 
sort back.
+  override def restoreSparkPlan(children: Seq[SparkPlan]): SparkPlan =

Review Comment:
   `CometExec.sparkFallback` is the existing hook for this. Its doc says that 
operators which change the Spark plan shape must override it. 
`RevertNativeForTransitionHeavyStages.revertToSpark` (line 311) and 
`MakeDateEvaluation` (line 442) call `sparkFallback`, not `restoreSparkPlan`. 
So with `spark.comet.exec.transitionRevert.enabled` also on, a reverted stage 
gets a Spark `SortAggregateExec` in `Final` mode over unsorted shuffle output. 
That operator emits a row for each run of equal keys, so the result has 
duplicate groups. Overriding `sparkFallback` here and calling it from the three 
`CometExecRule` sites would cover every path and remove the second method. I 
did not run this.



##########
spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala:
##########
@@ -306,6 +337,72 @@ case class CometExecRule(session: SparkSession, 
queryStagePrep: Boolean = false)
     }
   }
 
+  /**
+   * Runs native sort aggregates without the sort on their grouping keys that 
Spark planned below
+   * them. Spark plans a sort aggregate when its aggregation buffer cannot 
hold a value, such as a
+   * string `min` or `max`. The native aggregate hashes its groups whatever 
its input order, so
+   * the sort, which buffers and can spill the whole input, is needed only for 
the order Spark
+   * expects of the output:
+   *
+   *   - A partial aggregate under a shuffle drops the sort and no longer 
reports an ordering; the
+   *     shuffle discards it anyway, and Spark sorts again below the final 
aggregate.
+   *   - A final or complete aggregate drops the sort and keeps 
`ordered_by_grouping_keys`, so the
+   *     native planner sorts the aggregated rows, one per group, to keep the 
order Spark reports
+   *     and may have removed a sort above on the strength of.
+   *
+   * This runs after the conversion pass, so it only removes a sort that 
converted together with
+   * its aggregate; a sort below an aggregate that stays in Spark is never 
touched. An aggregate
+   * that later falls back to Spark gets its sort back from `restoreSparkPlan`.
+   */
+  private def dropSortAggregateInputSorts(plan: SparkPlan): SparkPlan = {
+    def isFinal(agg: CometSortAggregateExec): Boolean =
+      agg.modes.nonEmpty && agg.modes.forall(m => m == Final || m == Complete)
+    def isPartial(agg: CometSortAggregateExec): Boolean =
+      agg.modes.nonEmpty && agg.modes.forall(m => m == Partial || m == 
PartialMerge)
+
+    plan.transformUp {
+      case exchange: ShuffleExchangeLike =>
+        exchange.child match {
+          case agg: CometSortAggregateExec if isPartial(agg) =>
+            withoutInputSort(agg, orderedOutput = false)
+              .map(newAgg => exchange.withNewChildren(Seq(newAgg)))
+              .getOrElse(exchange)
+          case _ => exchange
+        }
+      case agg: CometSortAggregateExec if isFinal(agg) =>

Review Comment:
   This rewrite does not reach the native plan when the final aggregate has a 
native parent. When a parent is converted, its `nativeOp` embeds its children's 
`nativeOp` (`builder.addChildren(childOp)` in the conversion around line 1466), 
and `convertBlock` serializes only the root's `nativeOp`. Take a final 
aggregate under `CometSortMergeJoinExec`, `CometProjectExec` or 
`CometFilterExec`. The Spark plan shows no `CometSortExec` and sets 
`droppedInputSort`, but the block still runs the old `HashAgg` over `Sort`. The 
comment at line 473 describes the same trap. The PR description says the gain 
and the loss both come from the partial, and a partial under a shuffle never 
has a native ancestor in its block. I suggest dropping only the partial's sort 
and removing the final branch, `Complete` and the `orderedOutput` parameter. A 
dropped sort would then always mean no output ordering. If the final branch 
stays, its ancestors need their `nativeOp` rebuilt, as 
`refreshStaleShuffleScans` does w
 ith `withRefreshedNativeOp`.



##########
spark/src/test/scala/org/apache/comet/exec/CometAggregateSuite.scala:
##########
@@ -4687,6 +4687,177 @@ class CometAggregateSuite extends CometTestBase with 
AdaptiveSparkPlanHelper {
       CometConf.COMET_ENABLE_FINAL_HASH_AGGREGATE.key -> "false")
   }
 
+  /** Runs `f` over a table whose string `max` makes Spark plan sort 
aggregates. */
+  private def withSortAggregateTables(dropInputSort: Boolean)(f: => Unit): 
Unit = {
+    withSQLConf(
+      CometConf.COMET_EXEC_SORT_AGGREGATE_DROP_INPUT_SORT_ENABLED.key -> 
dropInputSort.toString,
+      CometConf.COMET_SHUFFLE_ENABLED.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
+      withParquetTable((0 until 200).map(i => (i % 17, s"v${(i * 7919) % 
211}", i)), "sa") {
+        withParquetTable((0 until 17).map(i => (i, s"u$i")), "sa_keys") {
+          f
+        }
+      }
+    }
+  }
+
+  private def sortAggregates(plan: SparkPlan): Seq[CometSortAggregateExec] =
+    collect(plan) { case agg: CometSortAggregateExec => agg }
+
+  test("SortAggregate drops the sort on its grouping keys when enabled") {
+    // The second query reorders the result, which puts a Projection above the 
native aggregate.
+    Seq(
+      "SELECT _1, max(_2), min(_2), count(_3) FROM sa GROUP BY _1",
+      "SELECT max(_2) AS m, _1 FROM sa GROUP BY _1").foreach { query =>
+      Seq("false", "true").foreach { aqe =>
+        withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe) {
+          withSortAggregateTables(dropInputSort = true) {
+            val (_, plan) = checkSparkAnswerAndOperator(sql(query))
+            val aggs = sortAggregates(plan)
+            assert(aggs.map(_.modes).toSet == Set(Seq(Partial), Seq(Final)), 
plan)
+            assert(aggs.forall(_.droppedInputSort.isDefined), plan)
+            assert(!aggs.exists(_.child.isInstanceOf[CometSortExec]), plan)
+            // The final aggregate sorts its aggregated rows instead, and 
keeps its ordering.
+            val (partial, finalAgg) =
+              (aggs.find(_.modes == Seq(Partial)).get, aggs.find(_.modes == 
Seq(Final)).get)
+            assert(!partial.orderedOutput && partial.outputOrdering.isEmpty, 
plan)
+            assert(finalAgg.orderedOutput && finalAgg.outputOrdering.nonEmpty, 
plan)
+            // Falling back to Spark puts the sort back below the aggregate.
+            val restored = partial.restoreSparkPlan(partial.children)
+            assert(restored.children.head.isInstanceOf[SortExec], restored)
+          }
+          withSortAggregateTables(dropInputSort = false) {
+            val (_, plan) = checkSparkAnswerAndOperator(sql(query))
+            
assert(sortAggregates(plan).forall(_.child.isInstanceOf[CometSortExec]), plan)
+          }
+        }
+      }
+    }
+  }
+
+  test("SortAggregate keeps its input sort for an order-sensitive aggregate") {
+    withSortAggregateTables(dropInputSort = true) {
+      // first() reads the grouping key, the same in every row of a group, so 
it is deterministic.
+      val (_, plan) = checkSparkAnswerAndOperator(
+        sql("SELECT _1, first(CAST(_1 AS STRING)), max(_2) FROM sa GROUP BY 
_1"))
+      val aggs = sortAggregates(plan)
+      assert(aggs.nonEmpty && aggs.forall(_.droppedInputSort.isEmpty), plan)
+    }
+  }
+
+  test("SortAggregate without its input sort still feeds a sort-merge join in 
key order") {
+    // The final aggregate reports its output as ordered by _1, so Spark puts 
no sort between it
+    // and the join. The native planner sorts the aggregated rows to keep that 
promise.
+    Seq("false", "true").foreach { aqe =>
+      withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe) {
+        withSortAggregateTables(dropInputSort = true) {
+          val df = sql(
+            "SELECT a._1, a.m, b._2 FROM (SELECT _1, max(_2) AS m FROM sa 
GROUP BY _1) a " +
+              "JOIN sa_keys b ON a._1 = b._1")
+          val (_, plan) = checkSparkAnswer(df)
+          val finalAgg = sortAggregates(plan).find(_.modes == Seq(Final))

Review Comment:
   This test passes whether or not the final aggregate's output sort runs. The 
final's parent is the join, and the join's native plan still holds the 
aggregate's input `Sort` (see my comment on `dropSortAggregateInputSorts`). I 
found this by reading the code and did not run it. An assertion on the 
serialized native plan, for example that no `Sort` is the child of the final 
`HashAgg`, would show which plan actually runs. The same applies to the join 
query in the null, float and multi-column key test.



##########
spark/src/main/scala/org/apache/comet/CometConf.scala:
##########
@@ -428,6 +428,23 @@ object CometConf extends ShimCometConf {
         s"over a Comet shuffle. Supports a single column or coalesce 
expression. $TUNING_GUIDE.")
       .booleanConf
       .createWithDefault(false)
+  val COMET_EXEC_SORT_AGGREGATE_DROP_INPUT_SORT_ENABLED: ConfigEntry[Boolean] =
+    conf("spark.comet.exec.sortAggregate.dropInputSort.enabled")

Review Comment:
   Rule `T3` of the documentation style guide 
(`docs/source/contributor-guide/style_guide.md`) asks for "Rust-implemented" or 
"runs in Comet" instead of "native" on its own, as in "a native sort aggregate" 
and "The native aggregate hashes its groups". If only the partial keeps this 
behavior, the doc can also be shorter: say that a partial aggregate under a 
shuffle skips the sort, and that order-sensitive functions keep it.



##########
spark/src/test/scala/org/apache/comet/exec/CometAggregateSuite.scala:
##########
@@ -4687,6 +4687,177 @@ class CometAggregateSuite extends CometTestBase with 
AdaptiveSparkPlanHelper {
       CometConf.COMET_ENABLE_FINAL_HASH_AGGREGATE.key -> "false")
   }
 
+  /** Runs `f` over a table whose string `max` makes Spark plan sort 
aggregates. */
+  private def withSortAggregateTables(dropInputSort: Boolean)(f: => Unit): 
Unit = {
+    withSQLConf(
+      CometConf.COMET_EXEC_SORT_AGGREGATE_DROP_INPUT_SORT_ENABLED.key -> 
dropInputSort.toString,
+      CometConf.COMET_SHUFFLE_ENABLED.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
+      withParquetTable((0 until 200).map(i => (i % 17, s"v${(i * 7919) % 
211}", i)), "sa") {
+        withParquetTable((0 until 17).map(i => (i, s"u$i")), "sa_keys") {
+          f
+        }
+      }
+    }
+  }
+
+  private def sortAggregates(plan: SparkPlan): Seq[CometSortAggregateExec] =
+    collect(plan) { case agg: CometSortAggregateExec => agg }
+
+  test("SortAggregate drops the sort on its grouping keys when enabled") {
+    // The second query reorders the result, which puts a Projection above the 
native aggregate.
+    Seq(
+      "SELECT _1, max(_2), min(_2), count(_3) FROM sa GROUP BY _1",
+      "SELECT max(_2) AS m, _1 FROM sa GROUP BY _1").foreach { query =>
+      Seq("false", "true").foreach { aqe =>
+        withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe) {
+          withSortAggregateTables(dropInputSort = true) {
+            val (_, plan) = checkSparkAnswerAndOperator(sql(query))
+            val aggs = sortAggregates(plan)
+            assert(aggs.map(_.modes).toSet == Set(Seq(Partial), Seq(Final)), 
plan)
+            assert(aggs.forall(_.droppedInputSort.isDefined), plan)
+            assert(!aggs.exists(_.child.isInstanceOf[CometSortExec]), plan)
+            // The final aggregate sorts its aggregated rows instead, and 
keeps its ordering.
+            val (partial, finalAgg) =
+              (aggs.find(_.modes == Seq(Partial)).get, aggs.find(_.modes == 
Seq(Final)).get)
+            assert(!partial.orderedOutput && partial.outputOrdering.isEmpty, 
plan)
+            assert(finalAgg.orderedOutput && finalAgg.outputOrdering.nonEmpty, 
plan)
+            // Falling back to Spark puts the sort back below the aggregate.
+            val restored = partial.restoreSparkPlan(partial.children)
+            assert(restored.children.head.isInstanceOf[SortExec], restored)
+          }
+          withSortAggregateTables(dropInputSort = false) {
+            val (_, plan) = checkSparkAnswerAndOperator(sql(query))
+            
assert(sortAggregates(plan).forall(_.child.isInstanceOf[CometSortExec]), plan)
+          }
+        }
+      }
+    }
+  }
+
+  test("SortAggregate keeps its input sort for an order-sensitive aggregate") {
+    withSortAggregateTables(dropInputSort = true) {
+      // first() reads the grouping key, the same in every row of a group, so 
it is deterministic.
+      val (_, plan) = checkSparkAnswerAndOperator(
+        sql("SELECT _1, first(CAST(_1 AS STRING)), max(_2) FROM sa GROUP BY 
_1"))
+      val aggs = sortAggregates(plan)
+      assert(aggs.nonEmpty && aggs.forall(_.droppedInputSort.isEmpty), plan)
+    }
+  }
+
+  test("SortAggregate without its input sort still feeds a sort-merge join in 
key order") {
+    // The final aggregate reports its output as ordered by _1, so Spark puts 
no sort between it
+    // and the join. The native planner sorts the aggregated rows to keep that 
promise.
+    Seq("false", "true").foreach { aqe =>
+      withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe) {
+        withSortAggregateTables(dropInputSort = true) {
+          val df = sql(
+            "SELECT a._1, a.m, b._2 FROM (SELECT _1, max(_2) AS m FROM sa 
GROUP BY _1) a " +
+              "JOIN sa_keys b ON a._1 = b._1")
+          val (_, plan) = checkSparkAnswer(df)
+          val finalAgg = sortAggregates(plan).find(_.modes == Seq(Final))
+          assert(finalAgg.exists(_.droppedInputSort.isDefined), plan)
+        }
+      }
+    }
+  }
+
+  test("SortAggregate keeps a partial's input sort when no shuffle follows 
it") {
+    // With the input already partitioned on _1, the final aggregate reads the 
partial directly
+    // and relies on its order, so the partial keeps its sort.
+    withSortAggregateTables(dropInputSort = true) {
+      val (_, plan) = checkSparkAnswer(
+        sql("SELECT _1, max(_2) FROM (SELECT /*+ REPARTITION(_1) */ * FROM sa) 
GROUP BY _1"))
+      sortAggregates(plan).filter(_.modes == Seq(Partial)).foreach { partial =>

Review Comment:
   If the filter is empty, the `foreach` does nothing and the test passes. That 
happens if the partial stops converting or Spark stops planning one. Assert 
that a `Partial` aggregate was found, as the other tests do with `nonEmpty`.



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