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


##########
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:
   Good catch — simplified in 0e5de7f4a to drop only the input sort of a 
partial aggregate directly under a shuffle exchange, and removed the 
final/complete branch and `orderedOutput`. Since the shuffle ends the native 
block, the partial never has a native ancestor whose embedded `nativeOp` could 
go stale.



##########
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:
   Fixed in 0e5de7f4a: removed `restoreSparkPlan`, overrode 
`CometExec.sparkFallback` on `CometSortAggregateExec` (calling 
`super.sparkFallback` with the re-wrapped `SortExec` child), and switched the 
three `CometExecRule` sites to `sparkFallback`. Also added a 
`transitionRevert.enabled=true` test.



##########
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:
   Updated in 0e5de7f4a: with only the partial under a shuffle dropping its 
sort, the tests now assert both on `droppedInputSort.isDefined` and directly on 
the partial's serialized `nativeOp` protobuf 
(`!hasSortBelowHashAgg(partial.nativeOp)`).



##########
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:
   Fixed in 0e5de7f4a — added `assert(partials.nonEmpty, plan)` before the 
`foreach`.



##########
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:
   Updated in 0e5de7f4a to follow Rule T3 ("running in Comet" / 
"Rust-implemented") and shortened to describe the partial-under-shuffle 
behavior.



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